Exemplo n.º 1
0
 /**
  * Return statistics XLS file
  *
  * @param   string  $tpl  The name of the template file to parse; automatically searches through the template paths.
  *
  * @return  void
  */
 function display($tpl = null)
 {
     $this->item = $this->get('Item');
     // Get parameters
     $jinput = JFactory::getApplication()->input;
     $type = $jinput->get('type', null, 'string');
     $begin = $jinput->get('begin', null, 'string');
     $end = $jinput->get('end', null, 'string');
     // Convert date strings to JDate objects
     $beginDate = new JDate($begin);
     $endDate = new JDate($end . ' 23:59:59');
     // Get statistic model
     $statisticModel = JModelLegacy::getInstance('statistic', 'IsbnregistryModel');
     // Get statistics
     $data = $statisticModel->getStats($type, $beginDate, $endDate);
     // Set document properties
     $document = JFactory::getDocument();
     $document->setMimeEncoding('application/vnd.ms-excel; charset="UTF-8"');
     JResponse::setHeader('Content-disposition', 'attachment; filename="statistics.xml"', true);
     // Get Excel helper
     require_once JPATH_COMPONENT . '/helpers/php-export-data.class.php';
     // Create new Excled worksheet
     $excel = new ExportDataExcel('browser');
     $excel->filename = "statistics.xml";
     $excel->initialize();
     // Loop through data array
     foreach ($data as $row) {
         // Add rows
         $excel->addRow($row);
     }
     // Finalize
     $excel->finalize();
 }
Exemplo n.º 2
0
 public function act_export()
 {
     $ioType = intval($_GET['ioType']);
     $id = isset($_GET['id']) ? post_check($_GET['id']) : '';
     $ordersn = isset($_GET['ordersn']) ? post_check($_GET['ordersn']) : '';
     $ioTypeId = isset($_GET['ioTypeId']) ? post_check($_GET['ioTypeId']) : '';
     $sku = isset($_GET['sku']) ? post_check($_GET['sku']) : '';
     $purchaseId = isset($_GET['purchaseId']) ? post_check($_GET['purchaseId']) : '';
     $userId = isset($_GET['userId']) ? post_check($_GET['userId']) : '';
     $cStartTime = isset($_GET['cStartTime']) ? post_check($_GET['cStartTime']) : '';
     $cEndTime = isset($_GET['cEndTime']) ? post_check($_GET['cEndTime']) : '';
     if (empty($id) && empty($ordersn) && empty($ioTypeId) && empty($sku) && empty($purchaseId) && empty($userId) && empty($cStartTime) && empty($cEndTime)) {
         echo "请选择导出条件";
         exit;
     }
     $where = "WHERE ioType='{$ioType}' ";
     if (!empty($id)) {
         $where .= "AND id='{$id}' ";
     }
     if (!empty($ordersn)) {
         $where .= "AND ordersn='{$ordersn}' ";
     }
     if (!empty($ioTypeId)) {
         $where .= "AND ioTypeId='{$ioTypeId}' ";
     }
     if (!empty($sku)) {
         $where .= "AND sku='{$sku}' ";
     }
     if (!empty($purchaseId)) {
         $purchaseId = getUserIdByName($purchaseId);
         $where .= "AND purchaseId='{$purchaseId}' ";
     }
     if (!empty($userId)) {
         $userId = getUserIdByName($userId);
         $where .= "AND userId='{$userId}' ";
     }
     if (!empty($cStartTime)) {
         $startTime = strtotime($cStartTime . '00:00:00');
         $where .= "AND createdTime >='{$startTime}' ";
     }
     if (!empty($cEndTime)) {
         $endTime = strtotime($cEndTime . '23:59:59');
         $where .= "AND createdTime <='{$endTime}' ";
     }
     $lists = WhIoRecordsModel::getTNameList('wh_iorecords', '*', $where);
     if ($ioType == 1) {
         $excel = new ExportDataExcel('browser', "out_warehouse." . date('Y-m-d') . ".xls");
     } else {
         $excel = new ExportDataExcel('browser', "in_warehouse." . date('Y-m-d') . ".xls");
     }
     $excel->initialize();
     $tharr = array("日期", "料号", "仓位", "数量", "类型", "申请人", "订单号", "备注");
     $excel->addRow($tharr);
     foreach ($lists as $list) {
         $time = date('Y/m/d', $list['createdTime']);
         $sku = $list['sku'];
         $position_info = whShelfModel::selectPosition("where id={$list['positionId']}");
         $pName = $position_info[0]['pName'];
         $num = $list['amount'];
         $ioTypeName = WhIoStoreModel::getIoTypeNameById($list['ioTypeId']);
         $user = getUserNameById($list['userId']);
         $ordersn = $list['ordersn'];
         $reason = $list['reason'];
         $tdarr = array($time, $sku, $pName, $num, $ioTypeName, $user, $ordersn, $reason);
         $excel->addRow($tdarr);
     }
     $excel->finalize();
     exit;
 }
Exemplo n.º 3
0
 public function act_eubTrucknumber()
 {
     date_default_timezone_set("Asia/Chongqing");
     error_reporting(0);
     $transportationlist = CommonModel::getCarrierList();
     $transportation = array();
     foreach ($transportationlist as $k1 => $v1) {
         $transportation[$v1['id']] = $v1['carrierNameCn'];
     }
     /*
             $strOrder = '';
             $arr_orders   = array();
             $arr_accounts   = array();
             $arr_records = explode(',', $strTxet);
             foreach ($arr_records as $k => $v) {
                 list($order,$account) = explode('--', $v);
                 $arr_orders[] = $order;
                 $arr_accounts[] = $account;
                 $strOrder .= "','".$order;
             }
             echo "<pre>";
             echo $strOrder;
             //print_r($arr_orders);
             //print_r($arr_accounts);
             exit;*/
     /*$table = " `om_unshipped_order_detail` AS b 
                 LEFT JOIN `om_unshipped_order` AS a  ON a.id = b.omOrderId
                 LEFT JOIN `om_unshipped_order_userInfo` AS c ON a.id = c.omOrderId
                 LEFT JOIN `om_unshipped_order_extension_aliexpress` AS d ON a.id = d.omOrderId
                 LEFT JOIN `om_unshipped_order_detail_extension_aliexpress` AS e ON b.id = e.omOrderdetailId 
                 LEFT JOIN `om_order_tracknumber` as f ON a.id = f.omOrderId 
                 LEFT JOIN `om_account` AS g ON a.accountId = g.id ";
             
             $field = " a.recordNumber,g.account,c.platformUsername,a.ordersTime,a.paymentTime,a.onlineTotal,a.actualShipping,a.actualTotal,d.currency,a.calcWeight,d.declaredPrice,d.PayPalPaymentId,b.sku,b.amount,e.itemTitle,d.feedback,c.username,c.countryName,c.state,c.city,c.street,c.zipCode,c.landline,c.phone,a.transportId ";
     
             $where = " WHERE a.platformId = '16' AND a.orderAddTime > '1394035200' AND  a.orderAddTime < '1394467200' ";
     
             $omAvailableAct  = new OmAvailableAct();          
             $unShipOrderList =  $omAvailableAct->act_getTNameList($table, $field, $where);
     
             foreach ($unShipOrderList as $k2 => $v2) { //key代表最外层的维数           
                 $detail = $v;
                 $detail['transportName'] = $transportation[$v2['transportId']];
     
                 unset($detail['transportId']);
     
                 $excel->addRow($detail);
             }
     
     
             echo "<pre>";
             print_r($unShipOrderList);
             exit;*/
     $fileName = "UnShipments" . date('Y-m-d') . ".xls";
     $excel = new ExportDataExcel('browser', $fileName);
     $excel->initialize();
     $row = array('订单编号', '买家名称', '买家邮箱1', '买家邮箱2', '买家邮箱3', '下单时间', '付款时间', '产品总金额', '物流费用', '订单金额', '币种', 'Transaction ID', '申报价值', '估算重量', 'SKU', '数量', '产品名称', '订单备注', '收货人名称', '收货国家', '州/省', '城市', '地址', '邮编', '联系电话1', '联系电话2', '联系电话3', '手机', '买家选择物流', '平台账号', '跟踪号');
     $excel->addRow($row);
     $table = " `om_shipped_order_detail` AS b  \n            LEFT JOIN `om_shipped_order` AS a  ON a.id = b.omOrderId\n            LEFT JOIN `om_shipped_order_userInfo` AS c ON a.id = c.omOrderId\n            LEFT JOIN `om_shipped_order_extension_aliexpress` AS d ON a.id = d.omOrderId\n            LEFT JOIN `om_shipped_order_detail_extension_aliexpress` AS e ON b.id = e.omOrderdetailId LEFT JOIN `om_order_tracknumber` as f ON a.id = f.omOrderId \n            LEFT JOIN `om_account` AS g ON a.accountId = g.id \n            LEFT JOIN `om_order_notes` AS h ON a.id = h.omOrderId ";
     $field = " a.recordNumber,a.ordersTime,a.paymentTime,a.onlineTotal,a.actualShipping,a.actualTotal,a.calcWeight,a.transportId,d.declaredPrice,d.PayPalPaymentId,b.sku,b.amount,e.itemTitle,d.feedback,c.platformUsername,c.email,c.username,c.countryName,c.currency,c.state,c.city,c.street,c.zipCode,c.landline,c.phone,f.tracknumber,g.account,h.content ";
     $where = " WHERE a.recordNumber in ('559220080488213','61291048149790','61291014326917','61285636311954','61299676786510','61257847770012','1171653376007','1342566038012','1342550690012','1342524909012','1342515426012','1342413527012','1342399574012','1342390599012','1342367093012','1342314002012','1342310983012','1342290240012','1342133149012','1342120869012','1342118622012','1342081543012','1172474925007','1172315504007','1172299770007','1172296184007','1172272680007','1172232882007','1172223365007','1172182526007','1172126469007','558981387361611','558487478479670','558460023922925','557494022572438','DD14030800858','DD14030800269','DD14030800028','DD14030800525','DD14030800473','DD14030800333','DD14030800327','DD14030800255','DD14030800252','DD14030800222','DD14030800123','DD14030800120','DD14030800114','DD14030800111','DD14030701909','DD14030701900','DD14030701897','DD14030701870','DD14030701862','DD14030701825','DD14030701804','DD14030701724','DD14030701628','DD14030701582','DD14030701521','DD14030701456','DD14030701453','DD14030800027','DD14030701839','DD14030701759','171854-1','171795-1','21230-1','21221-1','61300512856554','DD14030600356','560386182450074','560445368025526','560735706789508','tt26353  clock-maker-2003','557295691973440','560574194439744','560875202763990','560762748300826','559871057882405','1171983566007','559987766894519','558843852813198','026-2038948-1825953','560195307202708','560118439761577','560614570129474','560604162366800','61233033960335','61225401138144','61275776866334','61283751550514','61284381471047','61271644078579','61285971256188','61286694581510','61286457896555','61273360806194','61287102116285','61288784939131','61289515402687','61290457641996','61291268481630','61292236773732','61278564524075','61298273217872','61284209829125','61300945144583','61271728212854','61303225891249','61266347810315','61282400441698','61257905772517','61283695281297','61273648438832','61279523250615','61297173545612','61300390671128','61301813182124','61283752032239','61284146363591','61287931644618','61293690836849','61299950555255','61300354697689','61288949877623','61286041305506','61301553743972','61277379550615','61294274238692','61281604636692','61261903830103','61257008371173','61275686039202','61291354923312','61291893569713','61278566094239','61278769877617','61293864388329','61282765315776','61298697699029','61284928938443','61299558787159','61302422095276','61272643402639','202-8393434-1143552','224697','188403','026-9661670-0337959','58452','223786','223741','220371','188117','186781','188235','223689','218802','197544','188074','60262','558246027770826','528226','223407','218656','101770','1341546884012','1760855','176832','526693','219168','CN100013211','222168','61270307460048','105-8385470-2341026','106-8240274-1106603','523208','218133','61274545010953','61280384012104','61281919468547','61285998314076','61278855631594','61280505522639','61268603902803','61219012417370','61279110037621','61274064981817','61264566746663','61279266542058','61282198497751','61283350036547','61275139782894','61276103852273','61280872818965','61280057928870','61278504882195','61281135133896','61281392411898','61281294973925','61268565467244','61282631771728','61269563947797','61279838412445','61274342499990','61263606811067','61274785500124','61222565934461','26354','26356','26349','26345  jerikavazquezbermudez','61275958205863','61269285568291','61270402108315','61274339549496','61274546569687','61274802947529','61275751827350','61262847093901','61276629817558','61278175910616','61266721802310','61279901031227','61280690942912','61286380743625','61297839638906','61307624738338','61277028514524','61261240188489','61299055455120','26335','DD14030700132','DD14030601731','DD14030601397','DD14030601302','DD14030601298','DD14030700978','DD14030700788','DD14030700499','DD14030700332','DD14030700214','DD14030700204','DD14030601996','DD14030601838','DD14030601748','DD14030601585','DD14030601395','DD14030601384','DD14030601297','DD14030601284','DD14030700241','DD14030700069','DD14030601842','DD14030601707','171767','171755','171731','171724','171716','171676','21193','171659','171636','23640','10060#EF14030600078#00001','10058#EF14030600033#00001','10053#ED14030500099#00003','10052#ED14030500099#00002','10052#CIC14030600011#00001','10051#EF14030600007#00002','10050#EF14030600001#00004','10039#ED14022800279#00001','61288625724862','61301695017139','61262016159344','61268148743481','61302659500997','61281583119393','61286067476828','61273077999487','61288025605103','1325','1324','1323','1319','1318','1317','1341033505012','1341009132012','1341824240012','1341696946012','1341694163012','1341575187012','1341552132012','1171516107007','1171507984007','1171492136007','1171575046007','1172017468007','1172004350007','1171994219007','1171984578007','1171926583007','1171924919007','1171904569007','1171903716007','1171840428007','1171820921007','1171933127007','1341496314012','1341452776012','1341430719012','1341387307012','1341344799012','1341318614012','1341248976012','1341228817012','1341187566012','1341113133012','1171038439007','1171033243007','1170993495007','1171481958007','1171474896007','1171472379007','1171457400007','1171449215007','1171447905007','1171416970007','1171251355007','1171196353007','1171165850007','1171147108007','1171039940007','26337','DL00063245','61281572272997','61280185621112','558897626662002','559457550085319','559964179142377','559936580977023','559364883586789','558042806763467','557981705438975','558266733802235','558198507852622','557953639231007','557957714549391','557958516721499','557183300613704','557882892610971','557616359665851','1171017114007','1171004617007','1170988981007','1170976546007','1170433249007','558951559459508','559400560676789','559630880572235','559540508725117','559070020338919','558834837695702','1169337760','5581989066539311','558007554317350','559143459057814','1456015806','1456031064','558064192600975','1168657452','CYBS06140309','559167238163972','557996971531592','557659877402622','558001924546789','557729957608803','558094428083493','558167306158085','558274562942401','558386251311684','558527284183280','880823','558088270434082','558796179128106','558923216912503','558797711647636','558884118112405','219398','112-8281922-9312205','558575557867256','1455857822','1455944107','1455944508','1455957240','1455959108','1455959695','1455964405','1455964817','1455974683','1455975207','1455991212','1456014821','1456020637','1456021409','1456043496','1456045982','1455952462','1455953028','1455956237','1455962265','1455962496','1455971675','1455971936','1455973327','1455976832','1455985967','1455987643','1455996313','526380','157972','187584','223184','223181','CYBS13140316','525712','223049','89562','CN100012942','DL00079730','DL00079644','DD14030502002','DD14030501926','DD14030501877','DD14030501771','DD14030501558','DD14030501507','DD14030501495','DD14030501444','DD14030501147','DD14030601105','DD14030601102','DD14030600470','DD14030600252','DD14030501930','DD14030501886','DD14030501804','DD14030501297','DD14030501232','BD14030601169','187186','DL00080075','DL00077878','218374','187024','523612','33598','558057068255073','557772672117459','1455848911','1455941088','1455954864','1455957247','1455959313','1455967410','196296','186350') ";
     $omAvailableAct = new OmAvailableAct();
     $unShipOrderList = $omAvailableAct->act_getTNameList($table, $field, $where);
     foreach ($unShipOrderList as $k2 => $v2) {
         //key代表最外层的维数
         $detail = $v2;
         $ordersTime = date('Y-m-d', $detail['ordersTime']);
         $paymentTime = date('Y-m-d', $detail['paymentTime']);
         $transport = $transportation[$v2['transportId']];
         $note = $detail['content'] . ' ' . $detail['feedback'];
         $detailRow = array($detail['recordNumber'], $detail['platformUsername'], $detail['email'], '', '', $ordersTime, $paymentTime, $detail['onlineTotal'], $detail['actualShipping'], $detail['actualTotal'], $detail['currency'], $detail['PayPalPaymentId'], $detail['declaredPrice'], $detail['calcWeight'], $detail['sku'], $detail['amount'], $detail['itemTitle'], $note, $detail['username'], $detail['countryName'], $detail['state'], $detail['city'], $detail['street'], $detail['zipCode'], $detail['landline'], '', '', $detail['phone'], $transport, $detail['account'], $detail['tracknumber']);
         $excel->addRow($detailRow);
     }
     $excel->finalize();
     exit;
 }
<?php

/**
 * تصدير العملاء الى اكسل
 */
