public function index()
 {
     $goods_id = abs(intval($_GET["goods_id"]));
     $craftModel = D("Craft");
     $crafts = $craftModel->order("listorder ASC")->select();
     $model = D("GoodsCraftView");
     $tmp = $model->where("goods_id=" . $goods_id)->order("listorder ASC")->select();
     //        var_dump($tmp);
     //        $model->getLastSql();exit;
     $goodsCrafts = array();
     foreach ($tmp as $k => $v) {
         $goodsCrafts[$v["craft_id"]] = $v;
     }
     //包含所有
     if (!$_GET["only_defined"]) {
         foreach ($crafts as $k => $v) {
             if ($goodsCrafts[$v["id"]]) {
                 continue;
             } else {
                 $v["listorder"] = 0;
                 $goodsCrafts[$v["id"]] = $v;
             }
         }
     }
     $goodsCrafts = reIndex($goodsCrafts);
     $this->response($goodsCrafts);
 }
 public function read()
 {
     if (!$_GET["includeRows"] or $_GET['workflow']) {
         return parent::read();
     }
     $formData = parent::read(true);
     $formData["start_time"] = $formData["start_time"] * 1000;
     $formData["end_time"] = $formData["end_time"] * 1000;
     $rowModel = D("ProducePlanDetailView");
     $rows = $rowModel->where("ProducePlanDetail.plan_id=" . $formData["id"])->select();
     //        echo $rowModel->getLastSql();exit;
     $modelIds = array();
     $rowData = array();
     foreach ($rows as $v) {
         $tmp = explode(DBC("goods.unique.separator"), $v["factory_code_all"]);
         //根据factory_code_all factory_code - standard - version
         $factory_code = array_shift($tmp);
         $modelIds = array_merge($modelIds, $tmp);
         $v["modelIds"] = $tmp;
         $v["stock"] = $v["stock_id"];
         $v["stock_label"] = $v["stock_name"];
         $v["goods_id"] = sprintf("%s_%s_%s", $factory_code, $v["goods_id"], $v["goods_category_id"]);
         // factory_code, id, catid
         $v["goods_id_label"] = sprintf("%s", $v["goods_name"]);
         $rowData[$v["id"]] = $v;
     }
     //        array_flip(array_flip($modelIds));
     $params = array($rowData, $modelIds);
     tag("assign_dataModel_data", $params);
     $formData["rows"] = reIndex($params[0]);
     $this->response($formData);
 }
Example #3
0
 public function index()
 {
     $data = parent::index(true);
     if ($_GET["mergeSameRows"] && $_GET["batch"] === "all") {
         $tmp = array();
         foreach ($data as $row) {
             $k = $row["factory_code_all"] . "|" . $row["repository_id"];
             if (!$tmp[$k]) {
                 $tmp[$k] = $row;
                 $tmp[$k]["stocks"][] = $row["stock_name"];
             } else {
                 $tmp[$k]["num"] += $row["num"];
                 if (!in_array($row["stock_name"], $tmp[$k]["stocks"])) {
                     $tmp[$k]["stocks"][] = $row["stock_name"];
                 }
             }
         }
         foreach ($tmp as $k => $v) {
             $tmp[$k]["stock_name"] = implode(",", $v["stocks"]);
             unset($tmp[$k]["stocks"]);
         }
         $this->response(reIndex($tmp));
     } else {
         $this->response($data);
     }
 }
Example #4
0
 public function read()
 {
     if (!$_GET["includeRows"] or $_GET['workflow']) {
         return parent::read();
     }
     $formData = parent::read(true);
     $formData["inputTime"] = $formData["dateline"] * 1000;
     $rowModel = D("ReturnsDetailView");
     $rows = $rowModel->where("ReturnsDetail.returns_id=" . $formData["id"])->select();
     //        echo $rowModel->getLastSql();exit;
     $modelIds = array();
     $rowData = array();
     foreach ($rows as $v) {
         $tmp = explode(DBC("goods.unique.separator"), $v["factory_code_all"]);
         //根据factory_code_all factory_code - standard - version
         $factory_code = array_shift($tmp);
         $modelIds = array_merge($modelIds, $tmp);
         $v["modelIds"] = $tmp;
         $v["goods_id"] = sprintf("%s_%s_%s", $factory_code, $v["goods_id"], $v["goods_category_id"]);
         // factory_code, id, catid
         $v["goods_id_label"] = sprintf("%s", $v["goods_name"]);
         $v["unit_price"] = $v["price"];
         $v["amount"] = $v["num"];
         $rowData[$v["id"]] = $v;
     }
     //        array_flip(array_flip($modelIds));
     $formData["customer_id_label"] = $formData["customer"];
     $dataModel = D("DataModelDataView");
     $rowData = $dataModel->assignModelData($rowData, $modelIds);
     $formData["rows"] = reIndex($rowData);
     $this->response($formData);
 }
Example #5
0
 public function read()
 {
     if (!$_GET["includeRows"] or $_GET['workflow']) {
         return parent::read();
     }
     //        $this->readModel = "PurchaseView";
     //        $formData = parent::read(true);
     $formData = D("PurchaseView")->find($_GET['id']);
     $formData["inputTime"] = $formData["dateline"] * 1000;
     //        $formData["total_amount"] = $formData["total_price"];
     //        $formData["total_amount_real"] = $formData["total_price_real"];
     //        $formData["total_num"] = $formData["quantity"];
     $rowModel = D("PurchaseDetailView");
     $rows = $rowModel->where("PurchaseDetail.purchase_id=" . $formData["id"])->select();
     //        echo $rowModel->getLastSql();exit;
     $modelIds = array();
     $rowData = array();
     foreach ($rows as $v) {
         $tmp = explode(DBC("goods.unique.separator"), $v["factory_code_all"]);
         //根据factory_code_all factory_code - standard - version
         $factory_code = array_shift($tmp);
         $modelIds = array_merge($modelIds, $tmp);
         $v["modelIds"] = $tmp;
         $v["goods_id"] = sprintf("%s_%s_%s", $factory_code, $v["goods_id"], $v["goods_category_id"]);
         // factory_code, id, catid
         $v["goods_id_label"] = sprintf("%s", $v["goods_name"]);
         //             $v["amount"] = $v["price"];
         $rowData[$v["id"]] = $v;
     }
     //        array_flip(array_flip($modelIds));
     $formData["customer_id_label"] = $formData["customer"];
     $params = array($rowData, $modelIds);
     tag("assign_dataModel_data", $params);
     $formData["rows"] = reIndex($params[0]);
     /*
      * 相关单据
      * **/
     $relateItem = array();
     $id = abs(intval($_GET["id"]));
     if (isAppLoaded("store")) {
         $tmp = D("Stockin")->toRelatedItem("Purchase", $id);
         if ($tmp) {
             $relateItem = array_merge($relateItem, $tmp);
         }
     }
     if (isAppLoaded("finance")) {
         $tmp = D("FinancePayPlan")->toRelatedItem("Purchase", $id);
         if ($tmp) {
             $relateItem = array_merge($relateItem, $tmp);
         }
     }
     if ($formData["source_model"] == "ProducePlan" && $formData["source_id"] && isAppLoaded("produce")) {
         $tmp = D("ProducePlan")->getRelatedItem($formData["source_id"]);
         if ($tmp) {
             $relateItem[] = $tmp;
         }
     }
     $formData["relatedItems"] = $relateItem;
     $this->response($formData);
 }
Example #6
0
 public static function parse($app, $schemas, $tables = "all", $exclude_meta = false)
 {
     $result = array();
     foreach ($schemas as $table => $schema) {
         if (!$table) {
             continue;
         }
         if ($tables !== "all" && !in_array($table, $tables)) {
             continue;
         }
         $fields = array();
         $ignore = array('$meta', 'company', '_trashed', '_rate');
         foreach ($schema as $field => $option) {
             if (in_array($field, $ignore)) {
                 continue;
             }
             $fields[$field] = self::deal_with_field_config($field, (array) $option);
         }
         $meta = $schema['$meta'];
         $meta['list_display'] = array();
         // 处理foreignKey
         foreach ($meta["foreign"] as $foreign_table => $foreign_option) {
             $foreign_field = $foreign_option['foreign_key'] ? $foreign_option['foreign_key'] : $foreign_table . '_id';
             $fields[$foreign_table] = array("map" => $foreign_field, "field" => $foreign_field, "type" => "foreign", "data_source" => $foreign_table);
         }
         //            print_r($fields);exit;
         /*
          * 数据模型字段
          * 会覆盖默认数据表中数据
          * */
         $data_model_service = D("DataModel/DataModelField", "Service");
         $module = sprintf('%s.%s', lcfirst($app), lcfirst(camelCase($table)));
         $extra_fields = $data_model_service->get_fields_by_module($module);
         $efs = array();
         foreach ($extra_fields as $ef) {
             //                $fields[$ef['alias']] = array(
             //                    'label' => $ef['label'],
             //                    'type'  => $ef['data_type'],
             //                    'widget'=> $ef['widget'],
             //                    'value' => $ef['default'],
             //                    'limit' => $ef['limit'],
             //                    'blank' => $ef['blank']
             //                );
             $efs[] = $ef['id'];
             $fields[$field] = self::deal_with_field_config($ef['alias'], (array) $ef);
             //list_display
             if ($ef['list_display']) {
                 $meta['list_display'][] = $ef['alias'];
             }
         }
         if ($efs) {
             $fields['_data_model_fields_'] = array('field' => "_data_model_fields_", 'widget' => 'hidden', 'type' => 'hidden', 'value' => implode(',', $efs), 'required' => false);
         }
         $result[$table] = $meta;
         $result[$table]["structure"] = reIndex($fields);
     }
     return $result;
 }
 public function getStockoutBill($id)
 {
     $data = $this->find($id);
     if (!$data) {
         return false;
     }
     if ($data["source_model"]) {
         $sourceModel = D($data["source_model"] . "View");
         $data["source"] = $sourceModel->find($data["source_id"]);
         if ($_GET["includeRelated"]) {
             try {
                 $model = D($data["source_model"]);
                 $related = $model->getRelatedItem($data["source_id"]);
                 $data["relatedItems"][] = $related;
             } catch (Exception $e) {
             }
         }
         if ($_GET["includeSourceRows"]) {
             $sourceDetailModel = D($data["source_model"] . "Detail");
             $foreignKey = $sourceDetailModel->foreignKey ? $sourceDetailModel->foreignKey : lcfirst($data["source_model"]) . "_id";
             $map[$foreignKey] = $data["source_id"];
             $tmp = $sourceDetailModel->where($map)->select();
             foreach ($tmp as $t) {
                 $data["source_detail"][$t["factory_code_all"]] = $t;
             }
         }
     }
     $detailModel = D("StockoutDetailView");
     $data["rows"] = $detailModel->where("stockout_id=" . $data["id"])->select();
     /**
      * 每列信息处理
      */
     $modelIds = array();
     foreach ($data["rows"] as $k => $v) {
         $tmp = explode(DBC("goods.unique.separator"), $v["factory_code_all"]);
         //根据factory_code_all factory_code - standard - version
         $factory_code = array_shift($tmp);
         $modelIds = array_merge($modelIds, $tmp);
         $v["modelIds"] = $tmp;
         $v["stock"] = $v["stock_id"];
         $v["stock_label"] = $v["stock_name"];
         $v["goods_id"] = sprintf("%s_%s_%s", $factory_code, $v["goods_id"], $v["goods_category_id"]);
         // factory_code, id, catid
         $v["goods_id_label"] = sprintf("%s", $v["goods_name"]);
         $v["total_num"] = $v["num"];
         $v["num"] = $v["num"] - $v["outed"];
         $data["rows"][$k] = $v;
         $fca[] = $v["factory_code_all"];
     }
     $params = array($data["rows"], $modelIds);
     tag("assign_dataModel_data", $params);
     $data["rows"] = reIndex($params[0]);
     //
     //        $dataModel = D("DataModelDataView");
     //        $data["rows"] = $dataModel->assignModelData($data["rows"], $modelIds);
     return $data;
 }
 public function index()
 {
     //获取所有节点
     if (!$_GET["mainrow_id"]) {
         return parent::index();
     }
     //仅获取当前数据的下一ID
     //        $map = array();
     //        $this->_filter($map);
     import("@.Workflow.Workflow");
     $workflow = new Workflow($_GET["workflow_alias"]);
     $process = $workflow->getCurrentProcess($_GET["mainrow_id"]);
     $this->response(reIndex($process["nextNode"]));
 }
 public function get($uid = 0, $reIndex = true)
 {
     $uid = $uid ? $uid : getCurrentUid();
     $data = $this->where("uid=" . $uid)->getField("data");
     $data = json_decode($data, true);
     if (!$data) {
         return array();
     }
     if ($reIndex) {
         $data["blocks"] = reIndex($data["blocks"]);
     }
     $data["btns"] = multi_array_sort($data["btns"], "listorder", SORT_ASC);
     return $data;
 }
Example #10
0
 public function on_list()
 {
     $data = parent::on_list(true);
     $list = $data[1];
     $product_ids = get_array_by_field($list, 'product_id');
     $map = ['product_id' => ['IN', $product_ids]];
     $total_balance = D('Storage/Stock')->field('SUM(balance) as total_balance, product_id, product_unique_id')->where($map)->group('product_unique_id')->select();
     $total_balance = get_array_to_ka($total_balance, 'product_unique_id');
     foreach ($list as $k => $v) {
         if (array_key_exists($v['product_unique_id'], $total_balance)) {
             $list[$k]['total_balance'] = $total_balance[$v['product_unique_id']]['total_balance'];
         }
     }
     $data[1] = reIndex($list);
     $this->response($data, 'stock', true);
 }
Example #11
0
 protected function ForSaleTotal($data, $start, $end, $step, $format = "m-d")
 {
     $dateRange = makeDateRange($start, $end, $step, $format);
     //        print_r($dateRange);exit;
     foreach ($dateRange as $dr) {
         $tmp[$dr]["displayName"] = "销售金额";
         $tmp[$dr]["value"] = 0;
         $tmp[$dr]["label"] = $dr;
         foreach ($data as $v) {
             $key = date($format, $v["dateline"]);
             if ($dr == $key) {
                 $tmp[$dr]["value"] += $v["total_amount_real"];
             }
         }
     }
     foreach ($tmp as $k => $v) {
         $tmp[$k]["value"] = $v["value"];
     }
     return reIndex($tmp);
 }
function AssessAntagonism($checkstr, &$AntagonisticWordsArray)
{
    DebugToLog('DEBUG: Begin func AssessAntagonism');
    $checkstr = str_replace('-', ' ', $checkstr);
    // People use hyphens between words all the time for no good reason. Replace hyphens with spaces.
    $EachWord = str_word_count($checkstr, 1);
    // put all in array, note the '1' parm
    if (!is_array($EachWord)) {
        DebugToLog('DEBUG:  (A1) $EachWord is NOT an array');
        return NULL;
    } else {
        DebugToLog('DEBUG:  (A1) $EachWord IS an array');
    }
    DebugToLog('DUMP: $EachWord' . print_r($EachWord, true));
    DebugToLog('DEBUG: (a9) $EachWord imploded=' . implode(' ', $EachWord));
    DebugToLog('DUMP: $AntagonisticWordsArray' . print_r($AntagonisticWordsArray, true));
    $EachWord = arrayUnique($EachWord);
    // if the antagonistc word  'black' occurrs 6x in text about a  black history, you need to count it only once so as to be conservative in assessing antagonism.
    $EachWord = reIndex(0, $EachWord);
    // this needed? Yes
    $EachWord_cnt = count($EachWord);
    DebugToLog('DEBUG: $EachWord_cnt=' . $EachWord_cnt);
    if (!is_array($EachWord)) {
        DebugToLog('DEBUG: $EachWord is NOT an array');
        return;
        NULL;
    }
    for ($x = 0; $x < $EachWord_cnt; $x++) {
        $y = strlen($EachWord[$x]);
        if ($EachWord[$x][$y - 1] == 's' and $y > 2 and $EachWord[$x][$y - 2] == '\'') {
            $EachWord[$x] = substr($EachWord[$x], 0, $y - 2);
        }
    }
    for ($x = 0; $x < $EachWord_cnt; $x++) {
        $EachWord[$x] = strtolower($EachWord[$x]);
        // so now we have an array of all words in the input string ($checkstr) with possesive 's' removed, all lowercase and recuded to a single instance of each word
    }
    $Antag_cnt = count($AntagonisticWordsArray);
    $TotalAntagonisticWords = 0;
    for ($y = 0; $y < $Antag_cnt; $y++) {
        for ($x = 0; $x < $EachWord_cnt; $x++) {
            // DebugToLog('SUPERDUMP: $EachWord=' . $EachWord[$x]. '  ANTAG singular=' . $AntagonisticWordsArray[$y]['theword'] . '  plural=' . $AntagonisticWordsArray[$y]['plural'] );
            if ($EachWord[$x] != "" and (strtolower($EachWord[$x]) == $AntagonisticWordsArray[$y]['theword'] or strtolower($EachWord[$x]) == $AntagonisticWordsArray[$y]['plural'])) {
                DebugToLog('DUMP: $EachWord' . implode(' ', $EachWord));
                DebugToLog('SUBRULE MATCH: Antagonism match - input string word =' . $EachWord[$x] . '  antagarray =' . $AntagonisticWordsArray[$y]['theword'] . '  plural =' . $AntagonisticWordsArray[$y]['plural']);
                $TotalAntagonisticWords++;
                break;
                // break becuase we only need to match one instance of an antagonistic word
            }
        }
    }
    DebugToLog('DEBUG: $TotalAntagonisticWords= ' . $TotalAntagonisticWords);
    return $TotalAntagonisticWords;
}
Example #13
0
 public function on_list($return = false)
 {
     if ($api_method = $this->api_version_method_exists('on_list')) {
         return $this->{$api_method}($return);
     }
     $extra_method = '_EM_' . I('get._m');
     if (I('get._m') && method_exists($this, $extra_method)) {
         return $this->{$extra_method}($return);
     }
     unset($extra_method);
     // 无ID GET时
     if (in_array($this->_method, array('event_get'))) {
         return $this->on_read();
     }
     $modelName = sprintf("%s/%s", MODULE_NAME, CONTROLLER_NAME);
     $this->_external_action();
     if ($this->breakAction) {
         return;
     }
     if (method_exists($this, "_before_index")) {
         $this->_before_index();
     }
     $modelName = $this->listModel ? $this->listModel : $modelName;
     $model = D($modelName, "Model");
     if (empty($model)) {
         E(__("Server error"));
     }
     //fix non-view model
     if (method_exists($model, 'getProperty') && !$model->getProperty('viewFields')) {
         $viewFields = array();
         $viewFields[CONTROLLER_NAME] = array('*', '_type' => 'left');
         $model->setProperty('viewFields', $viewFields);
     }
     // 查询字段
     if (I('get._fd')) {
         $model = $model->field(I('get._fd'));
     }
     // 前置操作
     $limit = $this->beforeLimit();
     $map = $this->beforeFilter($model);
     $order = $this->beforeOrder($model);
     $this->_filter($map);
     $this->_order($order);
     //仅返回条目数量
     if (I("get._oc")) {
         $total = $model->where($map)->count();
         $this->response(array(array("count" => $total)));
         return;
     } else {
         // 数据模型字段
         if (I('get._df')) {
             $model = $this->assign_data_model_data($modelName, $model, $map);
         }
         $model = $model->where($map)->order($order);
         //AutoComplete字段默认只取10条
         if (isset($_GET['typeahead'])) {
             $limit = 10;
         }
         if (isset($_GET["get.limit"])) {
             $limit = abs(intval(I("get.limit")));
         }
         if ($limit) {
             $model = $model->limit($limit);
         }
         if ($order) {
             $model = $model->order($order);
         }
         $list = $model->select();
         //            echo $model->getLastSql();exit;
         $this->queryMeta = array("map" => $map, "limit" => $limit, "order" => $order);
     }
     $list = reIndex((array) $list);
     $list = !$list[0] ? [] : $list;
     //包含总数
     if (I("get._ic")) {
         $total = $model->where($map)->count();
         $totalPages = ceil($total / I("get._ps"));
         if (!$totalPages) {
             $totalPages = 1;
         }
         $list = Schema::data_format($list, $model);
         $list = reIndex($list);
         $returnData = array(array("count" => $total, "totalPages" => $totalPages), $list);
         if ($return) {
             return $returnData;
         }
         $this->response($returnData);
     } else {
         if ($return) {
             return $list;
         }
         $this->response($list, $model);
     }
 }
