      1:   2:   3:   4:   5:   6:   7:   8:   9:  10:  11:  12:  13:  14:  15:  16:  17:  18:  19:  20:  21:  22:  23:  24:  25:  26:  27:  28:  29:  30:  31:  32:  33:  34:  35:  36:  37:  38:  39:  40:  41:  42:  43:  44:  45:  46:  47:  48:  49:  50:  51:  52:  53:  54:  55:  56:  57:  58:  59:  60:  61:  62:  63:  64:  65:  66:  67:  68:  69:  70:  71:  72:  73:  74:  75:  76:  77:  78:  79:  80:  81:  82:  83:  84:  85:  86:  87:  88:  89:  90:  91:  92:  93:  94:  95:  96:  97:  98:  99: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112: 113: 114: 115: 116: 117: 118: 119: 120: 121: 122: 123: 124: 125: 126: 127: 128: 129: 130: 131: 132: 133: 134: 135: 136: 137: 138: 139: 140: 141: 142: 143: 144: 145: 146: 147: 148: 149: 150: 151: 152: 153: 154: 155: 156: 157: 158: 159: 160: 161: 162: 163: 164: 165: 166: 167: 168: 169: 170: 171: 172: 173: 174: 175: 176: 177: 178: 179: 180: 181: 182: 183: 184: 185: 186: 187: 188: 189: 190: 191: 192: 193: 194: 195: 196: 197: 198: 199: 200: 201: 202: 203: 204: 205: 206: 207: 208: 209: 210: 211: 212: 213: 214: 215: 216: 217: 218: 219: 220: 221: 222: 223: 224: 225: 226: 227: 228: 229: 230: 231: 232: 233: 234: 235: 236: 237: 238: 239: 240: 241: 242: 243: 244: 245: 246: 247: 248: 249: 250: 251: 252: 253: 254: 255: 256: 257: 258: 259: 260: 261: 262: 263: 264: 265: 266: 267: 268: 269: 270: 271: 272: 273: 274: 275: 276: 277: 278: 279: 280: 281: 282: 283: 284: 285: 286: 287: 288: 289: 290: 291: 292: 293: 294: 295: 296: 297: 298: 299: 300: 301: 302: 303: 304: 305: 306: 307: 308: 309: 310: 311: 312: 313: 314: 315: 316: 317: 318: 319: 320: 321: 322: 323: 324: 325: 326: 327: 328: 329: 330: 331: 332: 333:

    <?php

    namespace WPGMZA;

    class AjaxTable extends Table
    {
        public function __construct($table_name, $rest_api_route, $ajax_parameters=null)
        {
            Table::__construct($table_name);

            $this->element->setAttribute('data-wpgmza-php-class', get_called_class());

            $this->setRestAPIRoute($rest_api_route);

            if($ajax_parameters)
                $this->setAjaxParameters($ajax_parameters);
        }

        public function getAjaxParameters()
        {
            return $this->getAttributeParams('data-wpgmza-ajax-parameters');
        }

        public function setAjaxParameters($ajax_parameters)
        {
            $this->setAttributeParams('data-wpgmza-ajax-parameters', $ajax_parameters);
        }

        protected function getAttributeParams($name)
        {
            if(!$this->element->hasAttribute($name))
                return (object)array();

            return json_decode($this->element->getAttribute($name));
        }

        protected function setAttributeParams($name, $params)
        {
            if(!(is_array($params) || is_object($params)))
                throw new \Exception('Parameters must be JSON serializable');

            $obj = $this->getAttributeParams($name);

            foreach($params as $key => $value)
                $obj->{$key} = $value;

            $this->element->setAttribute($name, json_encode($obj));
        }

        protected function getRestAPIRoute()
        {
            return $this->element->getAttribute('data-wpgmza-rest-api-route');
        }

        protected function setRestAPIRoute($route)
        {
            if(!is_string($route))
                throw new \Exception('Invalid REST API route');

            $this->element->setAttribute('data-wpgmza-rest-api-route', $route);
        }

        protected function getColumns()
        {
            throw new \Exception('Abstract function called');
        }

        protected function getColumnNameByIndex($index)
        {
            $i = 0;
            $columns = $this->getColumns();

            foreach($columns as $key => $value)
            {
                if($i++ == $index)
                    return $key;
            }

            return null;
        }

        protected function getOrderBy($input_params, $column_keys)
        {
            return 'id';
        }

        protected function getOrderDirection($input_params)
        {
            return 'DESC';
        }

        protected function getWhereClause($input_params, &$query_params, $clause_for_total=false)
        {
            global $wpgmza;

            $clauses = array();

            if(isset($input_params['overrideMarkerIDs']))
            {
                $markerIDs = $input_params['overrideMarkerIDs'];

                if(is_string($markerIDs))
                    $markerIDs = explode(',', $markerIDs);

                if(empty($markerIDs))
                    return '0';
                else
                    return 'id IN (' . implode(', ', array_map('intval', $markerIDs)) . ')';
            }

            if(isset($input_params['mashup_ids']))
            {
                // NB: This is Pro logic and should be moved ideally
                $mashup_ids     = $input_params['mashup_ids'];
                $placeholders   = implode(',', array_fill(0, count($mashup_ids), '%d'));

                $clauses['mashup_ids'] = 'map_id IN (' . $placeholders. ')';

                for($i = 0; $i < count($mashup_ids); $i++)
                    $query_params[] = $mashup_ids[$i];
            }
            else if(isset($input_params['map_id']))
            {
                $clauses['map_id'] = 'map_id=%d';
                $query_params[] = $input_params['map_id'];
            }

            if(!(is_admin() || (preg_match('/page=wp-google-maps-menu/', $_SERVER['HTTP_REFERER']) && current_user_can('administrator'))))
            {
                $clauses['approved'] = 'approved=%d';
                $query_params[] = 1;
            }

            if(!$clause_for_total)
            {
                $search_clause = $this->getSearchClause($input_params, $query_params);
                if(!empty($search_clause))
                    $clauses['search'] = $search_clause;
            }

            if(empty($clauses))
                return '1';

            return implode(' AND ', $clauses);
        }

        protected function getSearchClause($input_params, &$query_params, $exclude_columns=null)
        {
            global $wpdb;

            if(isset($input_params['overrideMarkerIDs']))
                return "";

            if(empty($input_params['search']['value']))
                return "";

            $columns = $this->getColumns();

            $clauses = array();
            $term = $input_params['search']['value'];
            $subclauses = array();

            foreach($columns as $key => $label)
            {
                if($exclude_columns && array_search($key, $exclude_columns) !== false)
                    continue;

                array_push($subclauses, "$key LIKE %s");
                array_push($query_params, "%%" . $wpdb->esc_like($term) . "%%");
            }

            if(empty($subclauses))
                return '';

            $result = "(" . implode(' OR ', $subclauses) . ")";

            return $result;
        }

        /**
         * Gets the HAVING clause for the table query
         * @return string
         */
        protected function getHavingClause($input_params, &$query_params, $exclude_columns=null)
        {
            return '';
        }

        /**
         * Override this function to add additional columns to the query
         * @return array
         */
        protected function filterColumns(&$columns, $input_params)
        {
            foreach($columns as $key => $value)
            {
                if($value == 'mark')
                    $columns[$key] = '\'<input type="checkbox" name="mark"/>\' AS mark';
                //else
                    //$columns[$key] = "`$value`";
            }

            return $columns;
        }

        /**
         * Override this function to manipulate data before it's converted to datatables numeric array format
         * @return array
         */
        protected function filterResults(&$rows)
        {
            return $rows;
        }

        /**
         * Function can be used to override order by column
         * @return string
         */
        protected function filterOrderBy($orderBy, $keys)
        {
            return $orderBy;
        }

        /**
         * Function can be used to override order by column
         * @return string
         */
        protected function filterOrderDirection($orderDirection)
        {
            return $orderDirection;
        }

        public function getRecords($input_params)
        {
            global $wpdb;
            global $wpgmza;

            // Build query
            $columns = $this->getColumns();
            $keys = array_keys($columns);

            $query_params = array();
            $total_query_params = array();

            // Where / Having
            $where = $this->getWhereClause($input_params, $query_params);
            $having = $this->getHavingClause($input_params, $query_params);

            // Order by
            $order_column = $this->filterOrderBy( $this->getOrderBy($input_params, $keys), $keys );
            $order_dir = $this->filterOrderDirection( $this->getOrderDirection($input_params) );

            // Columns to select
            $columns = $this->filterColumns($keys, $input_params);

            $imploded = implode(',', $columns);

            $qstr = "SELECT SQL_CALC_FOUND_ROWS $imploded FROM {$this->table_name} WHERE $where";
            if(!empty($having))
                $qstr .= " HAVING $having";

            // This code allows for more natural numeric sorting on text fields, not just numeric fields
            if(empty($order_column))
                $order_column = 'id';
            if(empty($order_dir))
                $order_dir = 'ASC';
            $qstr .= " ORDER BY ISNULL({$order_column}), {$order_column}+0 {$order_dir}, {$order_column} {$order_dir}";

            // Limit
            if(isset($input_params['length']))
            {
                $length = $input_params['length'];
                if(isset($length) &&
                    $length != '-1' &&
                    !preg_match('/^all$/i', $length))
                {
                    $qstr .= " LIMIT " . intval($input_params['length']);

                    if(isset($input_params['start']))
                        $qstr .= " OFFSET " . intval($input_params['start']);
                }
            }

            // Total count
            $count_query_params = array();
            $count_where = $this->getWhereClause($input_params, $count_query_params, true);

            $count_qstr = "SELECT COUNT(id) FROM {$this->table_name} WHERE $count_where";

            if(!empty($query_params))
                $stmt = $wpdb->prepare($count_qstr, $count_query_params);
            else
                $stmt = $count_qstr;

            $total_count = (int)$wpdb->get_var($stmt);

            // Body
            if(!empty($query_params))
                $stmt = $wpdb->prepare($qstr, $query_params);
            else
                $stmt = $qstr;

            $rows = $wpdb->get_results($stmt);

            $this->filterResults($rows);

            // Found rows
            $found_rows = $wpdb->get_var('SELECT FOUND_ROWS()');

            // Meta
            $meta = array();
            foreach($rows as $key => $value)
                $meta[$key] = $value;

            $result = (object)array(
                'recordsTotal'      => $total_count,
                'recordsFiltered'   => $found_rows,
                'data'              => apply_filters('wpgmza_ajax_table_records', $rows),
                'meta'              => apply_filters('wpgmza_ajax_table_meta', $meta)
            );

            if($wpgmza->isInDeveloperMode())
                $result->query      = $stmt;

            return $result;
        }

        public function data($input_params)
        {
            return $this->getRecords($input_params);
        }
    }