include '../config.php';
// When executed in a browser, this script will prompt for download
// of 'test.xls' which can then be opened by Excel or OpenOffice.
require '../Class/php-export-data.class.php';
$exporter = new ExportDataExcel('browser', 'Coustemers.xls');
$exporter->initialize();
// starts streaming data to web browser
$db->join("typedevices", "devices.IDTypeDevice = typedevices.ID", "LEFT");
$db->join("coustemers", "devices.IdCustemer = coustemers.ID", "LEFT");
$devicesList = $db->where('devices.Finsh', '0');
$db->orderBy("devices.Finsh", "asc");
$db->orderBy("devices.DateAdded", "asc");
$devicesList = $db->get('devices');
$exporter->addRow(array('نوع الجهاز', 'سيريال', 'العميل', 'تاريخ الاستلام', 'مرجع', 'بوليصة الشحن :'));
foreach ($devicesList as $v) {
    $IDDevices = $v['idDevices'];
    $nd = $v['NameDevices'];
    $s = $v['Serial'];
    $n = $v['Name'];
    $d = $v['DateAdded'];
    $r = $v['Ref'];
    $t = $v['tracNumber'];
    $exporter->addRow(array($nd, $s, $n, $d, $r, $t));
}
$exporter->finalize();
// writes the footer, flushes remaining data to browser.
Exemplo n.º 5
0
    /**
     * Generate JSON array for grid rendering
     * @param $grid_id Unique ID for grid
     */
    function render($grid_id)
    {
        // render grid for first time (non ajax), but specific grid on ajax calls
        $is_ajax = isset($_REQUEST["nd"]) || isset($_REQUEST["oper"]) || isset($_REQUEST["export"]);
        if ($is_ajax && $_REQUEST["grid_id"] != $grid_id) {
            return;
        }
        $append_by = strpos($this->options["url"], "?") === false ? "?" : "&";
        $this->options["url"] .= $append_by . "grid_id={$grid_id}";
        $this->options["editurl"] .= $append_by . "grid_id={$grid_id}";
        $this->options["cellurl"] .= $append_by . "grid_id={$grid_id}";
        if (isset($_REQUEST["subgrid"])) {
            $grid_id = "_" . $_REQUEST["subgrid"];
            #$grid_id = "_".preg_replace("/[^a-zA-Z0-9]+/", "", $grid_id);
        }
        $this->id = $grid_id;
        ### P ###
        // custom on select event execution
        if (!empty($this->events["on_select"])) {
            $func = $this->events["on_select"][0];
            $obj = $this->events["on_select"][1];
            $continue = $this->events["on_select"][2];
            $event_sql = "";
            $event_sql_count = "";
            if ($obj) {
                call_user_func(array($obj, $func), array("param" => $_REQUEST, "grid" => $this, "sql" => &$event_sql, "sql_count" => &$event_sql_count));
            } else {
                call_user_func($func, array("param" => $_REQUEST, "grid" => $this, "sql" => &$event_sql, "sql_count" => &$event_sql_count));
            }
            $this->internal["sql_count"] = $event_sql_count;
            $this->internal["sql"] = $event_sql;
        }
        // generate column names, if not defined
        if (!$this->options["colNames"]) {
            $this->set_columns();
        }
        ### P ###
        // persist search if asked
        if ($this->options["persistsearch"] === true) {
            $this->options["search"] = true;
            $this->options["postData"] = array("filters" => $_SESSION["jqgrid_{$grid_id}_searchstr"]);
            // this performs the search
            $array_of_search_values = json_decode($_SESSION["jqgrid_{$grid_id}_searchstr"], true);
            foreach ($array_of_search_values["rules"] as &$rules) {
                foreach ($this->options["colModel"] as &$col) {
                    if ($rules['field'] == $col["name"]) {
                        $search_word = $rules['data'];
                        $col["searchoptions"] = array("defaultValue" => $search_word);
                    }
                }
            }
        }
        ### P ###
        // manage uploaded files (grid_id check for master-detail fix || subgrid check)
        if (count($_FILES) && ($_REQUEST["grid_id"] == $grid_id || "_" . $_REQUEST["subgrid"] == $grid_id)) {
            $files = array_keys($_FILES);
            $fileElementName = $files[0];
            if (!empty($_FILES[$fileElementName]['error'])) {
                switch ($_FILES[$fileElementName]['error']) {
                    case '1':
                        $error = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
                        break;
                    case '2':
                        $error = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
                        break;
                    case '3':
                        $error = 'The uploaded file was only partially uploaded';
                        break;
                    case '4':
                        $error = 'No file was uploaded.';
                        break;
                    case '6':
                        $error = 'Missing a temporary folder';
                        break;
                    case '7':
                        $error = 'Failed to write file to disk';
                        break;
                    case '8':
                        $error = 'File upload stopped by extension';
                        break;
                    case '999':
                    default:
                        $error = 'No error code avaiable';
                }
            } elseif (empty($_FILES[$fileElementName]['tmp_name']) || $_FILES[$fileElementName]['tmp_name'] == 'none') {
                $error = 'No file was uploaded';
            } else {
                foreach ($this->options["colModel"] as $c) {
                    if ($c["upload_dir"] != "" && $c["name"] . "_file" == $fileElementName) {
                        $tmp_name = $_FILES[$fileElementName]["tmp_name"];
                        $name = $_FILES[$fileElementName]["name"];
                        $uploads_dir = $c["upload_dir"];
                        @mkdir($uploads_dir, 0755, true);
                        // set to rename file by default
                        if (empty($c["editrules"]["ifexist"])) {
                            $c["editrules"]["ifexist"] = "rename";
                        }
                        // check if required
                        if ($c["editrules"]["ifexist"] == "error") {
                            if (file_exists("{$uploads_dir}/{$name}")) {
                                $error = "File already exist: {$uploads_dir}/{$name}";
                                break;
                            }
                        } else {
                            if ($c["editrules"]["ifexist"] == "rename") {
                                // rename file if exist
                                $ext = strrchr($name, '.');
                                $prefix = substr($name, 0, -strlen($ext));
                                $i = 0;
                                while (file_exists("{$uploads_dir}/{$name}")) {
                                    $name = $prefix . "_" . ++$i . $ext;
                                }
                            }
                        }
                        if (@move_uploaded_file($tmp_name, "{$uploads_dir}/{$name}")) {
                            $msg = "{$uploads_dir}/{$name}";
                        } else {
                            $error = "Unable to move to desired folder {$uploads_dir}/{$name}";
                        }
                        break;
                    }
                }
            }
            echo "{";
            echo "error: '" . $error . "',";
            echo "msg: '" . $msg . "'";
            echo "}//";
            # fix for upload lib, it get response from doc body that include <canvas>
            die;
        }
        ### P-END ###
        if (isset($_POST['oper'])) {
            $op = $_POST['oper'];
            $data = $_POST;
            $pk_field = $this->options["colModel"][0]["index"];
            // fix for dialog edit v/s inline edit
            $id = isset($data[$pk_field]) ? $data[$pk_field] : $data["id"];
            // fix for mssql utf8 fix
            if (strpos($this->db_driver, "mssql") !== false) {
                $data = array_utf8_decode_recursive($data);
            }
            // formatters array for k->v
            $is_numeric = array();
            // reformat date w.r.t mysql
            foreach ($this->options["colModel"] as $c) {
                // don't fix vars that are not posted (celledit mode)
                if (!isset($data[$c["index"]])) {
                    continue;
                }
                // fix for short weekday name
                if (strstr($c["formatoptions"]["newformat"], "D")) {
                    $data[$c["index"]] = str_ireplace(array("sun", "mon", "tue", "wed", "thu", "fri", "sat"), "", $data[$c["index"]]);
                    $data[$c["index"]] = trim($data[$c["index"]]);
                }
                // fix for d/m/Y date format. strtotime expects m/d/Y
                if (strstr($c["formatoptions"]["newformat"], "d/m/Y")) {
                    $tmp = explode("/", $data[$c["index"]]);
                    $data[$c["index"]] = $tmp[1] . "/" . $tmp[0] . "/" . $tmp[2];
                }
                // put zeros for blank date field
                if (($c["formatter"] == "date" || $c["formatter"] == "datetime") && (empty($data[$c["index"]]) || $data[$c["index"]] == "//")) {
                    $data[$c["index"]] = "NULL";
                } else {
                    if ($c["isnull"] && empty($data[$c["index"]])) {
                        $data[$c["index"]] = "NULL";
                    } else {
                        if ($c["formatter"] == "date") {
                            $data[$c["index"]] = date("Y-m-d", strtotime($data[$c["index"]]));
                        } else {
                            if ($c["formatter"] == "datetime") {
                                $data[$c["index"]] = date("Y-m-d H:i:s", strtotime($data[$c["index"]]));
                            } else {
                                if ($c["formatter"] == "autocomplete" && $c["index"] != $c["formatoptions"]["update_field"]) {
                                    unset($data[$c["index"]]);
                                } else {
                                    if ($c["formatter"] == "password" && $data[$c["index"]] == "*****") {
                                        unset($data[$c["index"]]);
                                    }
                                }
                            }
                        }
                    }
                }
                // isnumeric check for sql '' issue
                if ($c["isnum"] === true) {
                    $is_numeric[$c["index"]] = true;
                }
            }
            // handle grid operations of CRUD
            switch ($op) {
                ### P ###
                case "autocomplete":
                    $field = $data['element'];
                    $term = $data['term'];
                    foreach ($this->options["colModel"] as $c) {
                        if ($c["index"] == $field) {
                            // if subqurey
                            if (preg_match('/SELECT (.*) \\((.*)\\) (.*)/', $c["formatoptions"]["sql"], $match)) {
                                if (preg_match('/SELECT .* \\((.*)\\) (.*) WHERE (.*)/', $c["formatoptions"]["sql"], $match)) {
                                    $cond = "AND";
                                } else {
                                    $cond = "WHERE";
                                }
                            } else {
                                if (stristr($c["formatoptions"]["sql"], " WHERE ")) {
                                    $cond = "AND";
                                } else {
                                    $cond = "WHERE";
                                }
                            }
                            $sql = $c["formatoptions"]["sql"] . " {$cond} {$c["formatoptions"]["search_on"]} like '{$term}%'";
                            $result = $this->execute_query($sql);
                            if ($this->con) {
                                $rows = $result->GetArray();
                                foreach ($rows as $key => $row) {
                                    $arr = array();
                                    $arr['id'] = isset($row["K"]) ? $row["K"] : $row["k"];
                                    $arr['label'] = isset($row["V"]) ? $row["V"] : $row["v"];
                                    $arr['value'] = isset($row["V"]) ? $row["V"] : $row["v"];
                                    $data_arr[] = $arr;
                                }
                            } else {
                                while ($row = mysql_fetch_assoc($result)) {
                                    $arr = array();
                                    $arr['id'] = $row['k'];
                                    $arr['label'] = $row['v'];
                                    $arr['value'] = $row['v'];
                                    $data_arr[] = $arr;
                                }
                            }
                            header('Content-type: application/json');
                            echo json_encode($data_arr);
                            die;
                        }
                    }
                    break;
                    ### P ###
                ### P ###
                case "clone":
                    // only clone if grid id is matched (fix for master-detail)
                    if ($data["grid_id"] != $grid_id) {
                        break;
                    }
                    $src_id = $data['id'];
                    // get columns to build INSERT - SELECT query
                    $sql = "SELECT * FROM " . $this->table . " LIMIT 1 OFFSET 0";
                    $sql = $this->prepare_sql($sql, $this->db_driver);
                    $result = $this->execute_query($sql);
                    // and exclude PK
                    if ($this->con) {
                        $arr = $result->FetchRow();
                        foreach ($arr as $k => $rs) {
                            if ($k != $pk_field) {
                                $f[] = $k;
                            }
                        }
                    } else {
                        $numfields = mysql_num_fields($result);
                        for ($i = 0; $i < $numfields; $i++) {
                            $k = mysql_field_name($result, $i);
                            if ($k != $pk_field) {
                                $f[] = $k;
                            }
                        }
                    }
                    // custom onclone event execution
                    if (!empty($this->events["on_clone"])) {
                        $func = $this->events["on_clone"][0];
                        $obj = $this->events["on_clone"][1];
                        $continue = $this->events["on_clone"][2];
                        if ($obj) {
                            call_user_func(array($obj, $func), array($pk_field => $src_id, "params" => &$f));
                        } else {
                            call_user_func($func, array($pk_field => $src_id, "params" => &$f));
                        }
                        if (!$continue) {
                            break;
                        }
                    }
                    $fields_str = implode(",", $f);
                    $sql = "INSERT INTO {$this->table} ({$fields_str}) SELECT {$fields_str} FROM {$this->table} WHERE {$pk_field} = {$src_id}";
                    $insert_id = $this->execute_query($sql, "insert_id");
                    if (intval($insert_id) > 0) {
                        $res = array("id" => $insert_id, "success" => true);
                    } else {
                        $res = array("id" => 0, "success" => false);
                    }
                    echo json_encode($res);
                    break;
                case "add":
                    if ($pk_field != "id") {
                        unset($data['id']);
                    }
                    unset($data['oper']);
                    $update_str = array();
                    ### P ###
                    // custom oninsert event execution
                    if (!empty($this->events["on_insert"])) {
                        $func = $this->events["on_insert"][0];
                        $obj = $this->events["on_insert"][1];
                        $continue = $this->events["on_insert"][2];
                        if ($obj) {
                            call_user_func(array($obj, $func), array($pk_field => $id, "params" => &$data));
                        } else {
                            call_user_func($func, array($pk_field => $id, "params" => &$data));
                        }
                        if (!$continue) {
                            break;
                        }
                    }
                    foreach ($data as $k => $v) {
                        // skip first column while insert, unless autoid = false
                        if ($k == $pk_field && $this->options["colModel"][0]["autoid"] !== false) {
                            continue;
                        }
                        $k = addslashes($k);
                        $v = $this->escape_string($v);
                        $v = $v == "NULL" || $is_numeric[$k] === true ? $v : "'{$v}'";
                        $values_str[] = "{$v}";
                        // add tilde sign for mysql
                        if (strpos($this->db_driver, "mysql") !== false || !isset($this->db_driver)) {
                            $k = "`{$k}`";
                        }
                        $fields_str[] = "{$k}";
                    }
                    $insert_str = "(" . implode(",", $fields_str) . ") VALUES (" . implode(",", $values_str) . ")";
                    $sql = "INSERT INTO {$this->table} {$insert_str}";
                    $insert_id = $this->execute_query($sql, "insert_id");
                    ### P ###
                    // custom onupdate event execution
                    if (!empty($this->events["on_after_insert"])) {
                        $func = $this->events["on_after_insert"][0];
                        $obj = $this->events["on_after_insert"][1];
                        $continue = $this->events["on_after_insert"][2];
                        if ($obj) {
                            call_user_func(array($obj, $func), array($pk_field => $insert_id, "params" => &$data));
                        } else {
                            call_user_func($func, array($pk_field => $insert_id, "params" => &$data));
                        }
                        if (!$continue) {
                            break;
                        }
                    }
                    // for inline row addition, return insert id to update PK of grid (e.g. order_id#33)
                    if ($id == "new_row") {
                        die($pk_field . "#" . $insert_id);
                    }
                    // return JSON response for insert id
                    if (intval($insert_id) > 0) {
                        $res = array("id" => $insert_id, "success" => true);
                    } else {
                        $res = array("id" => 0, "success" => false);
                    }
                    echo json_encode($res);
                    break;
                case "edit":
                    //pr($_POST);
                    if ($pk_field != "id") {
                        unset($data['id']);
                    }
                    unset($data['oper']);
                    $update_str = array();
                    ### P ###
                    // custom onupdate event execution
                    if (!empty($this->events["on_update"])) {
                        $func = $this->events["on_update"][0];
                        $obj = $this->events["on_update"][1];
                        $continue = $this->events["on_update"][2];
                        if ($obj) {
                            call_user_func(array($obj, $func), array($pk_field => $id, "params" => &$data));
                        } else {
                            call_user_func($func, array($pk_field => $id, "params" => &$data));
                        }
                        if (!$continue) {
                            break;
                        }
                    }
                    foreach ($data as $k => $v) {
                        $k = addslashes($k);
                        // skip PK in update sql
                        if ($k == $pk_field) {
                            continue;
                        }
                        // add tilde sign for mysql
                        if (strpos($this->db_driver, "mysql") !== false || !isset($this->db_driver)) {
                            $k = "`{$k}`";
                        }
                        $v = $this->escape_string($v);
                        // dont update blank fields in case of bulk edit
                        if (strstr($id, ",") !== false && ($v === "" || $v == "NULL")) {
                            continue;
                        }
                        $v = $v == "NULL" || $is_numeric[$k] === true ? $v : "'{$v}'";
                        $update_str[] = "{$k}={$v}";
                    }
                    // don't run update if no field is changed (in bulk edit)
                    if (count($update_str) == 0) {
                        break;
                    }
                    $update_str = "SET " . implode(",", $update_str);
                    $id = "'" . implode("','", explode(",", $id)) . "'";
                    $sql = "UPDATE {$this->table} {$update_str} WHERE {$pk_field} IN ({$id})";
                    $ret = $this->execute_query($sql);
                    ### P ###
                    // custom on after update event execution
                    if (!empty($this->events["on_after_update"])) {
                        $func = $this->events["on_after_update"][0];
                        $obj = $this->events["on_after_update"][1];
                        $continue = $this->events["on_after_update"][2];
                        if ($obj) {
                            call_user_func(array($obj, $func), array($pk_field => $id, "params" => &$data));
                        } else {
                            call_user_func($func, array($pk_field => $id, "params" => &$data));
                        }
                        if (!$continue) {
                            break;
                        }
                    }
                    // return JSON response for update (passing id that was updated)
                    if ($ret) {
                        $res = array("id" => $id, "success" => true);
                    } else {
                        $res = array("id" => 0, "success" => false);
                    }
                    echo json_encode($res);
                    break;
                case "del":
                    // row to delete is passed as id
                    $id = $data["id"];
                    ### P ###
                    // custom on delete event execution
                    if (!empty($this->events["on_delete"])) {
                        $func = $this->events["on_delete"][0];
                        $obj = $this->events["on_delete"][1];
                        $continue = $this->events["on_delete"][2];
                        if ($obj) {
                            call_user_func(array($obj, $func), array($pk_field => $id));
                        } else {
                            call_user_func($func, array($pk_field => $id));
                        }
                        if (!$continue) {
                            break;
                        }
                    }
                    $id = "'" . implode("','", explode(",", $id)) . "'";
                    $sql = "DELETE FROM {$this->table} WHERE {$pk_field} IN ({$id})";
                    $this->execute_query($sql);
                    ### P ###
                    // custom on after delete event execution
                    if (!empty($this->events["on_after_delete"])) {
                        $func = $this->events["on_after_delete"][0];
                        $obj = $this->events["on_after_delete"][1];
                        $continue = $this->events["on_after_delete"][2];
                        if ($obj) {
                            call_user_func(array($obj, $func), array($pk_field => $id));
                        } else {
                            call_user_func($func, array($pk_field => $id));
                        }
                        if (!$continue) {
                            break;
                        }
                    }
                    break;
            }
            die;
        }
        // apply search conditions (where clause)
        $wh = "";
        if (!isset($_REQUEST['_search'])) {
            $_REQUEST['_search'] = "";
        }
        $searchOn = $this->strip($_REQUEST['_search']);
        if ($searchOn == 'true') {
            $fld = $this->strip($_REQUEST['searchField']);
            $cols = array();
            foreach ($this->options["colModel"] as $col) {
                $cols[] = $col["index"];
            }
            // quick search bar
            if (!$fld) {
                $searchstr = $this->strip($_REQUEST['filters']);
                // persist search string
                $_SESSION["jqgrid_{$this->id}_searchstr"] = $searchstr;
                $wh = $this->construct_where($searchstr);
            } else {
                if (in_array($fld, $cols)) {
                    $fldata = $this->strip($_REQUEST['searchString']);
                    $foper = $this->strip($_REQUEST['searchOper']);
                    // costruct where
                    $wh .= " AND " . $fld;
                    switch ($foper) {
                        case "eq":
                            if (is_numeric($fldata)) {
                                $wh .= " = " . $fldata;
                            } else {
                                $wh .= " = '" . $fldata . "'";
                            }
                            break;
                        case "ne":
                            if (is_numeric($fldata)) {
                                $wh .= " <> " . $fldata;
                            } else {
                                $wh .= " <> '" . $fldata . "'";
                            }
                            break;
                        case "lt":
                            if (is_numeric($fldata)) {
                                $wh .= " < " . $fldata;
                            } else {
                                $wh .= " < '" . $fldata . "'";
                            }
                            break;
                        case "le":
                            if (is_numeric($fldata)) {
                                $wh .= " <= " . $fldata;
                            } else {
                                $wh .= " <= '" . $fldata . "'";
                            }
                            break;
                        case "gt":
                            if (is_numeric($fldata)) {
                                $wh .= " > " . $fldata;
                            } else {
                                $wh .= " > '" . $fldata . "'";
                            }
                            break;
                        case "ge":
                            if (is_numeric($fldata)) {
                                $wh .= " >= " . $fldata;
                            } else {
                                $wh .= " >= '" . $fldata . "'";
                            }
                            break;
                        case "ew":
                            $wh .= " LIKE '%" . $fldata . "'";
                            break;
                        case "en":
                            $wh .= " NOT LIKE '%" . $fldata . "'";
                            break;
                        case "cn":
                            $wh .= " LIKE '%" . $fldata . "%'";
                            break;
                        case "nc":
                            $wh .= " NOT LIKE '%" . $fldata . "%'";
                            break;
                        case "in":
                            $wh .= " IN (" . $fldata . ")";
                            break;
                        case "ni":
                            $wh .= " NOT IN (" . $fldata . ")";
                            break;
                        case "nu":
                            $wh .= " IS NULL";
                            break;
                        case "nn":
                            $wh .= " IS NOT NULL";
                            break;
                        case "bw":
                        default:
                            $fldata .= "%";
                            $wh .= " LIKE '" . $fldata . "'";
                            break;
                    }
                }
            }
            // setting to persist where clause in export option
            $_SESSION["jqgrid_{$grid_id}_filter"] = $wh;
            $_SESSION["jqgrid_{$grid_id}_filter_request"] = $_REQUEST["filters"];
        } elseif ($searchOn == 'false') {
            unset($_SESSION["jqgrid_{$grid_id}_filter"]);
            unset($_SESSION["jqgrid_{$grid_id}_filter_request"]);
        }
        // generate main json
        if (isset($_GET['jqgrid_page'])) {
            $page = $_GET['jqgrid_page'];
            // get the requested page
            $limit = $_GET['rows'];
            // get how many rows we want to have into the grid
            $sidx = $_GET['sidx'];
            // get index row - i.e. user click to sort
            $sord = $_GET['sord'];
            // get the direction
            if (!$sidx) {
                $sidx = 1;
            }
            if (!$limit) {
                $limit = 20;
            }
            // persist for export data
            if (isset($_GET["export"])) {
                $sidx = $_SESSION["jqgrid_{$grid_id}_sort_by"];
                $sord = $_SESSION["jqgrid_{$grid_id}_sort_order"];
                $limit = $_SESSION["jqgrid_{$grid_id}_rows"];
            } else {
                $_SESSION["jqgrid_{$grid_id}_sort_by"] = $sidx;
                $_SESSION["jqgrid_{$grid_id}_sort_order"] = $sord;
                $_SESSION["jqgrid_{$grid_id}_rows"] = $limit;
            }
            ### P ###
            // if export option is requested
            if (isset($_GET["export"])) {
                set_time_limit(0);
                $arr = array();
                // export data array (if grid loaded from array)
                if (is_array($this->table)) {
                    $t = $this->table;
                    foreach ($t[0] as $k => $v) {
                        $temp[$k] = ucwords($k);
                    }
                    $arr[] = $temp;
                    foreach ($t as $key => $value) {
                        $arr[] = $value;
                    }
                    // custom export function if needed
                    if (!empty($this->events["on_export"])) {
                        $func = $this->events["on_export"][0];
                        $obj = $this->events["on_export"][1];
                        $continue = $this->events["on_export"][2];
                        if ($obj) {
                            call_user_func(array($obj, $func), array("data" => $arr, "grid" => &$this));
                        } else {
                            call_user_func($func, array("data" => $arr, "grid" => &$this));
                        }
                        if (!$continue) {
                            exit(0);
                        }
                    }
                } else {
                    // by default export all
                    $export_where = "";
                    if ($this->options["export"]["range"] == "filtered") {
                        $export_where = $_SESSION["jqgrid_{$grid_id}_filter"];
                    }
                    $limit_sql = "";
                    if ($this->options["export"]["paged"] == "1") {
                        $offset = $limit * $page - $limit;
                        // do not put $limit*($page - 1)
                        if ($offset < 0) {
                            $offset = 0;
                        }
                        $limit_sql = "LIMIT {$limit} OFFSET {$offset}";
                    }
                    // if sql is set on on_select event
                    if (!empty($this->internal["sql"])) {
                        $SQL = $this->internal["sql"] . " {$limit_sql}";
                    } else {
                        if (($p = stripos($this->select_command, "GROUP BY")) !== false) {
                            $start = substr($this->select_command, 0, $p);
                            $end = substr($this->select_command, $p);
                            $SQL = $start . $export_where . $end . " ORDER BY {$sidx} {$sord} {$limit_sql}";
                        } else {
                            $SQL = $this->select_command . $export_where . " ORDER BY {$sidx} {$sord} {$limit_sql}";
                        }
                    }
                    // custom export function if needed
                    if (!empty($this->events["on_export"])) {
                        $func = $this->events["on_export"][0];
                        $obj = $this->events["on_export"][1];
                        $continue = $this->events["on_export"][2];
                        if ($obj) {
                            call_user_func(array($obj, $func), array("sql" => $SQL, "grid" => &$this));
                        } else {
                            call_user_func($func, array("sql" => $SQL, "grid" => &$this));
                        }
                        if (!$continue) {
                            exit(0);
                        }
                    }
                    $SQL = $this->prepare_sql($SQL, $this->db_driver);
                    $result = $this->execute_query($SQL);
                    foreach ($this->options["colModel"] as $c) {
                        $header[$c["name"]] = $c["title"];
                    }
                    $arr[] = $header;
                    if ($this->con) {
                        $rows = $result->GetRows();
                        foreach ($rows as $row) {
                            $export_data = array();
                            foreach ($header as $k => $v) {
                                $export_data[$k] = $row[$k];
                            }
                            $arr[] = $export_data;
                        }
                    } else {
                        while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
                            $export_data = array();
                            foreach ($header as $k => $v) {
                                $export_data[$k] = $row[$k];
                            }
                            $arr[] = $export_data;
                        }
                    }
                }
                $col_widths = array();
                // export only selected columns
                $cols_not_to_export = array();
                $cols_to_export = array();
                if ($this->options["colModel"]) {
                    foreach ($this->options["colModel"] as $c) {
                        // column chooser integration with export
                        if (isset($_COOKIE["jqgrid_colchooser"])) {
                            $colchooser = explode(",", $_COOKIE["jqgrid_colchooser"]);
                            if (!in_array($c["name"], $colchooser)) {
                                $c["export"] = false;
                            }
                        }
                        if ($c["export"] === false) {
                            $cols_not_to_export[] = $c["name"];
                        } else {
                            $cols_to_export[] = $c["name"];
                            $col_widths[$c["name"]] = !empty($c["width"]) ? $c["width"] : 'auto';
                        }
                    }
                }
                // custom on_data_display event execution (for export)
                if (!empty($this->events["on_data_display"])) {
                    $func = $this->events["on_data_display"][0];
                    $obj = $this->events["on_data_display"][1];
                    // remove header
                    $h = array_shift($arr);
                    if ($obj) {
                        call_user_func(array($obj, $func), array("params" => &$arr));
                    } else {
                        call_user_func($func, array("params" => &$arr));
                    }
                    // add header
                    array_unshift($arr, $h);
                }
                // fix for d/m/Y date format in export. strtotime expects m/d/Y
                foreach ($this->options["colModel"] as $c) {
                    foreach ($arr as &$rec) {
                        // skip header from date format conversion
                        if ($rec === $arr[0]) {
                            continue;
                        }
                        // show masked data in password
                        if (isset($c["formatter"]) && $c["formatter"] == "password") {
                            $rec[$c["name"]] = "*****";
                        }
                        if (!empty($rec[$c["name"]]) && ($c["formatter"] == "date" || $c["formatter"] == "datetime")) {
                            $dt = $rec[$c["name"]];
                            $js_dt_fmt = $c["formatoptions"]["newformat"];
                            $js_dt_fmt = str_replace("yy", "Y", $js_dt_fmt);
                            $js_dt_fmt = str_replace("mm", "m", $js_dt_fmt);
                            $js_dt_fmt = str_replace("dd", "d", $js_dt_fmt);
                            $rec[$c["name"]] = date($js_dt_fmt, strtotime($dt));
                        }
                        ### P ###
                        // Replace condition data in pdf export
                        $col_name = $c["name"];
                        if (isset($c["default"]) && !isset($rec[$col_name])) {
                            $rec[$col_name] = $c["default"];
                        }
                        // link data in grid to any given url
                        if (!empty($link_c["default"])) {
                            // replace any param in link e.g. http://domain.com?id={id} given that, there is a $col["name"] = "id" exist
                            $rec[$col_name] = $this->replace_row_data($rec, $c["default"]);
                        }
                        // check conditional data
                        if (!empty($c["condition"][0])) {
                            $r = true;
                            // replace {} placeholders from connditional data
                            $c["condition"][1] = $this->replace_row_data($rec, $c["condition"][1]);
                            $c["condition"][2] = $this->replace_row_data($rec, $c["condition"][2]);
                            $row = $rec;
                            eval("\$r = " . $c["condition"][0] . ";");
                            $rec[$col_name] = $r ? $c["condition"][1] : $c["condition"][2];
                            $rec[$col_name] = strip_tags($rec[$col_name]);
                        }
                        // check data filter (alternate of grid on_data_display, but for current column)
                        if (!empty($c["on_data_display"])) {
                            $func = $c["on_data_display"][0];
                            $obj = $c["on_data_display"][1];
                            if ($obj) {
                                $row[$col_name] = call_user_func(array($obj, $func), $rec);
                            } else {
                                $row[$col_name] = call_user_func($func, $rec);
                            }
                        }
                    }
                }
                // remove db columns as well as virtual columns
                if (!empty($cols_to_export)) {
                    $export_arr = array();
                    foreach ($arr as $arr_item) {
                        foreach ($arr_item as $k => $i) {
                            if (!in_array($k, $cols_to_export)) {
                                unset($arr_item[$k]);
                            }
                        }
                        $export_arr[] = $arr_item;
                    }
                    $arr = $export_arr;
                }
                // fix for mssql utf8 fix
                if (strpos($this->db_driver, "mssql") !== false) {
                    $arr = array_utf8_encode_recursive($arr);
                }
                if (!$this->options["export"]["filename"]) {
                    $this->options["export"]["filename"] = $grid_id;
                }
                if (!$this->options["export"]["sheetname"]) {
                    $this->options["export"]["sheetname"] = ucwords($grid_id) . " Sheet";
                }
                // fix for ie - http://support.microsoft.com/kb/316431
                if (preg_match('/(?i)msie /', $_SERVER['HTTP_USER_AGENT'])) {
                    header('Cache-control: cache,must-revalidate');
                }
                if ($this->options["export"]["format"] == "pdf") {
                    if ($this->options["export"]["render_type"] == "html") {
                        $html = "";
                        // if customized pdf render is defined, use that
                        if (!empty($this->events["on_render_pdf"])) {
                            $func = $this->events["on_render_pdf"][0];
                            $obj = $this->events["on_render_pdf"][1];
                            if ($obj) {
                                $html = call_user_method($func, $obj, array("grid" => $this, "data" => $arr));
                            } else {
                                $html = call_user_func($func, array("grid" => $this, "data" => $arr));
                            }
                        } else {
                            $html .= "<h1>" . $this->options["export"]["heading"] . "</h1>";
                            $html .= '<table border="0" cellpadding="4" cellspacing="2">';
                            $i = 0;
                            foreach ($arr as $v) {
                                $shade = $i++ % 2 ? 'bgcolor="#efefef"' : '';
                                $html .= "<tr>";
                                foreach ($v as $d) {
                                    // bold header
                                    if ($i == 1) {
                                        $html .= "<td bgcolor=\"lightgrey\"><strong>{$d}</strong></td>";
                                    } else {
                                        $html .= "<td {$shade}>{$d}</td>";
                                    }
                                }
                                $html .= "</tr>";
                            }
                            $html .= "</table>";
                        }
                    }
                    $orientation = $this->options["export"]["orientation"];
                    if ($orientation == "landscape") {
                        $orientation = "L";
                    } else {
                        $orientation = "P";
                    }
                    $paper = $this->options["export"]["paper"];
                    // Using opensource TCPdf lib
                    // for more options visit http://www.tcpdf.org/examples.php
                    require_once 'tcpdf/config/lang/eng.php';
                    require_once 'tcpdf/class.TCPDF.EasyTable.php';
                    // create new PDF document
                    $pdf = new TCPDF_EasyTable($orientation, PDF_UNIT, $paper, true, 'UTF-8', false);
                    // set document information
                    $pdf->SetCreator("www.phpgrid.org");
                    $pdf->SetAuthor('www.phpgrid.org');
                    $pdf->SetTitle('www.phpgrid.org');
                    $pdf->SetSubject($this->options["caption"]);
                    $pdf->SetKeywords('www.phpgrid.org');
                    // remove default header/footer
                    $pdf->setPrintHeader(true);
                    $pdf->setPrintFooter(true);
                    // set default monospaced font
                    $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
                    $pdf->setFontSubsetting(false);
                    //set margins
                    $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
                    //set auto page breaks
                    $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
                    //set image scale factor
                    $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
                    // set some language dependent data:
                    // lines for rtl pdf generation
                    if ($this->options["direction"] == "rtl") {
                        $lg = array();
                        $lg['a_meta_charset'] = 'UTF-8';
                        $lg['a_meta_dir'] = 'rtl';
                        $lg['a_meta_language'] = 'fa';
                        $lg['w_page'] = 'page';
                    }
                    $pdf->setLanguageArray($lg);
                    // To set your custom font
                    // $fontname = $pdf->addTTFfont('/path-to-font/DejaVuSans.ttf', 'TrueTypeUnicode', '', 32);
                    // set font http://www.tcexam.org/doc/code/classTCPDF.html#afd56e360c43553830d543323e81bc045
                    # Table parameters
                    $pdf->SetFont('helvetica', '', 12);
                    // for special charset language, uncoment this line
                    // $pdf->SetFont('cid0jp', '', 10);
                    // add a page
                    $pdf->AddPage();
                    // output the HTML content
                    if ($this->options["export"]["render_type"] == "html") {
                        $pdf->writeHTML($html, true, false, true, false, '');
                        $pdf->Output($this->options["export"]["filename"] . ".pdf", 'I');
                        die;
                    }
                    $pdf->SetY(10, true);
                    $pdf->Cell(0, 15, $this->options["export"]["heading"], 0, 1);
                    $pdf->SetHeaderCellsFontStyle('');
                    // 'b'
                    $pdf->SetHeaderCellsFillColor(150, 150, 150);
                    $pdf->SetHeaderCellsFontColor(0, 0, 0);
                    $pdf->SetFillColor(240, 240, 240);
                    // for cells background
                    $pdf->SetCellFontColor(0, 0, 0);
                    // auto set column widths based on grid column width
                    $margins = $pdf->GetMargins();
                    $pdf_page_width = $pdf->GetPageWidth() - $margins['left'] - $margins['right'];
                    $total_width = 0;
                    foreach ($col_widths as $key => $value) {
                        $total_width += $value;
                    }
                    $new_widths = array();
                    foreach ($col_widths as $key => $value) {
                        $new_widths[$key] = $pdf_page_width * ($value / $total_width);
                        $new_widths[] = $pdf_page_width * ($value / $total_width);
                    }
                    $pdf->SetCellWidths($new_widths);
                    $pdf->SetCellFillStyle(2);
                    $pdf->SetCellPadding(1);
                    $pdf->SetCellMinimumHeight(null);
                    // if customized pdf render is defined, use that
                    if (!empty($this->events["on_render_pdf"])) {
                        $func = $this->events["on_render_pdf"][0];
                        $obj = $this->events["on_render_pdf"][1];
                        if ($obj) {
                            call_user_func(array($obj, $func), array("pdf" => &$pdf, "data" => &$arr));
                        } else {
                            call_user_func($func, array("pdf" => &$pdf, "data" => &$arr));
                        }
                    }
                    $h = $arr[0];
                    array_shift($arr);
                    $pdf->EasyTable($arr, $h);
                    if (strstr($this->options["export"]["filename"], ".pdf") === false) {
                        $this->options["export"]["filename"] .= ".pdf";
                    }
                    //Close and output PDF document
                    $pdf->Output($this->options["export"]["filename"], 'I');
                    die;
                } else {
                    if ($this->options["export"]["format"] == "csv") {
                        if (strstr($this->options["export"]["filename"], ".csv") === false) {
                            $this->options["export"]["filename"] .= ".csv";
                        }
                        header('Content-Type: text/csv');
                        header('Content-Disposition: attachment;filename=' . $this->options["export"]["filename"]);
                        $fp = fopen('php://output', 'w');
                        foreach ($arr as $key => $value) {
                            fputcsv($fp, $value);
                        }
                        die;
                    } else {
                        include_once "php-export-data.class.php";
                        $excel = new ExportDataExcel('browser');
                        if (strstr($this->options["export"]["filename"], ".xls") === false && strstr($this->options["export"]["filename"], ".xlsx") === false) {
                            $this->options["export"]["filename"] .= ".xls";
                        }
                        $excel->filename = $this->options["export"]["filename"];
                        $excel->initialize();
                        foreach ($arr as $row) {
                            $excel->addRow($row);
                        }
                        $excel->finalize();
                        die;
                    }
                }
            }
            // if defined in on_select event
            if (!empty($this->internal["sql_count"])) {
                $sql_count = $this->internal["sql_count"];
            } else {
                if (!empty($this->select_count)) {
                    $sql_count = $this->select_count . $wh;
                } else {
                    if (($p = stripos($this->select_command, "GROUP BY")) !== false) {
                        $sql_count = $this->select_command;
                        $p = stripos($sql_count, "GROUP BY");
                        $start_q = substr($sql_count, 0, $p);
                        $end_q = substr($sql_count, $p);
                        $sql_count = "SELECT count(*) as c FROM ({$start_q} {$wh} {$end_q}) pg_tmp";
                    } else {
                        $sql_count = $this->select_command . $wh;
                        $sql_count = "SELECT count(*) as c FROM (" . $sql_count . ") pg_tmp";
                    }
                }
            }
            # print_r($sql_count);
            $result = $this->execute_query($sql_count);
            if ($this->con) {
                $row = $result->FetchRow();
            } else {
                $row = mysql_fetch_array($result, MYSQL_ASSOC);
            }
            $count = $row['c'];
            // fix for oracle, alias in capitals
            if (empty($count)) {
                $count = $row['C'];
            }
            if ($count > 0) {
                $total_pages = ceil($count / $limit);
            } else {
                $total_pages = 0;
            }
            if ($page > $total_pages) {
                $page = $total_pages;
            }
            $start = $limit * $page - $limit;
            // do not put $limit*($page - 1)
            if ($start < 0) {
                $start = 0;
            }
            $responce = new stdClass();
            $responce->page = $page;
            $responce->total = $total_pages;
            $responce->records = $count;
            if (!empty($this->internal["sql"])) {
                $SQL = $this->internal["sql"] . " LIMIT {$limit} OFFSET {$start}";
            } else {
                if (($p = stripos($this->select_command, "GROUP BY")) !== false) {
                    $start_q = substr($this->select_command, 0, $p);
                    $end_q = substr($this->select_command, $p);
                    $SQL = "{$start_q} {$wh} {$end_q} ORDER BY {$sidx} {$sord} LIMIT {$limit} OFFSET {$start}";
                } else {
                    $SQL = $this->select_command . $wh . " ORDER BY {$sidx} {$sord} LIMIT {$limit} OFFSET {$start}";
                }
            }
            $SQL = $this->prepare_sql($SQL, $this->db_driver);
            $result = $this->execute_query($SQL);
            if ($this->con) {
                $rows = $result->GetRows();
                // simulate artificial paging for mssql
                if (count($rows) > $limit) {
                    $rows = array_slice($rows, count($rows) - $limit);
                }
            } else {
                $rows = array();
                while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
                    $rows[] = $row;
                }
            }
            ### P ###
            // custom on_data_display event execution
            if (!empty($this->events["on_data_display"])) {
                $func = $this->events["on_data_display"][0];
                $obj = $this->events["on_data_display"][1];
                if ($obj) {
                    call_user_func(array($obj, $func), array("params" => &$rows));
                } else {
                    call_user_func($func, array("params" => &$rows));
                }
            }
            // preserve userdata for response
            if (!empty($rows["userdata"])) {
                $userdata = $rows["userdata"];
                unset($rows["userdata"]);
            }
            foreach ($rows as $row) {
                $orig_row = $row;
                // apply php level formatter for image url 30.12.10
                foreach ($this->options["colModel"] as $c) {
                    $col_name = $c["name"];
                    ### P ###
                    if (isset($c["default"]) && !isset($row[$col_name])) {
                        $row[$col_name] = $c["default"];
                    }
                    // link data in grid to any given url
                    if (!empty($c["default"])) {
                        // replace any param in link e.g. http://domain.com?id={id} given that, there is a $col["name"] = "id" exist
                        $row[$col_name] = $this->replace_row_data($orig_row, $c["default"]);
                    }
                    // check conditional data
                    if (!empty($c["condition"][0])) {
                        $r = true;
                        // replace {} placeholders from connditional data
                        $c["condition"][1] = $this->replace_row_data($orig_row, $c["condition"][1]);
                        $c["condition"][2] = $this->replace_row_data($orig_row, $c["condition"][2]);
                        eval("\$r = " . $c["condition"][0] . ";");
                        $row[$col_name] = $r ? $c["condition"][1] : $c["condition"][2];
                    }
                    // check data filter (alternate of grid on_data_display, but for current column)
                    if (!empty($c["on_data_display"])) {
                        $func = $c["on_data_display"][0];
                        $obj = $c["on_data_display"][1];
                        if ($obj) {
                            $row[$col_name] = call_user_func(array($obj, $func), $row);
                        } else {
                            $row[$col_name] = call_user_func($func, $row);
                        }
                    }
                    ### P-END ###
                    // link data in grid to any given url
                    if (!empty($c["link"])) {
                        // replace any param in link e.g. http://domain.com?id={id} given that, there is a $col["name"] = "id" exist
                        // replace_row_data not used due to urlencode work
                        foreach ($this->options["colModel"] as $link_c) {
                            // if there is url in data, don't urlencode
                            if (strstr($orig_row[$link_c["name"]], "http://")) {
                                $link_row_data = $orig_row[$link_c["name"]];
                            } else {
                                $link_row_data = urlencode($orig_row[$link_c["name"]]);
                            }
                            $c["link"] = str_replace("{" . $link_c["name"] . "}", $link_row_data, $c["link"]);
                        }
                        $attr = "";
                        if (!empty($c["linkoptions"])) {
                            $attr = $c["linkoptions"];
                        }
                        // fix for mssql utf8 fix
                        if (strpos($this->db_driver, "mssql") !== false) {
                            $row[$col_name] = htmlentities(utf8_encode($row[$col_name]), ENT_QUOTES, "UTF-8");
                        } else {
                            $row[$col_name] = htmlentities($row[$col_name], ENT_QUOTES, "UTF-8");
                        }
                        // if link is made with custom date format
                        if (isset($c["formatoptions"]["newformat"])) {
                            $js_dt_fmt = $c["formatoptions"]["newformat"];
                            $js_dt_fmt = str_replace("yy", "Y", $js_dt_fmt);
                            $js_dt_fmt = str_replace("mm", "m", $js_dt_fmt);
                            $js_dt_fmt = str_replace("dd", "d", $js_dt_fmt);
                            $row[$col_name] = date($c["formatoptions"]["newformat"], strtotime($row[$col_name]));
                        }
                        $row[$col_name] = "<a {$attr} href='{$c["link"]}'>{$row[$col_name]}</a>";
                    }
                    // render row data as "src" value of <img> tag
                    if (isset($c["formatter"]) && $c["formatter"] == "image") {
                        $attr = array();
                        foreach ($c["formatoptions"] as $k => $v) {
                            $attr[] = "{$k}='{$v}'";
                        }
                        $attr = implode(" ", $attr);
                        $row[$col_name] = "<img {$attr} src='" . $row[$col_name] . "'>";
                    }
                    // show masked data in password
                    if (isset($c["formatter"]) && $c["formatter"] == "password") {
                        $row[$col_name] = "*****";
                    }
                }
                foreach ($row as $k => $r) {
                    $row[$k] = stripslashes($row[$k]);
                }
                $responce->rows[] = $row;
            }
            // set custom userdata in footer (controlled with on_data_display event)
            if (!empty($userdata)) {
                $responce->userdata = $userdata;
            }
            // fix for mssql utf8 fix
            if (strpos($this->db_driver, "mssql") !== false) {
                $responce = array_utf8_encode_recursive($responce);
            }
            echo json_encode($responce);
            die;
        }
        ### P ###
        // if loading from array
        if (is_array($this->table)) {
            $this->options["data"] = json_encode($this->table);
            $this->options["datatype"] = "local";
            $this->actions["rowactions"] = false;
            $this->actions["add"] = false;
            $this->actions["edit"] = false;
            $this->actions["delete"] = false;
        }
        // few overides - pagination fixes
        $this->options["pager"] = '#' . $grid_id . "_pager";
        $this->options["jsonReader"] = array("repeatitems" => false, "id" => "0");
        // allow/disallow edit,del operations
        if ($this->actions["edit"] === false && $this->actions["delete"] === false || $this->options["cellEdit"] === true) {
            $this->actions["rowactions"] = false;
        }
        if ($this->actions["rowactions"] !== false) {
            // CRUD operation column
            $f = false;
            $defined = false;
            foreach ($this->options["colModel"] as &$c) {
                if ($c["name"] == "act") {
                    $defined =& $c;
                }
                if (!empty($c["width"])) {
                    $f = true;
                }
            }
            // icon col fix, text links as old behavior (fixed:true, mean exact px)
            if ($this->internal["actionicon"] === true) {
                $w = $this->actions["clone"] === true ? "80" : "55";
            } else {
                $w = $this->actions["clone"] === true ? "120" : "100";
            }
            // width adjustment for row actions column
            $action_column = array("name" => "act", "fixed" => true, "align" => "center", "index" => "act", "width" => "{$w}", "sortable" => false, "search" => false, "viewable" => false);
            if (!$defined) {
                $this->options["colNames"][] = "Actions";
                $this->options["colModel"][] = $action_column;
            } else {
                $defined = array_merge($action_column, $defined);
            }
        }
        // simulate field access right options
        $str_add_form = '';
        $str_edit_form = '';
        $str_delete_form = '';
        $str_edit_access = '';
        $str_inline_access = '';
        foreach ($this->options["colModel"] as &$c) {
            // auto reload & edit for link pattern fix
            if (!empty($c["link"])) {
                $this->options["reloadedit"] = true;
                $c["formatter"] = "function(cellvalue, options, rowObject){ \n\n\t\t\t\t\t\t\t\t\t\tarr = jQuery(document).data('link_{$c["name"]}');\n\t\t\t\t\t\t\t\t\t\tif (!arr) arr = {};\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\tif (jQuery(cellvalue).text() != '')\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tarr[jQuery(cellvalue).text()] = cellvalue;\n\t\t\t\t\t\t\t\t\t\t\tjQuery(document).data('link_{$c["name"]}',arr);\n\t\t\t\t\t\t\t\t\t\t\treturn arr[jQuery(cellvalue).text()];\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t// fix for link text 'undefined'\n\t\t\t\t\t\t\t\t\t\t\tif (typeof(arr[cellvalue]) == 'undefined')\n\t\t\t\t\t\t\t\t\t\t\t\treturn '';\n\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\treturn arr[cellvalue];\n\t\t\t\t\t\t\t\t\t\t}\n\n\n\t\t\t\t\t\t\t\t\t}";
                $c["unformat"] = "function(cellvalue, options, cell){return jQuery(cell).text();}";
            }
            // make readonly field while editing
            if (isset($c["editrules"]["readonly"])) {
                if ($c["editrules"]["readonly"] === true) {
                    $tag = "input";
                    if (!empty($c["edittype"])) {
                        $tag = $c["edittype"];
                    }
                    if (!empty($c["editrules"]["readonly-when"])) {
                        $cond = $c["editrules"]["readonly-when"];
                        if (!is_numeric($cond[1])) {
                            $cond[1] = '"' . $cond[1] . '"';
                        }
                        $str_edit_access .= 'if (jQuery("#tr_' . $c["index"] . ' .DataTD ' . $tag . '",formid).val() ' . $cond[0] . ' ' . $cond[1] . ')';
                        $str_inline_access .= 'if (jQuery("' . $tag . '[name=' . $c["index"] . ']:last").val() ' . $cond[0] . ' ' . $cond[1] . ')';
                    }
                    // make textbox hidden, for postback
                    $str_edit_access .= '{';
                    if ($tag == "select") {
                        $str_edit_access .= 'jQuery("#tr_' . $c["index"] . ' .DataTD",formid).append("&nbsp;" + jQuery("#tr_' . $c["index"] . ' .DataTD ' . $tag . ' option:selected",formid).text());';
                    } else {
                        $str_edit_access .= 'jQuery("#tr_' . $c["index"] . ' .DataTD",formid).append("&nbsp;" + jQuery("#tr_' . $c["index"] . ' .DataTD ' . $tag . '",formid).val());';
                    }
                    $str_edit_access .= 'jQuery("#tr_' . $c["index"] . ' .DataTD ' . $tag . '",formid).hide();';
                    // remove required (*) from readonly
                    $str_edit_access .= 'jQuery("#tr_' . $c["index"] . ' .DataTD font",formid).hide();';
                    $str_edit_access .= '}';
                    $str_inline_access .= '{';
                    $str_inline_access .= 'jQuery("' . $tag . '[name=' . $c["index"] . ']:last").hide();';
                    $str_inline_access .= 'jQuery("' . $tag . '[name=' . $c["index"] . ']:last").parent().not(":has(span)").append("<span></span>");';
                    $str_inline_access .= 'jQuery("' . $tag . '[name=' . $c["index"] . ']:last").parent().children("span").html(jQuery("' . $tag . '[name=' . $c["index"] . ']:last").val());';
                    $str_inline_access .= '}';
                }
            }
            if (!empty($c["show"])) {
                if ($c["show"]["list"] === false) {
                    $c["hidden"] = true;
                } else {
                    $c["hidden"] = false;
                }
                if ($c["formoptions"]["rowpos"]) {
                    $str_pos = '';
                    $str_pos .= 'jQuery("#TblGrid_' . $grid_id . ' tr:eq(' . ($c["formoptions"]["rowpos"] + 1) . ') td:nth-child(' . $c["formoptions"]["colpos"] * 2 . ')").html("");';
                    $str_pos .= 'jQuery("#TblGrid_' . $grid_id . ' tr:eq(' . ($c["formoptions"]["rowpos"] + 1) . ') td:nth-child(' . ($c["formoptions"]["colpos"] * 2 - 1) . ')").html("");';
                }
                if ($c["show"]["edit"] === false) {
                    $str_edit_access .= 'jQuery("#tr_' . $c["index"] . '",formid).hide();';
                    if (!empty($str_pos)) {
                        $str_edit_access .= $str_pos;
                    }
                } else {
                    $str_edit_access .= 'jQuery("#tr_' . $c["index"] . '",formid).show();';
                }
                if ($c["show"]["add"] === false) {
                    $str_add_access .= 'jQuery("#tr_' . $c["index"] . '",formid).hide();';
                    if (!empty($str_pos)) {
                        $str_add_access .= $str_pos;
                    }
                } else {
                    $str_add_access .= 'jQuery("#tr_' . $c["index"] . '",formid).show();';
                }
                if ($c["show"]["view"] === false) {
                    $str_view_access .= 'jQuery("#trv_' . $c["index"] . '").hide();';
                    if ($c["formoptions"]["rowpos"]) {
                        $str_pos = '';
                        $str_pos .= 'jQuery("#ViewTbl_' . $grid_id . ' tr:eq(' . ($c["formoptions"]["rowpos"] - 1) . ') td:nth-child(' . $c["formoptions"]["colpos"] * 2 . ')").html("");';
                        $str_pos .= 'jQuery("#ViewTbl_' . $grid_id . ' tr:eq(' . ($c["formoptions"]["rowpos"] - 1) . ') td:nth-child(' . ($c["formoptions"]["colpos"] * 2 - 1) . ')").html("");';
                        $str_view_access .= $str_pos;
                    }
                } else {
                    $str_view_access .= 'jQuery("#trv_' . $c["index"] . '").show();';
                }
                unset($c["show"]);
            }
        }
        // set before show form events
        if (!empty($this->internal["add_options"]["beforeShowForm"])) {
            $str_add_form = $str_add_access . $this->internal["add_options"]["beforeShowForm"];
        } else {
            $str_add_form = $str_add_access;
        }
        if (!empty($this->internal["edit_options"]["beforeShowForm"])) {
            $str_edit_form = $str_edit_access . $this->internal["edit_options"]["beforeShowForm"];
        } else {
            $str_edit_form = $str_edit_access;
        }
        if (!empty($this->internal["delete_options"]["beforeShowForm"])) {
            $str_delete_form = $str_delete_access . $this->internal["delete_options"]["beforeShowForm"];
        } else {
            $str_delete_form = $str_delete_access;
        }
        if (!empty($this->internal["view_options"]["beforeShowForm"])) {
            $str_view_form = $str_view_access . $this->internal["view_options"]["beforeShowForm"];
        } else {
            $str_view_form = $str_view_access;
        }
        ### P ###
        $this->options["add_options"]["beforeShowForm"] = 'function(formid) { ' . $str_add_form . ' }';
        $this->options["edit_options"]["beforeShowForm"] = 'function(formid) { ' . $str_edit_form . ' }';
        $this->options["delete_options"]["beforeShowForm"] = 'function(formid) { ' . $str_delete_form . ' }';
        // append view options beforeShowForm implementation
        $fx = "";
        if (!empty($this->options["view_options"]["beforeShowForm"])) {
            $fx = "var o=" . $this->options["view_options"]["beforeShowForm"] . "; o(formid);";
        }
        $this->options["view_options"]["beforeShowForm"] = 'function(formid) { ' . $str_view_form . $fx . ' }';
        // focus / select newly inserted row
        $this->options["add_options"]["afterComplete"] = "function (response, postdata) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tr = JSON.parse(response.responseText); \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tjQuery( document ).ajaxComplete(function() {\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tjQuery('#{$grid_id}').setSelection(r.id);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tjQuery( document ).unbind('ajaxComplete');\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}";
        // event for dialog < > navigation
        $this->options["view_options"]["afterclickPgButtons"] = 'function(formid) { ' . $str_view_access . ' }';
        ### P-END ###
        $reload_after_edit = "";
        // after save callback
        if (!empty($this->options["onAfterSave"])) {
            $reload_after_edit .= "var fx_save = {$this->options["onAfterSave"]}; fx_save();";
        }
        if ($this->options["reloadedit"] === true) {
            $reload_after_edit .= "jQuery('#{$grid_id}').jqGrid().trigger('reloadGrid',[{jqgrid_page:1}]);";
        }
        ### P ###
        if (empty($this->options["add_options"]["success_msg"])) {
            $this->options["add_options"]["success_msg"] = "Enr&eacute;gistrement ajout&eacute;";
        }
        if (empty($this->options["edit_options"]["success_msg"])) {
            $this->options["edit_options"]["success_msg"] = "Enr&eacute;gistrement mis &agrave; jour";
        }
        if (empty($this->options["edit_options"]["success_msg_bulk"])) {
            $this->options["edit_options"]["success_msg_bulk"] = "Enr&eacute;gistrements ajout&eacute;s";
        }
        if (empty($this->options["delete_options"]["success_msg"])) {
            $this->options["delete_options"]["success_msg"] = "Enr&eacute;gistrement effac&eacute";
        }
        if (empty($this->options["add_options"]["afterSubmit"])) {
            $this->options["add_options"]["afterSubmit"] = 'function(response) { if(response.status == 200)
																				{ 
																					fx_success_msg("' . $this->options["add_options"]["success_msg"] . '",1);
																			      	return [true,""];
																				} 
																			}';
        }
        if (empty($this->options["edit_options"]["afterSubmit"])) {
            $this->options["edit_options"]["afterSubmit"] = 'function(response) { if(response.status == 200)
																				{ 
																					' . $reload_after_edit . '
																					fx_success_msg("' . $this->options["edit_options"]["success_msg"] . '",1);
																			      	return [true,""];
																				} 
																			}';
        }
        if (empty($this->options["delete_options"]["afterSubmit"])) {
            $this->options["delete_options"]["afterSubmit"] = 'function(response) { if(response.status == 200)
																				{ 
																					fx_success_msg("' . $this->options["delete_options"]["success_msg"] . '",1);
																			      	return [true,""];
																				} 
																			}';
        }
        ### P-END ###
        // search options for templates
        $this->options["search_options"]["closeAfterSearch"] = true;
        $this->options["search_options"]["multipleSearch"] = $this->actions["search"] == "advance" ? true : false;
        $this->options["search_options"]["sopt"] = array('eq', 'ne', 'lt', 'le', 'gt', 'ge', 'bw', 'bn', 'in', 'ni', 'ew', 'en', 'cn', 'nc', 'nu', 'nn');
        $out = json_encode_jsfunc($this->options);
        $out = substr($out, 0, strlen($out) - 1);
        // create Edit/Delete - Save/Cancel column in grid
        if ($this->actions["rowactions"] !== false) {
            $act_links = array();
            ### P-START ###
            if ($this->internal["actionicon"] === true) {
                if ($this->actions["edit"] !== false) {
                    $act_links[] = "<a class=\"ui-custom-icon ui-icon ui-icon-pencil\" title=\"Editer la ligne\" href=\"javascript:void(0);\" onclick=\"jQuery(this).dblclick();\"></a>";
                }
                ### P ###
                if ($this->actions["clone"] === true) {
                    $act_links[] = "<a class=\"ui-custom-icon ui-icon ui-icon-copy\" title=\"Cloner la ligne\" href=\"javascript:void(0);\" onclick=\"fx_clone_row(\\'{$grid_id}\\',\\''+cl+'\\'); \"></a>";
                }
                ### P-END ###
                if ($this->actions["delete"] !== false) {
                    $act_links[] = "<a class=\"ui-custom-icon ui-icon ui-icon-trash\" title=\"Effacer la ligne\" href=\"javascript:void(0);\" onclick=\"jQuery(\\'#{$grid_id}\\').delGridRow(\\''+cl+'\\',{errorTextFormat:function(r){ return r.responseText;}}); jQuery(\\'#delmod{$grid_id}\\').abscenter(); \"></a>";
                }
                $act_links = implode("", $act_links);
                $out .= ",'gridComplete': function()\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tvar ids = jQuery('#{$grid_id}').jqGrid('getDataIDs');\n\t\t\t\t\t\t\t\tfor(var i=0;i < ids.length;i++)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tvar cl = ids[i];\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tbe = '{$act_links}';\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t// il_save, ilcancel, iledit are clicked for inlineNav button reset\n\t\t\t\t\t\t\t\t\tse = '<a class=\"ui-custom-icon ui-icon ui-icon-disk\" title=\"Save this row\" href=\"javascript:void(0);\" onclick=\"jQuery(\\'#{$grid_id}_ilsave\\').click(); if (jQuery(\\'#{$grid_id}\\').saveRow(\\''+cl+'\\') || jQuery(\\'.editable\\').length==0) { jQuery(this).parent().hide(); jQuery(this).parent().prev().show(); " . addslashes($reload_after_edit) . " }\"></a>';\n\t\t\t\t\t\t\t\t\tce = '<a class=\"ui-custom-icon ui-icon ui-icon-cancel\" title=\"Restore this row\" href=\"javascript:void(0);\" onclick=\"jQuery(\\'#{$grid_id}_ilcancel\\').click(); jQuery(\\'#{$grid_id}\\').restoreRow(\\''+cl+'\\'); jQuery(this).parent().hide(); jQuery(this).parent().prev().show();\"></a>';\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t// for inline add option\n\t\t\t\t\t\t\t\t\tif (ids[i].indexOf('jqg') != -1)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tse = '<a class=\"ui-custom-icon ui-icon ui-icon-disk\" title=\"Save this row\" href=\"javascript:void(0);\" onclick=\"jQuery(\\'#{$grid_id}_ilsave\\').click(); \">Save</a>';\n\t\t\t\t\t\t\t\t\t\tce = '<a class=\"ui-custom-icon ui-icon ui-icon-cancel\" title=\"Restore this row\" href=\"javascript:void(0);\" onclick=\"jQuery(\\'#{$grid_id}_ilcancel\\').click(); jQuery(this).parent().hide(); jQuery(this).parent().prev().show();\">Cancel</a>';\n\t\t\t\t\t\t\t\t\t\tjQuery('#{$grid_id}').jqGrid('setRowData',ids[i],{act:'<span style=display:none id=\"edit_row_{$grid_id}_'+cl+'\">'+be+'</span>'+'<span id=\"save_row_{$grid_id}_'+cl+'\">'+se+ce+'</span>'});\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\tjQuery('#{$grid_id}').jqGrid('setRowData',ids[i],{act:'<span id=\"edit_row_{$grid_id}_'+cl+'\">'+be+'</span>'+'<span style=display:none id=\"save_row_{$grid_id}_'+cl+'\">'+se+ce+'</span>'});\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}";
            } else {
                if ($this->actions["edit"] !== false) {
                    $act_links[] = "<a title=\"Editer la ligne\" href=\"javascript:void(0);\" onclick=\"jQuery(this).dblclick();\">Edit</a>";
                }
                ### P ###
                if ($this->actions["clone"] === true) {
                    $act_links[] = "<a title=\"Cloner la ligne\" href=\"javascript:void(0);\" onclick=\"fx_clone_row(\\'{$grid_id}\\',\\''+cl+'\\'); \">Clone</a>";
                }
                ### P-END ###
                if ($this->actions["delete"] !== false) {
                    $act_links[] = "<a title=\"Effacer la ligne\" href=\"javascript:void(0);\" onclick=\"jQuery(\\'#{$grid_id}\\').delGridRow(\\''+cl+'\\',{errorTextFormat:function(r){ return r.responseText;}}); jQuery(\\'#delmod{$grid_id}\\').abscenter(); \">Delete</a>";
                }
                $act_links = implode(" | ", $act_links);
                $out .= ",'gridComplete': function()\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\tvar ids = jQuery('#{$grid_id}').jqGrid('getDataIDs');\n\t\t\t\t\t\t\t\tfor(var i=0;i < ids.length;i++)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\tvar cl = ids[i];\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tbe = '{$act_links}'; \n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// il_save, ilcancel, iledit are clicked for inlineNav button reset\n\t\t\t\t\t\t\tse = ' <a title=\"Save this row\" href=\"javascript:void(0);\" onclick=\"jQuery(\\'#{$grid_id}_ilsave\\').click(); if (jQuery(\\'#{$grid_id}\\').saveRow(\\''+cl+'\\') || jQuery(\\'.editable\\').length==0) { jQuery(this).parent().hide(); jQuery(this).parent().prev().show(); " . addslashes($reload_after_edit) . " }\">Save</a>'; \n\t\t\t\t\t\t\tce = ' | <a title=\"Restore this row\" href=\"javascript:void(0);\" onclick=\"jQuery(\\'#{$grid_id}_ilcancel\\').click(); jQuery(\\'#{$grid_id}\\').restoreRow(\\''+cl+'\\'); jQuery(this).parent().hide(); jQuery(this).parent().prev().show();\">Cancel</a>'; \n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// for inline add option\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif (ids[i].indexOf('jqg') != -1)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tse = ' <a title=\"Save this row\" href=\"javascript:void(0);\" onclick=\"jQuery(\\'#{$grid_id}_ilsave\\').click(); \">Save</a>'; \n\t\t\t\t\t\t\t\tce = ' | <a title=\"Restore this row\" href=\"javascript:void(0);\" onclick=\"jQuery(\\'#{$grid_id}_ilcancel\\').click(); jQuery(this).parent().hide(); jQuery(this).parent().prev().show();\">Cancel</a>'; \n\t\t\t\t\t\t\t\tjQuery('#{$grid_id}').jqGrid('setRowData',ids[i],{act:'<span style=display:none id=\"edit_row_{$grid_id}_'+cl+'\">'+be+'</span>'+'<span id=\"save_row_{$grid_id}_'+cl+'\">'+se+ce+'</span>'});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tjQuery('#{$grid_id}').jqGrid('setRowData',ids[i],{act:'<span id=\"edit_row_{$grid_id}_'+cl+'\">'+be+'</span>'+'<span style=display:none id=\"save_row_{$grid_id}_'+cl+'\">'+se+ce+'</span>'});\n\t\t\t\t\t\t}\t\n\t\t\t\t\t}";
            }
        }
        $out .= ",'ondblClickRow': function (id, iRow, iCol, e) {";
        // double click editing option
        if ($this->actions["rowactions"] !== false && $this->actions["edit"] !== false && $this->options["cellEdit"] !== true) {
            $out .= "\n\t\t\t\t\t\t\tif (!e) e = window.event;\n\t\t\t\t\t\t\tvar element = e.target || e.srcElement;\n\n\t\t\t\t\t\t\tif(id && id!==lastSel && lastSel != 'jqg1')\n\t\t\t\t\t\t\t{ \n\t\t\t\t\t\t\t\t// reset data msg, for new row edit without save last row\n\t\t\t\t\t\t\t\tif (typeof(lastSel) != 'undefined' && jQuery('.editable').length >0 && !confirm('Changes are not saved, Reset changes?'))\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tjQuery('#{$grid_id}').restoreRow(lastSel); \n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t// to enable autosave on dblclick new row + dont edit on validation error\n\t\t\t\t\t\t\t\t// if (typeof(lastSel) != 'undefined')\n\t\t\t\t\t\t\t\t\t// if (!jQuery('#{$grid_id}').saveRow(lastSel))\n\t\t\t\t\t\t\t\t\t\t// return;\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t// disabled previously edit icons\n\t\t\t\t\t\t\t\tjQuery('#edit_row_{$grid_id}_'+lastSel).show();\n\t\t\t\t\t\t\t\tjQuery('#save_row_{$grid_id}_'+lastSel).hide();\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tlastSel=id; \t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tjQuery('#{$grid_id}').editRow(id, true, function()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// focus on dblclicked element\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsetTimeout(function(){ jQuery('input, select, textarea', element).focus(); },100);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfunction()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tjQuery('#edit_row_{$grid_id}_'+id).show();\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tjQuery('#save_row_{$grid_id}_'+id).hide();\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},null,null,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfunction()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// force reload grid after inline save\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{$reload_after_edit}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},null,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfunction()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tjQuery('#edit_row_{$grid_id}_'+id).show();\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tjQuery('#save_row_{$grid_id}_'+id).hide();\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t); \n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// for inlineNav edit button fix\n\t\t\t\t\t\t\tif (jQuery('#{$grid_id}_iledit').length)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tjQuery('#{$grid_id}').setSelection(id, true);\n\t\t\t\t\t\t\t\tjQuery('#{$grid_id}_iledit').click();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tjQuery('#edit_row_{$grid_id}_'+id).hide();\n\t\t\t\t\t\t\tjQuery('#save_row_{$grid_id}_'+id).show();\n\n\t\t\t\t\t\t\t{$str_inline_access}";
        }
        // chain 'onSelectRow' function with base working
        if (!empty($this->options["ondblClickRow"])) {
            $out .= "var fx = " . $this->options["ondblClickRow"] . "; fx(id, iRow, iCol);";
            unset($this->options["ondblClickRow"]);
        }
        $out .= "}";
        ### P ###
        // if subgrid is there, enable subgrid feature
        if (isset($this->options["subgridurl"]) && $this->options["subgridurl"] != '') {
            // we pass two parameters
            // subgrid_id is a id of the div tag created within a table
            // the row_id is the id of the row
            // If we want to pass additional parameters to the url we can use
            // the method getRowData(row_id) - which returns associative array in type name-value
            // here we can easy construct the following
            $pass_params = "false";
            if (!empty($this->options["subgridparams"])) {
                $pass_params = "true";
            }
            // chain 'subGridRowExpanded' function with base working
            if (!empty($this->options["subGridRowExpanded"])) {
                $str_fx = "var fx = " . $this->options["subGridRowExpanded"] . "; fx();";
                unset($this->options["subGridRowExpanded"]);
            }
            $out .= ",'subGridRowExpanded': function(subgridid, id) \n\t\t\t\t\t\t\t\t\t\t\t{ \n\t\t\t\t\t\t\t\t\t\t\t\tvar data = {subgrid:subgridid, rowid:id};\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\tif('{$pass_params}' == 'true') {\n\t\t\t\t\t\t\t\t\t\t\t\t\tvar anm= '" . $this->options["subgridparams"] . "';\n\t\t\t\t\t\t\t\t\t\t\t\t\tanm = anm.split(',');\n\t\t\t\t\t\t\t\t\t\t\t\t\tvar rd = jQuery('#" . $grid_id . "').jqGrid('getRowData', id);\n\t\t\t\t\t\t\t\t\t\t\t\t\tif(rd) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor(var i=0; i<anm.length; i++) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif(rd[anm[i]]) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdata[anm[i]] = rd[anm[i]];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\tjQuery('#'+jQuery.jgrid.jqID(subgridid)).load('" . $this->options["subgridurl"] . "',data,function(){ " . $str_fx . " });\n\t\t\t\t\t\t\t\t\t\t\t}";
        }
        // on error
        $out .= ",'loadError': function(xhr,status, err) { \n\t\t\t\t\ttry \n\t\t\t\t\t{\n\t\t\t\t\t\tjQuery.jgrid.info_dialog(jQuery.jgrid.errors.errcap,'<div class=\"ui-state-error\">'+ xhr.responseText +'</div>', \n\t\t\t\t\t\t\t\t\t\t\t\t\tjQuery.jgrid.edit.bClose,{buttonalign:'right'});\n\n\t\t\t\t\t} \n\t\t\t\t\tcatch(e) { alert(xhr.responseText);}\n\t\t\t\t}\n\t\t\t\t";
        // on row selection operation
        $out .= ",'onSelectRow': function(ids) { ";
        ### P ###
        if (isset($this->options["detail_grid_id"]) && $this->options["detail_grid_id"] != '') {
            $detail_grid_id = $this->options["detail_grid_id"];
            $d_grids = explode(",", $detail_grid_id);
            foreach ($d_grids as $detail_grid_id) {
                $detail_url = $this->options["url"];
                // remove master grid's grid_id param
                $detail_url = str_replace('grid_id=', '', $detail_url);
                // append grid_id param for detail grid
                $s = strstr($this->options["url"], "?") ? "&" : "?";
                $detail_url .= $s . "grid_id=" . $detail_grid_id;
                $out .= "\n\t\t\n\t\t\t\t\t\tvar data = '';\n\t\t\t\t\t\tif ('{$this->options["subgridparams"]}'.length > 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tvar anm = '" . $this->options["subgridparams"] . "';\n\t\t\t\t\t\t\tanm = anm.split(',');\n\t\t\t\t\t\t\tvar rd = jQuery('#" . $grid_id . "').jqGrid('getRowData', ids);\n\t\t\t\t\t\t\tif(rd) {\n\t\t\t\t\t\t\t\tfor(var i=0; i<anm.length; i++) {\n\t\t\t\t\t\t\t\t\tif(rd[anm[i]]) {\n\t\t\t\t\t\t\t\t\t\tdata += '&' + anm[i] + '=' + rd[anm[i]];\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\tif(ids == null) \n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tids=0;\n\t\t\t\t\t\t\tif(jQuery('#" . $detail_grid_id . "').jqGrid('getGridParam','records') >0 )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tjQuery('#" . $detail_grid_id . "').jqGrid('setGridParam',{url:'" . $detail_url . "&rowid='+ids+data,editurl:'" . $detail_url . "&rowid='+ids,jqgrid_page:1});\n\t\t\t\t\t\t\t\tjQuery('#" . $detail_grid_id . "').trigger('reloadGrid',[{jqgrid_page:1}]);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} \n\t\t\t\t\t\telse \n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tjQuery('#" . $detail_grid_id . "').jqGrid('setGridParam',{url:'" . $detail_url . "&rowid='+ids+data,editurl:'" . $detail_url . "&rowid='+ids,jqgrid_page:1});\n\t\t\t\t\t\t\tjQuery('#" . $detail_grid_id . "').trigger('reloadGrid',[{jqgrid_page:1}]);\t\t\t\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// enable detail grid buttons if master row selected\n\t\t\t\t\t\tjQuery('#" . $detail_grid_id . "_pager_left .ui-pg-button').not(':has(span.ui-separator)').removeClass('ui-state-disabled');\n\t\t\t\t\t\tjQuery('#" . $detail_grid_id . "_ilsave, #" . $detail_grid_id . "_ilcancel').addClass('ui-state-disabled');\n\t\t\t\t\t\t\n\t\t\t\t\t\tjQuery('#" . $detail_grid_id . "').data('jqgrid_detail_grid_params','&rowid='+ids+data);\n\t\t\t\t\t\t";
            }
        }
        ### P ###
        // obseleted now
        if (!empty($this->events["js_on_select_row"])) {
            $out .= "if (typeof({$this->events["js_on_select_row"]}) != 'undefined') {$this->events["js_on_select_row"]}(ids);";
        }
        // chain 'onSelectRow' function with base working
        if (!empty($this->options["onSelectRow"])) {
            $out .= "var fx = " . $this->options["onSelectRow"] . "; fx(ids);";
            unset($this->options["onSelectRow"]);
        }
        // closing of select row events
        $out .= "}";
        // fix for formatting, to apply on only new records of virtual scroll
        if ($this->options["scroll"] == true) {
            $out .= ",'beforeRequest': function() {";
            $out .= "jQuery('#{$grid_id}').data('jqgrid_rows',jQuery('#{$grid_id} tr.jqgrow').length);";
            $out .= "}";
        }
        // on load complete operation
        $out .= ",'loadComplete': function(ids) {";
        // In case 'All' param is used in pager
        $out .= "jQuery('#{$grid_id}_pager option[value=\"All\"]').val(99999);";
        // show no record message at center
        $out .= "if (jQuery('#{$grid_id}').getGridParam('records') == 0) \n\t\t\t\t\t\t{ \n\t\t\t\t\t\t\tif (jQuery('#div_no_record_{$grid_id}').length==0) \n\t\t\t\t\t\t\t\tjQuery('#gbox_{$grid_id} .ui-jqgrid-bdiv').not('.frozen-bdiv').append('<div id=\"div_no_record_{$grid_id}\" align=\"center\" style=\"padding:30px 0;\">'+jQuery.jgrid.defaults.emptyrecords+'</div>'); \n\t\t\t\t\t\t\telse \n\t\t\t\t\t\t\t\tjQuery('#div_no_record_{$grid_id}').show();\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tjQuery('#div_no_record_{$grid_id}').hide();\n\t\t\t\t\t\t}";
        if (isset($this->options["detail_grid_id"]) && $this->options["detail_grid_id"] != '') {
            $detail_grid_id = $this->options["detail_grid_id"];
            $d_grids = explode(",", $detail_grid_id);
            foreach ($d_grids as $detail_grid_id) {
                $detail_url = $this->options["url"];
                $s = strstr($this->options["url"], "?") ? "&" : "?";
                $detail_url .= $s . "grid_id=" . $detail_grid_id;
                $out .= "\n\t\t\t\t\t\t\t\tjQuery('#" . $detail_grid_id . "').jqGrid('setGridParam',{url:'" . $detail_url . "&rowid=',editurl:'" . $detail_url . "&rowid=',jqgrid_page:1});\n\t\t\t\t\t\t\t\tjQuery('#" . $detail_grid_id . "').trigger('reloadGrid',[{jqgrid_page:1}]);\n\t\t\t\t\t\t\t\tjQuery('#" . $detail_grid_id . "').data('jqgrid_detail_grid_params','');\n\t\t\t\t\t\t\t\tjQuery('#" . $detail_grid_id . "_pager_left .ui-pg-button').addClass('ui-state-disabled');\n\t\t\t\t\t\t\t\t";
            }
        }
        // formatting fix for virtual scrolling
        $fix_format = "";
        if ($this->options["scroll"] == true) {
            $fix_format .= " var last_rows = 0;\n\t\t\t\t\t\t\t\t\tif (typeof(jQuery('#{$grid_id}').data('jqgrid_rows')) != 'undefined')\n\t\t\t\t\t\t\t\t\t\ti = i + jQuery('#{$grid_id}').data('jqgrid_rows');\n\t\t\t\t\t\t\t\t\t";
        }
        // celledit option and readonly mode
        if ($this->options["cellEdit"] === true) {
            foreach ($this->options["colModel"] as $t) {
                if ($t["editrules"]["readonly"] == true) {
                    $fix_format .= "jQuery('#{$grid_id} tr.jqgrow:eq('+i+') td[aria-describedby={$grid_id}_{$t[name]}]').addClass('not-editable-cell');";
                }
            }
        }
        $out .= "if(ids && ids.rows) jQuery.each(ids.rows,function(i){\n\t\t\t\t\t\t\t{$fix_format}\n\t\t\t\t\t\t\t";
        ### P ###
        if (count($this->conditional_css)) {
            foreach ($this->conditional_css as $value) {
                // if wrong column specified, skip formatting
                $out .= "if (typeof(this.{$value[column]}) == 'undefined') return;";
                // using {column} placeholder in formatting value
                preg_match('/{(.*)}/', $value[value], $match);
                if (count($match)) {
                    // if html remove it using text(), if string convert toString(), if numeric use parseFloat
                    if ($value["op"] == "cn" || $value["op"] == "eq" || $value["op"] == "=") {
                        $value[value] = "'+ (jQuery(this.{$match['1']}).html() ? jQuery(this.{$match['1']}).text() : (jQuery.isNumeric(this.{$match['1']}) ? parseFloat(this.{$match['1']}) : this.{$match['1']}.toString()) )+ '";
                    } else {
                        $value[value] = "(jQuery(this.{$match['1']}).html() ? jQuery(this.{$match['1']}).text() : (jQuery.isNumeric(this.{$match['1']}) ? parseFloat(this.{$match['1']}) : this.{$match['1']}.toString()) )";
                    }
                }
                $out .= "this.{$value[column]} = this.{$value[column]}.replace(/(<([^>]+)>)/ig,'');";
                if ($value["op"] == "cn") {
                    $out .= "\n\t\t\t\t\t\t\t\t\t\tif (this.{$value[column]}.toLowerCase().indexOf('{$value[value]}'.toLowerCase()) != -1)\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tif ('" . $value["class"] . "' != '')\n\t\t\t\t\t\t\t\t\t\t\t\tjQuery('#{$grid_id} tr.jqgrow:eq('+i+')').addClass('" . $value["class"] . "');\n\t\t\t\t\t\t\t\t\t\t\telse if (\"" . $value["css"] . "\" != '')\n\t\t\t\t\t\t\t\t\t\t\t\tjQuery('#{$grid_id} tr.jqgrow:eq('+i+')').css('background-image','inherit').css({{$value[css]}});\n\t\t\t\t\t\t\t\t\t\t\telse if ('" . $value["cellclass"] . "' != '')\n\t\t\t\t\t\t\t\t\t\t\t{ \n\t\t\t\t\t\t\t\t\t\t\t\tjQuery('#{$grid_id} tr.jqgrow:eq('+i+')').css('background-image','inherit'); \n\t\t\t\t\t\t\t\t\t\t\t\tjQuery('#{$grid_id} tr.jqgrow:eq('+i+') td[aria-describedby={$grid_id}_{$value[column]}]').addClass('" . $value["cellclass"] . "');\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\telse if (\"" . $value["cellcss"] . "\" != '')\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tjQuery('#{$grid_id} tr.jqgrow:eq('+i+')').css('background-image','inherit');\n\t\t\t\t\t\t\t\t\t\t\t\tjQuery('#{$grid_id} tr.jqgrow:eq('+i+') td[aria-describedby={$grid_id}_{$value[column]}]').css('background','inherit').css({{$value[cellcss]}});\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}";
                } else {
                    if ($value["op"] == "eq" || $value["op"] == "=") {
                        $out .= "\n\t\t\t\t\t\t\t\t\t\tif (this.{$value[column]}.toLowerCase() == '{$value[value]}'.toLowerCase())\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tif ('" . $value["class"] . "' != '')\n\t\t\t\t\t\t\t\t\t\t\t\tjQuery('#{$grid_id} tr.jqgrow:eq('+i+')').addClass('" . $value["class"] . "');\n\t\t\t\t\t\t\t\t\t\t\telse if (\"" . $value["css"] . "\" != '')\n\t\t\t\t\t\t\t\t\t\t\t\tjQuery('#{$grid_id} tr.jqgrow:eq('+i+')').css('background-image','inherit').css({{$value[css]}});\n\t\t\t\t\t\t\t\t\t\t\telse if ('" . $value["cellclass"] . "' != '')\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tjQuery('#{$grid_id} tr.jqgrow:eq('+i+')').css('background-image','inherit');\n\t\t\t\t\t\t\t\t\t\t\t\tjQuery('#{$grid_id} tr.jqgrow:eq('+i+') td[aria-describedby={$grid_id}_{$value[column]}]').addClass('" . $value["cellclass"] . "');\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\telse if (\"" . $value["cellcss"] . "\" != '')\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tjQuery('#{$grid_id} tr.jqgrow:eq('+i+')').css('background-image','inherit');\n\t\t\t\t\t\t\t\t\t\t\t\tjQuery('#{$grid_id} tr.jqgrow:eq('+i+') td[aria-describedby={$grid_id}_{$value[column]}]').css('background','inherit').css({{$value[cellcss]}});\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}";
                    } else {
                        if ($value["op"] == "<" || $value["op"] == "<=" || $value["op"] == ">" || $value["op"] == ">=" || $value["op"] == "!=") {
                            $out .= "\n\t\t\t\t\t\t\t\t\t\tif (parseFloat(this.{$value[column]}) {$value["op"]} {$value[value]})\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tif ('" . $value["class"] . "' != '')\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tjQuery('#{$grid_id} tr.jqgrow:eq('+i+')').addClass('" . $value["class"] . "');\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\telse if (\"" . $value["css"] . "\" != '')\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tjQuery('#{$grid_id} tr.jqgrow:eq('+i+')').css('background-image','inherit').css({{$value[css]}});\n\t\t\t\t\t\t\t\t\t\t\t\tjQuery('#{$grid_id} tr.jqgrow:eq('+i+') a').css('background-image','inherit').css({{$value[css]}});\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\telse if ('" . $value["cellclass"] . "' != '')\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tjQuery('#{$grid_id} tr.jqgrow:eq('+i+')').css('background-image','inherit');\n\t\t\t\t\t\t\t\t\t\t\t\tjQuery('#{$grid_id} tr.jqgrow:eq('+i+') td[aria-describedby={$grid_id}_{$value[column]}]').addClass('" . $value["cellclass"] . "');\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\telse if (\"" . $value["cellcss"] . "\" != '')\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tjQuery('#{$grid_id} tr.jqgrow:eq('+i+')').css('background-image','inherit');\n\t\t\t\t\t\t\t\t\t\t\t\tjQuery('#{$grid_id} tr.jqgrow:eq('+i+') td[aria-describedby={$grid_id}_{$value[column]}]').css('background','inherit').css({{$value[cellcss]}});\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}";
                        } else {
                            if (empty($value["op"]) && !empty($value["column"]) && !empty($value["css"])) {
                                $out .= "\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tif (jQuery.browser.msie)\n\t\t\t\t\t\t\t\t\t\t\t\tjQuery('#{$grid_id} td[aria-describedby={$grid_id}_{$value["column"]}]').css('background','inherit').css({{$value[css]}});\n\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t\tjQuery('#{$grid_id} td[aria-describedby={$grid_id}_{$value["column"]}]').removeClass('.ui-widget-content').css({{$value[css]}});\n\t\t\t\t\t\t\t\t\t\t}";
                            }
                        }
                    }
                }
            }
        }
        ### P-END ###
        $out .= "});";
        ### P ###
        // obseleted now
        if (!empty($this->events["js_on_load_complete"])) {
            $out .= "if (typeof({$this->events["js_on_load_complete"]}) != 'undefined') {$this->events["js_on_load_complete"]}(ids);";
        }
        // chain 'loadComplete' function with base working
        if (!empty($this->options["loadComplete"])) {
            $out .= "var fx = " . $this->options["loadComplete"] . "; fx(ids);";
            unset($this->options["loadComplete"]);
        }
        // closing of load complete events
        $out .= "}";
        // closing of param list
        $out .= "}";
        // Navigational grid params
        if (!isset($this->navgrid["param"])) {
            $this->navgrid["param"]["edit"] = $this->actions["edit"] === false ? false : true;
            $this->navgrid["param"]["add"] = $this->actions["add"] === false ? false : true;
            $this->navgrid["param"]["del"] = $this->actions["delete"] === false ? false : true;
            $this->navgrid["param"]["view"] = $this->actions["view"] === true ? true : false;
            $this->navgrid["param"]["refresh"] = $this->actions["refresh"] === false ? false : true;
            ### P ### -- turn false
            $this->navgrid["param"]["search"] = $this->actions["search"] === false ? false : true;
            // fix for del and delete text
            if (!empty($this->navgrid["param"]["delete"])) {
                $this->navgrid["param"]["del"] = $this->navgrid["param"]["delete"];
            }
        }
        // Generate HTML/JS code
        ob_start();
        ?>
			<table id="<?php 
        echo $grid_id;
        ?>