Example #14
0
 function Render()
 {
     // get post and get variables
     global $Translation;
     $adminConfig = config('adminConfig');
     $FiltersPerGroup = 4;
     $buttonWholeWidth = 136;
     $current_view = '';
     /* TV, DV, TVDV, TVP, DVP, Filters */
     $Embedded = intval($_REQUEST['Embedded']);
     if ($_SERVER['REQUEST_METHOD'] == 'GET') {
         $SortField = $_GET["SortField"];
         $SortDirection = $_GET["SortDirection"];
         $FirstRecord = $_GET["FirstRecord"];
         $ScrollUp_y = $_GET["ScrollUp_y"];
         $ScrollDn_y = $_GET["ScrollDn_y"];
         $Previous_x = $_GET["Previous_x"];
         $Next_x = $_GET["Next_x"];
         $Filter_x = $_GET["Filter_x"];
         $SaveFilter_x = $_GET["SaveFilter_x"];
         $NoFilter_x = $_GET["NoFilter_x"];
         $CancelFilter = $_GET["CancelFilter"];
         $ApplyFilter = $_GET["ApplyFilter"];
         $Search_x = $_GET["Search_x"];
         $SearchString = get_magic_quotes_gpc() ? stripslashes($_GET['SearchString']) : $_GET['SearchString'];
         $CSV_x = $_GET["CSV_x"];
         $FilterAnd = $_GET["FilterAnd"];
         $FilterField = $_GET["FilterField"];
         $FilterOperator = $_GET["FilterOperator"];
         if (is_array($_GET['FilterValue'])) {
             foreach ($_GET['FilterValue'] as $fvi => $fv) {
                 $FilterValue[$fvi] = get_magic_quotes_gpc() ? stripslashes($fv) : $fv;
             }
         }
         $Print_x = $_GET['Print_x'];
         $PrintTV = $_GET['PrintTV'];
         $PrintDV = $_GET['PrintDV'];
         $SelectedID = get_magic_quotes_gpc() ? stripslashes($_GET['SelectedID']) : $_GET['SelectedID'];
         $insert_x = $_GET['insert_x'];
         $update_x = $_GET['update_x'];
         $delete_x = $_GET['delete_x'];
         $SkipChecks = $_GET['confirmed'];
         $deselect_x = $_GET['deselect_x'];
         $addNew_x = $_GET['addNew_x'];
         $dvprint_x = $_GET['dvprint_x'];
         $DisplayRecords = in_array($_GET['DisplayRecords'], array('user', 'group')) ? $_GET['DisplayRecords'] : 'all';
     } else {
         $SortField = $_POST['SortField'];
         $SortDirection = $_POST['SortDirection'];
         $FirstRecord = $_POST['FirstRecord'];
         $ScrollUp_y = $_POST['ScrollUp_y'];
         $ScrollDn_y = $_POST['ScrollDn_y'];
         $Previous_x = $_POST['Previous_x'];
         $Next_x = $_POST['Next_x'];
         $Filter_x = $_POST['Filter_x'];
         $SaveFilter_x = $_POST['SaveFilter_x'];
         $NoFilter_x = $_POST['NoFilter_x'];
         $CancelFilter = $_POST['CancelFilter'];
         $ApplyFilter = $_POST['ApplyFilter'];
         $Search_x = $_POST['Search_x'];
         $SearchString = get_magic_quotes_gpc() ? stripslashes($_POST['SearchString']) : $_POST['SearchString'];
         $CSV_x = $_POST['CSV_x'];
         $FilterAnd = $_POST['FilterAnd'];
         $FilterField = $_POST['FilterField'];
         $FilterOperator = $_POST['FilterOperator'];
         if (is_array($_POST['FilterValue'])) {
             foreach ($_POST['FilterValue'] as $fvi => $fv) {
                 $FilterValue[$fvi] = get_magic_quotes_gpc() ? stripslashes($fv) : $fv;
             }
         }
         $Print_x = $_POST['Print_x'];
         $PrintTV = $_POST['PrintTV'];
         $PrintDV = $_POST['PrintDV'];
         $SelectedID = get_magic_quotes_gpc() ? stripslashes($_POST['SelectedID']) : $_POST['SelectedID'];
         $insert_x = $_POST['insert_x'];
         $update_x = $_POST['update_x'];
         $delete_x = $_POST['delete_x'];
         $SkipChecks = $_POST['confirmed'];
         $deselect_x = $_POST['deselect_x'];
         $addNew_x = $_POST['addNew_x'];
         $dvprint_x = $_POST['dvprint_x'];
         $DisplayRecords = in_array($_POST['DisplayRecords'], array('user', 'group')) ? $_POST['DisplayRecords'] : 'all';
     }
     $mi = getMemberInfo();
     // insure authenticity of user inputs:
     if (is_array($FilterAnd)) {
         foreach ($FilterAnd as $i => $f) {
             if ($f && !preg_match('/^(and|or)$/i', trim($f))) {
                 $FilterAnd[$i] = 'and';
             }
         }
     }
     if (is_array($FilterOperator)) {
         foreach ($FilterOperator as $i => $f) {
             if ($f && !in_array(trim($f), array_keys($GLOBALS['filter_operators']))) {
                 $FilterOperator[$i] = '';
             }
         }
     }
     if (!preg_match('/^\\s*[1-9][0-9]*\\s*(asc|desc)?(\\s*,\\s*[1-9][0-9]*\\s*(asc|desc)?)*$/i', $SortField)) {
         $SortField = '';
     }
     if (!preg_match('/^(asc|desc)$/i', $SortDirection)) {
         $SortDirection = '';
     }
     if (!$this->AllowDelete) {
         $delete_x = '';
     }
     if (!$this->AllowDeleteOfParents) {
         $SkipChecks = '';
     }
     if (!$this->AllowInsert) {
         $insert_x = '';
         $addNew_x = '';
     }
     if (!$this->AllowUpdate) {
         $update_x = '';
     }
     if (!$this->AllowFilters) {
         $Filter_x = '';
     }
     if (!$this->AllowPrinting) {
         $Print_x = '';
         $PrintTV = '';
     }
     if (!$this->QuickSearch) {
         $SearchString = '';
     }
     if (!$this->AllowCSV) {
         $CSV_x = '';
     }
     // enforce record selection if user has edit/delete permissions on the current table
     $AllowPrintDV = 1;
     $this->Permissions = getTablePermissions($this->TableName);
     if ($this->Permissions[3] || $this->Permissions[4]) {
         // current user can edit or delete?
         $this->AllowSelection = 1;
     } elseif (!$this->AllowSelection) {
         $SelectedID = '';
         $AllowPrintDV = 0;
         $PrintDV = '';
     }
     if (!$this->AllowSelection || !$SelectedID) {
         $dvprint_x = '';
     }
     $this->QueryFieldsIndexed = reIndex($this->QueryFieldsFilters);
     // determine type of current view: TV, DV, TVDV, TVP, DVP or Filters?
     if ($this->SeparateDV) {
         $current_view = 'TV';
         if ($Print_x != '' || $PrintTV != '') {
             $current_view = 'TVP';
         } elseif ($dvprint_x != '' || $PrintDV != '') {
             $current_view = 'DVP';
         } elseif ($Filter_x != '') {
             $current_view = 'Filters';
         } elseif ($SelectedID && !$deselect_x && !$delete_x || $addNew_x != '') {
             $current_view = 'DV';
         }
     } else {
         $current_view = 'TVDV';
         if ($Print_x != '' || $PrintTV != '') {
             $current_view = 'TVP';
         } elseif ($dvprint_x != '' || $PrintDV != '') {
             $current_view = 'DVP';
         } elseif ($Filter_x != '') {
             $current_view = 'Filters';
         }
     }
     $this->HTML .= '<div class="row"><div class="col-xs-11 col-md-12">';
     $this->HTML .= '<form ' . (datalist_image_uploads_exist ? 'enctype="multipart/form-data" ' : '') . 'method="post" name="myform" action="' . $this->ScriptFileName . '">';
     if ($Embedded) {
         $this->HTML .= '<input name="Embedded" value="1" type="hidden" />';
     }
     $this->HTML .= '<script>';
     $this->HTML .= 'function enterAction(){';
     $this->HTML .= '   if($$("input[name=SearchString]:focus")[0] != undefined){ $("Search").click(); }';
     $this->HTML .= '   return false;';
     $this->HTML .= '}';
     $this->HTML .= '</script>';
     $this->HTML .= '<input id="EnterAction" type="submit" style="position: absolute; left: 0px; top: -250px;" onclick="return enterAction();">';
     $this->ContentType = 'tableview';
     // default content type
     if ($PrintTV != '') {
         $Print_x = 1;
         $_POST['Print_x'] = 1;
     }
     // handle user commands ...
     if ($deselect_x != '') {
         $SelectedID = '';
         $this->showTV();
     } elseif ($insert_x != '') {
         $SelectedID = call_user_func($this->TableName . '_insert');
         // redirect to a safe url to avoid refreshing and thus
         // insertion of duplicate records.
         $url = $this->RedirectAfterInsert;
         $insert_status = 'record-added-ok=' . rand();
         if (!$SelectedID) {
             $insert_status = 'record-added-error=' . rand();
         }
         // compose filters and sorting
         foreach ($this->filterers as $filterer => $caption) {
             if ($_REQUEST['filterer_' . $filterer] != '') {
                 $filtersGET .= '&filterer_' . $filterer . '=' . urlencode($_REQUEST['filterer_' . $filterer]);
             }
         }
         for ($i = 1; $i <= 20 * $FiltersPerGroup; $i++) {
             // Number of filters allowed
             if ($FilterField[$i] != '' && $FilterOperator[$i] != '' && ($FilterValue[$i] != '' || strpos($FilterOperator[$i], 'empty'))) {
                 $filtersGET .= "&FilterAnd[{$i}]={$FilterAnd[$i]}&FilterField[{$i}]={$FilterField[$i]}&FilterOperator[{$i}]={$FilterOperator[$i]}&FilterValue[{$i}]=" . urlencode($FilterValue[$i]);
             }
         }
         if ($Embedded) {
             $filtersGET .= '&Embedded=1&SelectedID=' . urlencode($SelectedID);
         }
         $filtersGET .= "&SortField={$SortField}&SortDirection={$SortDirection}&FirstRecord={$FirstRecord}";
         $filtersGET .= "&DisplayRecords={$DisplayRecords}";
         $filtersGET .= '&SearchString=' . urlencode($SearchString);
         $filtersGET = substr($filtersGET, 1);
         // remove initial &
         if ($url) {
             /* if designer specified a redirect-after-insert url */
             $url .= (strpos($url, '?') !== false ? '&' : '?') . $insert_status;
             $url .= strpos($url, $this->ScriptFileName) !== false ? "&{$filtersGET}" : '';
             $url = str_replace("#ID#", urlencode($SelectedID), $url);
         } else {
             /* if no redirect-after-insert url, use default */
             $url = "{$this->ScriptFileName}?{$insert_status}&{$filtersGET}";
             /* if DV and TV in same page, select new record */
             if (!$this->SeparateDV) {
                 $url .= '&SelectedID=' . urlencode($SelectedID);
             }
         }
         @header('Location: ' . $url);
         $this->HTML .= "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"0;url=" . $url . "\">";
         return;
     } elseif ($delete_x != '') {
         $d = call_user_func($this->TableName . '_delete', $SelectedID, $this->AllowDeleteOfParents, $SkipChecks);
         // handle ajax delete requests
         if (is_ajax()) {
             die($d ? $d : 'OK');
         }
         if ($d) {
             //$_REQUEST['record-deleted-error'] = 1;
             $this->HTML .= error_message($d);
         } else {
             $_REQUEST['record-deleted-ok'] = 1;
             $SelectedID = '';
             $this->showTV();
         }
     } elseif ($update_x != '') {
         $updated = call_user_func($this->TableName . '_update', $SelectedID);
         $update_status = 'record-updated-ok=' . rand();
         if ($updated === false) {
             $update_status = 'record-updated-error=' . rand();
         }
         // compose filters and sorting
         foreach ($this->filterers as $filterer => $caption) {
             if ($_REQUEST['filterer_' . $filterer] != '') {
                 $filtersGET .= '&filterer_' . $filterer . '=' . urlencode($_REQUEST['filterer_' . $filterer]);
             }
         }
         for ($i = 1; $i <= 20 * $FiltersPerGroup; $i++) {
             // Number of filters allowed
             if ($FilterField[$i] != '' && $FilterOperator[$i] != '' && ($FilterValue[$i] != '' || strpos($FilterOperator[$i], 'empty'))) {
                 $filtersGET .= "&FilterAnd[{$i}]={$FilterAnd[$i]}&FilterField[{$i}]={$FilterField[$i]}&FilterOperator[{$i}]={$FilterOperator[$i]}&FilterValue[{$i}]=" . urlencode($FilterValue[$i]);
             }
         }
         $filtersGET .= "&SortField={$SortField}&SortDirection={$SortDirection}&FirstRecord={$FirstRecord}&Embedded={$Embedded}";
         $filtersGET .= "&DisplayRecords={$DisplayRecords}";
         $filtersGET .= '&SearchString=' . urlencode($SearchString);
         $filtersGET = substr($filtersGET, 1);
         // remove initial &
         $redirectUrl = $this->ScriptFileName . '?SelectedID=' . urlencode($SelectedID) . '&' . $filtersGET . '&' . $update_status;
         @header("Location: {$redirectUrl}");
         $this->HTML .= '<META HTTP-EQUIV="Refresh" CONTENT="0;url=' . $redirectUrl . '">';
         return;
     } elseif ($addNew_x != '') {
         $SelectedID = '';
         $this->hideTV();
     } elseif ($Print_x != '') {
         // print code here ....
         $this->AllowNavigation = 0;
         $this->AllowSelection = 0;
     } elseif ($SaveFilter_x != '' && $this->AllowSavingFilters) {
         $filter_link = $_SERVER['HTTP_REFERER'] . '?SortField=' . urlencode($SortField) . '&SortDirection=' . $SortDirection . '&';
         for ($i = 1; $i <= 20 * $FiltersPerGroup; $i++) {
             // Number of filters allowed
             if (($FilterField[$i] != '' || $i == 1) && $FilterOperator[$i] != '' && ($FilterValue[$i] != '' || strpos($FilterOperator[$i], 'empty'))) {
                 $filter_link .= urlencode("FilterAnd[{$i}]") . '=' . urlencode($FilterAnd[$i]) . '&';
                 $filter_link .= urlencode("FilterField[{$i}]") . '=' . urlencode($FilterField[$i]) . '&';
                 $filter_link .= urlencode("FilterOperator[{$i}]") . '=' . urlencode($FilterOperator[$i]) . '&';
                 $filter_link .= urlencode("FilterValue[{$i}]") . '=' . urlencode($FilterValue[$i]) . '&';
             }
         }
         $filter_link = substr($filter_link, 0, -1);
         /* trim last '&' */
         $this->HTML .= '<div id="saved_filter_source_code" class="row"><div class="col-md-6 col-md-offset-3">';
         $this->HTML .= '<div class="panel panel-info">';
         $this->HTML .= '<div class="panel-heading"><h3 class="panel-title">' . $Translation["saved filters title"] . "</h3></div>";
         $this->HTML .= '<div class="panel-body">';
         $this->HTML .= $Translation["saved filters instructions"];
         $this->HTML .= '<textarea rows="4" class="form-control vspacer-lg" style="width: 100%;" onfocus="$j(this).select();">' . "&lt;a href=\"{$filter_link}\"&gt;Saved filter link&lt;a&gt;" . '</textarea>';
         $this->HTML .= "<div><a href=\"{$filter_link}\" title=\"" . htmlspecialchars($filter_link) . "\">{$Translation['permalink']}</a></div>";
         $this->HTML .= '<button type="button" class="btn btn-default btn-block vspacer-lg" onclick="$j(\'#saved_filter_source_code\').remove();"><i class="glyphicon glyphicon-remove"></i> ' . $Translation['hide code'] . '</button>';
         $this->HTML .= '</div>';
         $this->HTML .= '</div>';
         $this->HTML .= '</div></div>';
     } elseif ($Filter_x != '') {
         $orderBy = array();
         if ($SortField) {
             $sortFields = explode(',', $SortField);
             $i = 0;
             foreach ($sortFields as $sf) {
                 $tob = preg_split('/\\s+/', $sf, 2);
                 $orderBy[] = array(trim($tob[0]) => strtolower(trim($tob[1])) == 'desc' ? 'desc' : 'asc');
                 $i++;
             }
             $orderBy[$i - 1][$tob[0]] = strtolower(trim($SortDirection)) == 'desc' ? 'desc' : 'asc';
         }
         $currDir = dirname(__FILE__) . '/hooks';
         // path to hooks folder
         $uff = "{$currDir}/{$this->TableName}.filters.{$mi['username']}.php";
         // user-specific filter file
         $gff = "{$currDir}/{$this->TableName}.filters.{$mi['group']}.php";
         // group-specific filter file
         $tff = "{$currDir}/{$this->TableName}.filters.php";
         // table-specific filter file
         /*
         	if no explicit filter file exists, look for filter files in the hooks folder in this order:
         		1. tablename.filters.username.php ($uff)
         		2. tablename.filters.groupname.php ($gff)
         		3. tablename.filters.php ($tff)
         */
         if (!is_file($this->FilterPage)) {
             $this->FilterPage = 'defaultFilters.php';
             if (is_file($uff)) {
                 $this->FilterPage = $uff;
             } elseif (is_file($gff)) {
                 $this->FilterPage = $gff;
             } elseif (is_file($tff)) {
                 $this->FilterPage = $tff;
             }
         }
         if ($this->FilterPage != '') {
             ob_start();
             @(include $this->FilterPage);
             $out = ob_get_contents();
             ob_end_clean();
             $this->HTML .= $out;
         }
         // hidden variables ....
         $this->HTML .= '<input name="SortField" value="' . $SortField . '" type="hidden" />';
         $this->HTML .= '<input name="SortDirection" type="hidden" value="' . $SortDirection . '" />';
         $this->HTML .= '<input name="FirstRecord" type="hidden" value="1" />';
         $this->ContentType = 'filters';
         return;
     } elseif ($NoFilter_x != '') {
         // clear all filters ...
         for ($i = 1; $i <= datalist_filters_count * $FiltersPerGroup; $i++) {
             // Number of filters allowed
             $FilterField[$i] = '';
             $FilterOperator[$i] = '';
             $FilterValue[$i] = '';
         }
         $DisplayRecords = 'all';
         $SearchString = '';
         $FirstRecord = 1;
         // clear filterers
         foreach ($this->filterers as $filterer => $caption) {
             $_REQUEST['filterer_' . $filterer] = '';
         }
     } elseif ($SelectedID) {
         $this->hideTV();
     }
     // apply lookup filterers to the query
     foreach ($this->filterers as $filterer => $caption) {
         if ($_REQUEST['filterer_' . $filterer] != '') {
             if ($this->QueryWhere == '') {
                 $this->QueryWhere = "where ";
             } else {
                 $this->QueryWhere .= " and ";
             }
             $this->QueryWhere .= "`{$this->TableName}`.`{$filterer}`='" . makeSafe($_REQUEST['filterer_' . $filterer]) . "' ";
             break;
             // currently, only one filterer can be applied at a time
         }
     }
     // apply quick search to the query
     if ($SearchString != '') {
         if ($Search_x != '') {
             $FirstRecord = 1;
         }
         if ($this->QueryWhere == '') {
             $this->QueryWhere = "where ";
         } else {
             $this->QueryWhere .= " and ";
         }
         foreach ($this->QueryFieldsQS as $fName => $fCaption) {
             if (strpos($fName, '<img') === False) {
                 $this->QuerySearchableFields[$fName] = $fCaption;
             }
         }
         $this->QueryWhere .= '(' . implode(" LIKE '%" . makeSafe($SearchString) . "%' or ", array_keys($this->QuerySearchableFields)) . " LIKE '%" . makeSafe($SearchString) . "%')";
     }
     // set query filters
     $QueryHasWhere = 0;
     if (strpos($this->QueryWhere, 'where ') !== FALSE) {
         $QueryHasWhere = 1;
     }
     $WhereNeedsClosing = 0;
     for ($i = 1; $i <= datalist_filters_count * $FiltersPerGroup; $i += $FiltersPerGroup) {
         // Number of filters allowed
         // test current filter group
         $GroupHasFilters = 0;
         for ($j = 0; $j < $FiltersPerGroup; $j++) {
             if ($FilterField[$i + $j] != '' && $this->QueryFieldsIndexed[$FilterField[$i + $j]] != '' && $FilterOperator[$i + $j] != '' && ($FilterValue[$i + $j] != '' || strpos($FilterOperator[$i + $j], 'empty'))) {
                 $GroupHasFilters = 1;
                 break;
             }
         }
         if ($GroupHasFilters) {
             if (!stristr($this->QueryWhere, "where ")) {
                 $this->QueryWhere = "where (";
             } elseif ($QueryHasWhere) {
                 $this->QueryWhere .= " and (";
                 $QueryHasWhere = 0;
             }
             $this->QueryWhere .= " <FilterGroup> " . $FilterAnd[$i] . " (";
             for ($j = 0; $j < $FiltersPerGroup; $j++) {
                 if ($FilterField[$i + $j] != '' && $this->QueryFieldsIndexed[$FilterField[$i + $j]] != '' && $FilterOperator[$i + $j] != '' && ($FilterValue[$i + $j] != '' || strpos($FilterOperator[$i + $j], 'empty'))) {
                     if ($FilterAnd[$i + $j] == '') {
                         $FilterAnd[$i + $j] = 'and';
                     }
                     // test for date/time fields
                     $tries = 0;
                     $isDateTime = FALSE;
                     $isDate = FALSE;
                     $fieldName = str_replace('`', '', $this->QueryFieldsIndexed[$FilterField[$i + $j]]);
                     list($tn, $fn) = explode('.', $fieldName);
                     while (!($res = sql("show columns from `{$tn}` like '{$fn}'", $eo)) && $tries < 2) {
                         $tn = substr($tn, 0, -1);
                         $tries++;
                     }
                     if ($row = @db_fetch_array($res)) {
                         if ($row['Type'] == 'date' || $row['Type'] == 'time') {
                             $isDateTime = TRUE;
                             if ($row['Type'] == 'date') {
                                 $isDate = True;
                             }
                         }
                     }
                     // end of test
                     if ($FilterOperator[$i + $j] == 'is-empty' && !$isDateTime) {
                         $this->QueryWhere .= " <FilterItem> " . $FilterAnd[$i + $j] . " (" . $this->QueryFieldsIndexed[$FilterField[$i + $j]] . "='' or " . $this->QueryFieldsIndexed[$FilterField[$i + $j]] . " is NULL) </FilterItem>";
                     } elseif ($FilterOperator[$i + $j] == 'is-not-empty' && !$isDateTime) {
                         $this->QueryWhere .= " <FilterItem> " . $FilterAnd[$i + $j] . " " . $this->QueryFieldsIndexed[$FilterField[$i + $j]] . "!='' </FilterItem>";
                     } elseif ($FilterOperator[$i + $j] == 'is-empty' && $isDateTime) {
                         $this->QueryWhere .= " <FilterItem> " . $FilterAnd[$i + $j] . " (" . $this->QueryFieldsIndexed[$FilterField[$i + $j]] . "=0 or " . $this->QueryFieldsIndexed[$FilterField[$i + $j]] . " is NULL) </FilterItem>";
                     } elseif ($FilterOperator[$i + $j] == 'is-not-empty' && $isDateTime) {
                         $this->QueryWhere .= " <FilterItem> " . $FilterAnd[$i + $j] . " " . $this->QueryFieldsIndexed[$FilterField[$i + $j]] . "!=0 </FilterItem>";
                     } elseif ($FilterOperator[$i + $j] == 'like' && !strstr($FilterValue[$i + $j], "%") && !strstr($FilterValue[$i + $j], "_")) {
                         $this->QueryWhere .= " <FilterItem> " . $FilterAnd[$i + $j] . " " . $this->QueryFieldsIndexed[$FilterField[$i + $j]] . " like '%" . makeSafe($FilterValue[$i + $j]) . "%' </FilterItem>";
                     } elseif ($FilterOperator[$i + $j] == 'not-like' && !strstr($FilterValue[$i + $j], "%") && !strstr($FilterValue[$i + $j], "_")) {
                         $this->QueryWhere .= " <FilterItem> " . $FilterAnd[$i + $j] . " " . $this->QueryFieldsIndexed[$FilterField[$i + $j]] . " not like '%" . makeSafe($FilterValue[$i + $j]) . "%' </FilterItem>";
                     } elseif ($isDate) {
                         $dateValue = toMySQLDate($FilterValue[$i + $j]);
                         $this->QueryWhere .= " <FilterItem> " . $FilterAnd[$i + $j] . " " . $this->QueryFieldsIndexed[$FilterField[$i + $j]] . " " . $GLOBALS['filter_operators'][$FilterOperator[$i + $j]] . " '{$dateValue}' </FilterItem>";
                     } else {
                         $this->QueryWhere .= " <FilterItem> " . $FilterAnd[$i + $j] . " " . $this->QueryFieldsIndexed[$FilterField[$i + $j]] . " " . $GLOBALS['filter_operators'][$FilterOperator[$i + $j]] . " '" . makeSafe($FilterValue[$i + $j]) . "' </FilterItem>";
                     }
                 }
             }
             $this->QueryWhere .= ") </FilterGroup>";
             $WhereNeedsClosing = 1;
         }
     }
     if ($WhereNeedsClosing) {
         $this->QueryWhere .= ")";
     }
     // set query sort
     if (!stristr($this->QueryOrder, "order by ") && $SortField != '' && $this->AllowSorting) {
         $actualSortField = $SortField;
         foreach ($this->SortFields as $fieldNum => $fieldSort) {
             $actualSortField = str_replace(" {$fieldNum} ", " {$fieldSort} ", " {$actualSortField} ");
             $actualSortField = str_replace(",{$fieldNum} ", ",{$fieldSort} ", " {$actualSortField} ");
         }
         $this->QueryOrder = "order by {$actualSortField} {$SortDirection}";
     }
     // clean up query
     $this->QueryWhere = str_replace('( <FilterGroup> and ', '( ', $this->QueryWhere);
     $this->QueryWhere = str_replace('( <FilterGroup> or ', '( ', $this->QueryWhere);
     $this->QueryWhere = str_replace('( <FilterItem> and ', '( ', $this->QueryWhere);
     $this->QueryWhere = str_replace('( <FilterItem> or ', '( ', $this->QueryWhere);
     $this->QueryWhere = str_replace('<FilterGroup>', '', $this->QueryWhere);
     $this->QueryWhere = str_replace('</FilterGroup>', '', $this->QueryWhere);
     $this->QueryWhere = str_replace('<FilterItem>', '', $this->QueryWhere);
     $this->QueryWhere = str_replace('</FilterItem>', '', $this->QueryWhere);
     // if no 'order by' clause found, apply default sorting if specified
     if ($this->DefaultSortField != '' && $this->QueryOrder == '') {
         $this->QueryOrder = "order by " . $this->DefaultSortField . " " . $this->DefaultSortDirection;
     }
     // get count of matching records ...
     $TempQuery = 'SELECT count(1) from ' . $this->QueryFrom . ' ' . $this->QueryWhere;
     $RecordCount = sqlValue($TempQuery);
     $FieldCountTV = count($this->QueryFieldsTV);
     $FieldCountCSV = count($this->QueryFieldsCSV);
     $FieldCountFilters = count($this->QueryFieldsFilters);
     if (!$RecordCount) {
         $FirstRecord = 1;
     }
     // Output CSV on request
     if ($CSV_x != '') {
         $this->HTML = '';
         if (datalist_db_encoding == 'UTF-8') {
             $this->HTML = "";
         }
         // BOM characters for UTF-8 output
         // execute query for CSV output
         $fieldList = '';
         foreach ($this->QueryFieldsCSV as $fn => $fc) {
             $fieldList .= "{$fn} as `{$fc}`, ";
         }
         $fieldList = substr($fieldList, 0, -2);
         $csvQuery = 'SELECT ' . $fieldList . ' from ' . $this->QueryFrom . ' ' . $this->QueryWhere . ' ' . $this->QueryOrder;
         // hook: table_csv
         if (function_exists($this->TableName . '_csv')) {
             $args = array();
             $mq = call_user_func_array($this->TableName . '_csv', array($csvQuery, $mi, &$args));
             $csvQuery = $mq ? $mq : $csvQuery;
         }
         $result = sql($csvQuery, $eo);
         // output CSV field names
         for ($i = 0; $i < $FieldCountCSV; $i++) {
             $this->HTML .= "\"" . db_field_name($result, $i) . "\"" . $this->CSVSeparator;
         }
         $this->HTML .= "\n\n";
         // output CSV data
         while ($row = db_fetch_row($result)) {
             for ($i = 0; $i < $FieldCountCSV; $i++) {
                 $this->HTML .= "\"" . str_replace(array("\r\n", "\r", "\n", '"'), array(' ', ' ', ' ', '""'), strip_tags($row[$i])) . "\"" . $this->CSVSeparator;
             }
             $this->HTML .= "\n\n";
         }
         $this->HTML = str_replace($this->CSVSeparator . "\n\n", "\n", $this->HTML);
         $this->HTML = substr($this->HTML, 0, -1);
         // clean any output buffers
         while (@ob_end_clean()) {
         }
         // output CSV HTTP headers ...
         header('HTTP/1.1 200 OK');
         header('Date: ' . @date("D M j G:i:s T Y"));
         header('Last-Modified: ' . @date("D M j G:i:s T Y"));
         header("Content-Type: application/force-download");
         header("Content-Length: " . (string) strlen($this->HTML));
         header("Content-Transfer-Encoding: Binary");
         header("Content-Disposition: attachment; filename={$this->TableName}.csv");
         // send output and quit script
         echo $this->HTML;
         exit;
     }
     $t = time();
     // just a random number for any purpose ...
     // should SelectedID be reset on clicking TV buttons?
     $resetSelection = $this->SeparateDV ? "document.myform.SelectedID.value = '';" : "document.myform.writeAttribute('novalidate', 'novalidate');";
     if ($current_view == 'DV' && !$Embedded) {
         $this->HTML .= '<div class="page-header">';
         $this->HTML .= '<h1>';
         $this->HTML .= '<a style="text-decoration: none; color: inherit;" href="' . $this->TableName . '_view.php"><img src="' . $this->TableIcon . '"> ' . $this->TableTitle . '</a>';
         $this->HTML .= '</h1>';
         $this->HTML .= '</div>';
     }
     // quick search and TV action buttons
     if (!$this->HideTableView && !($dvprint_x && $this->AllowSelection && $SelectedID) && !$PrintDV) {
         $buttons_all = $quick_search_html = '';
         if ($Print_x == '') {
             // display 'Add New' icon
             if ($this->Permissions[1] && $this->SeparateDV) {
                 $buttons_all .= '<button type="submit" id="addNew" name="addNew_x" value="1" class="btn btn-success"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Add New'] . '</button>';
                 $buttonsCount++;
             }
             // display Print icon
             if ($this->AllowPrinting) {
                 $buttons_all .= '<button onClick="document.myform.NoDV.value=1; ' . $resetSelection . ' return true;" type="submit" name="Print_x" id="Print" value="1" class="btn btn-default"><i class="glyphicon glyphicon-print"></i> ' . $Translation['Print Preview'] . '</button>';
                 $buttonsCount++;
             }
             // display CSV icon
             if ($this->AllowCSV) {
                 $buttons_all .= '<button onClick="document.myform.NoDV.value=1; ' . $resetSelection . ' return true;" type="submit" name="CSV_x" id="CSV" value="1" class="btn btn-default"><i class="glyphicon glyphicon-download-alt"></i> ' . $Translation['CSV'] . '</button>';
                 $buttonsCount++;
             }
             // display Filter icon
             if ($this->AllowFilters) {
                 $buttons_all .= '<button onClick="document.myform.NoDV.value=1; ' . $resetSelection . ' return true;" type="submit" name="Filter_x" id="Filter" value="1" class="btn btn-default"><i class="glyphicon glyphicon-filter"></i> ' . $Translation['filter'] . '</button>';
                 $buttonsCount++;
             }
             // display Show All icon
             if ($this->AllowFilters) {
                 $buttons_all .= '<button onClick="document.myform.NoDV.value=1; ' . $resetSelection . ' return true;" type="submit" name="NoFilter_x" id="NoFilter" value="1" class="btn btn-default"><i class="glyphicon glyphicon-remove-circle"></i> ' . $Translation['Reset Filters'] . '</button>';
                 $buttonsCount++;
             }
             $quick_search_html .= '<div class="input-group" id="quick-search">';
             $quick_search_html .= '<input type="text" name="SearchString" value="' . htmlspecialchars($SearchString, ENT_QUOTES, 'iso-8859-1') . '" class="form-control" placeholder="' . htmlspecialchars($this->QuickSearchText) . '">';
             $quick_search_html .= '<span class="input-group-btn">';
             $quick_search_html .= '<button name="Search_x" value="1" id="Search" type="submit" onClick="' . $resetSelection . ' document.myform.NoDV.value=1; return true;"  class="btn btn-default" title="' . htmlspecialchars($this->QuickSearchText) . '"><i class="glyphicon glyphicon-search"></i></button>';
             $quick_search_html .= '<button name="NoFilter_x" value="1" id="NoFilter_x" type="submit" onClick="' . $resetSelection . ' document.myform.NoDV.value=1; return true;"  class="btn btn-default" title="' . htmlspecialchars($Translation['Reset Filters']) . '"><i class="glyphicon glyphicon-remove-circle"></i></button>';
             $quick_search_html .= '</span>';
             $quick_search_html .= '</div>';
         } else {
             $buttons_all .= '<button class="btn btn-primary" type="button" id="sendToPrinter" onClick="window.print();"><i class="glyphicon glyphicon-print"></i> ' . $Translation['Print'] . '</button>';
             $buttons_all .= '<button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-remove-circle"></i> ' . $Translation['Cancel Printing'] . '</button>';
         }
         /* if user can print DV, add action to 'More' menu */
         $selected_records_more = array();
         if ($AllowPrintDV) {
             $selected_records_more[] = array('function' => $this->SeparateDV ? 'print_multiple_dv_sdv' : 'print_multiple_dv_tvdv', 'title' => $Translation['Print Preview Detail View'], 'icon' => 'print');
         }
         /* if user can mass-delete selected records, add action to 'More' menu */
         if ($this->AllowMassDelete && $this->AllowDelete) {
             $selected_records_more[] = array('function' => 'mass_delete', 'title' => $Translation['Delete'], 'icon' => 'trash', 'class' => 'text-danger');
         }
         /* if user is admin, add 'Change owner' action to 'More' menu */
         /* also, add help link for adding more actions */
         if ($mi['admin']) {
             $selected_records_more[] = array('function' => 'mass_change_owner', 'title' => $Translation['Change owner'], 'icon' => 'user');
             $selected_records_more[] = array('function' => 'add_more_actions_link', 'title' => $Translation['Add more actions'], 'icon' => 'question-sign', 'class' => 'text-info');
         }
         /* user-defined actions ... should be set in the {tablename}_batch_actions() function in hooks/{tablename}.php */
         $user_actions = array();
         if (function_exists($this->TableName . '_batch_actions')) {
             $args = array();
             $user_actions = call_user_func_array($this->TableName . '_batch_actions', array(&$args));
             if (is_array($user_actions) && count($user_actions)) {
                 $selected_records_more = array_merge($selected_records_more, $user_actions);
             }
         }
         $actual_more_count = 0;
         $more_menu = $more_menu_js = '';
         if (count($selected_records_more)) {
             $more_menu .= '<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" id="selected_records_more"><i class="glyphicon glyphicon-check"></i> ' . $Translation['More'] . ' <span class="caret"></span></button>';
             $more_menu .= '<ul class="dropdown-menu" role="menu">';
             foreach ($selected_records_more as $action) {
                 if (!$action['function'] || !$action['title']) {
                     continue;
                 }
                 $action['class'] = !isset($action['class']) ? '' : $action['class'];
                 $action['icon'] = !isset($action['icon']) ? '' : $action['icon'];
                 $actual_more_count++;
                 $more_menu .= '<li>' . '<a href="#" id="selected_records_' . $action['function'] . '">' . '<span class="' . $action['class'] . '">' . ($action['icon'] ? '<i class="glyphicon glyphicon-' . $action['icon'] . '"></i> ' : '') . $action['title'] . '</span>' . '</a>' . '</li>';
                 // on clicking an action, call its js handler function, passing the current table name and an array of selected IDs to it
                 $more_menu_js .= "jQuery('[id=selected_records_{$action['function']}]').click(function(){ {$action['function']}('{$this->TableName}', get_selected_records_ids()); return false; });";
             }
             $more_menu .= '</ul>';
         }
         if ($Embedded) {
             $this->HTML .= '<script>$j(function(){ $j(\'[id^=notification-]\').parent().css({\'margin-top\': \'15px\', \'margin-bottom\': \'0\'}); })</script>';
         } else {
             $this->HTML .= '<div class="page-header">';
             $this->HTML .= '<h1>';
             $this->HTML .= '<div class="row">';
             $this->HTML .= '<div class="col-sm-8">';
             $this->HTML .= '<a style="text-decoration: none; color: inherit;" href="' . $this->TableName . '_view.php"><img src="' . $this->TableIcon . '"> ' . $this->TableTitle . '</a>';
             $this->HTML .= '</div>';
             if ($this->QuickSearch) {
                 $this->HTML .= '<div class="col-sm-4">';
                 $this->HTML .= $quick_search_html;
                 $this->HTML .= '</div>';
             }
             $this->HTML .= '</div>';
             $this->HTML .= '</h1>';
             $this->HTML .= '</div>';
             $this->HTML .= '<div id="top_buttons" class="hidden-print">';
             /* .all_records: container for buttons that don't need a selection */
             /* .selected_records: container for buttons that need a selection */
             $this->HTML .= '<div class="btn-group btn-group-lg visible-md visible-lg all_records pull-left">' . $buttons_all . '</div>';
             $this->HTML .= '<div class="btn-group btn-group-lg visible-md visible-lg selected_records hidden pull-left hspacer-lg">' . $buttons_selected . ($actual_more_count ? $more_menu : '') . '</div>';
             $this->HTML .= '<div class="btn-group-vertical btn-group-lg visible-xs visible-sm all_records">' . $buttons_all . '</div>';
             $this->HTML .= '<div class="btn-group-vertical btn-group-lg visible-xs visible-sm selected_records hidden vspacer-lg">' . $buttons_selected . ($actual_more_count ? $more_menu : '') . '</div>';
             $this->HTML .= '<div class="clearfix"></div><p></p>';
             $this->HTML .= '</div>';
         }
         if ($Print_x != '') {
             /* fix top margin for print-preview */
             $this->HTML .= '<style>body{ padding-top: 0 !important; }</style>';
             /* disable links inside table body to prevent printing their href */
             $this->HTML .= '<script>jQuery(function(){ jQuery("tbody a").removeAttr("href").removeAttr("rel"); });</script>';
         }
         // script for focusing into the search box on loading the page
         // and for declaring record action handlers
         $this->HTML .= '<script>jQuery(function(){ jQuery("input[name=SearchString]").focus();  ' . $more_menu_js . ' });</script>';
     }
     // begin table and display table title
     if (!$this->HideTableView && !($dvprint_x && $this->AllowSelection && $SelectedID) && !$PrintDV && !$Embedded) {
         $this->HTML .= '<div class="table-responsive"><table class="table table-striped table-bordered table-hover">';
         $this->HTML .= '<thead><tr>';
         if (!$Print_x) {
             $this->HTML .= '<th style="width: 18px;" class="text-center"><input class="hidden-print" type="checkbox" title="' . htmlspecialchars($Translation['Select all records']) . '" id="select_all_records"></th>';
         }
         // Templates
         if ($this->Template != '') {
             $rowTemplate = @implode('', @file('./' . $this->Template));
             if (!$rowTemplate) {
                 $rowTemplate = '';
                 $selrowTemplate = '';
             } else {
                 if ($this->SelectedTemplate != '') {
                     $selrowTemplate = @implode('', @file('./' . $this->SelectedTemplate));
                     if (!$selrowTemplate) {
                         $selrowTemplate = '';
                     }
                 } else {
                     $selrowTemplate = '';
                 }
             }
         } else {
             $rowTemplate = '';
             $selrowTemplate = '';
         }
         // process translations
         if ($rowTemplate) {
             foreach ($Translation as $symbol => $trans) {
                 $rowTemplate = str_replace("<%%TRANSLATION({$symbol})%%>", $trans, $rowTemplate);
             }
         }
         if ($selrowTemplate) {
             foreach ($Translation as $symbol => $trans) {
                 $selrowTemplate = str_replace("<%%TRANSLATION({$symbol})%%>", $trans, $selrowTemplate);
             }
         }
         // End of templates
         // $this->ccffv: map $FilterField values to field captions as stored in ColCaption
         $this->ccffv = array();
         foreach ($this->ColCaption as $captionIndex => $caption) {
             $ffv = 1;
             foreach ($this->QueryFieldsFilters as $uselessKey => $filterCaption) {
                 if ($caption == $filterCaption) {
                     $this->ccffv[$captionIndex] = $ffv;
                 }
                 $ffv++;
             }
         }
         // display table headers
         $totalColWidth = array_sum($this->ColWidth);
         $forceHeaderWidth = false;
         if ($rowTemplate == '' || $this->ShowTableHeader) {
             for ($i = 0; $i < count($this->ColCaption); $i++) {
                 /* Sorting icon and link */
                 $sort1 = $sort2 = $filterHint = '';
                 if ($this->AllowSorting == 1) {
                     if ($current_view != 'TVP') {
                         $sort1 = "<a href=\"{$this->ScriptFileName}?SortDirection=asc&SortField=" . $this->ColNumber[$i] . "\" onClick=\"{$resetSelection} document.myform.NoDV.value=1; document.myform.SortDirection.value='asc'; document.myform.SortField.value = '" . $this->ColNumber[$i] . "'; document.myform.submit(); return false;\" class=\"TableHeader\">";
                         $sort2 = "</a>";
                     }
                     if ($this->ColNumber[$i] == $SortField) {
                         $SortDirection = $SortDirection == "asc" ? "desc" : "asc";
                         if ($current_view != 'TVP') {
                             $sort1 = "<a href=\"{$this->ScriptFileName}?SortDirection={$SortDirection}&SortField=" . $this->ColNumber[$i] . "\" onClick=\"{$resetSelection} document.myform.NoDV.value=1; document.myform.SortDirection.value='{$SortDirection}'; document.myform.SortField.value = " . $this->ColNumber[$i] . "; document.myform.submit(); return false;\" class=\"TableHeader\">";
                         }
                         $sort2 = " <i class=\"text-warning glyphicon glyphicon-sort-by-attributes" . ($SortDirection == 'desc' ? '' : '-alt') . "\"></i>{$sort2}";
                         $SortDirection = $SortDirection == "asc" ? "desc" : "asc";
                     }
                 } else {
                     $sort1 = '';
                     $sort2 = '';
                 }
                 /* Filtering icon and hint */
                 if ($this->AllowFilters && is_array($FilterField)) {
                     // check to see if there is any filter applied on the current field
                     if (isset($this->ccffv[$i]) && in_array($this->ccffv[$i], $FilterField)) {
                         // render filter icon
                         $filterHint = '&nbsp;<button type="submit" class="btn btn-default btn-xs' . ($current_view == 'TVP' ? ' disabled' : '') . '" name="Filter_x" value="1" title="' . htmlspecialchars($Translation['filtered field']) . '"><i class="glyphicon glyphicon-filter"></i></button>';
                     }
                 }
                 $this->HTML .= "\t<th class=\"{$this->TableName}-{$this->ColFieldName[$i]}\" " . ($forceHeaderWidth ? ' style="width: ' . ($this->ColWidth[$i] ? $this->ColWidth[$i] : 100) . 'px;"' : '') . ">{$sort1}{$this->ColCaption[$i]}{$sort2}{$filterHint}</th>\n";
             }
         } else {
             // Display a Sort by drop down
             $this->HTML .= "\t<th><td colspan=" . (count($this->ColCaption) + 1) . ">";
             if ($this->AllowSorting == 1) {
                 $sortCombo = new Combo();
                 for ($i = 0; $i < count($this->ColCaption); $i++) {
                     $sortCombo->ListItem[] = $this->ColCaption[$i];
                     $sortCombo->ListData[] = $this->ColNumber[$i];
                 }
                 $sortCombo->SelectName = "FieldsList";
                 $sortCombo->SelectedData = $SortField;
                 $sortCombo->Class = 'TableBody';
                 $sortCombo->SelectedClass = 'TableBodySelected';
                 $sortCombo->Render();
                 $d = $sortCombo->HTML;
                 $d = str_replace('<select ', "<select onChange=\"document.myform.SortDirection.value='{$SortDirection}'; document.myform.SortField.value=document.myform.FieldsList.value; document.myform.NoDV.value=1; document.myform.submit();\" ", $d);
                 if ($SortField) {
                     $SortDirection = $SortDirection == "desc" ? "asc" : "desc";
                     $sort = "<a href=\"javascript: document.myform.NoDV.value=1; document.myform.SortDirection.value='{$SortDirection}'; document.myform.SortField.value='{$SortField}'; document.myform.submit();\" class=TableHeader><img src={$SortDirection}.gif border=0 width=11 height=11 hspace=3></a>";
                     $SortDirection = $SortDirection == "desc" ? "asc" : "desc";
                 } else {
                     $sort = '';
                 }
                 $this->HTML .= $Translation['order by'] . " {$d} {$sort}";
             }
             $this->HTML .= "</td></th>\n";
         }
         // table view navigation code ...
         if ($RecordCount && $this->AllowNavigation && $RecordCount > $this->RecordsPerPage) {
             while ($FirstRecord > $RecordCount) {
                 $FirstRecord -= $this->RecordsPerPage;
             }
             if ($FirstRecord == '' || $FirstRecord < 1) {
                 $FirstRecord = 1;
             }
             if ($Previous_x != '') {
                 $FirstRecord -= $this->RecordsPerPage;
                 if ($FirstRecord <= 0) {
                     $FirstRecord = 1;
                 }
             } elseif ($Next_x != '') {
                 $FirstRecord += $this->RecordsPerPage;
                 if ($FirstRecord > $RecordCount) {
                     $FirstRecord = $RecordCount - $RecordCount % $this->RecordsPerPage + 1;
                 }
                 if ($FirstRecord > $RecordCount) {
                     $FirstRecord = $RecordCount - $this->RecordsPerPage + 1;
                 }
                 if ($FirstRecord <= 0) {
                     $FirstRecord = 1;
                 }
             }
         } elseif ($RecordCount) {
             $FirstRecord = 1;
             $this->RecordsPerPage = 2000;
             // a limit on max records in print preview to avoid performance drops
         }
         // end of table view navigation code
         $this->HTML .= "\n\t</tr>\n\n</thead>\n\n<tbody><!-- tv data below -->\n";
         $i = 0;
         $hc = new CI_Input();
         $hc->charset = datalist_db_encoding;
         if ($RecordCount) {
             $i = $FirstRecord;
             // execute query for table view
             $fieldList = '';
             foreach ($this->QueryFieldsTV as $fn => $fc) {
                 $fieldList .= "{$fn} as `{$fc}`, ";
             }
             $fieldList = substr($fieldList, 0, -2);
             if ($this->PrimaryKey) {
                 $fieldList .= ", {$this->PrimaryKey} as '" . str_replace('`', '', $this->PrimaryKey) . "'";
             }
             $tvQuery = 'SELECT ' . $fieldList . ' from ' . $this->QueryFrom . ' ' . $this->QueryWhere . ' ' . $this->QueryOrder;
             $result = sql($tvQuery . " limit " . ($i - 1) . ",{$this->RecordsPerPage}", $eo);
             while (($row = db_fetch_array($result)) && $i < $FirstRecord + $this->RecordsPerPage) {
                 $attr_id = htmlspecialchars($row[$FieldCountTV], ENT_QUOTES, 'iso-8859-1');
                 /* pk value suitable for inserting into html tag attributes */
                 $js_id = addslashes($row[$FieldCountTV]);
                 /* pk value suitable for inserting into js strings */
                 $alt = ($i - $FirstRecord) % 2;
                 if (($PrintTV || $Print_x) && count($_POST['record_selector']) && !in_array($row[$FieldCountTV], $_POST['record_selector'])) {
                     continue;
                 }
                 $class = "TableBody" . ($alt ? 'Selected' : '') . ($fNumeric ? 'Numeric' : '');
                 if ($Print_x != '') {
                     $this->HTML .= '<tr>';
                 }
                 if (!$Print_x) {
                     $this->HTML .= $SelectedID == $row[$FieldCountTV] ? '<tr class="active">' : '<tr>';
                     $checked = is_array($_POST['record_selector']) && in_array($row[$FieldCountTV], $_POST['record_selector']) ? ' checked' : '';
                     $this->HTML .= "<td class=\"text-center\"><input class=\"hidden-print record_selector\" type=\"checkbox\" id=\"record_selector_{$attr_id}\" name=\"record_selector[]\" value=\"{$attr_id}\"{$checked}></td>";
                 }
                 // templates
                 if ($rowTemplate != '') {
                     if ($this->AllowSelection == 1 && $SelectedID == $row[$FieldCountTV] && $selrowTemplate != '') {
                         $rowTemp = $selrowTemplate;
                     } else {
                         $rowTemp = $rowTemplate;
                     }
                     if ($this->AllowSelection == 1 && $SelectedID != $row[$FieldCountTV]) {
                         $rowTemp = str_replace('<%%SELECT%%>', "<a onclick=\"document.myform.SelectedField.value=this.parentNode.cellIndex; document.myform.SelectedID.value='" . addslashes($row[$FieldCountTV]) . "'; document.myform.submit(); return false;\" href=\"{$this->ScriptFileName}?SelectedID=" . htmlspecialchars($row[$FieldCountTV], ENT_QUOTES) . "\" class=\"{$class}\" style=\"display: block; padding:0px;\">", $rowTemp);
                         $rowTemp = str_replace('<%%ENDSELECT%%>', '</a>', $rowTemp);
                     } else {
                         $rowTemp = str_replace('<%%SELECT%%>', '', $rowTemp);
                         $rowTemp = str_replace('<%%ENDSELECT%%>', '', $rowTemp);
                     }
                     for ($j = 0; $j < $FieldCountTV; $j++) {
                         $fieldTVCaption = current(array_slice($this->QueryFieldsTV, $j, 1));
                         $fd = $hc->xss_clean(nl2br($row[$j]));
                         /* Sanitize output against XSS attacks */
                         /*
                         	the TV template could contain field placeholders in the format 
                         	<%%FIELD_n%%> or <%%VALUE(Field name)%%> 
                         */
                         $rowTemp = str_replace("<%%FIELD_{$j}%%>", thisOr($fd), $rowTemp);
                         $rowTemp = str_replace("<%%VALUE({$fieldTVCaption})%%>", thisOr($fd), $rowTemp);
                         if (strpos($rowTemp, "<%%YOUTUBETHUMB({$fieldTVCaption})%%>") !== false) {
                             $rowTemp = str_replace("<%%YOUTUBETHUMB({$fieldTVCaption})%%>", thisOr(get_embed('youtube', $fd, '', '', 'thumbnail_url'), 'blank.gif'), $rowTemp);
                         }
                         if (strpos($rowTemp, "<%%GOOGLEMAPTHUMB({$fieldTVCaption})%%>") !== false) {
                             $rowTemp = str_replace("<%%GOOGLEMAPTHUMB({$fieldTVCaption})%%>", thisOr(get_embed('googlemap', $fd, '', '', 'thumbnail_url'), 'blank.gif'), $rowTemp);
                         }
                         if (thisOr($fd) == '&nbsp;' && preg_match('/<a href=".*?&nbsp;.*?<\\/a>/i', $rowTemp, $m)) {
                             $rowTemp = str_replace($m[0], '', $rowTemp);
                         }
                     }
                     if ($alt && $SelectedID != $row[$FieldCountTV]) {
                         $rowTemp = str_replace("TableBody", "TableBodySelected", $rowTemp);
                         $rowTemp = str_replace("TableBodyNumeric", "TableBodySelectedNumeric", $rowTemp);
                         $rowTemp = str_replace("SelectedSelected", "Selected", $rowTemp);
                     }
                     if ($SearchString != '') {
                         $rowTemp = highlight($SearchString, $rowTemp);
                     }
                     $this->HTML .= $rowTemp;
                     $rowTemp = '';
                 } else {
                     // end of templates
                     for ($j = 0; $j < $FieldCountTV; $j++) {
                         $fType = db_field_type($result, $j);
                         $fNumeric = stristr($fType, 'int') || stristr($fType, 'float') || stristr($fType, 'decimal') || stristr($fType, 'numeric') || stristr($fType, 'real') || stristr($fType, 'double') ? true : false;
                         if ($this->AllowSelection == 1) {
                             $sel1 = "<a href=\"{$this->ScriptFileName}?SelectedID=" . htmlspecialchars($row[$FieldCountTV], ENT_QUOTES) . "\" onclick=\"document.myform.SelectedID.value='" . addslashes($row[$FieldCountTV]) . "'; document.myform.submit(); return false;\" class=\"{$class}\" style=\"padding:0px;\">";
                             $sel2 = "</a>";
                         } else {
                             $sel1 = '';
                             $sel2 = '';
                         }
                         $this->HTML .= "<td valign=top class={$class}><div class={$class}>&nbsp;{$sel1}" . $row[$j] . "{$sel2}&nbsp;</div></td>";
                     }
                 }
                 $this->HTML .= "</tr>\n";
                 $i++;
             }
             $i--;
         }
         $this->HTML = preg_replace("/<a href=\"(mailto:)?&nbsp;[^\n]*title=\"&nbsp;\"><\\/a>/", '&nbsp;', $this->HTML);
         $this->HTML = preg_replace("/<a [^>]*>(&nbsp;)*<\\/a>/", '&nbsp;', $this->HTML);
         $this->HTML = preg_replace("/<%%.*%%>/U", '&nbsp;', $this->HTML);
         // end of data
         $this->HTML .= '<!-- tv data above -->';
         $this->HTML .= "\n</tbody>";
         if ($Print_x == '') {
             // TV
             $pagesMenu = '';
             if ($RecordCount > $this->RecordsPerPage) {
                 $pagesMenuId = "{$this->TableName}_pagesMenu";
                 $pagesMenu = $Translation['go to page'] . ' <select class="input-sm" id="' . $pagesMenuId . '" onChange="document.myform.writeAttribute(\'novalidate\', \'novalidate\'); document.myform.NoDV.value=1; document.myform.FirstRecord.value=(this.value * ' . $this->RecordsPerPage . '+1); document.myform.submit();">';
                 $pagesMenu .= '</select>';
                 $pagesMenu .= '<script>';
                 $pagesMenu .= 'var lastPage = ' . (ceil($RecordCount / $this->RecordsPerPage) - 1) . ';';
                 $pagesMenu .= 'var currentPage = ' . ($FirstRecord - 1) / $this->RecordsPerPage . ';';
                 $pagesMenu .= 'var pagesMenu = document.getElementById("' . $pagesMenuId . '");';
                 $pagesMenu .= 'var lump = ' . datalist_max_page_lump . ';';
                 $pagesMenu .= 'if(lastPage <= lump * 3){';
                 $pagesMenu .= '  addPageNumbers(0, lastPage);';
                 $pagesMenu .= '}else{';
                 $pagesMenu .= '  addPageNumbers(0, lump - 1);';
                 $pagesMenu .= '  if(currentPage < lump) addPageNumbers(lump, currentPage + lump / 2);';
                 $pagesMenu .= '  if(currentPage >= lump && currentPage < (lastPage - lump)){';
                 $pagesMenu .= '    addPageNumbers(';
                 $pagesMenu .= '      Math.max(currentPage - lump / 2, lump),';
                 $pagesMenu .= '      Math.min(currentPage + lump / 2, lastPage - lump - 1)';
                 $pagesMenu .= '    );';
                 $pagesMenu .= '  }';
                 $pagesMenu .= '  if(currentPage >= (lastPage - lump)) addPageNumbers(currentPage - lump / 2, lastPage - lump - 1);';
                 $pagesMenu .= '  addPageNumbers(lastPage - lump, lastPage);';
                 $pagesMenu .= '}';
                 $pagesMenu .= 'function addPageNumbers(fromPage, toPage){';
                 $pagesMenu .= '  var ellipsesIndex = 0;';
                 $pagesMenu .= '  if(fromPage > toPage) return;';
                 $pagesMenu .= '  if(fromPage > 0){';
                 $pagesMenu .= '    if(pagesMenu.options[pagesMenu.options.length - 1].text != fromPage){';
                 $pagesMenu .= '      ellipsesIndex = pagesMenu.options.length;';
                 $pagesMenu .= '      fromPage--;';
                 $pagesMenu .= '    }';
                 $pagesMenu .= '  }';
                 $pagesMenu .= '  for(i = fromPage; i <= toPage; i++){';
                 $pagesMenu .= '    var option = document.createElement("option");';
                 $pagesMenu .= '    option.text = (i + 1);';
                 $pagesMenu .= '    option.value = i;';
                 $pagesMenu .= '    if(i == currentPage){ option.selected = "selected"; }';
                 $pagesMenu .= '    try{';
                 $pagesMenu .= '      /* for IE earlier than version 8 */';
                 $pagesMenu .= '      pagesMenu.add(option, pagesMenu.options[null]);';
                 $pagesMenu .= '    }catch(e){';
                 $pagesMenu .= '      pagesMenu.add(option, null);';
                 $pagesMenu .= '    }';
                 $pagesMenu .= '  }';
                 $pagesMenu .= '  if(ellipsesIndex > 0){';
                 $pagesMenu .= '    pagesMenu.options[ellipsesIndex].text = " ... ";';
                 $pagesMenu .= '  }';
                 $pagesMenu .= '}';
                 $pagesMenu .= '</script>';
             }
             $this->HTML .= "\n\t";
             if ($i) {
                 // 1 or more records found
                 $this->HTML .= "<tfoot><tr><td colspan=" . (count($this->ColCaption) + 1) . '>';
                 $this->HTML .= $Translation['records x to y of z'];
                 $this->HTML .= '</td></tr></tfoot>';
             }
             if (!$i) {
                 // no records found
                 $this->HTML .= "<tfoot><tr><td colspan=" . (count($this->ColCaption) + 1) . '>';
                 $this->HTML .= '<div class="alert alert-warning">';
                 $this->HTML .= '<i class="glyphicon glyphicon-warning-sign"></i> ';
                 $this->HTML .= $Translation['No matches found!'];
                 $this->HTML .= '</div>';
                 $this->HTML .= '</td></tr></tfoot>';
             }
         } else {
             // TVP
             if ($i) {
                 $this->HTML .= "\n\t<tfoot><tr><td colspan=" . (count($this->ColCaption) + 1) . '>' . $Translation['records x to y of z'] . '</td></tr></tfoot>';
             }
             if (!$i) {
                 $this->HTML .= "\n\t<tfoot><tr><td colspan=" . (count($this->ColCaption) + 1) . '>' . $Translation['No matches found!'] . '</td></tr></tfoot>';
             }
         }
         $this->HTML = str_replace("<FirstRecord>", number_format($FirstRecord), $this->HTML);
         $this->HTML = str_replace("<LastRecord>", number_format($i), $this->HTML);
         $this->HTML = str_replace("<RecordCount>", number_format($RecordCount), $this->HTML);
         $tvShown = true;
         $this->HTML .= "</table></div>\n";
         if ($Print_x == '' && $i) {
             // TV
             $this->HTML .= '<div class="row">';
             $this->HTML .= '<div class="col-sm-4 col-md-3 col-lg-2 vspacer-lg">';
             $this->HTML .= '<button onClick="' . $resetSelection . ' document.myform.NoDV.value = 1; return true;" type="submit" name="Previous_x" id="Previous" value="1" class="btn btn-default btn-block"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Previous'] . '</button>';
             $this->HTML .= '</div>';
             $this->HTML .= '<div class="col-sm-4 col-md-4 col-lg-2 col-md-offset-1 col-lg-offset-3 text-center vspacer-lg">';
             $this->HTML .= $pagesMenu;
             $this->HTML .= '</div>';
             $this->HTML .= '<div class="col-sm-4 col-md-3 col-lg-2 col-md-offset-1 col-lg-offset-3 text-right vspacer-lg">';
             $this->HTML .= '<button onClick="' . $resetSelection . ' document.myform.NoDV.value=1; return true;" type="submit" name="Next_x" id="Next" value="1" class="btn btn-default btn-block">' . $Translation['Next'] . ' <i class="glyphicon glyphicon-chevron-right"></i></button>';
             $this->HTML .= '</div>';
             $this->HTML .= '</div>';
         }
     }
     /* that marks the end of the TV table */
     // hidden variables ....
     foreach ($this->filterers as $filterer => $caption) {
         if ($_REQUEST['filterer_' . $filterer] != '') {
             $this->HTML .= "<input name=\"filterer_{$filterer}\" value=\"" . htmlspecialchars($_REQUEST['filterer_' . $filterer], ENT_QUOTES, 'iso-8859-1') . "\" type=\"hidden\" />";
             break;
             // currently, only one filterer can be applied at a time
         }
     }
     $this->HTML .= '<input name="SortField" value="' . $SortField . '" type="hidden">';
     $this->HTML .= '<input name="SelectedID" value="' . htmlspecialchars($SelectedID, ENT_QUOTES, 'iso-8859-1') . '" type="hidden">';
     $this->HTML .= '<input name="SelectedField" value="" type="hidden">';
     $this->HTML .= '<input name="SortDirection" type="hidden" value="' . $SortDirection . '">';
     $this->HTML .= '<input name="FirstRecord" type="hidden" value="' . $FirstRecord . '">';
     $this->HTML .= '<input name="NoDV" type="hidden" value="">';
     $this->HTML .= '<input name="PrintDV" type="hidden" value="">';
     if ($this->QuickSearch && !strpos($this->HTML, 'SearchString')) {
         $this->HTML .= '<input name="SearchString" type="hidden" value="' . htmlspecialchars($SearchString, ENT_QUOTES, 'iso-8859-1') . '">';
     }
     // hidden variables: filters ...
     $FiltersCode = '';
     for ($i = 1; $i <= datalist_filters_count * $FiltersPerGroup; $i++) {
         // Number of filters allowed
         if ($i % $FiltersPerGroup == 1 && $i != 1 && $FilterAnd[$i] != '') {
             $FiltersCode .= "<input name=\"FilterAnd[{$i}]\" value=\"{$FilterAnd[$i]}\" type=\"hidden\">\n";
         }
         if ($FilterField[$i] != '' && $FilterOperator[$i] != '' && ($FilterValue[$i] != '' || strpos($FilterOperator[$i], 'empty'))) {
             if (!strstr($FiltersCode, "<input name=\"FilterAnd[{$i}]\" value=")) {
                 $FiltersCode .= "<input name=\"FilterAnd[{$i}]\" value=\"{$FilterAnd[$i]}\" type=\"hidden\">\n";
             }
             $FiltersCode .= "<input name=\"FilterField[{$i}]\" value=\"{$FilterField[$i]}\" type=\"hidden\">\n";
             $FiltersCode .= "<input name=\"FilterOperator[{$i}]\" value=\"{$FilterOperator[$i]}\" type=\"hidden\">\n";
             $FiltersCode .= "<input name=\"FilterValue[{$i}]\" value=\"" . htmlspecialchars($FilterValue[$i], ENT_QUOTES, 'iso-8859-1') . "\" type=\"hidden\">\n";
         }
     }
     $FiltersCode .= "<input name=\"DisplayRecords\" value=\"{$DisplayRecords}\" type=\"hidden\" />";
     $this->HTML .= $FiltersCode;
     // display details form ...
     if (($this->AllowSelection || $this->AllowInsert || $this->AllowUpdate || $this->AllowDelete) && $Print_x == '' && !$PrintDV) {
         if ($this->SeparateDV && $this->HideTableView || !$this->SeparateDV) {
             $dvCode = call_user_func("{$this->TableName}_form", $SelectedID, $this->AllowUpdate, $this->HideTableView && $SelectedID ? 0 : $this->AllowInsert, $this->AllowDelete, $this->SeparateDV);
             $this->HTML .= "\n\t<div class=\"panel panel-default detail_view\">{$dvCode}</div>";
             $this->HTML .= $this->SeparateDV ? '<input name="SearchString" value="' . htmlspecialchars($SearchString, ENT_QUOTES, 'iso-8859-1') . '" type="hidden">' : '';
             if ($dvCode) {
                 $this->ContentType = 'detailview';
                 $dvShown = true;
             }
         }
     }
     // display multiple printable detail views
     if ($PrintDV) {
         $dvCode = '';
         $_POST['dvprint_x'] = $_GET['dvprint_x'] = $_REQUEST['dvprint_x'] = 1;
         // hidden vars
         foreach ($this->filterers as $filterer => $caption) {
             if ($_REQUEST['filterer_' . $filterer] != '') {
                 $this->HTML .= "<input name=\"filterer_{$filterer}\" value=\"" . htmlspecialchars($_REQUEST['filterer_' . $filterer], ENT_QUOTES, 'iso-8859-1') . "\" type=\"hidden\" />";
                 break;
                 // currently, only one filterer can be applied at a time
             }
         }
         // count selected records
         $selectedRecords = 0;
         if (is_array($_POST['record_selector'])) {
             foreach ($_POST['record_selector'] as $id) {
                 $selectedRecords++;
                 $this->HTML .= '<input type="hidden" name="record_selector[]" value="' . htmlspecialchars($id, ENT_QUOTES, 'iso-8859-1') . '">' . "\n";
             }
         }
         if ($selectedRecords && $selectedRecords <= datalist_max_records_dv_print) {
             // if records selected > {datalist_max_records_dv_print} don't show DV preview to avoid db performance issues.
             foreach ($_POST['record_selector'] as $id) {
                 $dvCode .= call_user_func($this->TableName . '_form', $id, 0, 0, 0, 1);
             }
             if ($dvCode != '') {
                 $dvCode = preg_replace('/<input .*?type="?image"?.*?>/', '', $dvCode);
                 $this->HTML .= $dvCode;
             }
         } else {
             $this->HTML .= error_message($Translation['Maximum records allowed to enable this feature is'] . ' ' . datalist_max_records_dv_print);
             $this->HTML .= '<input type="submit" class="print-button" value="' . $Translation['Print Preview Table View'] . '">';
         }
     }
     $this->HTML .= "</form>";
     $this->HTML .= '</div><div class="col-xs-1 md-hidden lg-hidden"></div></div>';
     // $this->HTML .= '<font face="garamond">'.htmlspecialchars($tvQuery).'</font>';  // uncomment this line for debugging the table view query
     if ($dvShown && $tvShown) {
         $this->ContentType = 'tableview+detailview';
     }
     if ($dvprint_x != '') {
         $this->ContentType = 'print-detailview';
     }
     if ($Print_x != '') {
         $this->ContentType = 'print-tableview';
     }
     if ($PrintDV != '') {
         $this->ContentType = 'print-detailview';
     }
     // call detail view javascript hook file if found
     $dvJSHooksFile = dirname(__FILE__) . '/hooks/' . $this->TableName . '-dv.js';
     if (is_file($dvJSHooksFile) && ($this->ContentType == 'detailview' || $this->ContentType == 'tableview+detailview')) {
         $this->HTML .= "\n<script src=\"hooks/{$this->TableName}-dv.js\"></script>\n";
     }
 }