"></table> 
			<div id="<?php 
        echo $grid_id . "_pager";
        ?>
"></div> 
			<script>
			var phpgrid = jQuery("#<?php 
        echo $grid_id;
        ?>
");
			var phpgrid_pager = jQuery("#<?php 
        echo $grid_id . "_pager";
        ?>
");
			var fx_ajax_file_upload;
			var fx_replace_upload;
			var fx_bulk_update;
			var fx_get_dropdown;

			jQuery(document).ready(function(){
				<?php 
        echo $this->render_js($grid_id, $out);
        ?>
			});	

			</script>	
		<?php 
        return ob_get_clean();
    }
Exemplo n.º 6
0
session_cache_expire(30);
//session有效时间为30分钟
$fileName = "/data/htdocs/zhuqingting.dev.com/pc.valsun.cn/html/excel/noCZCatetroy" . date("Y-m-d_H_i_s") . ".xls";
$propertyName = '材质';
$tName = 'pc_archive_property';
$select = 'categoryPath';
$where = "WHERE propertyName='{$propertyName}' group by categoryPath";
$ppList = OmAvailableModel::getTNameList($tName, $select, $where);
$haveCZArr = array();
foreach ($ppList as $value) {
    $haveCZArr[] = $value['categoryPath'];
}
$tName = 'pc_goods_category';
$select = 'path';
$where = "WHERE is_delete=0";
$pathList = OmAvailableModel::getTNameList($tName, $select, $where);
$excel = new ExportDataExcel('file');
$excel->filename = $fileName;
$excel->initialize();
$excel->addRow(array('无材质属性类别'));
foreach ($pathList as $value) {
    $tName = 'pc_goods_category';
    $where = "WHERE path like'{$value['path']}-%' and is_delete=0";
    $count = OmAvailableModel::getTNameCount($tName, $where);
    if (!in_array($value['path'], $haveCZArr) && !$count) {
        $categoryName = getAllCateNameByPath($value['path']);
        $excel->addRow(array($categoryName));
        //echo $value['path']."\n";
    }
}
$excel->finalize();
Exemplo n.º 7
0
 /**
  * ShipfeeQueryAct::actBatchShipfeeQueryImport()
  * 批量运费验证信息导入导出
  * @return array 
  */
 public function actBatchShipfeeQueryImport()
 {
     $data = array();
     $uid = intval($_SESSION[C('USER_AUTH_SYS_ID')]);
     if (isset($_FILES['upfile']) && !empty($_FILES['upfile'])) {
         $fielName = $uid . "_batch_shipfee_" . date('YmdHis') . '_' . rand(1, 3009) . ".xls";
         $fileName = WEB_PATH . 'html/temp/' . $fielName;
         if (move_uploaded_file($_FILES['upfile']['tmp_name'], $fileName)) {
             $filePath = $fileName;
         }
     }
     if (substr($filePath, -3) != 'xls') {
         show_message($this->smarty, "导入的文件名格式错误!", "index.php?mod=shipfeeQuery&act=shipfeeQueryImport");
         @unlink($filePath);
         exit;
     }
     //读取导入文件
     require_once WEB_PATH . "lib/PHPExcel.php";
     //如果读取的表较大,需要调整内存和时间限制
     ini_set('memory_limit', '20M');
     // ini_set('max_execution_time', '2');
     $PHPExcel = new PHPExcel();
     $PHPReader = new PHPExcel_Reader_Excel2007();
     if (!$PHPReader->canRead($filePath)) {
         $PHPReader = new PHPExcel_Reader_Excel5();
         if (!$PHPReader->canRead($filePath)) {
             show_message($this->smarty, "文件内容无法读取!", "index.php?mod=shipfeeQuery&act=shipfeeQueryImport");
             @unlink($filePath);
             exit;
         }
     }
     $PHPExcel = $PHPReader->load($filePath);
     $currentSheet = $PHPExcel->getSheet(0);
     //取得共有多少列,若不使用此静态方法,获得的$col是文件列的最大的英文大写字母
     $cols = PHPExcel_Cell::columnIndexFromString($currentSheet->getHighestColumn());
     $rows = $currentSheet->getHighestRow();
     if ($rows > C('EXCELL_ROWS_MAX')) {
         show_message($this->smarty, "单个EXCELL文件行数超过系统处理最大值: <b>" . C('EXCELL_ROWS_MAX') . "</b> 行!", "index.php?mod=shipfeeQuery&act=shipfeeQueryImport");
         @unlink($filePath);
         exit;
     }
     $row = 1;
     $res = array();
     while (1) {
         $flag = true;
         $rowFlag = true;
         $country = '';
         $weight = 0;
         $tracknum = '';
         $carrier = '';
         $carrierId = 0;
         $fee = 0;
         $totalFee = 0;
         $carrierNew = '';
         $aa = 'A' . $row;
         $bb = 'B' . $row;
         $cc = 'C' . $row;
         $dd = 'D' . $row;
         $ee = 'E' . $row;
         $ff = 'F' . $row;
         $gg = 'G' . $row;
         $country = post_check(trim($currentSheet->getCell($aa)->getValue()));
         $tracknum = post_check(trim($currentSheet->getCell($bb)->getValue()));
         $weight = post_check(trim($currentSheet->getCell($cc)->getValue()));
         $carrier = post_check(trim($currentSheet->getCell($dd)->getValue()));
         $carrierNew = post_check(trim($currentSheet->getCell($ee)->getValue()));
         $totalFee = post_check(trim($currentSheet->getCell($ff)->getValue()));
         $fee = post_check(trim($currentSheet->getCell($gg)->getValue()));
         if (empty($country)) {
             break;
         }
         if ($row == 1) {
             if ($country != '国家' || $tracknum != '挂号条码' || $weight != '重量' || $carrier != '运输方式' || $carrierNew != '最优运输方式' || $totalFee != '总运费' || $fee != '折扣运费') {
                 show_message($this->smarty, '<font color="red">文件导入失败,导入模版内容有误,请勿修改表头</font>', "index.php?mod=shipfeeQuery&act=shipfeeQueryImport");
                 @unlink($filePath);
                 exit;
             }
             $res[] = array("国家", "挂号条码", "重量", "运输方式", "最优运输方式", "总运费", "折扣运费");
         } else {
             if (!empty($tracknum)) {
                 $carrierId = self::getErpCarrierId($carrier);
             }
             if (empty($carrierId)) {
                 $fees = TransOpenApiAct::act_getBestCarrierNew(1, $country, $weight);
             } else {
                 $fees = TransOpenApiAct::act_fixCarrierQueryNew($carrierId, $country, $weight);
             }
             if (empty($fees)) {
                 self::$errMsg .= "运费校验失败:{$carrier}==={$country}==={$weight}!<br/>";
                 $res[] = array($country, $tracknum, $weight, $carrier, '', '', '');
             } else {
                 $fee = $fees['fee'];
                 $totalFee = $fees['totalFee'];
                 $carrierNew = self::getErpCarrierId($fees['carrierId'], true);
                 $res[] = array($country, $tracknum, $weight, $carrier, $carrierNew, $totalFee, $fee);
             }
         }
         $row++;
     }
     $fileName = 'batch_shipfee_infos_' . $uid;
     $fileUrl = WEB_URL . "temp/" . date('Ymd') . "/" . $fileName . ".xls";
     $filePath = WEB_PATH . "html/temp/" . date('Ymd') . "/" . $fileName . ".xls";
     require_once WEB_PATH . "lib/php-export-data.class.php";
     $excel = new ExportDataExcel('file');
     $excel->filename = $filePath;
     $excel->initialize();
     foreach ($res as $row) {
         $excel->addRow($row);
     }
     $excel->finalize();
     unset($res);
     $data['url'] = $fileUrl;
     $data['res'] = self::$errMsg;
     return $data;
 }
Exemplo n.º 8
0
 public function view_ebayStatisticsExport()
 {
     $start = isset($_GET['start']) ? post_check($_GET['start']) : '';
     $end = isset($_GET['end']) ? post_check($_GET['end']) : '';
     $start = strtotime($start);
     $end = strtotime($end);
     //$start	= 1356972800;
     //$end	= 1399972800;
     $where = " where is_delete = 0";
     if ($start != '') {
         $where .= " and feedbacktime >= '{$start}' ";
     }
     if ($end != '') {
         $where .= " and feedbacktime <= '{$end}' ";
     }
     $accAct = new AccountAct();
     $accountList = $accAct->act_getAccountList('account', 'where platformId = 1 and is_delete = 0');
     $FBAct = new EbayFeedbackAct();
     $exporter = new ExportDataExcel("browser", "ebayStatistics_" . date('Y-m-d') . ".xls");
     $exporter->initialize();
     $exporter->addRow(array('eBay帐号', '好评数', '中评数', '差评数', '总评数', '好评率'));
     foreach ($accountList as $k => $v) {
         $account = $v['account'];
         $positive = $FBAct->act_getOrderList('count(*)', " {$where} and account='{$account}' and CommentType='Positive'");
         $positiveTotal = $positive[0]['count(*)'];
         $neutral = $FBAct->act_getOrderList('count(*)', " {$where} and account='{$account}' and CommentType='Neutral'");
         $neutralTotal = $neutral[0]['count(*)'];
         $negative = $FBAct->act_getOrderList('count(*)', " {$where} and account='{$account}' and CommentType='Negative'");
         $negativeTotal = $negative[0]['count(*)'];
         $total = $positiveTotal + $neutralTotal * 0.6 + $negativeTotal;
         $total = round_num($total, 1);
         if ($total != 0) {
             $per_positive = $positiveTotal / $total;
             $per_positive = round_num($per_positive * 100, 2);
             //$per_positive = round_num($positiveTotal * 100,2).'%';
         } else {
             $per_positive = 0;
         }
         $data = array($account, $positiveTotal, $neutralTotal, $negativeTotal, $total, $per_positive);
         $exporter->addRow($data);
     }
     $exporter->finalize();
     exit;
 }
Exemplo n.º 9
0
<?php

require_once '../../admin/functions.php';
require_once 'php-export-data.class.php';
$req = get_param();
list($db_name, $table_name) = null_exit($req, 'db', 'table');
$columns = objects_read($db_name, $table_name, true);
$exporter = new ExportDataExcel('browser', $db_name . '-' . $table_name . '.xls');
$exporter->initialize();
//开始发送表格流数据到浏览器
$has_header = false;
foreach ($columns as $column) {
    if (!$has_header) {
        $exporter->addRow(array_keys($column));
        $has_header = true;
    }
    $datas = array();
    foreach ($column as $key => $val) {
        if (is_array($val)) {
            $unicode_str = json_encode($val);
            $datas[] = decodeUnicode($unicode_str);
        } else {
            $datas[] = $val;
        }
    }
    $exporter->addRow($datas);
}
$exporter->finalize();
//完成页脚,发送剩余数据到浏览器
function decodeUnicode($str)
{
Exemplo n.º 10
0
$propertyName = '材质';
$tName = 'pc_archive_property';
$select = 'id';
$where = "WHERE propertyName='{$propertyName}'";
$ppList = OmAvailableModel::getTNameList($tName, $select, $where);
$czIdArr = array();
foreach ($ppList as $value) {
    $czIdArr[] = $value['id'];
}
$czIdStr = implode(',', $czIdArr);
$tName = 'pc_archive_spu_property_value_relation';
$select = 'spu';
$where = "WHERE propertyId in({$czIdStr})";
$haveCzSpuList = OmAvailableModel::getTNameList($tName, $select, $where);
$haveCzSpuArr = array();
foreach ($haveCzSpuList as $value) {
    $haveCzSpuArr[] = "'" . $value['spu'] . "'";
}
$haveCzSpuStr = implode(',', $haveCzSpuArr);
$tName = 'pc_auto_create_spu';
$select = 'spu';
$where = "WHERE is_delete=0 and isSingSpu=1 and spu not in({$haveCzSpuStr})";
$autoSpuList = OmAvailableModel::getTNameList($tName, $select, $where);
$excel = new ExportDataExcel('file');
$excel->filename = $fileName;
$excel->initialize();
$excel->addRow(array('无材质SPU'));
foreach ($autoSpuList as $value) {
    $excel->addRow(array($value['spu']));
}
$excel->finalize();
Exemplo n.º 11
0
 /**
  * custom_init()
  * 
  * Process booking post data
  * 
  * @param none
  * @return none
  */
 public function custom_init()
 {
     $action = browser_request('action');
     if ($action != '') {
         switch ($action) {
             case 'check_availability':
                 $data = $_POST;
                 push_to_booking_session(array('date_in' => array_data($data, 'date_in', date('Y-m-d')), 'date_out' => array_data($data, 'date_out', add_days_to_date(date('Y-m-d'), 1)), 'no_of_adult' => array_data($data, 'no_of_adult', 1), 'no_of_room' => array_data($data, 'no_of_room', 0), 'type' => 'BOOKING', 'no_of_child' => array_data($data, 'no_of_child', 0)));
                 redirect_by_page_path('rooms');
                 break;
             case 'book_room':
                 $data = $_POST;
                 if (array_data($data, 'room_type_ID', '') == '' || !is_bookable($data['room_type_ID'])) {
                     add_this_notices('error', 'Selected room is Out of Order.');
                     return;
                 }
                 if (is_date_and_room_not_available($data['room_type_ID'], format_db_date($data['date_in']), format_db_date($data['date_out']))) {
                     return;
                 }
                 if (!has_sufficient_room($data)) {
                     return;
                 }
                 $nights = count_nights($data['date_in'], $data['date_out']);
                 $room_price = get_room_price_with_nights($data['room_type_ID'], $data['date_in'], $data['date_out']);
                 $total_amount = calculate_total_amount($data['room_type_ID'], $data['date_in'], $data['date_out'], $data['no_of_room']);
                 push_to_booking_session(array('date_in' => $data['date_in'], 'date_out' => $data['date_out'], 'no_of_adult' => $data['no_of_adult'], 'no_of_child' => array_data($data, 'no_of_child', 0), 'room_type_ID' => $data['room_type_ID'], 'no_of_night' => $nights, 'no_of_room' => $data['no_of_room'], 'room_price' => $room_price, 'amount' => $total_amount, 'booking_ID' => 0, 'amount_paid' => 0, 'payment_status' => PAYMENT_DEFAULT_STATUS, 'booking_status' => BOOKING_DEFAULT_STATUS));
                 redirect_by_page_path('review');
                 break;
             case 'make_reservation':
                 if (is_empty_booking()) {
                     add_this_notices('error', 'Please select date.');
                     redirect_by_page_path('/');
                     return;
                 }
                 $data = get_booking_session();
                 if (!is_bookable($data['room_type_ID'])) {
                     add_this_notices('error', 'Selected room is Out of Order.');
                     return;
                 }
                 $data = push_to_booking_session(array_merge($data, $_POST, array('date_booked' => date('Y-m-d H:i:s'))));
                 if ($this->process($data)) {
                     redirect_by_page_path('success');
                 }
                 break;
             case 'save_booking':
                 if (isset($_POST['save_booking_field']) && wp_verify_nonce($_POST['save_booking_field'], 'save_booking_action')) {
                     $info = get_booking_by_id(browser_request('bid', 0));
                     $post = array_merge((array) $info, $_POST);
                     $post['no_of_night'] = count_nights($post['date_in'], $post['date_out']);
                     $post['room_price'] = get_room_price_with_nights($post['room_type_ID'], $post['date_in'], $post['date_out']);
                     $post['amount'] = calculate_total_amount($post['room_type_ID'], $post['date_in'], $post['date_out'], $post['no_of_room']);
                     $post['date_booked'] = array_data($info, 'date_booked', date('Y-m-d H:i:s'));
                     $post['type'] = 'RESERVATION';
                     $post['room_code'] = room_code($post['room_type_ID']);
                     if (($bid = $this->process($post)) != false) {
                         exit(wp_redirect('admin.php?page=edit-booking&bid=' . $bid));
                     }
                 }
                 break;
             case 'export-bookings':
                 $results = get_bookings_for_export();
                 // When executed in a browser, this script will prompt for download
                 // of 'test.xls' which can then be opened by Excel or OpenOffice.
                 require_class('php-export-data.class.php');
                 // 'browser' tells the library to stream the data directly to the browser.
                 // other options are 'file' or 'string'
                 // 'test.xls' is the filename that the browser will use when attempting to
                 // save the download
                 $exporter = new ExportDataExcel('browser', 'reports.xls');
                 $exporter->initialize();
                 // starts streaming data to web browser
                 $exporter->addRow(array('BOOKING NO', 'ROOM TYPE', 'ROOM PRICE', 'CHECK IN', 'CHECK OUT', 'NO OF NIGHTS', 'NO OF ROOMS', 'TOTAL AMOUNT', 'AMOUNT PAID', 'NO OF ADULT', 'NO OF CHILD', 'BOOKED BY', 'BIRTHDATE', 'EMAIL ADDRESS', 'PHONE', 'COUNTRY', 'ADDRESS 1', 'ADDRESS 2', 'PROVINCE', 'CITY', 'ZIPCODE', 'NATIONALITY', 'BOOKING STATUS', 'PAYMENT STATUS', 'DATE BOOKED'));
                 foreach ($results as $i => $r) {
                     // pass addRow() an array and it converts it to Excel XML format and sends
                     // it to the browser
                     $exporter->addRow($r);
                 }
                 $exporter->finalize();
                 // writes the footer, flushes remaining data to browser.
                 exit;
                 // all done
                 break;
         }
     }
 }
Exemplo n.º 12
0
 /**
  * PrintLabelAct::act_export()
  * 报表导出
  * @author Gary
  * @return void
  */
 function act_export()
 {
     $printer = intval(trim($_GET['checkUser']));
     $sku = trim($_GET['sku']);
     $startdate = trim($_GET['startdate']);
     $enddate = trim($_GET['enddate']);
     if (empty($checkUser) && empty($sku) && empty($startdate) && empty($enddate)) {
         echo "请选择导出条件";
         exit;
     }
     $lists = printLabelModel::getExportData($printer, $sku, $startdate, $enddate);
     $excel = new ExportDataExcel('browser', "PrintLabelData " . $startdate . '--' . $enddate . ".xls");
     $excel->initialize();
     $tharr = array("打标人", "SKU", "打标数量", '打印状态', "打标时间", "贴标人员", "贴标数量");
     $excel->addRow($tharr);
     foreach ($lists as $list) {
         $user = getUserNameById($list['printerId']);
         $sku = $list['sku'];
         $num = $list['printNum'];
         $status = $list['status'] == 1 ? '已确认' : '未确认';
         $printTime = date('Y-m-d H:i:s', $list['printTime']);
         $labelUser = $list['labelUserId'] ? getUserNameById($list['labelUserId']) : '无';
         $labelNum = $list['labelNum'] ? $list['labelNum'] : '无';
         $tdarr = array($user, $sku, $num, $status, $printTime, $labelUser, $labelNum);
         $excel->addRow($tdarr);
     }
     $excel->finalize();
     exit;
 }
<?php

require "../php-export-data.class.php";
$excel = new ExportDataExcel('browser');
$excel->filename = "test.xml";
$data = array(array(1, 2, 3), array("asdf", "jkl", "semi"), array("1273623874628374634876", "=asdf", "10-10"), array("2010-01-02 10:00AM", "1/1/11", "10-10"), array("1234", "12.34", "-123."), array("-12345678901234567890", "0.0000000000123456789", "-"));
$excel->initialize();
foreach ($data as $row) {
    $excel->addRow($row);
}
$excel->finalize();
Exemplo n.º 14
0
<?php

// When executed in a browser, this script will prompt for download
// of 'test.xls' which can then be opened by Excel or OpenOffice.
require 'php-export-data.class.php';
$username = "******";
$password = "******";
$database = "cpa_trial";
mysql_connect('192.168.0.5', $username, $password);
@mysql_select_db($database) or die("Unable to select database");
$query = "SELECT * FROM testval";
$result = mysql_query($query);
$num = mysql_numrows($result);
mysql_close();
$exporter = new ExportDataExcel('browser', 'temp_data.xls');
$exporter->initialize();
// starts streaming data to web browser
// pass addRow() an array and it converts it to Excel XML format and sends
// it to the browser
$exporter->addRow(array("Timestamp", "Temperature 1", "Temperature 2", "Temperature 3", "Temperature 4", "PWM 1", "PWM 2", "PWM 3", "PWM 4"));
$i = 0;
while ($i < $num) {
    $datetime = mysql_result($result, $i, "datetime");
    $t1 = mysql_result($result, $i, "t1");
    $t2 = mysql_result($result, $i, "t2");
    $t3 = mysql_result($result, $i, "t3");
    $t4 = mysql_result($result, $i, "t4");
    $pwm1 = mysql_result($result, $i, "pwm1");
    $pwm2 = mysql_result($result, $i, "pwm2");
    $pwm3 = mysql_result($result, $i, "pwm3");
    $pwm4 = mysql_result($result, $i, "pwm4");
Exemplo n.º 15
0
 public function view_exportsToXls3()
 {
     error_reporting(E_ALL);
     $type = isset($_GET['type']) ? $_GET['type'] : "";
     $order = isset($_GET['order']) ? $_GET['order'] : "";
     //echo typeof();
     if ($type == 1) {
         $arr = explode(",", $order);
         $ostatus = $arr[0];
         $otype = $arr[1];
         $where = "where da.orderStatus='{$ostatus}' and da.orderType='{$otype}' and da.is_delete=0";
     } elseif ($type == 2) {
         $where = "where da.id in({$order})";
     }
     //
     $orderarr = OrderindexModel::showSearchOrderList("om_unshipped_order", $where);
     //echo "<pre>"; print_r($orderarr[98]);exit;
     $exporter = new ExportDataExcel("browser", "xls3" . $date . ".xls");
     $exporter->initialize();
     // starts streaming data to web browser
     $exporter->addRow(array("SKU编号", "商品中文名称", "商品英文名称", "重量(3位小数)", "报关价格(整数)", "原寄地", "保存至系统SKU"));
     foreach ($orderarr as $id => $order) {
         foreach ($order['orderDetail'] as $key => $value) {
             //$goods = exportsToXlsModel::getGoods($value['orderDetailData']['sku']);
             $goods = GoodsModel::getSkuList($value['orderDetailData']['sku']);
             //print_r($goods);
             $exporter->addRow(array($value['orderDetailData']['sku'], $goods['goodsName'], $value['orderDetailExtenData']['itemTitle'], $goods['goodsWeight'], "3", "CN", "1"));
         }
     }
     $exporter->finalize();
     // writes the footer, flushes remaining data to browser.
     exit;
 }
Exemplo n.º 16
0
 public function act_export()
 {
     $checkUser = $_GET['checkUser'];
     $status = $_GET['status'];
     $sku = $_GET['sku'];
     $startdate = $_GET['startdate'];
     $enddate = $_GET['enddate'];
     if (empty($checkUser) && empty($status) && empty($sku) && empty($startdate) && empty($enddate)) {
         echo "请选择导出条件";
         exit;
     }
     if (!empty($checkUser)) {
         $where[] = "a.labelUserId='{$checkUser}'";
     }
     if (!empty($status)) {
         if ($status == 1) {
             $where[] = "a.labelUserId is NULL";
         }
         if ($status == 2) {
             $where[] = "a.labelUserId is not NULL";
         }
     }
     if (!empty($sku)) {
         $where[] = "b.sku = '{$sku}'";
     }
     if (!empty($startdate)) {
         $start = strtotime($startdate);
         $where[] = "a.labelTime >={$start}";
     }
     if (!empty($enddate)) {
         $end = strtotime($enddate);
         $where[] = "a.labelTime <={$end}";
     }
     $where = implode(" AND ", $where);
     $where = " where a.is_delete=0 and a.status=1 and " . $where . " order by a.id desc";
     $lists = PasteLabelModel::selectList($where);
     $excel = new ExportDataExcel('browser', "labelKpiExport" . date('Y-m-d') . ".xls");
     $excel->initialize();
     $tharr = array("贴标人", "贴标时间", "SKU", "数量", "分组号", "批次号");
     $excel->addRow($tharr);
     foreach ($lists as $list) {
         if (!empty($list['labelUserId'])) {
             $user = getUserNameById($list['labelUserId']);
             $time = date('Y-m-d H:i:s', $list['labelTime']);
         } else {
             $user = '';
             $time = '';
         }
         $sku = $list['sku'];
         $num = $list['labelNum'];
         $id = $list['id'];
         $batchNum = $list['batchNum'];
         $tdarr = array($user, $time, $sku, $num, $id, $batchNum);
         $excel->addRow($tdarr);
     }
     $excel->finalize();
     exit;
 }
require_once "/data/web/pc.valsun.cn/lib/php-export-data.class.php";
Core::getInstance();
session_start();
header("Content-type:text/html;charset=utf-8");
date_default_timezone_set("Asia/Shanghai");
session_cache_expire(30);
//session有效时间为30分钟
error_reporting(E_ALL);
$startTime = date('Y-m-d H:i:s');
//开始时间
echo "程序开始运行时间:{$startTime} \n";
$tName = 'pc_auto_create_spu';
$select = 'spu';
$where = "WHERE is_delete=0 AND isSingSpu=1";
$autoCreateSpuList = OmAvailableModel::getTNameList($tName, $select, $where);
$excel = new ExportDataExcel('file');
$excel->filename = "/data/web/pc.valsun.cn/html/excel/spuSalersInfo" . ".xls";
$excel->initialize();
$tableHeader = array('SPU', 'SKU', '真实料号信息', '类别', '状态', '采购', '组合人', '网页制作人', 'ebay销售', '接手时间', 'SMT销售', '接手时间', 'AM销售', '接手时间', '海外仓销售', '接手时间');
$excel->addRow($tableHeader);
//$totalRows= array();
$i = 1;
foreach ($autoCreateSpuList as $value1) {
    $spu = $value1['spu'];
    $tName = 'pc_spu_saler_single';
    $select = 'platformId,salerId,isHandsOn,addTime';
    $where = "WHERE is_delete=0 AND spu='{$spu}'";
    $singleSpuSalerList = OmAvailableModel::getTNameList($tName, $select, $where);
    $tName = 'pc_spu_web_maker';
    $select = 'webMakerId,isAgree';
    $where = "WHERE is_delete=0 AND spu='{$spu}' order by id desc limit 1";
Exemplo n.º 18
0
 function act_packageOrderRecord()
 {
     error_reporting(E_ALL);
     header("Content-type:text/html;charset=utf-8");
     $start = isset($_POST['start4']) ? trim($_POST['start4']) : "";
     $end = isset($_POST['end4']) ? trim($_POST['end4']) : "";
     $date = $start . "————" . $end;
     $flat = array("中国邮政平邮", "香港小包平邮");
     $regiest = array("中国邮政挂号", "香港小包挂号", "EUB", "UPS美国专线", "Global Mail", "德国邮政挂号", "新加坡小包挂号");
     //$fastmail = "快递";
     $info = array("simple*flat" => array("0-1000" => 1, "1001-2000" => 2), "multi*flat" => array("0-200" => 1, "201-1000" => 2, "1001-2000" => 2.5), "many*flat" => array("0-200" => 1, "201-1000" => 2.2, "1001-2000" => 3.2), "simple*regiest" => array("0-1000" => 1.3, "1001-2000" => 2.5), "multi*regiest" => array("0-200" => 1.2, "201-1000" => 2, "1001-2000" => 3), "many*regiest" => array("0-200" => 1.2, "201-1000" => 2.5, "1001-2000" => 3.5));
     $orderlist = KpiListModel::getOrderList($start, $end);
     $exporter = new ExportDataExcel("browser", "packageOrderRecord" . $date . ".xls");
     $exporter->initialize();
     // starts streaming data to web browser
     $exporter->addRow(array("日期", "订单编号", "料号", "数量", "重量", "仓位号", "国家", "包裹总价值", "币种", "挂号条码", "邮费", "运输方式", "包装员", "包装折算数量", "复核时间"));
     $idarr = array();
     foreach ($orderlist as $key => $order) {
         if (in_array($order['ebay_id'], $idarr)) {
             continue;
         } else {
             $idarr[] = $order['ebay_id'];
         }
         $ebay_id = $order['ebay_id'];
         //$ebay_ordersn = $order['ebay_ordersn'];
         $scantime = empty($order['scantime']) ? "" : date("Y-m-d", $order['scantime']);
         $sctime = empty($order['scantime']) ? "" : date("Y-m-d H:i:s", $order['scantime']);
         //$order = KpiListModel::selectOrder($ebay_id);
         $ebay_ordersn = $order['ebay_ordersn'];
         $packager = $order['packagingstaff'];
         $detaillist = KpiListModel::getOrderDetailList($ebay_ordersn);
         if (count($detaillist) == 1 && $detaillist[0]['ebay_amount'] == 1) {
             $msg = "simple";
         } elseif (count($detaillist) == 1 && $detaillist[0]['ebay_amount'] > 1) {
             $msg = "multi";
         } elseif (count($detaillist) > 1) {
             $msg = "many";
         }
         if (in_array($order['ebay_carrier'], $flat)) {
             $carrier_msg = "flat";
         } elseif (in_array($order['ebay_carrier'], $regiest)) {
             $carrier_msg = "regiest";
         } else {
             $carrier_msg = "快递";
         }
         $type = array();
         if ($carrier_msg !== "快递") {
             $info_msg = $msg . "*" . $carrier_msg;
             foreach ($info[$info_msg] as $key_msg => $value_msg) {
                 $weight = explode("-", $key_msg);
                 if ($order['orderweight2'] >= $weight[0] && $order['orderweight2'] <= $weight[1]) {
                     $num2 = $value_msg;
                 }
             }
         } else {
             $num2 = 50;
         }
         if (count($detaillist) == 1) {
             $exporter->addRow(array($scantime, $ebay_id, $detaillist[0]['sku'], $detaillist[0]['ebay_amount'], $order['orderweight2'], $detaillist[0]['goods_location'], $order['ebay_countryname'], $order['ebay_total'], $order['ebay_currency'], $order['ebay_tracknumber'], $order['ordershipfee'], $order['ebay_carrier'], $packager, $num2, $sctime));
         } else {
             $amount = 0;
             foreach ($detaillist as $detail) {
                 $amount += $detail['ebay_amount'];
             }
             $exporter->addRow(array($scantime, $ebay_id, "", $amount, $order['orderweight2'], "", $order['ebay_countryname'], $order['ebay_total'], $order['ebay_currency'], $order['ebay_tracknumber'], $order['ordershipfee'], $order['ebay_carrier'], $packager, $num2, $sctime));
             foreach ($detaillist as $orderdetail) {
                 $exporter->addRow(array("", $ebay_id, $orderdetail['sku'], $orderdetail['ebay_amount'], "", $orderdetail['goods_location'], $order['ebay_countryname'], "", "", "", "", $order['ebay_carrier'], "", "", ""));
             }
         }
     }
     $exporter->finalize();
     // writes the footer, flushes remaining data to browser.
     exit;
 }
Exemplo n.º 19
0
 public function act_export()
 {
     $checkUser = $_GET['checkUser'];
     $sku = $_GET['sku'];
     $startdate = $_GET['startdate'];
     $enddate = $_GET['enddate'];
     if (empty($checkUser) && empty($sku) && empty($startdate) && empty($enddate)) {
         echo "请选择导出条件";
         exit;
     }
     if (!empty($checkUser)) {
         $where[] = "tallyUserId='{$checkUser}'";
     }
     if (!empty($sku)) {
         $where[] = "sku = '{$sku}'";
     }
     if (!empty($startdate)) {
         $start = strtotime($startdate);
         $where[] = "entryTime >{$start}";
     }
     if (!empty($enddate)) {
         $end = strtotime($enddate);
         $where[] = "entryTime <{$end}";
     }
     $where = implode(" AND ", $where);
     $where = " where is_delete=0 and entryStatus=0 and " . $where;
     $lists = packageCheckModel::selectList($where);
     $excel = new ExportDataExcel('browser', "pointKpiExport" . date('Y-m-d') . ".xls");
     $excel->initialize();
     /** edit by Gary**/
     $tharr = array("点货人", "点货时间", "SKU", "数量", "良品数", "上架数", "批次号", '打标时间', '贴标时间', '检测时间', '上架时间', '备注');
     $excel->addRow($tharr);
     foreach ($lists as $list) {
         $user = getUserNameById($list['tallyUserId']);
         $time = date('Y-m-d H:i:s', $list['entryTime']);
         $sku = $list['sku'];
         $num = $list['num'];
         $ichibanNums = $list['ichibanNums'];
         $shelvesNums = $list['shelvesNums'];
         $batchNum = $list['batchNum'];
         //新增打标、贴标、检测、上架时间
         $printTime = $list['printTime'] ? date('Y-m-d H:i:s', $list['printTime']) : '无';
         $pasteTime = getSkuTime(array('type' => 'paste', 'tallyList' => $list['id']));
         $checkTime = $list['ichibanTime'] ? date('Y-m-d H:i:s', $list['ichibanTime']) : '无';
         $inputArray = array('type' => 'input', 'sku' => $list['sku'], 'finishTime' => $list['finishTime'], 'shelvesNums' => $list['shelvesNums']);
         $inputTime = getSkuTime($inputArray);
         $tdarr = array($user, $time, $sku, $num, $ichibanNums, $shelvesNums, $batchNum, $printTime, $pasteTime, $checkTime, $inputTime, $list['note']);
         /** end**/
         $excel->addRow($tdarr);
     }
     $excel->finalize();
     exit;
 }
Exemplo n.º 20
0
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('E1','采购');
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('F1','产品重量');
//$objPHPExcel->setActiveSheetIndex(0)->setCellValue('G1','采购助理');   新系统废弃字段
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('G1','仓位号');
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('H1','实际库存');
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('I1','产品类别');
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('J1','存货位');
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('K1','成本核算价');
// LIMIT 1,10
$row  = 2;*/
mysql_query('SET NAMES UTF8');
$exportSql = "SELECT a.spu, a.sku, a.goodsName, a.goodsCost, a.purchaseId, a.goodsWeight, c.pName, b.nums,a.goodsCategory,\n                c.type, a.checkCost  FROM `pc_goods` a LEFT JOIN wh_product_position_relation b \n                ON a.id = b.pId AND b.is_delete =0 LEFT JOIN wh_position_distribution c \n                ON c.id = b.positionId WHERE a.is_delete =0 ORDER BY a.id ASC";
$exportSql = $dbConn->query($exportSql);
$exportSql = $dbConn->fetch_array_all($exportSql);
//print_r($exportSql);exit;
$excel = new ExportDataExcel('file', 'priceInfo_' . date('Y-n-j') . '_' . date('Y-n-j') . '.xls');
//实例化excel类
$excel->initialize();
$tharr = array('主料号', '料号', '产品描述', '现行单价', '采购', '产品重量', '仓位号', '实际库存', '产品类别', '存货位', '成本核算价');
$excel->addRow($tharr);
foreach ($exportSql as $priceInfo) {
    $spu = $priceInfo['spu'];
    //主料号
    $sku = $priceInfo['sku'];
    //料号
    $goodsName = $priceInfo['goodsName'];
    //产品描述
    $goodsCost = $priceInfo['goodsCost'];
    //现行单价
    //获取采购人名称
    $usermodel = UserModel::getInstance();
Exemplo n.º 21
0
 /**
  * TrackWarnExportModel::exportXls()
  * 导出xls文件
  * @param array $res 结果值
  * @return string 文件路径
  */
 private function exportXls($tharr, $res)
 {
     $data = array();
     $tdarr = array();
     $dates = array();
     $pos = array();
     $filename = 'track_number_info_' . date('Y-m-d', time()) . '_' . $_SESSION[C('USER_AUTH_SYS_ID')];
     $statusList = C('TRACK_STATUS_DETAIL');
     $fileurl = WEB_URL . "temp/" . $filename . ".xls";
     $filepath = WEB_PATH . "html/temp/" . $filename . ".xls";
     array_push($data, $tharr);
     foreach ($res as $v) {
         $nodeList = TransOpenApiModel::getTrackNodeList($v['carrierId'], $v['channelId']);
         $detail = TransOpenApiModel::getTrackInfoLocal($v['trackNumber'], $v['carrierId']);
         $i = 0;
         foreach ($nodeList as $n) {
             foreach ($detail as $val) {
                 $keys = explode(" ", $n['nodeKey']);
                 foreach ($keys as $key) {
                     if (strpos($val['event'], $key) !== false && !in_array($val['event'], array('未妥投'))) {
                         $dates[$i] = !empty($val['trackTime']) ? date('Y-m-d H:i:s', $val['trackTime']) : '';
                         $pos[$i] = $val['postion'];
                         break;
                     }
                 }
             }
             $i++;
         }
         $tdarr = array($v['carrierNameCn'], $v['channelName'], $v['orderSn'], $v['recordId'], $v['trackNumber'], $v['weight'], $v['cost'], date('Y-m-d H:i:s', $v['scanTime']), $v['toCountry'], $v['lastEvent'], $v['lastPostion'], date('Y-m-d H:i:s', $v['lastTime']), $statusList[$v['status']], $dates[0], $pos[0], $dates[1], $pos[1], $dates[2], $pos[2], $v['platAccount'], $v['platForm']);
         array_push($data, $tdarr);
     }
     require_once WEB_PATH . "lib/php-export-data.class.php";
     $excel = new ExportDataExcel('file');
     $excel->filename = $filepath;
     $excel->initialize();
     foreach ($data as $row) {
         $excel->addRow($row);
     }
     $excel->finalize();
     unset($data);
     if (file_exists($filepath)) {
         return $fileurl;
     } else {
         return "fail";
     }
 }
Exemplo n.º 22
0
<?php

require 'php-export-data.class.php';
$filename = uniqid(rand(), true) . '.xls';
$exporter = new ExportDataExcel('string');
$exporter->initialize();
$exporter->addRow(array('Input', 'Value'));
$exporter->addRow(array('School name', $_POST['schoolname']));
$exporter->addRow(array('Name of teacher', $_POST['moderatorname']));
$exporter->addRow(array('Number', $_POST['number']));
$exporter->addRow(array('Email', $_POST['email']));
for ($i = 1; $i <= 34; $i++) {
    $participant = array('Participant ' . $i, $_POST['participant' . $i]);
    $exporter->addRow($participant);
}
$tmpfile = fopen("register_xls/" . $filename, "w");
fwrite($tmpfile, $exporter->getString());
fclose($tmpfile);
$exporter->finalize();
$url = 'https://api.sendgrid.com/';
$user = '******';
$pass = '******';
$filePath = 'register_xls';
$params = array('api_user' => $user, 'api_key' => $pass, 'to' => '*****@*****.**', 'cc' => '*****@*****.**', 'subject' => 'New register from page', 'html' => 'XLS file attached.', 'text' => 'XLS file attached.', 'from' => '*****@*****.**', 'files[' . $filename . ']' => '@' . $filePath . '/' . $filename);
$request = $url . 'api/mail.send.json';
$session = curl_init($request);
curl_setopt($session, CURLOPT_POST, true);
curl_setopt($session, CURLOPT_POSTFIELDS, $params);
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
Exemplo n.º 23
0
	                 $form['a'][$r['codice']]['col'] = 'red';
	           } elseif ($magval['q_g']>0) {
	                 $form['chk_on'.$r['codice']] = ' checked ';
	                 $form['a'][$r['codice']]['col'] = '';
	           } else {
	                 $form['chk_on'.$r['codice']] = '';
	                 $form['a'][$r['codice']]['col'] = '';
	           }
	           // Calcolo totale valore giacenza by DF
	           $tot_val_giac += $magval['v_g'];
           }
         }
      }

      
$exporter = new ExportDataExcel('browser', $name_file);

if (isset($form['a'])) {
	$exporter->initialize();
	$exporter->addRow( array( "Categoria", "Codice", "Descrizione","Valore Unitario", "Quantita", "Giac.", "Val Totale", "Alla Data: ". $date ) );
	$elem_n=0;
	
	foreach($form['a'] as $k=>$v) {
		if ($ctrl_cm <> $v['i_g']) {
			$ctrl_cm = $v['i_g'];
		}
		
		$exporter->addRow(
				array(
						$v['g_d'],
						"-$k-",
Exemplo n.º 24
0
 /**
  * WhGoodsAssignAct::export_data()
  * 导出调拨数据 
  * @return void
  */
 public function export_data()
 {
     $ids = trim($_GET['ids']);
     if ($ids) {
         $assignList = WhGoodsAssignModel::getAssignList(" and a.id in ({$ids})", '', '', 'a.id');
         $assign_status = C('assign_status');
         //print_r($assign_status);exit;
         $name = 'assignList' . date('Y-m-d') . ".xls";
         //$name   =   iconv('UTF-8', 'gb2312//ignore', $name);
         $excel = new ExportDataExcel('browser', $name);
         $excel->initialize();
         $tharr = array("调拨单号", "SKU", "产品名称", "转出仓库", "转入仓库", "需求数量", "配货数量", '出库复核数量', '接收数量', '生成人员', '生成时间', '调拨单状态', '状态变更时间');
         $excel->addRow($tharr);
         if (!empty($assignList)) {
             foreach ($assignList as $assign) {
                 $outStore = WarehouseManagementModel::warehouseManagementModelList(" where id = {$assign['outStoreId']}");
                 $outStore = $outStore[0]['whName'];
                 $inStore = WarehouseManagementModel::warehouseManagementModelList(" where id = {$assign['inStoreId']}");
                 $inStore = $inStore[0]['whName'];
                 $maker = getUserNameById($assign['createUid']);
                 $make_date = date('Y-m-d H:i:s', $assign['createTime']);
                 $state_date = date('Y-m-d H:i:s', $assign['statusTime']);
                 $status = $assign_status[$assign['status']];
                 $details = WhGoodsAssignModel::getsAssignListDetail($assign['id']);
                 foreach ($details as $k => $val) {
                     $tdarr = array($k == 0 ? $assign['assignNumber'] : '', $val['sku'], $val['goodsName'], $outStore, $inStore, $val['num'], $val['assignNum'], $val['outCheckNum'], $val['inCheckNum'], $k == 0 ? $maker : '', $k == 0 ? $make_date : '', $k == 0 ? $status : '', $k == 0 ? $state_date : '');
                     //print_r($tdarr);exit;
                     $excel->addRow($tdarr);
                 }
             }
         }
         $excel->finalize();
         exit;
     }
 }
Exemplo n.º 25
0
 public function view_excelOutPut()
 {
     require_once WEB_PATH . "lib/php-export-data.class.php";
     //$fileName = "pic".$startTimeDate.'_'.$endTimeDate.".xls";
     $starttime = $_GET['startdate'] ? $_GET['startdate'] : '';
     $endtime = $_GET['enddate'] ? $_GET['enddate'] : "";
     $scanuser = $_GET['scanuser'] ? $_GET['scanuser'] : "";
     $pictype = $_GET['pic_type'];
     $pic_status = $_GET['pic_status'];
     //$auditUser		=	$_GET['userName']?$_GET['userName']:"";
     if (empty($starttime)) {
         $status = "开始时间不能为空";
     }
     if (empty($endtime)) {
         $status = "结束时间不能为空";
     }
     if ($endtime < $starttime) {
         $status = "结束时间不能大于开始时间";
     }
     if (!empty($starttime)) {
         $starttime = strtotime($starttime);
     }
     if (!empty($endtime)) {
         $endtime = strtotime($endtime);
     }
     $pictureAct = new PictureAuditAct();
     $picdata = $pictureAct->act_excelouput($starttime, $endtime, $scanuser, $pictype, $pic_status);
     //var_dump($picdata);exit;
     if ($picdata) {
         $fileName = "picdata_" . date("Y-m-d H:i", time()) . ".xls";
         $excel = new ExportDataExcel('browser', $fileName);
         //$excel = new ExportDataExcel('file', $fileName);
         $excel->initialize();
         $tableHeader = array('订单号', '拍照人', '拍照类型', '状态', '审核人', '拍照时间');
         $excel->addRow($tableHeader);
         //添加表头
         $totalRows = array();
         foreach ($picdata as $row) {
             if ($row['audit_status'] == 0) {
                 $row['audit_status'] = '不合格';
             }
             if ($row['audit_status'] == 1) {
                 $row['audit_status'] = '合格';
             }
             if ($row['picture_type'] == 'fh') {
                 $row['picture_type'] = '复核';
             }
             if ($row['picture_type'] == 'cz') {
                 $row['picture_type'] = '称重';
             }
             $row['scantime'] = date("Y/m/d H:i", "{$row['scantime']}");
             $excel->addRow($row);
         }
         $excel->finalize();
         exit;
         $status = "导出成功";
     } else {
         echo "出错了!";
     }
 }
Exemplo n.º 26
0
 /**
  * 国内-销售报表数据新版导出:
  */
 public function act_InnerSaleData()
 {
     $start = strtotime($_POST['innerSaleStart']);
     $end = strtotime($_POST['innerSaleEnd']);
     $accountIdArr = $_POST['innerSaleAccount'];
     if (empty($accountIdArr)) {
         $statusStr = '账号为空,请选择!';
         echo '<script language="javascript">
                 alert("' . $statusStr . '");
                 history.back();
               </script>';
         exit;
     }
     if ($start >= $end) {
         $statusStr = '起始时间要小于结束时间';
         echo '<script language="javascript">
                 alert("' . $statusStr . '");
                 history.back();
               </script>';
         exit;
     }
     $shipOrderList = $this->act_getfullOrderByaccountNScantime($start, $end, $accountIdArr);
     ############################基础数据##########################################
     $packings = $this->getPmList();
     //包材数组
     $accounts = $this->getAccountList();
     //账号数组
     $carriers = $this->getCarrierList();
     //运输方式数组
     $channels = $this->getChannelLists();
     //渠道数组
     $stores = array(1 => "赛维网络");
     $users = $this->getUserList();
     //用户数组
     $operater = get_usernamebyid(get_userid());
     //统计员
     F('order');
     $fileName = "Inner_Sale_" . date("Y-m-d_H_i_s") . ".xls";
     $excel = new ExportDataExcel('browser', $fileName);
     $excel->initialize();
     $data = array('序号', '交易类型', '订单日期', 'store Name', '订单号', '料号(SKU)', '订单数量(PCS)', '仓位号', '付款币别', '付款账号', 'Transaction ID', '付款金额', '实收金额', '实时汇率', '客户付款运费', '线下批发到账金额', '备注', '客户国家', '客户名称联系地址', 'email地址', '买家note', '发货日期', '货运方式', '货运单号', '重量(Kg)', '系统导出邮费', '修正邮费(RMB)', '备注', '产品进货单价RMB/PCS', '包材费用', '货本', '订单处理成本', '虚拟毛利', '是否合并订单', '是否复制订单', '是否拆分订单', '包装员', '是否发货', '邮寄公司');
     $excel->addRow($data);
     foreach ($shipOrderList as $key => $fullOrderData) {
         /*
          * $value分别有7个对应的键分别为
          * order订单表头数据记录
          * orderExtension//订单表扩展数据记录
          * orderUserInfo//订单表中客户的数据记录
          * orderWarehouse//物料对订单进行操作的数据记录
          * orderNote //订单的备注(销售人员添加)记录
          * orderTracknumber//订单的追踪号记录
          * orderDetail //订单明细记录
          */
         $ordernumber = $key + 1;
         //序号
         $orderData = $fullOrderData['order'];
         // 订单表头数据记录,为一维数组
         $orderExtenData = $fullOrderData['orderExtension'];
         // 扩展表头数据记录,为一维数组
         $orderUserInfoData = $fullOrderData['orderUserInfo'];
         // 订单客户数据记录,为一维数组
         $orderWhInfoData = $fullOrderData['orderWarehouse'];
         // 物料对订单进行操作的数据记录,为一维数组
         $orderNote = $fullOrderData['orderNote'];
         // 订单备注记录,二维数组
         $orderTracknumber = $fullOrderData['orderTracknumber'];
         // 订单跟踪号,一维数组
         $orderDetail = $fullOrderData['orderDetail'];
         // 订单明细记录,三维数组
         $orderId = $orderData['id'];
         // ****订单编号 $ebay_id
         $mailway = "xxxxx";
         // unsure发货分区
         #######################orderData中获取的数据######################################
         $ShippedTime = $orderData['ShippedTime'];
         //发货日期
         $paymentTime = $orderData['paymentTime'];
         //付款时间
         $accountId = $orderData['accountId'];
         //账号
         $accountName = $accounts[$accountId];
         $recordNumber = $orderData['recordNumber'];
         //交易号
         $storeId = $orderData['storeId'];
         //仓位号
         $storeId = $stores[$storeId];
         $currency = $orderData['currency'];
         //币种
         $calcWeight = $orderData['calcWeight'];
         //实际重量
         $calShipping = $orderData['calShipping'];
         //邮费
         $actualTotal = $orderData['actualTotal'];
         //包裹总价值
         $transportId = $orderData['transportId'];
         //运输方式
         $transportName = $carriers['transportId'];
         //$omOrderId            = $orderData['omOrderId'];//订单编号
         $isCopy = $orderData['isCopy'];
         //是否复制订单
         $isSplit = $orderData['isSplit'];
         //是否拆分订单
         $combinePackage = $orderData['combinePackage'];
         //合并包裹
         $pmId = $orderData['pmId'];
         $pmName = $packings[$pmId]['pmName'];
         //包材
         $pmCost = $packings[$pmId]['pmCost'];
         //包材费用
         ######################orderExtenData中获取的数据###################################
         $payPalPaymentId = $orderExtenData['payPalPaymentId'];
         //交易ID
         $PayPalEmailAddress = $orderExtenData['PayPalEmailAddress'];
         //PayPal邮箱
         ######################orderUserInfo中获取的数据######################################
         $E = chr(13);
         $username = $orderUserInfoData['username'];
         //客户ID
         $countryName = $orderUserInfoData['countryName'];
         //国家
         $email = $orderUserInfoData['email'];
         //客户邮箱
         $street = $orderUserInfoData['street'];
         $city = $orderUserInfoData['city'];
         $state = $orderUserInfoData['state'];
         $phone = $orderUserInfoData['phone'];
         $zipCode = $orderUserInfoData['zipCode'];
         $address = $username . $E . $street . $E . $city . $E . $state . $E . $countryName . "{$E} zipcode:{$zipCode} {$E} phone:{$phone}";
         //客户联系地址
         ######unsure################orderTracknumber中获取#################################
         $tracknumber = isset($orderTracknumber['tracknumber']) ? $orderTracknumber['tracknumber'] : "";
         $isOrNo = empty($tracknumber) ? '否' : '是';
         ######################orderDetail中获取的数据#######################################
         $orderDetailNum = count($orderDetail);
         if ($orderDetailNum <= 1) {
             //单料号订单的处理
             foreach ($orderDetail as $key => $value) {
                 $sku = $orderDetail[$key]['orderDetail']['sku'];
                 //料号
                 $amount = $orderDetail[$key]['orderDetail']['amount'];
                 //数量
                 $itemId = $orderDetail[$key]['orderDetail']['itemId'];
                 $itemPrice = $orderDetail[$key]['orderDetail']['itemPrice'];
                 //产品价格
                 $shippingFee = $orderDetail[$key]['orderDetail']['shippingFee'];
                 //ebay运费
                 $note = $orderDetail[$key]['orderDetailExtension']['feedback'];
                 $cphb = $sku * $amount;
                 //产品货本
                 $skuinfo = M('InterfacePc')->getSkuInfo($sku);
                 $isConbime = $skuinfo["isCombine"];
                 //1 组合料号 0 非组合料号
                 if ($isConbime) {
                     $skus = array_keys($skuinfo['skuInfo']);
                     $truesku = implode(",", $skus);
                     //真实料号逗号隔开
                     $cgUser = $skuinfo['skuInfo'][$skus[0]]['skuDetail']['purchaseId'];
                     //unsure采购
                     $cgUser = $users[$cgUser];
                 } else {
                     $truesku = "";
                     //如果不是组号料号这里的真实料号为空
                     $cgUser = $skuinfo['skuInfo'][$sku]['skuDetail']['purchaseId'];
                     //unsure采购
                     $cgUser = $users[$cgUser];
                 }
             }
             $data = array($ordernumber, strpos($recordNumber, 'CYBS') === 0 ? '线下批发' : '线上交易', date('Y/m/d'), $accountName, $recordNumber, $sku, $amount, $storeId, $currency, "", $payPalPaymentId, $actualTotal, " ", "汇率", "", " ", "", $countryName, $address, $email, $note, $ShippedTime, $transportName, $tracknumber, $calcWeight, $calShipping, "", "", "", $pmCost, "", "", "", "", "", "", "", "", "");
             $excel->addRow($data);
         } else {
             //多料号订单的处理
             foreach ($orderDetail as $key => $value) {
                 $sku = $orderDetail[$key]['orderDetail']['sku'];
                 //料号
                 $amount = $orderDetail[$key]['orderDetail']['amount'];
                 //数量
                 $itemId = $orderDetail[$key]['orderDetail']['itemId'];
                 $itemPrice = $orderDetail[$key]['orderDetail']['itemPrice'];
                 //产品价格
                 $shippingFee = $orderDetail[$key]['orderDetail']['shippingFee'];
                 //ebay运费
                 $note = $orderDetail[$key]['orderDetailExtension']['feedback'];
                 $cphb = $sku * $amount;
                 //产品货本
                 $skuinfo = M('InterfacePc')->getSkuInfo($sku);
                 $isConbime = $skuinfo["isCombine"];
                 //1 组合料号 0 非组合料号
                 if ($isConbime) {
                     $skus = array_keys($skuinfo['skuInfo']);
                     $truesku = implode(",", $skus);
                     //真实料号逗号隔开
                     $cgUser = $skuinfo['skuInfo'][$skus[0]]['skuDetail']['purchaseId'];
                     //unsure采购
                     $cgUser = $users[$cgUser];
                 } else {
                     $truesku = "";
                     //如果不是组号料号这里的真实料号为空
                     $cgUser = $skuinfo['skuInfo'][$sku]['skuDetail']['purchaseId'];
                     //unsure采购
                     $cgUser = $users[$cgUser];
                 }
                 $data = array($ordernumber, strpos($recordNumber, 'CYBS') === 0 ? '线下批发' : '线上交易', date('Y/m/d'), $accountName, $recordNumber, $sku, $amount, $storeId, $currency, "", $payPalPaymentId, $actualTotal, " ", "汇率", "", " ", "", $countryName, $address, $email, $note, $ShippedTime, $transportName, $tracknumber, $calcWeight, $calShipping, "", "", "", $pmCost, "", "", "", "", "", "", "", "", "");
                 $excel->addRow($data);
             }
             //end of foreach orderDetail
         }
         //end of else num>1
     }
     //end of foreach shippingOrderList
     $excel->finalize();
     exit;
 }
Exemplo n.º 27
0
<?php

// When executed in a browser, this script will prompt for download
// of 'test.xls' which can then be opened by Excel or OpenOffice.
require 'php-export-data.class.php';
// 'browser' tells the library to stream the data directly to the browser.
// other options are 'file' or 'string'
// 'test.xls' is the filename that the browser will use when attempting to
// save the download
$exporter = new ExportDataExcel('browser', 'test.xls');
$exporter->initialize();
// starts streaming data to web browser
// pass addRow() an array and it converts it to Excel XML format and sends
// it to the browser
$exporter->addRow(array("This", "is", "a", "test"));
$exporter->addRow(array(1, 2, 3, "123-456-7890"));
// doesn't care how many columns you give it
$exporter->addRow(array("foo"));
$exporter->finalize();
// writes the footer, flushes remaining data to browser.
exit;
// all done
Exemplo n.º 28
0
/**
 * 生成xls
 * @param unknown $dir
 * @param unknown $name
 * @param unknown $data
 * by wcx
 */
function write_a_xls($data, $name, $type = "file", $dir = "")
{
    import('Vendor.Export');
    $excel = new \ExportDataExcel($type);
    if (!empty($dir)) {
        mkdirs2($dir);
    } else {
        if ($type == 'file') {
            mkdirs2($dir);
        }
    }
    $excel->filename = $dir . $name;
    $excel->initialize();
    $data = array_values($data);
    foreach ($data as $v) {
        $excel->addRow($v);
    }
    $excel->finalize();
}
Exemplo n.º 29
0
 public function act_export()
 {
     $invPeople = isset($_GET['invPeople']) ? $_GET['invPeople'] : '';
     $sku = isset($_GET['sku']) ? post_check($_GET['sku']) : '';
     $invType = isset($_GET['invType']) ? $_GET['invType'] : '';
     $startdate = isset($_GET['startdate']) ? post_check($_GET['startdate']) : '';
     $enddate = isset($_GET['enddate']) ? post_check($_GET['enddate']) : '';
     $auditStatus = isset($_GET['auditStatus']) ? post_check($_GET['auditStatus']) : '';
     if (empty($invPeople) && empty($sku) && empty($invType) && empty($startdate) && empty($enddate) && empty($auditStatus)) {
         echo "请选择导出条件";
         exit;
     }
     $where = 'where storeId=1 ';
     if ($invPeople) {
         $where .= "and invPeople ='{$invPeople}' ";
     }
     if ($sku) {
         $where .= "and sku ='{$sku}' ";
     }
     if ($invType) {
         $where .= "and invType ='{$invType}' ";
     }
     if ($startdate) {
         $starttime = strtotime($startdate);
         $where .= "and invTime >='{$starttime}' ";
     }
     if ($enddate) {
         $endtime = strtotime($enddate);
         $where .= "and invTime <='{$endtime}' ";
     }
     if ($auditStatus != '' && $auditStatus != 3) {
         $where .= "and auditStatus = {$auditStatus}";
     }
     $lists = InvRecordModel::getInvRecordList('*', $where);
     $excel = new ExportDataExcel('browser', "Files_warehouse" . date('Y-m-d') . ".xls");
     $excel->initialize();
     $tharr = array("日期", "料号", "仓位", "系统数量", "盘点数量", "差异数量", "料号单价", "类型", "盘点原因", "盘点人", "采购员", "物料管理人", "状态", '备注信息');
     $excel->addRow($tharr);
     foreach ($lists as $list) {
         $time = date('Y-m-d', $list['invTime']);
         $sku = $list['sku'];
         $location = $list['location'];
         $systemNums = $list['systemNums'];
         $sku_info = getSkuInfoBySku($list['sku']);
         $goodsCost = $sku_info['goodsCost'];
         $invNums = $list['invNums'];
         if ($list['invType'] == 1) {
             $num = $list['adjustNums'];
             $type = "盘盈";
         } elseif ($list['invType'] == 2) {
             $num = '-' . $list['adjustNums'];
             $type = "盘亏";
         } else {
             $num = $list['adjustNums'];
             $type = "";
         }
         $remark = $list['remark'] ? $list['remark'] : '';
         $reason_info = InvReasonModel::getInvReasonList("reasonName", "where id='{$list['reasonId']}'");
         $reason = $reason_info[0]['reasonName'];
         $invPeople = getUserNameById($list['invPeople']);
         //$sku_info    = getSkuInfoBySku($list['sku']);
         $purchaseName = $sku_info['purchaseId'] ? getUserNameById($sku_info['purchaseId']) : '无';
         $menergeMan = '';
         $mark = '';
         if ($list['auditStatus'] == 0) {
             $mark = '未审核';
         } else {
             if ($list['auditStatus'] == 1) {
                 $mark = '通过';
             } else {
                 if ($list['auditStatus'] == 2) {
                     $mark = '拒绝';
                 }
             }
         }
         $tdarr = array($time, $sku, $location, $systemNums, $invNums, $num, $goodsCost, $type, $reason, $invPeople, $purchaseName, $menergeMan, $mark, $remark);
         $excel->addRow($tdarr);
     }
     $excel->finalize();
     exit;
 }
Exemplo n.º 30
0
 /**
  * excel导出
  */
 function act_exportProductsFinished($select, $where)
 {
     $list = ProductsModel::getProducts($select, $where);
     $fileName = "excel/export_finished" . date("Y-m-d_H_i_s") . ".xls";
     $excel = new ExportDataExcel('file');
     $excel->filename = $fileName;
     $excel->initialize();
     $excel->addRow(array('spu', 'sku', '产品制作状态', '产品待处理类型', '签收人', '签收时间', '领取人', '领取时间', '完成人', '完成时间', '内部归还文员', '内部归还时间', '文员确认收到', '文员确认收到时间', '归还仓库', '归还仓库时间', '产品备注'));
     for ($i = 0; $i < count($list); $i++) {
         if ($list[$i]['productsStatus'] == 1) {
             $productsStatusName = '确认收到料号';
         } elseif ($list[$i]['productsStatus'] == 2) {
             $productsStatusName = '成功领取料号';
         } elseif ($list[$i]['productsStatus'] == 3) {
             $productsStatusName = '完成制作料号';
         } elseif ($list[$i]['productsStatus'] == 4) {
             $productsStatusName = '归还文员料号';
         } elseif ($list[$i]['productsStatus'] == 5) {
             $productsStatusName = '文员确认收到料号';
         } elseif ($list[$i]['productsStatus'] == 6) {
             $productsStatusName = '已归还仓库料号';
         }
         if ($list[$i]['productsType'] == 1) {
             $productsTypeName = '新产品待处理';
         } elseif ($list[$i]['productsType'] == 2) {
             $productsTypeName = '组合产品待处理';
         } elseif ($list[$i]['productsType'] == 3) {
             $productsTypeName = '产品待修改';
         }
         $productsComfirmer = UserModel::getUserNameById($list[$i]['productsComfirmerId']);
         $productsTaker = UserModel::getUserNameById($list[$i]['productsTakerId']);
         $productsCompleter = UserModel::getUserNameById($list[$i]['productsCompleterId']);
         $productsBacker = UserModel::getUserNameById($list[$i]['productsBackerId']);
         $productsReceiver = UserModel::getUserNameById($list[$i]['productsReceiverId']);
         $productsReturner = UserModel::getUserNameById($list[$i]['productsReturnerId']);
         $t_sku = $list[$i]['sku'];
         $spuList = GoodsModel::getGoodsList("spu", "where sku='{$t_sku}'");
         $spu = $spuList[0]['spu'];
         $sku = $list[$i]['sku'];
         $productsStatus = $productsStatusName;
         $productsType = $productsTypeName;
         $productsComfirmerId = $productsComfirmer;
         $productsComfirmTime = !empty($list[$i]['productsComfirmTime']) ? date("Y-m-d H:i:s", $list[$i]['productsComfirmTime']) : '';
         $productsTakerId = $productsTaker;
         $productsTakeTime = !empty($list[$i]['productsTakeTime']) ? date("Y-m-d H:i:s", $list[$i]['productsTakeTime']) : '';
         $productsCompleterId = $productsCompleter;
         $productsCompleteTime = !empty($list[$i]['CompleteTime']) ? date("Y-m-d H:i:s", $list[$i]['CompleteTime']) : '';
         //$productsComleteTime = date("Y-m-d H:i",$list[$i]['productsComleteTime']);
         $productsBackerId = $productsBacker;
         $productsBackTime = !empty($list[$i]['productsBackTime']) ? date("Y-m-d H:i:s", $list[$i]['productsBackTime']) : '';
         $productsReceiverId = $productsReceiver;
         $productsReceiveTime = !empty($list[$i]['productsReceiveTime']) ? date("Y-m-d H:i:s", $list[$i]['productsReceiveTime']) : '';
         $productsReturnerId = $productsReturner;
         $productsReturnTime = !empty($list[$i]['productsReturnTime']) ? date("Y-m-d H:i:s", $list[$i]['productsReturnTime']) : '';
         $productsNote = $list[$i]['productsNote'];
         $row = array($spu, $sku, $productsStatus, $productsType, $productsComfirmerId, $productsComfirmTime, $productsTakerId, $productsTakeTime, $productsCompleterId, $productsCompleteTime, $productsBackerId, $productsBackTime, $productsReceiverId, $productsReceiveTime, $productsReturnerId, $productsReturnTime, $productsNote);
         $excel->addRow($row);
     }
     $excel->finalize();
     return $fileName;
 }