Example #15
0
 /**
  * 格式化POST或者PUT的数据
  * @params $postData 提交的数据
  * @params $forceInsert 强制定义为插入,而非修改(billItem是否包含ID)
  */
 public function formatData($postData, $forceInsert = false)
 {
     $stockinModel = $this;
     $billData = array("bill_id" => makeBillCode(C("BILL_PREFIX.Stockin")), "subject" => $postData["subject"], "dateline" => $postData["dateline"] ? strtotime($postData["dateline"]) : CTS, "status" => 0, "user_id" => getCurrentUid(), "stock_manager" => 0, "total_num" => 0, "memo" => $postData["memo"], "type_id" => $postData["type_id"]);
     if ($postData["source_model"]) {
         $billData["source_model"] = $postData["source_model"];
         $billData["source_id"] = $postData["source_id"];
     }
     $id = abs(intval($_GET["id"]));
     if ($id) {
         $billData["id"] = $id;
     }
     $data = $postData["rows"];
     $billItems = array();
     $needed = array("goods_id", "num");
     foreach ($data as $k => $billItem) {
         if (!$billItem || !$billItem["num"] || !checkParamsFull($billItem, $needed)) {
             continue;
         }
         list($factory_code, $goodsId, $catid) = explode("_", $billItem["goods_id"]);
         $billItems[$k] = array("goods_id" => $goodsId, "num" => $billItem["num"], "factory_code_all" => makeFactoryCode($billItem, $factory_code), "memo" => $billItem["memo"], "stock_id" => $billItem["stock"]);
         $billData["total_num"] += $billItem["num"];
         if (!$forceInsert and $billItem["id"]) {
             $billItems[$k]["id"] = $billItem["id"];
         }
     }
     return array($billData, reIndex($billItems));
 }
 public function index()
 {
     $appConf = F("appConf");
     $appConf = $appConf[CURRENT_APP];
     $dateStart = strtotime(date("Y-m"));
     $dateEnd = CTS;
     if ($_GET["_filter_start_dateline"]) {
         $dateStart = strtotime($_GET["_filter_start_dateline"]);
     }
     if ($_GET["_filter_end_dateline"]) {
         $dateEnd = strtotime($_GET["_filter_end_dateline"]);
     }
     $limit = $this->beforeLimit();
     //库存信息
     $storeModel = D("StockProductList");
     $tmp = $storeModel->table(C("DB_PREFIX") . "stock_product_list StockProductList")->field("SUM(StockProductList.num) as store_num, goods_id, factory_code_all, Goods.name as goods_name, Goods.measure")->join(C("DB_PREFIX") . "goods Goods ON Goods.id=StockProductList.goods_id")->group("factory_code_all")->order("store_num DESC")->limit($limit)->select();
     $params = array($tmp, false);
     tag("assign_dataModel_data", $params);
     $tmp = $params[0];
     $storeInfo = array();
     foreach ($tmp as $v) {
         $storeInfo[$v["factory_code_all"]] = $v;
         $factoryCodes[] = $v["factory_code_all"];
     }
     //销售
     if (isAppLoaded("sale")) {
         $orderMap = array("OrdersDetail.factory_code_all" => array("IN", implode(",", $factoryCodes)), "Orders.dateline" => array("BETWEEN", array($dateStart, $dateEnd)), "Orders.status" => array("GT", 0), "Orders.deleted" => 0);
         $orderModel = D("OrdersDetailView");
         $tmp = $orderModel->field("factory_code_all, SUM(OrdersDetail.amount) AS total_amount, SUM(OrdersDetail.num) as total_num")->where($orderMap)->group("OrdersDetail.factory_code_all")->select();
         $ordersInfo = array();
         foreach ($tmp as $v) {
             $ordersInfo[$v["factory_code_all"]] = $v;
         }
     }
     //生产
     if (isAppLoaded("produce")) {
         $produceMap = array("ProducePlan.end_time" => array("BETWEEN", array($dateStart, $dateEnd)), "ProducePlan.status" => array("EGT", 4), "ProducePlanDetail.factory_code_all" => array("IN", implode(",", $factoryCodes)));
         $produceModel = D("ProducePlanDetailView");
         $tmp = $produceModel->field("factory_code_all, SUM(ProducePlanDetail.num) as total_num")->where($produceMap)->select();
         foreach ($tmp as $v) {
             $produceInfo[$v["factory_code_all"]] = $v["total_num"];
         }
     }
     //采购
     if (isAppLoaded("purchase")) {
         $purchaseModel = D("PurchaseDetailView");
         $purchaseMap = array("Purchase.dateline" => array("BETWEEN", array($dateStart, $dateEnd)), "Purchase.status" => array("EGT", 1), "PurchaseDetail.factory_code_all" => array("IN", implode(",", $factoryCodes)));
         $tmp = $purchaseModel->field("factory_code_all, SUM(PurchaseDetail.num) as total_num, SUM(PurchaseDetail.price) AS total_amount")->where($purchaseMap)->select();
         foreach ($tmp as $v) {
             $purchaseInfo[$v["factory_code_all"]] = $v;
         }
         foreach ($storeInfo as $k => $v) {
             $storeInfo[$k]["sale_num"] = $ordersInfo[$k]["total_num"];
             $storeInfo[$k]["sale_amount"] = $ordersInfo[$k]["total_amount"];
             $storeInfo[$k]["produce_num"] = $produceInfo[$k];
             $storeInfo[$k]["purchase_num"] = $purchaseInfo[$k]["total_num"];
             $storeInfo[$k]["purchase_amount"] = $purchaseInfo[$k]["total_amount"];
         }
     }
     $this->response(reIndex($storeInfo));
 }
Example #17
0
 /**
  * 根据AuthRule生成左侧导航,不同用户生成不同缓存
  * @todo 三级分类(快捷导航)
  */
 private function makeNav()
 {
     $navs = F("Nav/" . $this->user["id"]);
     if ($navs) {
         return $navs;
     }
     $navs = (require APP_PATH . "Conf" . DS . "navs.php");
     $appConf = $this->getAppConfig();
     //        print_r($appConf);exit;
     $navs = array_merge_recursive($navs, $appConf["navs"]);
     import("@.ORG.Auth");
     foreach ($navs as $rootLabel => $data) {
         $theChild = array();
         //二级菜单
         foreach ($data["childs"] as $childLabel => $childData) {
             $theThird = array();
             // 包含三级菜单
             if (is_array($childData)) {
                 foreach ($childData as $thirdLabel => $thirdUrl) {
                     list($thirdData, $thirdIcon) = explode(",", $thirdUrl);
                     if ($thirdLabel == "icon") {
                         continue;
                     }
                     if ($this->checkNavPermission($thirdData)) {
                         $theThird[] = array("label" => $thirdLabel, "url" => $thirdData, "icon" => $thirdIcon, "id" => md5($thirdData . $thirdLabel));
                     } else {
                         //                            print_r($thirdData);
                     }
                 }
             }
             if ($theThird) {
                 $theChild[$childLabel]["childs"] = $theThird;
                 if ($childData["icon"]) {
                     $theChild[$childLabel]["icon"] = $childData["icon"];
                 }
                 $childUrl = $childData;
             } else {
                 list($childUrl, $childIcon) = explode(",", $childData);
                 $tmpRs = $this->checkNavPermission($childUrl);
                 if ($tmpRs) {
                     $theChild[$childLabel]["url"] = $childUrl;
                     $theChild[$childLabel]["icon"] = $childIcon;
                 }
             }
             if ($theThird or $tmpRs) {
                 $theChild[$childLabel]["label"] = $childLabel;
                 $theChild[$childLabel]["id"] = md5($childLabel . json_encode($childUrl));
             }
         }
         $theChild = reIndex($theChild);
         if ($theChild or $this->checkNavPermission($data["action"])) {
             $theNav[$rootLabel] = array("childs" => $theChild, "label" => $rootLabel, "icon" => $data["icon"], "id" => md5($rootLabel . json_encode($data)), "url" => $data["action"] ? $data["action"] : "");
         }
     }
     $theNav = reIndex($theNav);
     return $theNav;
 }
Example #18
0
 /**
  *
  * 通用REST列表返回
  **/
 public function index($return = false, $returnIncludeCount = true)
 {
     $this->_external_action();
     if ($this->breakAction) {
         return;
     }
     if (method_exists($this, "_before_index")) {
         $this->_before_index();
     }
     $name = $this->indexModel ? $this->indexModel : $this->getActionName();
     $model = D($name);
     /**
      * 查看是否在fields列表中
      */
     if (empty($model)) {
         $this->error(L("Server error"));
     }
     $limit = $this->beforeLimit();
     $map = $this->beforeFilter($model);
     $order = $this->beforeOrder($model);
     $this->_filter($map);
     $this->_order($order);
     call_user_func_array(array($this, "_extend_rows_permission_index"), array(&$map));
     if ($_GET["onlyCount"]) {
         $total = $model->where($map)->count();
         $this->response(array(array("count" => $total)));
         return;
     } else {
         if ($this->relation && method_exists($model, "relation")) {
             $model = $model->relation(true);
         } else {
             if ($this->relation && $model->_link) {
                 $model = $model->switchModel("Relation", array("_link", $model->_link))->relation(true);
             }
         }
         $model = $model->where($map)->order($order);
         //AutoComplete字段默认只取10条
         if (isset($_GET["typeahead"])) {
             $limit = 10;
         }
         if (isset($_GET["limit"])) {
             $limit = abs(intval($_GET["limit"]));
         }
         if ($limit) {
             $model = $model->limit($limit);
         }
         if ($order) {
             $model = $model->order($order);
         }
         $list = $model->select();
         if ($this->echoSQL) {
             echo $model->getLastSql();
             exit;
         }
         $this->queryMeta = array("map" => $map, "limit" => $limit, "order" => $order);
         //绑定模型数据
         if ($this->dataModelAlias) {
             $params = array($list, $this->dataModelAlias, false, true);
             tag("assign_dataModel_data", $params);
             $list = $params[0];
         }
     }
     $list = reIndex($list);
     //包含总数
     if ($_GET["_ic"] && $returnIncludeCount) {
         $total = $model->where($map)->count();
         $totalPages = ceil($total / $_GET["_ps"]);
         if (!$totalPages) {
             $totalPages = 1;
         }
         $returnData = array(array("count" => $total, "totalPages" => $totalPages), reIndex($list));
         if ($return) {
             return $returnData;
         }
         $this->response($returnData);
     } else {
         if ($return) {
             return reIndex($list);
         }
         $this->response($list);
     }
 }
Example #19
0
 public function index()
 {
     import("@.ORG.httplib");
     $http = new httplib();
     //获取所有APP
     if ($_GET["queryAll"]) {
         //获取所有APP列表
         $http->set_header("Accept", "application/json,text/x-json,application/jsonrequest,text/json");
         $http->request($this->serviceUri . "App/getList/", array("_pn" => $_GET["_pn"], "_ps" => $_GET["_ps"], "_kw" => $_GET["_kw"], "lang" => $this->lang, "api_key" => C("SERVICE_API_KEY"), "secret_key" => C("SERVICE_SECRET_KEY")));
         $tmp = $http->get_data();
         $response = json_decode($tmp, true);
         if (!$response["count"]) {
             Log::write("get apps list failed");
             $this->error("get apps list failed");
             return;
         }
         $allApps = $response["apps"];
         $model = D("Apps");
         $tmp = $model->select();
         foreach ($tmp as $app) {
             $installedApps[] = $app["alias"];
             $installedAppVersions[$app["alias"]] = $app["version"];
             $installedaAppStatus[$app["alias"]] = $app["status"];
         }
         foreach ($allApps as $k => $app) {
             if (in_array($app["alias"], $installedApps)) {
                 $allApps[$k]["status_text"] = "Installed";
                 $allApps[$k]["installed"] = true;
                 if ($app["latest_version"] > $installedAppVersions[$app["alias"]]) {
                     $allApps[$k]["status_text"] = "HasUpdate";
                     $allApps[$k]["hasUpdate"] = true;
                 }
                 if ($installedaAppStatus[$app["alias"]]["status"] == 0) {
                     $allApps[$k]["status_text"] = "Inactive";
                 }
             }
         }
         $allApps = reIndex($allApps);
         if ($_GET["_ic"]) {
             $response["total"] = $response["total"] ? $response["total"] : $response["count"];
             $totalPages = ceil($response["total"] / $_GET["_ps"]);
             if (!$totalPages) {
                 $totalPages = 1;
             }
             $response = array(array("count" => $response["count"], "totalPages" => $totalPages), $allApps);
         } else {
             $response = $allApps;
         }
         $this->response($response);
     } else {
         $tmp = parent::index(true, false);
         if (!$tmp) {
             $this->response(array(array("count" => 0), array()));
             return;
         }
         foreach ($tmp as $app) {
             $installedApps[$app["alias"]] = $app;
             $installedAppAlias[] = $app["alias"];
         }
         $http->set_header("Accept", "application/json,text/x-json,application/jsonrequest,text/json");
         $http->request($this->serviceUri . "App/getList/", array("alias" => implode(",", $installedAppAlias), "lang" => $this->lang, "api_key" => C("SERVICE_API_KEY"), "secret_key" => C("SERVICE_SECRET_KEY")));
         $tmp = $http->get_data();
         $response = json_decode($tmp, true);
         foreach ($response["apps"] as $appMeta) {
             $installedApps[$appMeta["alias"]]["id"] = $appMeta["id"];
             $installedApps[$appMeta["alias"]]["name"] = $appMeta["name"];
             $installedApps[$appMeta["alias"]]["author"] = $appMeta["author"];
             $installedApps[$appMeta["alias"]]["link"] = $appMeta["link"];
             $installedApps[$appMeta["alias"]]["description"] = $appMeta["description"];
             $installedApps[$appMeta["alias"]]["status_text"] = "Installed";
             if ($appMeta["latest_version"] > $installedApps[$appMeta["alias"]]["version"]) {
                 $installedApps[$appMeta["alias"]]["status"] = "HasUpdate";
             }
             if ($installedApps[$appMeta["alias"]]["status"] == 0) {
                 $installedApps[$appMeta["alias"]]["status_text"] = "Inactive";
             }
         }
         $count = D("Apps")->where($this->queryMeta["map"])->count("id");
         $total = D("Apps")->count("id");
         $totalPages = ceil($total / $_GET["_ps"]);
         if (!$totalPages) {
             $totalPages = 1;
         }
         $this->response(array(array("count" => $count, "totalPages" => $totalPages), reIndex($installedApps)));
         return;
     }
 }
Example #20
0
 public function read()
 {
     if (!$_GET["includeRows"] or $_GET['workflow']) {
         return parent::read();
     }
     $formDatas = parent::read(true);
     $rowModel = D("StockinDetailView");
     if ($formDatas["id"]) {
         $isSingle = true;
         $formDatas = array($formDatas);
     }
     foreach ($formDatas as $id => $formData) {
         $formData["dateline"] *= 1000;
         $formData["stock_manager"] = toTruename($formData["stock_manager"]);
         $rows = $rowModel->where("StockinDetail.stockin_id=" . $formData["id"])->select();
         $modelIds = array();
         $rowData = array();
         foreach ($rows as $v) {
             $tmp = explode(DBC("goods.unique.separator"), $v["factory_code_all"]);
             //根据factory_code_all factory_code - standard - version
             $factory_code = array_shift($tmp);
             $modelIds = array_merge($modelIds, $tmp);
             $v["modelIds"] = $tmp;
             $v["stock"] = $v["stock_id"];
             $v["stock_label"] = $v["stock_name"];
             $v["goods_id"] = sprintf("%s_%s_%s", $factory_code, $v["goods_id"], $v["goods_category_id"]);
             // factory_code, id, catid
             $v["goods_id_label"] = sprintf("%s", $v["goods_name"]);
             $v["total_num"] = $v["num"];
             $v["num"] = $v["num"] - $v["ined"];
             $rowData[$v["id"]] = $v;
         }
         $params = array($rowData, $modelIds);
         tag("assign_dataModel_data", $params);
         $formData["rows"] = reIndex($params[0]);
         if ($formData["source_model"] && $formData["source_id"]) {
             $sourceModel = D($formData["source_model"] . "View");
             $formData["source"] = $sourceModel->find($formData["source_id"]);
             if ($_GET["includeRelated"]) {
                 try {
                     $model = D($formData["source_model"]);
                     $related = $model->getRelatedItem($formData["source_id"]);
                     $formData["relatedItems"][] = $related;
                 } catch (Exception $e) {
                 }
                 if ($_GET["includeSourceRows"]) {
                     $model = D($formData["source_model"] . "DetailView");
                     $foreignKey = $model->foreignKey ? $model->foreignKey : lcfirst($formData["source_model"]) . "_id";
                     $map[$foreignKey] = $formData["source_id"];
                     $formData["source_detail"] = $model->where($map)->select();
                 }
             }
         }
         $results[] = $formData;
     }
     if ($isSingle) {
         $this->response($formData);
         return;
     }
     $response = array("count" => count($results), "datas" => $results);
     $this->response($response);
 }
Example #21
0
 protected function ForSaleTotal($data, $start, $end, $step, $format = "m-d")
 {
     $dateRange = makeDateRange($start, $end, $step, $format);
     $value = array();
     $labels = array();
     foreach ($dateRange as $dr) {
         $labels[$dr] = $dr;
         $value[$dr] = 0;
         foreach ($data as $v) {
             $key = date($format, $v["dateline"]);
             if ($dr == $key) {
                 $value[$dr] += $v["total_amount_real"];
             }
         }
     }
     return array("series" => array(lang("amount")), "data" => array(reIndex($value)), "labels" => reIndex($labels));
 }
Example #22
0
function detailRowsReadFormat($rows)
{
    $modelIds = array();
    $rowData = array();
    foreach ($rows as $v) {
        $tmp = explode(DBC("goods.unique.separator"), $v["factory_code_all"]);
        //根据factory_code_all factory_code - standard - version
        $factory_code = array_shift($tmp);
        $modelIds = array_merge($modelIds, $tmp);
        $v["stock"] = $v["stock_id"];
        $v["stock_label"] = $v["stock_name"];
        $v["modelIds"] = $tmp;
        $v["goods_id"] = sprintf("%s_%s_%s", $factory_code, $v["goods_id"], $v["goods_category_id"]);
        // factory_code, id, catid
        $v["goods_id_label"] = $v["goods_name"];
        $rowData[$v["id"]] = $v;
    }
    return reIndex($rowData);
}
Example #23
0
 protected final function merge_same_rows($rows, $attribute_fields)
 {
     $cleaned_rows = [];
     foreach ($rows as $row) {
         if ($row['product_unique_id']) {
             $unique_key = sprintf('%s_%s', $row['product_unique_id'], $row['storage_id']);
         } else {
             if ($attribute_fields) {
                 $unique_key = sprintf('%d_%s_%d', $row['product_id'], implode('_', filter_array_fields($row, $attribute_fields)), $row['storage_id']);
             } else {
                 $unique_key = $row['product_id'] + '_' + $row['storage_id'];
             }
         }
         if (array_key_exists($unique_key, $cleaned_rows)) {
             $cleaned_rows[$unique_key]['quantity'] += $row['quantity'];
             continue;
         }
         $cleaned_rows[$unique_key] = $row;
     }
     return reIndex($cleaned_rows);
 }
 function Render()
 {
     // get post and get variables
     global $Translation;
     $FiltersPerGroup = 4;
     if ($_SERVER['REQUEST_METHOD'] == 'GET') {
         $SortField = $_GET["SortField"];
         $SortDirection = $_GET["SortDirection"];
         $FirstRecord = $_GET["FirstRecord"];
         $ScrollUp_y = $_GET["ScrollUp_y"];
         $ScrollDn_y = $_GET["ScrollDn_y"];
         $Previous_x = $_GET["Previous_x"];
         $Next_x = $_GET["Next_x"];
         $Filter_x = $_GET["Filter_x"];
         $SaveFilter_x = $_GET["SaveFilter_x"];
         $NoFilter_x = $_GET["NoFilter_x"];
         $CancelFilter = $_GET["CancelFilter"];
         $ApplyFilter = $_GET["ApplyFilter"];
         $Search_x = $_GET["Search_x"];
         $SearchString = get_magic_quotes_gpc() ? stripslashes($_GET['SearchString']) : $_GET['SearchString'];
         $CSV_x = $_GET["CSV_x"];
         $FilterAnd = $_GET["FilterAnd"];
         $FilterField = $_GET["FilterField"];
         $FilterOperator = $_GET["FilterOperator"];
         if (is_array($_GET['FilterValue'])) {
             foreach ($_GET['FilterValue'] as $fvi => $fv) {
                 $FilterValue[$fvi] = get_magic_quotes_gpc() ? stripslashes($fv) : $fv;
             }
         }
         $Print_x = $_GET["Print_x"];
         $SelectedID = get_magic_quotes_gpc() ? stripslashes($_GET['SelectedID']) : $_GET['SelectedID'];
         $insert_x = $_GET["insert_x"];
         $update_x = $_GET["update_x"];
         $delete_x = $_GET["delete_x"];
         $SkipChecks = $_GET['confirmed'];
         $deselect_x = $_GET["deselect_x"];
         $addNew_x = $_GET["addNew_x"];
         $dvprint_x = $_GET['dvprint_x'];
     } else {
         $SortField = $_POST["SortField"];
         $SortDirection = $_POST["SortDirection"];
         $FirstRecord = $_POST["FirstRecord"];
         $ScrollUp_y = $_POST["ScrollUp_y"];
         $ScrollDn_y = $_POST["ScrollDn_y"];
         $Previous_x = $_POST["Previous_x"];
         $Next_x = $_POST["Next_x"];
         $Filter_x = $_POST["Filter_x"];
         $SaveFilter_x = $_POST["SaveFilter_x"];
         $NoFilter_x = $_POST["NoFilter_x"];
         $CancelFilter = $_POST["CancelFilter"];
         $ApplyFilter = $_POST["ApplyFilter"];
         $Search_x = $_POST["Search_x"];
         $SearchString = get_magic_quotes_gpc() ? stripslashes($_POST['SearchString']) : $_POST['SearchString'];
         $CSV_x = $_POST["CSV_x"];
         $FilterAnd = $_POST['FilterAnd'];
         $FilterField = $_POST['FilterField'];
         $FilterOperator = $_POST['FilterOperator'];
         if (is_array($_POST['FilterValue'])) {
             foreach ($_POST['FilterValue'] as $fvi => $fv) {
                 $FilterValue[$fvi] = get_magic_quotes_gpc() ? stripslashes($fv) : $fv;
             }
         }
         $Print_x = $_POST['Print_x'];
         $PrintTV = $_POST['PrintTV'];
         $PrintDV = $_POST['PrintDV'];
         $SelectedID = get_magic_quotes_gpc() ? stripslashes($_POST['SelectedID']) : $_POST['SelectedID'];
         $insert_x = $_POST['insert_x'];
         $update_x = $_POST['update_x'];
         $delete_x = $_POST['delete_x'];
         $SkipChecks = $_POST['confirmed'];
         $deselect_x = $_POST['deselect_x'];
         $addNew_x = $_POST['addNew_x'];
         $dvprint_x = $_POST['dvprint_x'];
     }
     // insure authenticity of user inputs:
     if (!$this->AllowDelete) {
         $delete_x = "";
     }
     if (!$this->AllowDeleteOfParents) {
         $SkipChecks = "";
     }
     if (!$this->AllowInsert) {
         $insert_x = "";
         $addNew_x = "";
     }
     if (!$this->AllowUpdate) {
         $update_x = "";
     }
     if (!$this->AllowFilters) {
         $Filter_x = "";
     }
     if (!$this->AllowPrinting) {
         $Print_x = '';
         $PrintDV = '';
         $PrintTV = '';
     }
     if (!$this->AllowPrintingMultiSelection) {
         $PrintDV = '';
         $PrintTV = '';
     }
     if (!$this->QuickSearch) {
         $SearchString = "";
     }
     if (!$this->AllowCSV) {
         $CSV_x = "";
     }
     // enforce record selection if user has edit/delete permissions on the current table
     $AllowPrintDV = 1;
     $this->Permissions = getTablePermissions($this->TableName);
     if ($this->Permissions[3] || $this->Permissions[4]) {
         // current user can edit or delete?
         $this->AllowSelection = 1;
     } elseif (!$this->AllowSelection) {
         $SelectedID = '';
         $AllowPrintDV = 0;
         $PrintDV = '';
     }
     if (!$this->AllowSelection || !$SelectedID) {
         $dvprint_x = '';
     }
     $this->QueryFieldsIndexed = reIndex($this->QueryFieldsFilters);
     $this->HTML .= '<form method="post" name="myform" action="' . $this->ScriptFileName . '">';
     $this->HTML .= '<input type="submit" style="position: absolute; left: 0px; top: -100px;" onclick="return false;">';
     $this->ContentType = 'tableview';
     // default content type
     // handle user commands ...
     if ($PrintTV != '') {
         $Print_x = 1;
         $_POST['Print_x'] = 1;
     }
     if ($deselect_x != '') {
         $SelectedID = '';
         $this->showTV();
     } elseif ($insert_x != '') {
         $SelectedID = call_user_func($this->TableName . '_insert');
         // redirect to a safe url to avoid refreshing and thus
         // insertion of duplicate records.
         // compose filters and sorting
         for ($i = 1; $i <= 20 * $FiltersPerGroup; $i++) {
             // Number of filters allowed
             if ($FilterField[$i] != "" && $FilterOperator[$i] != "" && ($FilterValue[$i] != "" || strstr($FilterOperator[$i], 'Empty'))) {
                 $filtersGET .= "&FilterAnd[{$i}]={$FilterAnd[$i]}&FilterField[{$i}]={$FilterField[$i]}&FilterOperator[{$i}]={$FilterOperator[$i]}&FilterValue[{$i}]=" . urlencode($FilterValue[$i]);
             }
         }
         $filtersGET .= "&SortField={$SortField}&SortDirection={$SortDirection}&FirstRecord={$FirstRecord}";
         $filtersGET = substr($filtersGET, 1);
         // remove initial &
         if ($this->RedirectAfterInsert != "") {
             if (strpos($this->RedirectAfterInsert, '?')) {
                 $this->RedirectAfterInsert .= '&record-added-ok=' . rand();
             } else {
                 $this->RedirectAfterInsert .= '?record-added-ok=' . rand();
             }
             if (strpos($this->RedirectAfterInsert, $this->ScriptFileName) !== false) {
                 $this->RedirectAfterInsert .= '&' . $filtersGET;
             }
             $this->HTML .= "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"0;url=" . str_replace("#ID#", urlencode($SelectedID), $this->RedirectAfterInsert) . "\">";
             return;
         } else {
             $this->HTML .= '<META HTTP-EQUIV="Refresh" CONTENT="0;url=' . $this->ScriptFileName . '?SelectedID=' . urlencode($SelectedID) . '&' . $filtersGET . '">';
             return;
         }
     } elseif ($delete_x != "") {
         $d = call_user_func($this->TableName . '_delete', $SelectedID, $this->AllowDeleteOfParents, $SkipChecks);
         if ($d) {
             $this->HTML .= "<div class=Error>" . $Translation['error:'] . " {$d}</div>";
         } else {
             $SelectedID = "";
             $this->showTV();
         }
     } elseif ($update_x != "") {
         call_user_func($this->TableName . '_update', $SelectedID);
         // compose filters and sorting
         for ($i = 1; $i <= 20 * $FiltersPerGroup; $i++) {
             // Number of filters allowed
             if ($FilterField[$i] != "" && $FilterOperator[$i] != "" && ($FilterValue[$i] != "" || strstr($FilterOperator[$i], 'Empty'))) {
                 $filtersGET .= "&FilterAnd[{$i}]={$FilterAnd[$i]}&FilterField[{$i}]={$FilterField[$i]}&FilterOperator[{$i}]={$FilterOperator[$i]}&FilterValue[{$i}]=" . urlencode($FilterValue[$i]);
             }
         }
         $filtersGET .= "&SortField={$SortField}&SortDirection={$SortDirection}&FirstRecord={$FirstRecord}";
         $filtersGET = substr($filtersGET, 1);
         // remove initial &
         $this->HTML .= '<META HTTP-EQUIV="Refresh" CONTENT="0;url=' . $this->ScriptFileName . '?SelectedID=' . urlencode($SelectedID) . '&' . $filtersGET . '&record-updated-ok=' . rand() . '">';
         return;
     } elseif ($addNew_x != "") {
         $SelectedID = '';
         $this->hideTV();
     } elseif ($Print_x != "") {
         // print code here ....
         $this->AllowNavigation = 0;
         $this->AllowSelection = 0;
     } elseif ($SaveFilter_x != "" && $this->AllowSavingFilters) {
         $this->HTML .= "<table width=550 border=0 align=center><tr><td class=TableTitle>" . $Translation["saved filters title"] . "</td></tr>";
         $this->HTML .= "\n\t<tr><td class=TableHeader>" . $Translation["saved filters instructions"] . "</td></tr>";
         $this->HTML .= "\n\t<tr><td class=TableHeader><textarea cols=60 rows=12 wrap=off>";
         $SourceCode = "<html><body>\n";
         $SourceCode .= '<form method="post" action="' . $_SERVER['HTTP_REFERER'] . '">' . "\n";
         for ($i = 1; $i <= 20 * $FiltersPerGroup; $i++) {
             // Number of filters allowed
             if ($i % $FiltersPerGroup == 1 && $i != 1 && $FilterAnd[$i] != "") {
                 $SourceCode .= "\t<input name=FilterAnd[{$i}] value='{$FilterAnd[$i]}' type=hidden>\n";
             }
             if ($FilterField[$i] != "" && $FilterOperator[$i] != "" && ($FilterValue[$i] != "" || strstr($FilterOperator[$i], 'Empty'))) {
                 if (!strstr($SourceCode, "\t<input name=FilterAnd[{$i}] value=")) {
                     $SourceCode .= "\t<input name=FilterAnd[{$i}] value='{$FilterAnd[$i]}' type=hidden>\n";
                 }
                 $SourceCode .= "\t<input name=FilterField[{$i}] value='{$FilterField[$i]}' type=hidden>\n";
                 $SourceCode .= "\t<input name=FilterOperator[{$i}] value='{$FilterOperator[$i]}' type=hidden>\n";
                 $SourceCode .= "\t<input name=FilterValue[{$i}] value='" . htmlspecialchars($FilterValue[$i], ENT_QUOTES) . "' type=hidden>\n\n";
             }
         }
         $SourceCode .= "\n\t<input type=submit value=\"Show Filtered Data\">\n";
         $SourceCode .= "</form>\n</body></html>";
         $this->HTML .= $SourceCode;
         $this->HTML .= "</textarea>";
         $this->HTML .= "<br /><input type=submit value=\"" . $Translation["hide code"] . "\">";
         $this->HTML .= "\n\t</table>\n\n";
     } elseif ($Filter_x != "") {
         if ($this->FilterPage != "") {
             ob_start();
             @(include $this->FilterPage);
             $out = ob_get_contents();
             ob_end_clean();
             $this->HTML .= $out;
         } else {
             // filter page code here .....
             $this->HTML .= '<table border="0" align="center"><tr><td colspan="4" class="TableTitle">' . $this->TableTitle . " " . $Translation['filters'] . "</td></tr>";
             $this->HTML .= "\n\t<tr><td class=\"TableHeader\"></td><td class=\"TableHeader\">" . $Translation['filtered field'] . '</td><td class="TableHeader">' . $Translation['comparison operator'] . '</td><td class="TableHeader">' . $Translation['comparison value'] . '</td></tr>';
             $this->HTML .= "\n\t<tr><td colspan=\"4\" class=\"TableHeader\"></td></tr>";
             for ($i = 1; $i <= 3 * $FiltersPerGroup; $i++) {
                 // Number of filters allowed
                 $fields = "";
                 $operators = "";
                 if ($i % $FiltersPerGroup == 1 && $i != 1) {
                     $this->HTML .= "\n\t<tr><td colspan=4 class=TableHeader></td></tr>";
                     $this->HTML .= "\n\t<tr><td colspan=4 align=center>";
                     $seland = new Combo();
                     $seland->ListItem = array($Translation["or"], $Translation["and"]);
                     $seland->ListData = array("or", "and");
                     $seland->SelectName = "FilterAnd[{$i}]";
                     $seland->SelectedData = $FilterAnd[$i];
                     $seland->Render();
                     $this->HTML .= $seland->HTML . "</td></tr>";
                     $this->HTML .= "\n\t<tr><td colspan=4 class=TableHeader></td></tr>";
                 }
                 $this->HTML .= "\n\t<tr><td class=TableHeader style='text-align:left;'>&nbsp;" . $Translation["filter"] . sprintf("%02d", $i) . " ";
                 // And, Or select
                 if ($i % $FiltersPerGroup != 1) {
                     $seland = new Combo();
                     $seland->ListItem = array($Translation["and"], $Translation["or"]);
                     $seland->ListData = array("and", "or");
                     $seland->SelectName = "FilterAnd[{$i}]";
                     $seland->SelectedData = $FilterAnd[$i];
                     $seland->Render();
                     $this->HTML .= $seland->HTML . "</td>";
                 } else {
                     $this->HTML .= "</td>";
                 }
                 // Fields list
                 $selfields = new Combo();
                 $selfields->SelectName = "FilterField[{$i}]";
                 $selfields->SelectedData = $FilterField[$i];
                 $selfields->ListItem = array_values($this->QueryFieldsFilters);
                 $selfields->ListData = array_keys($this->QueryFieldsIndexed);
                 $selfields->Render();
                 $this->HTML .= "\n\t\t<td>{$selfields->HTML}</td>";
                 // Operators list
                 $selop = new Combo();
                 $selop->ListItem = array($Translation["equal to"], $Translation["not equal to"], $Translation["greater than"], $Translation["greater than or equal to"], $Translation["less than"], $Translation["less than or equal to"], $Translation["like"], $Translation["not like"], $Translation["is empty"], $Translation["is not empty"]);
                 $selop->ListData = array("<=>", "!=", ">", ">=", "<", "<=", "like", "not like", "isEmpty", "isNotEmpty");
                 $selop->SelectName = "FilterOperator[{$i}]";
                 $selop->SelectedData = $FilterOperator[$i];
                 $selop->Render();
                 $this->HTML .= "\n\t\t<td>{$selop->HTML}</td>";
                 // Comparison expression
                 $this->HTML .= "\n\t\t<td><input size=25 type=text name=FilterValue[{$i}] value=\"" . htmlspecialchars($FilterValue[$i], ENT_QUOTES) . "\" class=TextBox></td></tr>";
                 if (!$i % $FiltersPerGroup) {
                     $this->HTML .= "\n\t<tr><td colspan=4 class=TableHeader></td></tr>";
                 }
             }
             $this->HTML .= "\n\t<tr><td colspan=4 class=TableHeader></td></tr>";
             $this->HTML .= "\n\t<tr><td colspan=4 align=right><input type=image src=applyFilters.gif alt='" . $Translation["apply filters"] . "'>" . ($this->AllowSavingFilters ? " &nbsp; <input type=image src=save_search.gif alt='" . $Translation["save filters"] . "' name=SaveFilter>" : "") . "</td></tr>";
             $this->HTML .= "\n</table>";
         }
         // hidden variables ....
         $this->HTML .= "<input name=SortField value='" . (is_numeric($SortField) ? $SortField : $SortFieldNumeric) . "' type=hidden>";
         $this->HTML .= "<input name=SortDirection type=hidden value='{$SortDirection}'>";
         $this->HTML .= "<input name=FirstRecord type=hidden value='1'>";
         $this->ContentType = 'filters';
         return;
     } elseif ($NoFilter_x != "") {
         // clear all filters ...
         for ($i = 1; $i <= 20 * $FiltersPerGroup; $i++) {
             // Number of filters allowed
             $FilterField[$i] = "";
             $FilterOperator[$i] = "";
             $FilterValue[$i] = "";
         }
         $SearchString = "";
     } elseif ($SelectedID) {
         $this->hideTV();
     }
     if ($SearchString != '') {
         if ($Search_x != '') {
             $FirstRecord = 1;
         }
         if ($this->QueryWhere == '') {
             $this->QueryWhere = "where ";
         } else {
             $this->QueryWhere .= " and ";
         }
         foreach ($this->QueryFieldsQS as $fName => $fCaption) {
             if (strpos($fName, '<img') === False) {
                 $this->QuerySearchableFields[$fName] = $fCaption;
             }
         }
         $this->QueryWhere .= '(' . implode(" LIKE '%" . makeSafe($SearchString) . "%' or ", array_keys($this->QuerySearchableFields)) . " LIKE '%" . makeSafe($SearchString) . "%')";
     }
     // set query filters
     $QueryHasWhere = 0;
     if (strpos($this->QueryWhere, 'where ') !== FALSE) {
         $QueryHasWhere = 1;
     }
     $WhereNeedsClosing = 0;
     for ($i = 1; $i <= 20 * $FiltersPerGroup; $i += $FiltersPerGroup) {
         // Number of filters allowed
         // test current filter group
         $GroupHasFilters = 0;
         for ($j = 0; $j < $FiltersPerGroup; $j++) {
             if ($FilterField[$i + $j] != "" && $FilterOperator[$i + $j] != "" && ($FilterValue[$i + $j] != "" || strstr($FilterOperator[$i + $j], 'Empty'))) {
                 $GroupHasFilters = 1;
                 break;
             }
         }
         if ($GroupHasFilters) {
             if (!stristr($this->QueryWhere, "where ")) {
                 $this->QueryWhere = "where (";
             } elseif ($QueryHasWhere) {
                 $this->QueryWhere .= " and (";
                 $QueryHasWhere = 0;
             }
             $this->QueryWhere .= " <FilterGroup> " . $FilterAnd[$i] . " (";
             for ($j = 0; $j < $FiltersPerGroup; $j++) {
                 if ($FilterField[$i + $j] != "" && $FilterOperator[$i + $j] != "" && ($FilterValue[$i + $j] != "" || strstr($FilterOperator[$i + $j], 'Empty'))) {
                     if ($FilterAnd[$i + $j] == '') {
                         $FilterAnd[$i + $j] = 'and';
                     }
                     // test for date/time fields
                     $tries = 0;
                     $isDateTime = FALSE;
                     $isDate = FALSE;
                     $fieldName = str_replace('`', '', $this->QueryFieldsIndexed[$FilterField[$i + $j]]);
                     list($tn, $fn) = explode('.', $fieldName);
                     while (!($res = sql("show columns from `{$tn}` like '{$fn}'")) && $tries < 2) {
                         $tn = substr($tn, 0, -1);
                         $tries++;
                     }
                     if ($row = @mysql_fetch_array($res)) {
                         if ($row['Type'] == 'date' || $row['Type'] == 'time') {
                             $isDateTime = TRUE;
                             if ($row['Type'] == 'date') {
                                 $isDate = True;
                             }
                         }
                     }
                     // end of test
                     if ($FilterOperator[$i + $j] == 'isEmpty' && !$isDateTime) {
                         $this->QueryWhere .= " <FilterItem> " . $FilterAnd[$i + $j] . " (" . $this->QueryFieldsIndexed[$FilterField[$i + $j]] . "='' or " . $this->QueryFieldsIndexed[$FilterField[$i + $j]] . " is NULL) </FilterItem>";
                     } elseif ($FilterOperator[$i + $j] == 'isNotEmpty' && !$isDateTime) {
                         $this->QueryWhere .= " <FilterItem> " . $FilterAnd[$i + $j] . " " . $this->QueryFieldsIndexed[$FilterField[$i + $j]] . "!='' </FilterItem>";
                     } elseif ($FilterOperator[$i + $j] == 'isEmpty' && $isDateTime) {
                         $this->QueryWhere .= " <FilterItem> " . $FilterAnd[$i + $j] . " (" . $this->QueryFieldsIndexed[$FilterField[$i + $j]] . "=0 or " . $this->QueryFieldsIndexed[$FilterField[$i + $j]] . " is NULL) </FilterItem>";
                     } elseif ($FilterOperator[$i + $j] == 'isNotEmpty' && $isDateTime) {
                         $this->QueryWhere .= " <FilterItem> " . $FilterAnd[$i + $j] . " " . $this->QueryFieldsIndexed[$FilterField[$i + $j]] . "!=0 </FilterItem>";
                     } elseif ($FilterOperator[$i + $j] == 'like' && !strstr($FilterValue[$i + $j], "%") && !strstr($FilterValue[$i + $j], "_")) {
                         $this->QueryWhere .= " <FilterItem> " . $FilterAnd[$i + $j] . " " . $this->QueryFieldsIndexed[$FilterField[$i + $j]] . " " . $FilterOperator[$i + $j] . " '%" . makeSafe($FilterValue[$i + $j]) . "%' </FilterItem>";
                     } elseif ($FilterOperator[$i + $j] == 'not like' && !strstr($FilterValue[$i + $j], "%") && !strstr($FilterValue[$i + $j], "_")) {
                         $this->QueryWhere .= " <FilterItem> " . $FilterAnd[$i + $j] . " " . $this->QueryFieldsIndexed[$FilterField[$i + $j]] . " " . $FilterOperator[$i + $j] . " '%" . makeSafe($FilterValue[$i + $j]) . "%' </FilterItem>";
                     } elseif ($isDate) {
                         $dateValue = toMySQLDate($FilterValue[$i + $j]);
                         $this->QueryWhere .= " <FilterItem> " . $FilterAnd[$i + $j] . " " . $this->QueryFieldsIndexed[$FilterField[$i + $j]] . " " . $FilterOperator[$i + $j] . " '{$dateValue}' </FilterItem>";
                     } else {
                         $this->QueryWhere .= " <FilterItem> " . $FilterAnd[$i + $j] . " " . $this->QueryFieldsIndexed[$FilterField[$i + $j]] . " " . $FilterOperator[$i + $j] . " '" . makeSafe($FilterValue[$i + $j]) . "' </FilterItem>";
                     }
                 }
             }
             $this->QueryWhere .= ") </FilterGroup>";
             $WhereNeedsClosing = 1;
         }
     }
     if ($WhereNeedsClosing) {
         $this->QueryWhere .= ")";
     }
     // set query sort
     if (!stristr($this->QueryOrder, "order by ") && $SortField != "" && $this->AllowSorting) {
         $this->QueryOrder = "order by {$SortField} {$SortDirection}";
     }
     // clean up query
     $this->QueryWhere = str_replace("( <FilterGroup> and ", "( ", $this->QueryWhere);
     $this->QueryWhere = str_replace("( <FilterGroup> or ", "( ", $this->QueryWhere);
     $this->QueryWhere = str_replace("( <FilterItem> and ", "( ", $this->QueryWhere);
     $this->QueryWhere = str_replace("( <FilterItem> or ", "( ", $this->QueryWhere);
     $this->QueryWhere = str_replace("<FilterGroup>", "", $this->QueryWhere);
     $this->QueryWhere = str_replace("</FilterGroup>", "", $this->QueryWhere);
     $this->QueryWhere = str_replace("<FilterItem>", "", $this->QueryWhere);
     $this->QueryWhere = str_replace("</FilterItem>", "", $this->QueryWhere);
     // if no 'order by' clause found, apply default sorting if specified
     if ($this->DefaultSortField != "" && $this->QueryOrder == '') {
         $this->QueryOrder = "order by " . $this->DefaultSortField . " " . $this->DefaultSortDirection;
     }
     // get count of matching records ...
     $TempQuery = 'SELECT count(1) from ' . $this->QueryFrom . ' ' . $this->QueryWhere;
     $RecordCount = sqlValue($TempQuery);
     $FieldCountTV = count($this->QueryFieldsTV);
     $FieldCountCSV = count($this->QueryFieldsCSV);
     $FieldCountFilters = count($this->QueryFieldsFilters);
     if (!$RecordCount) {
         $FirstRecord = 1;
     }
     // disable multi-selection if too many records to avoid browser performance issues
     if ($RecordCount > 1000) {
         $this->AllowPrintingMultiSelection = 0;
     }
     // Output CSV on request
     if ($CSV_x != '') {
         $this->HTML = '';
         // execute query for CSV output
         $fieldList = '';
         foreach ($this->QueryFieldsCSV as $fn => $fc) {
             $fieldList .= "{$fn} as `{$fc}`, ";
         }
         $fieldList = substr($fieldList, 0, -2);
         $csvQuery = 'SELECT ' . $fieldList . ' from ' . $this->QueryFrom . ' ' . $this->QueryWhere . ' ' . $this->QueryOrder;
         // hook: table_csv
         if (function_exists($this->TableName . '_csv')) {
             $args = array();
             $mq = call_user_func($this->TableName . '_csv', $csvQuery, getMemberInfo(), $args);
             $csvQuery = $mq ? $mq : $csvQuery;
         }
         $result = sql($csvQuery);
         // output CSV field names
         for ($i = 0; $i < $FieldCountCSV; $i++) {
             $this->HTML .= "\"" . mysql_field_name($result, $i) . "\"" . $this->CSVSeparator;
         }
         $this->HTML .= "\n\n";
         // output CSV data
         while ($row = mysql_fetch_row($result)) {
             for ($i = 0; $i < $FieldCountCSV; $i++) {
                 $this->HTML .= "\"" . str_replace(array("\r\n", "\r", "\n", '"'), array(' ', ' ', ' ', '""'), $row[$i]) . "\"" . $this->CSVSeparator;
             }
             $this->HTML .= "\n\n";
         }
         $this->HTML = str_replace($this->CSVSeparator . "\n\n", "\n", $this->HTML);
         $this->HTML = substr($this->HTML, 0, strlen($this->HTML) - 1);
         // clean any output buffers
         while (@ob_end_clean()) {
         }
         // output CSV HTTP headers ...
         header('HTTP/1.1 200 OK');
         header('Date: ' . @date("D M j G:i:s T Y"));
         header('Last-Modified: ' . @date("D M j G:i:s T Y"));
         header("Content-Type: application/force-download");
         header("Content-Lenght: " . (string) strlen($this->HTML));
         header("Content-Transfer-Encoding: Binary");
         header("Content-Disposition: attachment; filename={$this->TableName}.csv");
         // send output and quit script
         echo $this->HTML;
         exit;
     }
     $t = time();
     // just a random number for any purpose ...
     //$this->HTML .= "<font face=garamond>".$this->Query."</font>";  // uncomment this line for debugging
     // should SelectedID be reset on clicking TV buttons?
     $resetSelection = $this->SeparateDV ? "document.myform.SelectedID.value=''; " : '';
     // begin table and display table title
     $this->HTML .= "<table align=center cellspacing=1 cellpadding=0 border=0><tr>\n";
     $this->HTML .= "<td colspan=" . ($FieldCountTV + 2) . ">";
     $sum_width = 0;
     for ($i = 0; $i < count($this->ColWidth); $i++) {
         $sum_width += $this->ColWidth[$i];
     }
     $this->HTML .= "<table" . ($this->HideTableView ? "" : " width=100%") . " cellspacing=0 cellpadding=0 border=0>" . ($dvprint_x && $this->AllowSelection && $SelectedID ? '' : "<tr><td align=left colspan=2><div class=TableTitle>{$this->TableTitle}</div><br /></td></tr>");
     if (!$this->HideTableView && !($dvprint_x && $this->AllowSelection && $SelectedID) && !$PrintDV) {
         $this->HTML .= "<tr>";
         // display tables navigator menu
         if ($Print_x == '') {
             $this->HTML .= "<td align=left>" . NavMenus() . "</td>";
         } else {
             $this->HTML .= "\n<style type=\"text/css\">@media print{.displayOnly {display: none;}}</style>\n";
             if ($this->AllowPrintingMultiSelection) {
                 $withSelected = '' . '<input class="print-button" type="button" id="selectAll" value="' . $Translation['Select all records'] . '" onClick="$(\'toggleAll\').checked=!$(\'toggleAll\').checked; toggleAllRecords();">' . '<span id="withSelected">' . '<input class="print-button" type="submit" name="PrintTV" value="' . $Translation['Print Preview Table View'] . '">' . ($AllowPrintDV ? '<input id="PrintDV" class="print-button" type="submit" name="PrintDV" value="' . $Translation['Print Preview Detail View'] . '">' : '') . '<input class="print-button" type="submit" name="Print_x" value="' . $Translation['Cancel Selection'] . '">' . ' &nbsp;</span>' . '<script>' . 'var countSelected=0; ' . 'document.observe(\'dom:loaded\', function(){ ' . 'setInterval("' . '$(\'withSelected\').style.display=(countSelected ? \'inline\' : \'none\');' . '", 500); ' . '});' . '</script>';
             }
             $this->HTML .= "\n" . '<td colspan="2" class="displayOnly" style="min-width: 65em;"><div>' . '<input class="print-button" type="submit" value="' . $Translation['Cancel Printing'] . '">' . '<input class="print-button" type="button" id="sendToPrinter" value="' . $Translation['Print'] . '" onClick="window.print();">' . $withSelected . '</div></td>' . "\n";
         }
         // display quick search box
         if ($this->QuickSearch > 0 && $this->QuickSearch < 4 && $Print_x == '') {
             if ($this->QuickSearch == 1 || $this->QuickSearch == 2) {
                 $this->HTML .= '</tr><tr>';
             }
             $this->HTML .= "<td><div class=TableBodySelected style='text-align:" . ($this->QuickSearch == 1 ? "left" : ($this->QuickSearch == 2 ? "center" : "right")) . ";'>";
             $this->HTML .= "<nobr><b>" . $this->QuickSearchText . "</b> <input type=text name=SearchString value='" . htmlspecialchars($SearchString, ENT_QUOTES) . "' size=15 class=TextBox>";
             $this->HTML .= "<input onClick=\"{$resetSelection} document.myform.NoDV.value=1;\" align=top border=0 name=Search type=image vspace=2 hspace=2 src=qsearch.gif alt='" . $this->QuickSearchText . "'>";
             $this->HTML .= "</nobr></div></td>";
         }
         $this->HTML .= "</tr>";
         $this->HTML .= "<tr><td colspan=2><div class=\"TableBody\" style=\"text-align:center;\"><nobr>";
         // display 'Add New' icon
         if ($this->Permissions[1] && $this->SeparateDV && $Print_x == '') {
             $this->HTML .= " <input type=image src=addNew.gif name=addNew alt='" . $Translation['add new record'] . "'>";
         }
         // display Print icon
         if ($this->AllowPrinting && $Print_x == '') {
             $this->HTML .= " <input onClick=\"document.myform.NoDV.value=1;\" type=image src=print.gif name=Print alt='" . $Translation["printer friendly view"] . "'>";
         }
         // display CSV icon
         if ($this->AllowCSV && $Print_x == '') {
             $this->HTML .= " <input onClick=\"document.myform.NoDV.value=1;\" type=image src=csv.gif name=CSV alt='" . $Translation["save as csv"] . "'>";
         }
         // display Filter icons
         if ($this->AllowFilters && $Print_x == '') {
             $this->HTML .= " <input onClick=\"document.myform.NoDV.value=1;\" type=image src=search.gif name=Filter alt='" . $Translation["edit filters"] . "'> <input onClick=\"{$resetSelection} document.myform.NoDV.value=1;\" type=image src=cancel_search.gif name=NoFilter alt='" . $Translation["clear filters"] . "'> ";
         }
         $this->HTML .= "</nobr></div></td></tr>";
         $this->HTML .= "<!--</td></tr>--></table></td></tr>";
         $this->HTML .= "<tr><td class=TableHeader>" . ($this->AllowSelection ? "&nbsp;&nbsp;" : "") . "</td>";
         if ($this->AllowPrintingMultiSelection && $Print_x != '') {
             $this->HTML .= '<td class="TableHeader displayOnly" align="left"><input type="checkbox" title="' . $Translation['Select all records'] . '" id="toggleAll" onclick="toggleAllRecords();"></td>';
         }
         // Templates
         if ($this->Template != '') {
             $rowTemplate = @implode('', @file('./' . $this->Template));
             if (!$rowTemplate) {
                 $rowTemplate = '';
                 $selrowTemplate = '';
             } else {
                 if ($this->SelectedTemplate != '') {
                     $selrowTemplate = @implode('', @file('./' . $this->SelectedTemplate));
                     if (!$selrowTemplate) {
                         $selrowTemplate = '';
                     }
                 } else {
                     $selrowTemplate = '';
                 }
             }
         } else {
             $rowTemplate = '';
             $selrowTemplate = '';
         }
         // process translations
         if ($rowTemplate) {
             foreach ($Translation as $symbol => $trans) {
                 $rowTemplate = str_replace("<%%TRANSLATION({$symbol})%%>", $trans, $rowTemplate);
             }
         }
         if ($selrowTemplate) {
             foreach ($Translation as $symbol => $trans) {
                 $selrowTemplate = str_replace("<%%TRANSLATION({$symbol})%%>", $trans, $selrowTemplate);
             }
         }
         // End of templates
         // display table headers
         global $SortFieldNumeric;
         if ($rowTemplate == '' || $this->ShowTableHeader == 1) {
             for ($i = 0; $i < count($this->ColCaption); $i++) {
                 if ($this->AllowSorting == 1) {
                     $sort1 = "<a href=\"{$this->ScriptFileName}?SortDirection=asc&SortField=" . $this->ColNumber[$i] . "\" onClick=\"{$resetSelection} document.myform.NoDV.value=1; document.myform.SortDirection.value='asc'; document.myform.SortField.value = '" . $this->ColNumber[$i] . "'; document.myform.submit(); return false;\" class=\"TableHeader\">";
                     $sort2 = "</a>";
                     if ($this->ColNumber[$i] == $SortField || $this->ColNumber[$i] == $SortFieldNumeric) {
                         $SortDirection = $SortDirection == "asc" ? "desc" : "asc";
                         $sort1 = "<a href=\"{$this->ScriptFileName}?SortDirection={$SortDirection}&SortField=" . $this->ColNumber[$i] . "\" onClick=\"{$resetSelection} document.myform.NoDV.value=1; document.myform.SortDirection.value='{$SortDirection}'; document.myform.SortField.value = " . $this->ColNumber[$i] . "; document.myform.submit(); return false;\" class=\"TableHeader\"><img src=\"{$SortDirection}.gif\" border=\"0\" hspace=\"3\">";
                         $SortDirection = $SortDirection == "asc" ? "desc" : "asc";
                     }
                 } else {
                     $sort1 = '';
                     $sort2 = '';
                 }
                 $this->HTML .= "\t<td valign=top nowrap width='" . ($this->ColWidth[$i] ? $this->ColWidth[$i] : 100) . "' class=TableHeader><div class=TableHeader>{$sort1}" . $this->ColCaption[$i] . "{$sort2}</div></td>\n";
             }
         } else {
             // Display a Sort by drop down
             $this->HTML .= "\t<td valign=top class=TableHeader colspan=" . ($FieldCountTV + 1) . "><div class=TableHeader>";
             if ($this->AllowSorting == 1) {
                 $sortCombo = new Combo();
                 //$sortCombo->ListItem[] = "";
                 //$sortCombo->ListData[] = "";
                 for ($i = 0; $i < count($this->ColCaption); $i++) {
                     $sortCombo->ListItem[] = $this->ColCaption[$i];
                     $sortCombo->ListData[] = $this->ColNumber[$i];
                 }
                 $sortCombo->SelectName = "FieldsList";
                 $sortCombo->SelectedData = is_numeric($SortField) ? $SortField : $SortFieldNumeric;
                 $sortCombo->Class = 'TableBody';
                 $sortCombo->SelectedClass = 'TableBodySelected';
                 $sortCombo->Render();
                 $d = $sortCombo->HTML;
                 $d = str_replace('<select ', "<select onChange=\"document.myform.SortDirection.value='{$SortDirection}'; document.myform.SortField.value=document.myform.FieldsList.value; document.myform.NoDV.value=1; document.myform.submit();\" ", $d);
                 if ($SortField) {
                     $SortDirection = $SortDirection == "desc" ? "asc" : "desc";
                     $sort = "<a href=\"javascript: document.myform.NoDV.value=1; document.myform.SortDirection.value='{$SortDirection}'; document.myform.SortField.value='{$SortField}'; document.myform.submit();\" class=TableHeader><img src={$SortDirection}.gif border=0 width=11 height=11 hspace=3></a>";
                     $SortDirection = $SortDirection == "desc" ? "asc" : "desc";
                 } else {
                     $sort = '';
                 }
                 $this->HTML .= $Translation['order by'] . " {$d} {$sort}";
             }
             $this->HTML .= "</div></td>\n";
         }
         // table view navigation code ...
         if ($RecordCount && $this->AllowNavigation && $RecordCount > $this->RecordsPerPage) {
             while ($FirstRecord > $RecordCount) {
                 $FirstRecord -= $this->RecordsPerPage;
             }
             if ($FirstRecord == "" || $FirstRecord < 1) {
                 $FirstRecord = 1;
             }
             if ($Previous_x != "") {
                 $FirstRecord -= $this->RecordsPerPage;
                 if ($FirstRecord <= 0) {
                     $FirstRecord = 1;
                 }
             } elseif ($Next_x != "") {
                 $FirstRecord += $this->RecordsPerPage;
                 if ($FirstRecord > $RecordCount) {
                     $FirstRecord = $RecordCount - $RecordCount % $this->RecordsPerPage + 1;
                 }
                 if ($FirstRecord > $RecordCount) {
                     $FirstRecord = $RecordCount - $this->RecordsPerPage + 1;
                 }
                 if ($FirstRecord <= 0) {
                     $FirstRecord = 1;
                 }
             } else {
                 // no scrolling action took place :)
             }
         } elseif ($RecordCount) {
             $FirstRecord = 1;
             $this->RecordsPerPage = $RecordCount;
         }
         // end of table view navigation code
         $this->HTML .= "\n\t</tr>\n";
         $this->HTML = "<script>\n\t\t\t\t\tfunction colorize(item, color){\n\t\t\t\t\t\tvar n=item.childNodes.length;\n\t\t\t\t\t\tfor(var i=0; i<n; i++){\n\t\t\t\t\t\t\tif(item.childNodes[i].nodeName=='TD'){\n\t\t\t\t\t\t\t\titem.childNodes[i].style.backgroundColor=color;\n\t\t\t\t\t\t\t\tif(item.childNodes[i].childNodes.length>0){\n\t\t\t\t\t\t\t\t\tif(item.childNodes[i].childNodes[0].nodeName=='A'){\n\t\t\t\t\t\t\t\t\t\titem.childNodes[i].childNodes[0].style.backgroundColor=color;\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}\n\t\t\t\t\t}\n\t\t\t\t</script>" . $this->HTML . '<!-- tv data below -->';
         $i = 0;
         $hc = new HtmlFilter();
         $hc->encoding = 'iso-8859-1';
         $hc->defaultProtocol = '';
         if ($RecordCount) {
             $i = $FirstRecord;
             // execute query for table view
             $fieldList = '';
             foreach ($this->QueryFieldsTV as $fn => $fc) {
                 $fieldList .= "{$fn} as `{$fc}`, ";
             }
             $fieldList = substr($fieldList, 0, -2);
             if ($this->PrimaryKey) {
                 $fieldList .= ", {$this->PrimaryKey} as '" . str_replace('`', '', $this->PrimaryKey) . "'";
             }
             $tvQuery = 'SELECT ' . $fieldList . ' from ' . $this->QueryFrom . ' ' . $this->QueryWhere . ' ' . $this->QueryOrder;
             $result = sql($tvQuery . " limit " . ($i - 1) . ",{$this->RecordsPerPage}");
             while (($row = mysql_fetch_array($result)) && $i < $FirstRecord + $this->RecordsPerPage) {
                 $alt = ($i - $FirstRecord) % 2;
                 if ($PrintTV && $_POST["select_{$row[$FieldCountTV]}"] != 1) {
                     continue;
                 }
                 $class = "TableBody" . ($alt ? "Selected" : "") . ($fNumeric ? "Numeric" : "");
                 $this->HTML .= "\t<tr onMouseOver=\"colorize(this, '" . $this->HighlightColor . "');\" onMouseOut=\"colorize(this, '');\">";
                 $this->HTML .= "<td class={$class} valign=top align=right width=12>" . ($SelectedID == $row[$FieldCountTV] ? "<font color=red>&rArr;</font>" : "&nbsp;") . "</td>";
                 if ($this->AllowPrintingMultiSelection && $Print_x != '') {
                     $this->HTML .= "<td class=\"{$class} displayOnly\" valign=\"top\" align=\"left\" width=\"12\"><input type=\"checkbox\" id=\"select_{$row[$FieldCountTV]}\" name=\"select_{$row[$FieldCountTV]}\" value=\"1\" onclick=\"if(\$('select_{$row[$FieldCountTV]}').checked) countSelected++; else countSelected--;\"></td>";
                     $toggleAllScript .= "\$('select_{$row[$FieldCountTV]}').checked=s;";
                 }
                 // templates
                 if ($rowTemplate != '') {
                     if ($this->AllowSelection == 1 && $SelectedID == $row[$FieldCountTV] && $selrowTemplate != "") {
                         $rowTemp = $selrowTemplate;
                     } else {
                         $rowTemp = $rowTemplate;
                     }
                     if ($this->AllowSelection == 1 && $SelectedID != $row[$FieldCountTV]) {
                         $rowTemp = str_replace('<%%SELECT%%>', "<a onclick=\"document.myform.SelectedField.value=this.parentNode.cellIndex; document.myform.SelectedID.value='" . addslashes($row[$FieldCountTV]) . "'; document.myform.submit(); return false;\" href=\"{$this->ScriptFileName}?SelectedID=" . htmlspecialchars($row[$FieldCountTV], ENT_QUOTES) . "\" class=\"{$class}\" style=\"display: block; padding:0px;\">", $rowTemp);
                         $rowTemp = str_replace('<%%ENDSELECT%%>', '</a>', $rowTemp);
                     } else {
                         $rowTemp = str_replace('<%%SELECT%%>', "", $rowTemp);
                         $rowTemp = str_replace('<%%ENDSELECT%%>', '', $rowTemp);
                     }
                     for ($j = 0; $j < $FieldCountTV; $j++) {
                         $fieldTVCaption = current(array_slice($this->QueryFieldsTV, $j, 1));
                         $fd = $hc->clean($row[$j]);
                         /*
                         	the TV template could contain field placeholders in the format 
                         	<%%FIELD_n%%> or <%%VALUE(Field Caption)%%> 
                         */
                         $rowTemp = str_replace("<%%FIELD_{$j}%%>", thisOr($fd), $rowTemp);
                         $rowTemp = str_replace("<%%VALUE({$fieldTVCaption})%%>", thisOr($fd), $rowTemp);
                         if (thisOr($fd) == '&nbsp;' && preg_match('/<a href=".*?&nbsp;.*?<\\/a>/i', $rowTemp, $m)) {
                             $rowTemp = str_replace($m[0], '', $rowTemp);
                         }
                     }
                     if ($alt && $SelectedID != $row[$FieldCountTV]) {
                         $rowTemp = str_replace("TableBody", "TableBodySelected", $rowTemp);
                         $rowTemp = str_replace("TableBodyNumeric", "TableBodySelectedNumeric", $rowTemp);
                         $rowTemp = str_replace("SelectedSelected", "Selected", $rowTemp);
                     }
                     if ($SearchString != '') {
                         $rowTemp = highlight($SearchString, $rowTemp);
                     }
                     $this->HTML .= $rowTemp;
                     $rowTemp = '';
                 } else {
                     // end of templates
                     for ($j = 0; $j < $FieldCountTV; $j++) {
                         $fType = mysql_field_type($result, $j);
                         $fNumeric = stristr($fType, 'int') || stristr($fType, 'float') || stristr($fType, 'decimal') || stristr($fType, 'numeric') || stristr($fType, 'real') || stristr($fType, 'double') ? true : false;
                         if ($this->AllowSelection == 1) {
                             $sel1 = "<a href=\"{$this->ScriptFileName}?SelectedID=" . htmlspecialchars($row[$FieldCountTV], ENT_QUOTES) . "\" onclick=\"document.myform.SelectedID.value='" . addslashes($row[$FieldCountTV]) . "'; document.myform.submit(); return false;\" class=\"{$class}\" style=\"padding:0px;\">";
                             $sel2 = "</a>";
                         } else {
                             $sel1 = "";
                             $sel2 = "";
                         }
                         $this->HTML .= "<td valign=top class={$class}><div class={$class}>&nbsp;{$sel1}" . $row[$j] . "{$sel2}&nbsp;</div></td>";
                     }
                 }
                 $this->HTML .= "</tr>\n";
                 $i++;
             }
             $i--;
         }
         $this->HTML = preg_replace("/<a href=\"(mailto:)?&nbsp;[^\n]*title=\"&nbsp;\"><\\/a>/", '&nbsp;', $this->HTML);
         $this->HTML = preg_replace("/<a [^>]*>(&nbsp;)*<\\/a>/", '&nbsp;', $this->HTML);
         $this->HTML = preg_replace("/<%%.*%%>/U", '&nbsp;', $this->HTML);
         if ($this->ShowRecordSlots) {
             for ($j = $i + 1; $j < $FirstRecord + $this->RecordsPerPage; $j++) {
                 $this->HTML .= "\n\t<tr><td colspan=" . ($FieldCountTV + 1) . "><div class=TableBody>&nbsp;</div></td></tr>";
             }
         }
         // end of data
         $this->HTML .= '<!-- tv data above -->';
         if ($Print_x == "") {
             $pagesMenu = '';
             if ($RecordCount > $this->RecordsPerPage) {
                 $pagesMenu = "<td align=center><div class=TableFooter>" . $Translation['go to page'] . " <select onChange=\"{$resetSelection} document.myform.NoDV.value=1; document.myform.FirstRecord.value=(this.value*" . $this->RecordsPerPage . "+1); document.myform.submit();\">";
                 for ($page = 0; $page < ceil($RecordCount / $this->RecordsPerPage); $page++) {
                     $pagesMenu .= "<option value=\"{$page}\" " . ($FirstRecord == $page * $this->RecordsPerPage + 1 ? 'selected' : '') . ">" . ($page + 1) . "</option>";
                 }
                 $pagesMenu .= '</select></div></td>';
             }
             $totalWidth = array_sum($this->ColWidth);
             $totalWidth = $totalWidth > 750 ? 750 : '100%';
             $this->HTML .= "\n\t<tr><td colspan=" . ($FieldCountTV + 1) . "><table width=100%><tr class=TableFooter><td align=left><input onClick=\"{$resetSelection} document.myform.NoDV.value=1;\" type=image name=Previous src=previousPage.gif></td><td align=center><div class=TableFooter>" . $Translation["records x to y of z"] . "</div></td>{$pagesMenu}<td align=right><input onClick=\"{$resetSelection} document.myform.NoDV.value=1;\" type=image name=Next src=nextPage.gif></td></tr></table></td></tr>";
         } else {
             $this->HTML .= "\n\t<tr><td colspan=" . ($FieldCountTV + 1) . "><nobr><div class=TableFooter>" . $Translation["records x to y of z"] . "</div></nobr></td></tr>";
         }
         $this->HTML = str_replace("<FirstRecord>", $FirstRecord, $this->HTML);
         $this->HTML = str_replace("<LastRecord>", $i, $this->HTML);
         $this->HTML = str_replace("<RecordCount>", $RecordCount, $this->HTML);
         $tvShown = true;
     }
     // hidden variables ....
     $this->HTML .= "<input name=SortField value='{$SortField}' type=hidden>";
     $this->HTML .= "<input name=SelectedID value=\"{$SelectedID}\" type=hidden>";
     $this->HTML .= "<input name=SelectedField value=\"\" type=hidden>";
     $this->HTML .= "<input name=SortDirection type=hidden value='{$SortDirection}'>";
     $this->HTML .= "<input name=FirstRecord type=hidden value='{$FirstRecord}'>";
     $this->HTML .= "<input name=NoDV type=hidden value=''>";
     if ($this->QuickSearch && !strpos($this->HTML, 'SearchString')) {
         $this->HTML .= '<input name="SearchString" type="hidden" value="' . htmlspecialchars($SearchString, ENT_QUOTES) . '">';
     }
     // hidden variables: filters ...
     $FiltersCode = '';
     for ($i = 1; $i <= 20 * $FiltersPerGroup; $i++) {
         // Number of filters allowed
         if ($i % $FiltersPerGroup == 1 && $i != 1 && $FilterAnd[$i] != "") {
             $FiltersCode .= "<input name=\"FilterAnd[{$i}]\" value=\"{$FilterAnd[$i]}\" type=\"hidden\">\n";
         }
         if ($FilterField[$i] != '' && $FilterOperator[$i] != '' && ($FilterValue[$i] != '' || strstr($FilterOperator[$i], 'Empty'))) {
             if (!strstr($FiltersCode, "<input name=\"FilterAnd[{$i}]\" value=")) {
                 $FiltersCode .= "<input name=\"FilterAnd[{$i}]\" value=\"{$FilterAnd[$i]}\" type=\"hidden\">\n";
             }
             $FiltersCode .= "<input name=\"FilterField[{$i}]\" value=\"{$FilterField[$i]}\" type=\"hidden\">\n";
             $FiltersCode .= "<input name=\"FilterOperator[{$i}]\" value=\"{$FilterOperator[$i]}\" type=\"hidden\">\n";
             $FiltersCode .= "<input name=\"FilterValue[{$i}]\" value=\"" . htmlspecialchars($FilterValue[$i], ENT_QUOTES) . "\" type=\"hidden\">\n";
         }
     }
     $this->HTML .= $FiltersCode;
     // display details form ...
     if (($this->AllowSelection || $this->AllowInsert || $this->AllowUpdate || $this->AllowDelete) && $Print_x == '' && !$PrintDV) {
         if ($this->SeparateDV && $this->HideTableView || !$this->SeparateDV) {
             $dvCode = call_user_func($this->TableName . '_form', $SelectedID, $this->AllowUpdate, $this->HideTableView && $SelectedID ? 0 : $this->AllowInsert, $this->AllowDelete, $this->SeparateDV);
             $this->HTML .= "\n\t<tr><td colspan=" . ($FieldCountTV + 2) . ">{$dvCode}</td></tr>";
             $this->HTML .= $this->SeparateDV ? "<input name=SearchString value='" . htmlspecialchars($SearchString, ENT_QUOTES) . "' type=hidden>" : "";
             if ($dvCode) {
                 $this->ContentType = 'detailview';
                 $dvShown = true;
             }
         }
     }
     // display multiple printable detail views
     if ($PrintDV) {
         $dvCode = '';
         $_POST['dvprint_x'] = 1;
         // hidden vars
         $this->HTML .= '<input type="hidden" name="Print_x" value="1">' . "\n";
         $this->HTML .= '<input type="hidden" name="PrintTV" value="1">' . "\n";
         // count selected records
         $selectedRecords = 0;
         foreach ($_POST as $n => $v) {
             if (strpos($n, 'select_') === 0) {
                 $id = str_replace('select_', '', $n);
                 $selectedRecords++;
                 $this->HTML .= '<input type="hidden" name="select_' . $id . '" value="1">' . "\n";
             }
         }
         if ($selectedRecords <= 100) {
             // if records selected > 100 don't show DV preview to avoid db performance issues.
             foreach ($_POST as $n => $v) {
                 if (strpos($n, 'select_') === 0) {
                     $id = str_replace('select_', '', $n);
                     $dvCode .= call_user_func($this->TableName . '_form', $id, 0, 0, 0, 1);
                 }
             }
             if ($dvCode != '') {
                 $dvCode = preg_replace('/<input .*?type="?image"?.*?>/', '', $dvCode);
                 $this->HTML .= "\n" . '<div class="TableBodySelected displayOnly">' . '<input class="print-button" type="submit" value="' . $Translation['Cancel Printing'] . '">' . '<input class="print-button" type="button" id="sendToPrinter" value="' . $Translation['Print'] . '" onClick="window.print();">' . '</div>' . "\n";
                 $this->HTML .= $dvCode;
             }
         } else {
             $this->HTML .= '<div class="Error">' . $Translation['Maximum records allowed to enable this feature is'] . ' 100.</div>';
             $this->HTML .= '<input type="submit" class="print-button" value="' . $Translation['Print Preview Table View'] . '">';
         }
     }
     $this->HTML .= "</table>\n";
     if ($this->AllowPrintingMultiSelection && $Print_x != '') {
         $this->HTML .= "<script>function toggleAllRecords(){ var s=\$('toggleAll').checked; {$toggleAllScript} if(s) countSelected={$RecordCount}; else countSelected=0; }</script>\n";
     }
     $this->HTML .= "</form></center>";
     if ($dvShown && $tvShown) {
         $this->ContentType = 'tableview+detailview';
     }
     if ($dvprint_x != '') {
         $this->ContentType = 'print-detailview';
     }
     if ($Print_x != '') {
         $this->ContentType = 'print-tableview';
     }
     //mysql_close();
     // Das ist Alles!
 }