'xcrud_list_view.php',
'create' => 'xcrud_detail_view.php',
'edit' => 'xcrud_detail_view.php',
'view' => 'xcrud_detail_view.php');
protected $grid_restrictions = array();
protected $direct_select_tags = array(); // get unselectable {tags}
protected $action = array();
protected $exception = false;
protected $exception_fields = array();
protected $exception_text = '';
protected $message = array();
protected $nested_rendered = array();
protected $default_tab = false;
protected $prefix = '';
protected $query = '';
protected $total_query = '';
protected $condition_backup = array();
protected $sess_id = null;
protected $is_rtl = true;
protected $strip_tags = true;
protected $safe_output = true;
protected $before_list = array();
protected $before_create = array();
protected $before_edit = array();
protected $before_view = array();
/** constructor, sets basic xcrud vars (they can be changed by public pethods) */
protected function __construct()
{
Xcrud_config::$scripts_url = self::check_url(Xcrud_config::$scripts_url, true);
Xcrud_config::$editor_url = self::check_url(Xcrud_config::$editor_url);
Xcrud_config::$editor_init_url = self::check_url(Xcrud_config::$editor_init_url);
$this->limit = Xcrud_config::$limit;
$this->limit_list = Xcrud_config::$limit_list;
$this->column_cut = Xcrud_config::$column_cut;
$this->show_primary_ai_field = Xcrud_config::$show_primary_ai_field;
$this->show_primary_ai_column = Xcrud_config::$show_primary_ai_column;
$this->benchmark = Xcrud_config::$benchmark;
$this->start_minimized = Xcrud_config::$start_minimized;
$this->remove_confirm = Xcrud_config::$remove_confirm;
$this->upload_folder_def = Xcrud_config::$upload_folder_def;
$this->theme = Xcrud_config::$theme;
$this->is_print = Xcrud_config::$enable_printout;
$this->is_title = Xcrud_config::$enable_table_title;
$this->is_csv = Xcrud_config::$enable_csv_export;
$this->is_numbers = Xcrud_config::$enable_numbers;
$this->is_pagination = Xcrud_config::$enable_pagination;
$this->is_search = Xcrud_config::$enable_search;
$this->is_limitlist = Xcrud_config::$enable_limitlist;
$this->is_sortable = Xcrud_config::$enable_sorting;
$this->language = Xcrud_config::$language;
$this->search_pattern = Xcrud_config::$search_pattern;
$this->demo_mode = Xcrud_config::$demo_mode;
$this->default_tab = Xcrud_config::$default_tab;
$this->prefix = Xcrud_config::$dbprefix;
$this->is_rtl = Xcrud_config::$is_rtl;
$this->strip_tags = Xcrud_config::$strip_tags;
$this->safe_output = Xcrud_config::$safe_output;
}
protected function __clone()
{
}
public function __toString()
{
return $this->render();
}
public static function get_instance($name = false)
{
self::init_prepare();
if (!$name)
$name = sha1(rand() . microtime());
if (!isset(self::$instance[$name]) || null === self::$instance[$name])
{
self::$instance[$name] = new self();
self::$instance[$name]->instance_name = $name;
}
self::$instance[$name]->instance_count = count(self::$instance);
return self::$instance[$name];
}
public static function get_requested_instance()
{
if (isset($_POST['xcrud']['instance']) && isset($_POST['xcrud']['key']) && isset($_POST['xcrud']['task']))
{
self::init_prepare('post');
$key = $_POST['xcrud']['key'] ? $_POST['xcrud']['key'] : self::error('Security key cannot be empty');
$inst_name = $_POST['xcrud']['instance'] ? $_POST['xcrud']['instance'] : self::error('Instance name cannot be empty');
$is_get = false;
}
elseif (isset($_GET['xcrud']['instance']) && isset($_GET['xcrud']['key']) && isset($_GET['xcrud']['task']) && $_GET['xcrud']['task'] ==
'file')
{
self::init_prepare('get');
$key = $_GET['xcrud']['key'] ? $_GET['xcrud']['key'] : self::error('Security key cannot be empty');
$inst_name = $_GET['xcrud']['instance'] ? $_GET['xcrud']['instance'] : self::error('Instance name cannot be empty');
$is_get = true;
}
else
{
self::error('Wrong request!');
}
if (isset($_SESSION['xcrud_session'][$inst_name]['key']) && $_SESSION['xcrud_session'][$inst_name]['key'] == $key)
{
self::$instance[$inst_name] = new self();
self::$instance[$inst_name]->is_get = $is_get;
self::$instance[$inst_name]->ajax_request = true;
self::$instance[$inst_name]->instance_name = $inst_name;
self::$instance[$inst_name]->import_vars($key);
self::$instance[$inst_name]->inner_where();
return self::$instance[$inst_name]->render();
}
else
self::error('The verification key is out of date
This means that your browser cached a previous version of this page with an old key (for security reasons the verification key is generated every request)
Why? Maybe you pressed the back button in your browser or opened a bookmark from last session.
Just reload the page, nothing happened :)');
}
protected static function init_prepare($method = false)
{
switch ($method)
{
case 'post':
$sess_name = (Xcrud_config::$dynamic_session && isset($_POST['xcrud']['sess_name']) && $_POST['xcrud']['sess_name']) ? $_POST['xcrud']['sess_name'] :
Xcrud_config::$sess_name;
break;
case 'get':
$sess_name = (Xcrud_config::$dynamic_session && isset($_GET['xcrud']['sess_name']) && $_GET['xcrud']['sess_name']) ? $_GET['xcrud']['sess_name'] :
Xcrud_config::$sess_name;
break;
default:
$sess_name = Xcrud_config::$sess_name;
break;
}
self::session_start($sess_name);
if (is_callable(Xcrud_config::$before_construct))
{
call_user_func(Xcrud_config::$before_construct);
}
}
public static function session_start($sess_name = false)
{
if (!$sess_name)
{
$sess_name = Xcrud_config::$sess_name;
}
if (!session_id() && !Xcrud_config::$external_session && !Xcrud_config::$alt_session)
{
if (!headers_sent())
{
session_name($sess_name);
session_cache_expire(Xcrud_config::$sess_expire);
session_set_cookie_params(0, '/');
session_start();
}
else
self::error('xCRUD can not create session, because the output is already sent into browser.
Try to define xCRUD instance before the output start or use session_start() at the beginning of your script');
}
if (Xcrud_config::$alt_session)
{
if (!headers_sent())
{
if (!isset($_COOKIE[$sess_name]))
{
$this->sess_id = base_convert(str_replace(' ', '', microtime()) . rand(), 10, 36);
}
else
{
$this->sess_id = $_COOKIE[$sess_name];
}
setcookie($sess_name, $this->sess_id, time() + Xcrud_config::$alt_lifetime * 60, '/');
}
else
self::error('xCRUD can not start session, because the output is already sent into browser.
Try to define xCRUD instance before the output start or use Xcrud::session_start(); at the beginning of your script');
}
}
public function connection($user = '', $pass = '', $table = '', $host = 'localhost', $encode = 'utf8')
{
if ($user && $table)
{
$this->connection = array(
$user,
$pass,
$table,
$host,
$encode);
}
return $this;
}
public function start_minimized($bool = true)
{
$this->start_minimized = (bool)$bool;
return $this;
}
public function remove_confirm($bool = true)
{
$this->remove_confirm = (bool)$bool;
return $this;
}
public function theme($theme = 'default')
{
$this->theme = $theme;
}
public function limit($limit = 20)
{
$this->limit = $limit;
return $this;
}
public function limit_list($limit_list = '')
{
if ($limit_list)
{
if (is_array($limit_list))
$this->limit_list = array_unique($limit_list);
else
{
$this->limit_list = array_unique($this->parse_comma_separated($limit_list));
}
}
return $this;
}
public function show_primary_ai_field($bool = true)
{
$this->show_primary_ai_field = (bool)$bool;
return $this;
}
public function show_primary_ai_column($bool = true)
{
$this->show_primary_ai_column = (bool)$bool;
return $this;
}
public function table($table = '', $prefix = '')
{
if ($prefix)
{
$this->prefix = $prefix;
}
$this->table = $this->prefix . $table;
return $this;
}
public function table_name($name = '', $tooltip = false, $icon = false)
{
if ($name)
$this->table_name = $name;
if ($tooltip)
{
$this->table_tooltip = array('tooltip' => $tooltip, 'icon' => $icon);
}
return $this;
}
public function where($fields = false, $where_val = false, $glue = 'AND', $index = false)
{
if ($fields && $where_val !== false)
{
$fdata = $this->_parse_field_names($fields, 'where');
foreach ($fdata as $fitem)
{
if ($index)
{
$this->where[$index] = array(
'table' => $fitem['table'],
'field' => $fitem['field'],
'value' => isset($fitem['value']) ? $fitem['value'] : $where_val,
'glue' => $glue);
}
else
{
$this->where[] = array(
'table' => $fitem['table'],
'field' => $fitem['field'],
'value' => isset($fitem['value']) ? $fitem['value'] : $where_val,
'glue' => $glue);
}
}
unset($fields, $fdata);
}
elseif ($fields && !is_array($fields) && $where_val === false)
{
if ($index)
{
$this->where[$index] = array('custom' => $fields, 'glue' => $glue);
}
else
{
$this->where[] = array('custom' => $fields, 'glue' => $glue);
}
unset($fields);
}
elseif (!$fields && $where_val)
{
if ($index)
{
$this->where[$index] = array('custom' => $where_val, 'glue' => $glue);
}
else
{
$this->where[] = array('custom' => $where_val, 'glue' => $glue);
}
unset($where_val);
}
elseif (!$fields && !$where_val && $index && isset($this->where[$index]))
{
unset($this->where[$index]);
}
return $this;
}
public function or_where($fields = '', $where_val = false)
{
return $this->where($fields = '', $where_val = '', 'OR');
}
public function order_by($fields = '', $direction = 'asc')
{
if ($fields)
{
if ($direction === false && is_string($fields))
{
$this->order_by[$fields] = false;
}
else
{
$fdata = $this->_parse_field_names($fields, 'order_by');
foreach ($fdata as $key => $fitem)
{
$this->order_by[$key] = isset($fitem['value']) ? $fitem['value'] : $direction;
}
}
}
unset($fields);
return $this;
}
public function relation($fields = '', $rel_tbl = '', $rel_field = '', $rel_name = '', $rel_where = array(), $order_by = false,
$multi = false, $rel_concat_separator = ' ', $tree = false, $depend_field = '', $depend_on = '')
{
if ($fields && $rel_tbl && $rel_field && $rel_name)
{
if ($depend_on)
{
$fdata = $this->_parse_field_names($depend_on, 'relation');
$depend_on = key($fdata) /*$fdata[0]['table'] . '.' . $fdata[0]['field']*/;
}
$fdata = $this->_parse_field_names($fields, 'relation');
foreach ($fdata as $fitem)
{
$this->relation[$fitem['table'] . '.' . $fitem['field']] = array(
'rel_tbl' => $rel_tbl,
'rel_alias' => 'alias' . rand(),
'rel_field' => $rel_field,
'rel_name' => $rel_name,
'rel_where' => $rel_where,
'rel_separator' => $rel_concat_separator,
'order_by' => $order_by,
'multi' => $multi,
'table' => $fitem['table'],
'field' => $fitem['field'],
'tree' => $tree,
'depend_field' => $depend_field,
'depend_on' => $depend_on);
}
}
return $this;
}
public function fk_relation($label = '', $fields = '', $fk_table = '', $in_fk_field = '', $out_fk_field = '', $rel_tbl =
'', $rel_field = '', $rel_name = '', $rel_where = array(), $rel_orderby = '', $rel_concat_separator = ' ', $before = '',
array $add_data = array())
{
if ($fields && $rel_tbl && $rel_field && $rel_name && $label)
{
$fdata = $this->_parse_field_names($fields, 'fk_relation');
$fitem = reset($fdata);
$table = $this->_get_table('subselect');
//foreach ($fdata as $key => $fitem)
//{
//$alias = 'tfkalias' . base_convert(rand(), 10, 36);
$alias = $table . '.' . $label;
$this->fk_relation[$alias] = array(
'table' => $fitem['table'],
'field' => $fitem['field'],
'label' => $label,
'before' => $before ? key(reset($this->_parse_field_names($before, 'fk_relation'))) : '',
'alias' => $alias,
'rel_alias' => 'ralias' . rand(),
'fk_alias' => 'fkalias' . rand(),
'fk_table' => $fk_table,
'in_fk_field' => $in_fk_field,
'out_fk_field' => $out_fk_field,
'rel_tbl' => $rel_tbl,
'rel_field' => $rel_field,
'rel_name' => $rel_name,
'rel_where' => $rel_where,
'rel_orderby' => $rel_orderby,
'rel_separator' => $rel_concat_separator,
'add_data' => $add_data);
$this->field_type[$alias] = 'fk_relation';
$this->defaults[$alias] = '';
if (!isset($this->field_attr[$alias]))
{
$this->field_attr[$alias] = array();
}
//}
}
return $this;
}
public function join($fields = '', $join_tbl = '', $join_field = '', $alias = false)
{
$fdata = $this->_parse_field_names($fields, 'join');
$alias = $alias ? $alias : $join_tbl;
$key = key($fdata);
$this->join[$alias] = array(
'table' => $fdata[$key]['table'],
'field' => $fdata[$key]['field'],
'join_table' => $this->prefix . $join_tbl,
'join_field' => $join_field);
//$this->field_type[$this->join[$alias]['join_table'] . '.' . $this->join[$alias]['join_field']] = 'hidden';
$this->pass_var($alias . '.' . $join_field, '{' . $key . '}', 'edit');
return $this;
}
/** nested table constructor */
public function nested_table($instance_name = '', $field = '', $inner_tbl = '', $tbl_field = '')
{
if ($instance_name && $field && $inner_tbl && $tbl_field)
{
$fdata = $this->_parse_field_names($field, 'nested_table');
foreach ($fdata as $fitem)
{
$this->inner_table_instance[$instance_name] = $fitem['table'] . '.' . $fitem['field']; // name of nested object will be stored in parent instance
$instance = Xcrud::get_instance($instance_name); // just another xcrud object
$instance->table($this->prefix . $inner_tbl);
$instance->is_inner = true; // nested flag
$fdata2 = $this->_parse_field_names($tbl_field, 'nested_table', $inner_tbl);
$instance->inner_where[$fitem['table'] . '.' . $fitem['field']] = key($fdata2); // this connects nested table with parent
return $instance; // only one cycle
}
}
}
public function fields($fields = '', $reverse = false, $tabname = false, $mode = false)
{
$fdata = $this->_parse_field_names($fields, 'fields');
switch ($mode)
{
case 'create':
if (!$reverse && $tabname)
{
$this->field_tabs['create'][$tabname] = $tabname;
}
break;
case 'edit':
if (!$reverse && $tabname)
{
$this->field_tabs['edit'][$tabname] = $tabname;
}
break;
case 'view':
if (!$reverse && $tabname)
{
$this->field_tabs['view'][$tabname] = $tabname;
}
break;
default:
if (!$reverse && $tabname)
{
$this->field_tabs['create'][$tabname] = $tabname;
$this->field_tabs['edit'][$tabname] = $tabname;
$this->field_tabs['view'][$tabname] = $tabname;
}
break;
}
foreach ($fdata as $fitem)
{
$fitem['tab'] = $tabname;
switch ($mode)
{
case 'create':
$this->fields_create[$fitem['table'] . '.' . $fitem['field']] = $fitem;
$this->reverse_fields['create'] = $reverse;
break;
case 'edit':
$this->fields_edit[$fitem['table'] . '.' . $fitem['field']] = $fitem;
$this->reverse_fields['edit'] = $reverse;
break;
case 'view':
$this->fields_view[$fitem['table'] . '.' . $fitem['field']] = $fitem;
$this->reverse_fields['view'] = $reverse;
break;
default:
$this->fields_create[$fitem['table'] . '.' . $fitem['field']] = $fitem;
$this->fields_edit[$fitem['table'] . '.' . $fitem['field']] = $fitem;
$this->fields_view[$fitem['table'] . '.' . $fitem['field']] = $fitem;
$this->reverse_fields['create'] = $reverse;
$this->reverse_fields['edit'] = $reverse;
$this->reverse_fields['view'] = $reverse;
break;
}
}
unset($fields, $fdata);
return $this;
}
public function unique($fields = '')
{
$fdata = $this->_parse_field_names($fields, 'unique');
foreach ($fdata as $fitem)
{
$this->unique[$fitem['table'] . '.' . $fitem['field']] = $fitem;
}
unset($fields);
return $this;
}
public function label($fields = '', $label = '')
{
$fdata = $this->_parse_field_names($fields, 'label');
foreach ($fdata as $fitem)
{
$this->labels[$fitem['table'] . '.' . $fitem['field']] = isset($fitem['value']) ? $fitem['value'] : $label;
}
return $this;
}
public function columns($columns = '', $reverse = false)
{
$fdata = $this->_parse_field_names($columns, 'columns');
foreach ($fdata as $fitem)
{
$this->fields_list[$fitem['table'] . '.' . $fitem['field']] = $fitem;
}
$this->reverse_fields['list'] = $reverse;
unset($columns);
return $this;
}
public function unset_add($bool = true)
{
$this->is_create = !(bool)$bool;
return $this;
}
public function unset_edit($bool = true, $field = false, $operand = false, $value = false)
{
$this->is_edit = !(bool)$bool;
if ($field && $operand && $value !== false)
{
$this->grid_restrictions['edit'] = array(
'field' => $field,
'operator' => $operand,
'value' => $value);
}
return $this;
}
public function unset_view($bool = true, $field = false, $operand = false, $value = false)
{
$this->is_view = !(bool)$bool;
if ($field && $operand && $value !== false)
{
$this->grid_restrictions['view'] = array(
'field' => $field,
'operator' => $operand,
'value' => $value);
}
return $this;
}
public function unset_remove($bool = true, $field = false, $operand = false, $value = false)
{
$this->is_remove = !(bool)$bool;
if ($field && $operand && $value !== false)
{
$this->grid_restrictions['remove'] = array(
'field' => $field,
'operator' => $operand,
'value' => $value);
}
return $this;
}
public function duplicate_button($bool = true, $field = false, $operand = false, $value = false)
{
$this->is_duplicate = (bool)$bool;
if ($field && $operand && $value !== false)
{
$this->grid_restrictions['duplicate'] = array(
'field' => $field,
'operator' => $operand,
'value' => $value);
}
return $this;
}
public function unset_csv($bool = true)
{
$this->is_csv = !(bool)$bool;
return $this;
}
public function unset_print($bool = true)
{
$this->is_print = !(bool)$bool;
return $this;
}
public function unset_title($bool = true)
{
$this->is_title = !(bool)$bool;
return $this;
}
public function unset_numbers($bool = true)
{
$this->is_numbers = !(bool)$bool;
return $this;
}
public function unset_search($bool = true)
{
$this->is_search = !(bool)$bool;
return $this;
}
public function unset_limitlist($bool = true)
{
$this->is_limitlist = !(bool)$bool;
return $this;
}
public function unset_pagination($bool = true)
{
$this->is_pagination = !(bool)$bool;
return $this;
}
public function unset_sortable($bool = true)
{
$this->is_sortable = !(bool)$bool;
return $this;
}
public function unset_list($bool = true)
{
$this->is_list = !(bool)$bool;
return $this;
}
public function button($link = '', $name = '', $icon = '', $class = '', $parameters = array(), $condition = array())
{
if ($link)
{
$this->buttons[] = array(
'link' => $link,
'name' => $name,
'icon' => $icon,
'class' => $class,
'params' => (array )$parameters);
}
if ($condition && is_array($condition) && count($condition) == 3 && $name)
{
list($field, $operator, $value) = $condition;
$this->grid_restrictions[$name] = array(
'field' => $field,
'operator' => $operator,
'value' => $value);
}
return $this;
}
public function change_type($fields = '', $type = '', $default = false, $attr = array())
{
if ($type)
{
$fdata = $this->_parse_field_names($fields, 'change_type');
foreach ($fdata as $fitem)
{
switch ($type)
{
case 'file':
case 'image':
$this->upload_config[$fitem['table'] . '.' . $fitem['field']] = $attr;
break;
case 'price':
$def_attr = array(
'max' => 10,
'decimals' => 2,
'separator' => ',',
'prefix' => '',
'suffix' => '',
'point' => '.');
$this->field_attr[$fitem['table'] . '.' . $fitem['field']] = array_merge($def_attr, (array )$attr);
break;
case 'select':
case 'multiselect':
case 'radio':
case 'checkboxes':
if (!is_array($attr) or !isset($attr['values']))
{
$this->field_attr[$fitem['table'] . '.' . $fitem['field']]['values'] = $attr;
}
else
{
$this->field_attr[$fitem['table'] . '.' . $fitem['field']] = $attr;
}
break;
case 'point':
//$this->field_attr[$fitem['table'] . '.' . $fitem['field']] = $map_attr;
$def_attr = array( // defaults
'text' => Xcrud_config::$default_text,
'search_text' => Xcrud_config::$default_search_text,
'zoom' => Xcrud_config::$default_zoom,
'width' => Xcrud_config::$default_width,
'height' => Xcrud_config::$default_height,
'search' => Xcrud_config::$default_coord,
'coords' => Xcrud_config::$default_search);
$this->field_attr[$fitem['table'] . '.' . $fitem['field']] = array_merge($def_attr, (array )$attr);
break;
case 'remote_image':
if (is_array($attr) && !isset($attr['link']))
{
$attr['link'] = '';
}
elseif (is_string($attr))
{
$attr = array('link' => $attr);
}
$this->field_attr[$fitem['table'] . '.' . $fitem['field']] = $attr;
default:
if ($attr && !is_array($attr))
{
$attr = array('maxlength' => (int)$attr);
}
$this->field_attr[$fitem['table'] . '.' . $fitem['field']] = $attr;
break;
}
$this->field_type[$fitem['table'] . '.' . $fitem['field']] = $type;
$this->defaults[$fitem['table'] . '.' . $fitem['field']] = $default;
}
}
return $this;
}
public function pass_default($fields = '', $value = '')
{
$fdata = $this->_parse_field_names($fields, 'pass_default');
foreach ($fdata as $fitem)
{
$this->defaults[$fitem['table'] . '.' . $fitem['field']] = isset($fitem['value']) ? $fitem['value'] : $value;
}
return $this;
}
public function pass_var($fields = '', $value = '', $type = 'all')
{
$fdata = $this->_parse_field_names($fields, 'pass_var');
$type = str_replace(' ', '', $type);
$types = $this->parse_comma_separated($type);
foreach ($fdata as $fitem)
{
$findex = $fitem['table'] . '.' . $fitem['field'];
$pass_var = array(
'table' => $fitem['table'],
'field' => $fitem['field'],
'value' => isset($fitem['value']) ? $fitem['value'] : $value);
foreach ($types as $tp)
{
if ($tp == 'all')
{
$this->pass_var['create'][$findex] = $pass_var;
$this->pass_var['edit'][$findex] = $pass_var;
$this->pass_var['view'][$findex] = $pass_var;
break;
}
elseif ($tp == 'create' || $tp == 'edit' || $tp == 'view')
{
$this->pass_var[$tp][$findex] = $pass_var;
}
}
}
return $this;
}
public function no_quotes($fields = '')
{
$fdata = $this->_parse_field_names($fields, 'no_quotes');
foreach ($fdata as $fkey => $fitem)
{
$this->no_quotes[$fkey] = true;
}
return $this;
}
public function sum($fields = '', $class = '', $custom_text = '')
{
$fdata = $this->_parse_field_names($fields, 'sum');
foreach ($fdata as $fkey => $fitem)
{
$this->sum[$fkey] = array(
'table' => $fitem['table'],
'column' => $fitem['field'],
'class' => isset($fitem['value']) ? $fitem['value'] : $class,
'custom' => $custom_text);
}
return $this;
}
public function readonly_on_create($field = '')
{
return $this->readonly($field, 'create');
}
public function disabled_on_create($field = '')
{
return $this->disabled($field, 'create');
}
public function readonly_on_edit($field = '')
{
return $this->readonly($field, 'edit');
}
public function disabled_on_edit($field = '')
{
return $this->disabled($field, 'edit');
}
public function readonly($fields = '', $mode = false) // needs to be re-written
{
$fdata = $this->_parse_field_names($fields, 'readonly');
foreach ($fdata as $key => $fitem)
{
$this->readonly[$key] = $this->parse_mode($mode);
}
return $this;
}
public function disabled($fields = '', $mode = false)
{
$fdata = $this->_parse_field_names($fields, 'disabled');
foreach ($fdata as $key => $fitem)
{
$this->disabled[$key] = $this->parse_mode($mode);
}
return $this;
}
public function condition($fields = '', $operator = '', $value = '', $method = '', $params = array(), $mode = false)
{
if ($fields && $method && $operator)
{
$fdata = $this->_parse_field_names($fields, 'condition');
foreach ($fdata as $key => $fitem)
{
$this->condition[] = array(
'field' => $key,
'value' => $value,
'operator' => $operator,
'method' => $method,
'params' => (array )$params,
'mode' => $this->parse_mode($mode));
}
}
return $this;
}
public function instance_name()
{
return $this->instance_name;
}
public function benchmark($bool = true)
{
$this->benchmark = (bool)$bool;
return $this;
}
public function column_cut($int = 50, $fields = false, $safe_output = false)
{
if ($fields === false)
{
$this->column_cut = (int)$int ? (int)$int : false;
$this->safe_output = $safe_output;
}
else
{
$fdata = $this->_parse_field_names($fields, 'column_cut');
foreach ($fdata as $fitem)
{
$this->column_cut_list[$fitem['table'] . '.' . $fitem['field']] = array('count' => $int, 'safe' => $safe_output);
}
}
return $this;
}
public function links_label($text = '')
{
if ($text)
{
$this->links_label['text'] = trim($text);
}
return $this;
}
public function emails_label($text = '')
{
if ($text)
{
$this->emails_label['text'] = trim($text);
}
return $this;
}
public function no_editor($fields = '')
{
$fdata = $this->_parse_field_names($fields, 'no_editor');
foreach ($fdata as $fitem)
{
$this->no_editor[$fitem['table'] . '.' . $fitem['field']] = true;
}
return $this;
}
public function validation_required($fields = '', $chars = 1)
{
$fdata = $this->_parse_field_names($fields, 'validation_required');
foreach ($fdata as $fitem)
{
$this->validation_required[$fitem['table'] . '.' . $fitem['field']] = isset($fitem['value']) ? $fitem['value'] : $chars;
}
return $this;
}
public function validation_pattern($fields = '', $pattern = '')
{
$fdata = $this->_parse_field_names($fields, 'validation_pattern');
foreach ($fdata as $fitem)
{
$this->validation_pattern[$fitem['table'] . '.' . $fitem['field']] = isset($fitem['value']) ? $fitem['value'] : $pattern;
}
return $this;
}
public function alert($columns = '', $cc = '', $subject = '', $message = '', $link = false, $field = false, $value = false,
$mode = 'all')
{
$fdata = $this->_parse_field_names($columns, 'alert');
if ($field && !strpos($field, '.'))
$field = $this->table . '.' . $field;
foreach ($fdata as $fitem)
{
if ($cc)
{
if (!is_array($cc))
$cc = $this->parse_comma_separated($cc);
}
if ($mode == 'all' or $mode == 'create')
$this->alert_create[] = array(
'column' => $fitem['table'] . '.' . $fitem['field'],
'cc' => $cc,
'subject' => $subject,
'message' => $message,
'link' => $link,
'field' => $field,
'value' => $value);
if ($mode == 'all' or $mode == 'edit')
$this->alert_edit[] = array(
'column' => $fitem['table'] . '.' . $fitem['field'],
'cc' => $cc,
'subject' => $subject,
'message' => $message,
'link' => $link,
'field' => $field,
'value' => $value);
}
return $this;
}
public function alert_create($column = '', $cc = '', $subject = '', $message = '', $link = false, $field = false, $value = false)
{
return $this->alert($column, $cc, $subject, $message, $link, $field, $value, $table, 'create');
}
public function alert_edit($column = '', $cc = '', $subject = '', $message = '', $link = false, $field = false, $value = false)
{
return $this->alert($column, $cc, $subject, $message, $link, $field, $value, $table, 'edit');
}
public function mass_alert($email_table = '', $email_column = '', $emeil_where = '', $subject = '', $message = '', $link = false,
$field = false, $value = false, $mode = 'all')
{
if (!$table)
$table = $this->_get_table('mass_alert');
$field = $this->table . '.' . $field;
if ($mode == 'all' or $mode == 'create')
$this->mass_alert_create[] = array(
'email_table' => $email_table,
'email_column' => $email_column,
'where' => $emeil_where,
'subject' => $subject,
'message' => $message,
'link' => $link,
'field' => $field,
'value' => $value,
'table' => $table);
if ($mode == 'all' or $mode == 'edit')
$this->mass_alert_edit[] = array(
'email_table' => $email_table,
'email_column' => $email_column,
'where' => $emeil_where,
'subject' => $subject,
'message' => $message,
'link' => $link,
'field' => $field,
'value' => $value,
'table' => $table);
return $this;
}
public function mass_alert_create($email_table = '', $email_column = '', $emeil_where = '', $subject = '', $message = '',
$link = false, $field = false, $value = false)
{
return $this->mass_alert($email_table, $email_column, $emeil_where, $subject, $message, $link, $field, $value, $table,
'create');
}
public function mass_alert_edit($email_table = '', $email_column = '', $emeil_where = '', $subject = '', $message = '',
$link = false, $field = false, $value = false)
{
return $this->mass_alert($email_table, $email_column, $emeil_where, $subject, $message, $link, $field, $value, $table,
'edit');
}
public function send_external($path, $data = array(), $method = 'include', $mode = 'all', $where_field = '', $where_val = '')
{
if ($where_field)
{
$fdata = $this->_parse_field_names($where_field, 'send_external');
$where_field = key($fdata) /*$fdata[0]['table'] . '.' . $fdata[0]['field']*/;
}
if ($mode == 'all' or $mode == 'create')
$this->send_external_create = array(
'data' => $data,
'path' => $path,
'method' => $method,
'where_field' => $where_field,
'where_val' => $where_val);
if ($mode == 'all' or $mode == 'edit')
$this->send_external_edit = array(
'data' => $data,
'path' => $path,
'method' => $method,
'where_field' => $where_field,
'where_val' => $where_val);
return $this;
}
public function page_call($url = '', $data = array(), $where_param = '', $where_value = '', $method = 'get')
{
return $this->send_external($url, $data, $method, 'all', $where_param, $where_value);
}
public function page_call_create($url = '', $data = array(), $where_param = '', $where_value = '', $method = 'get')
{
return $this->send_external($url, $data, $method, 'create', $where_param, $where_value);
}
public function page_call_edit($url = '', $data = array(), $where_param = '', $where_value = '', $method = 'get')
{
return $this->send_external($url, $data, $method, 'edit', $where_param, $where_value);
}
public function subselect($column_name = '', $sql = '', $before = false)
{
if ($column_name && $sql)
{
$table = $this->_get_table('subselect');
$column_alias = $table . '.' . $column_name;
if ($before)
{
$fdata = $this->_parse_field_names($before, 'subselect');
$before = key($fdata) /*$fdata[0]['table'] . '.' . $fdata[0]['field']*/;
}
$this->subselect[$column_alias] = $sql;
$this->subselect_before[$column_alias] = $before;
//$this->no_select[$column_alias] = true;
$this->labels[$column_alias] = $column_name;
$this->field_type[$column_alias] = 'none';
$this->defaults[$column_alias] = '';
}
return $this;
}
public function highlight($columns = '', $operator = '', $value = '', $color = '', $class = '')
{
if ($columns && $operator)
{
$fdata = $this->_parse_field_names($columns, 'highlight');
foreach ($fdata as $fitem)
{
$this->highlight[$fitem['table'] . '.' . $fitem['field']][] = array(
'value' => $value,
'operator' => $operator,
'color' => $color,
'class' => $class);
}
}
return $this;
}
public function highlight_row($columns = '', $operator = '', $value = '', $color = '', $class = '')
{
if ($columns && $operator)
{
$fdata = $this->_parse_field_names($columns, 'highlight_row');
foreach ($fdata as $fitem)
{
$this->highlight_row[] = array(
'field' => $fitem['table'] . '.' . $fitem['field'],
'value' => $value,
'operator' => $operator,
'color' => $color,
'class' => $class);
}
}
return $this;
}
public function modal($columns = '', $icon = false)
{
$fdata = $this->_parse_field_names($columns, 'modal');
foreach ($fdata as $fitem)
{
$this->modal[$fitem['table'] . '.' . $fitem['field']] = isset($fitem['value']) ? $fitem['value'] : $icon;
}
return $this;
}
public function column_class($columns = '', $class = '')
{
$fdata = $this->_parse_field_names($columns, 'column_class');
foreach ($fdata as $fitem)
{
$this->column_class[$fitem['table'] . '.' . $fitem['field']][] = isset($fitem['value']) ? $fitem['value'] : $class;
}
return $this;
}
public function language($lang = 'en')
{
$this->language = $lang;
return $this;
}
public function field_tooltip($fields = '', $tooltip = '', $icon = false)
{
if ($fields && $tooltip)
{
$fdata = $this->_parse_field_names($fields, 'column_class');
foreach ($fdata as $fitem)
{
$this->field_tooltip[$fitem['table'] . '.' . $fitem['field']] = array('tooltip' => isset($fitem['value']) ? $fitem['value'] :
$tooltip, 'icon' => $icon);
}
}
return $this;
}
public function search_columns($fields = '', $default = null)
{
if ($fields)
{
$fdata = $this->_parse_field_names($fields, 'search_columns');
foreach ($fdata as $fkey => $fitem)
{
$this->search_columns[$fkey] = $fitem;
}
}
if ($default)
{
$fdata = $this->_parse_field_names($default, 'search_columns');
$this->search_default = key($fdata) /*$fdata[0]['table'] . '.' . $fdata[0]['field']*/;
}
return $this;
}
public function column_width($fields = '', $width = '')
{
if ($fields && $width)
{
$fdata = $this->_parse_field_names($fields, 'column_width');
foreach ($fdata as $fitem)
{
$this->column_width[$fitem['table'] . '.' . $fitem['field']] = $width;
}
}
return $this;
}
public function before_insert($callable = '', $path = 'functions.php')
{
if ($callable && $path)
{
$this->before_insert['callable'] = $callable;
$this->before_insert['path'] = $path;
}
return $this;
}
public function before_update($callable = '', $path = 'functions.php')
{
if ($callable && $path)
{
$this->before_update['callable'] = $callable;
$this->before_update['path'] = $path;
}
return $this;
}
public function before_remove($callable = '', $path = 'functions.php')
{
if ($callable && $path)
{
$this->before_remove['callable'] = $callable;
$this->before_remove['path'] = $path;
}
return $this;
}
public function after_insert($callable = '', $path = 'functions.php')
{
if ($callable && $path)
{
$this->after_insert['callable'] = $callable;
$this->after_insert['path'] = $path;
}
return $this;
}
public function after_update($callable = '', $path = 'functions.php')
{
if ($callable && $path)
{
$this->after_update['callable'] = $callable;
$this->after_update['path'] = $path;
}
return $this;
}
public function after_remove($callable = '', $path = 'functions.php')
{
if ($callable && $path)
{
$this->after_remove['callable'] = $callable;
$this->after_remove['path'] = $path;
}
return $this;
}
public function after_upload($callable = '', $path = 'functions.php')
{
if ($callable && $path)
{
$this->after_upload['callable'] = $callable;
$this->after_upload['path'] = $path;
}
return $this;
}
public function before_upload($callable = '', $path = 'functions.php')
{
if ($callable && $path)
{
$this->before_upload['callable'] = $callable;
$this->before_upload['path'] = $path;
}
return $this;
}
public function column_callback($fields = '', $callback = '', $path = 'functions.php')
{
if ($fields && $callback && $path)
{
$fdata = $this->_parse_field_names($fields, 'column_callback');
foreach ($fdata as $fitem)
{
$this->column_callback[$fitem['table'] . '.' . $fitem['field']] = array(
'name' => $fitem['table'] . '.' . $fitem['field'],
'path' => rtrim($path, '/'),
'callback' => $callback);
}
}
return $this;
}
public function field_callback($fields = '', $callback = '', $path = 'functions.php')
{
if ($fields && $callback && $path)
{
$fdata = $this->_parse_field_names($fields, 'field_callback');
foreach ($fdata as $fitem)
{
$this->field_callback[$fitem['table'] . '.' . $fitem['field']] = array(
'name' => $fitem['table'] . '.' . $fitem['field'],
'path' => rtrim($path, '/'),
'callback' => $callback);
}
}
return $this;
}
public function replace_insert($callable = '', $path = 'functions.php')
{
if ($callable)
{
$this->replace_insert = array('callable' => $callable, 'path' => $path);
}
return $this;
}
public function replace_update($callable = '', $path = 'functions.php')
{
if ($callable)
{
$this->replace_update = array('callable' => $callable, 'path' => $path);
}
return $this;
}
public function replace_remove($callable = '', $path = 'functions.php')
{
if ($callable)
{
$this->replace_remove = array('callable' => $callable, 'path' => $path);
}
return $this;
}
public function before_list($callable = '', $path = 'functions.php')
{
if ($callable && $path)
{
$this->before_list['callable'] = $callable;
$this->before_list['path'] = $path;
}
return $this;
}
public function before_create($callable = '', $path = 'functions.php')
{
if ($callable && $path)
{
$this->before_create['callable'] = $callable;
$this->before_create['path'] = $path;
}
return $this;
}
public function before_edit($callable = '', $path = 'functions.php')
{
if ($callable && $path)
{
$this->before_edit['callable'] = $callable;
$this->before_edit['path'] = $path;
}
return $this;
}
public function before_view($callable = '', $path = 'functions.php')
{
if ($callable && $path)
{
$this->before_view['callable'] = $callable;
$this->before_view['path'] = $path;
}
return $this;
}
public function call_update($postdata, $primary)
{
if (!$this->task)
{
self::error('Sorry, but you must use call_update() only in callbacks');
}
return $this->_update($postdata->to_array(), $primary);
}
public function set_var($name = null, $value = null)
{
if ($name)
{
$this->custom_vars[$name] = $value;
}
return $this;
}
public function get_var($name = null)
{
if ($name)
{
return isset($this->custom_vars[$name]) ? $this->custom_vars[$name] : false;
}
else
{
return false;
}
}
public function unset_var($name)
{
if (isset($this->custom_vars[$name]))
{
unset($this->custom_vars[$name]);
}
return $this;
}
public function column_name($fields = '', $text = '')
{
$fdata = $this->_parse_field_names($fields, 'column_name');
foreach ($fdata as $fitem)
{
$this->column_name[$fitem['table'] . '.' . $fitem['field']] = $text;
}
unset($fields);
return $this;
}
public function column_pattern($fields, $patern)
{
if ($fields && $patern)
{
$fdata = $this->_parse_field_names($fields, 'column_pattern');
foreach ($fdata as $fkey => $fitem)
{
$this->column_pattern[$fkey] = $patern;
}
}
return $this;
}
public function column_tooltip($fields = '', $tooltip = '', $icon = false)
{
if ($fields && $tooltip)
{
$fdata = $this->_parse_field_names($fields, 'column_tooltip');
foreach ($fdata as $fkey => $fitem)
{
$this->column_tooltip[$fkey] = array('tooltip' => $this->html_safe(isset($fitem['value']) ? $fitem['value'] : $tooltip),
'icon' => $icon);
}
}
return $this;
}
public function buttons_position($position = 'left')
{
switch ($position)
{
case 'left':
case 'right':
case 'none':
$this->buttons_position = $position;
break;
}
return $this;
}
public function hide_button($names = '')
{
foreach ($this->parse_comma_separated($names) as $name)
{
$this->hide_button[$name] = 1;
}
return $this;
}
public function set_lang($var = '', $translate = '')
{
if ($var)
{
$this->set_lang[$var] = $translate;
}
return $this;
}
public function search_pattern($left = '%', $right = '%')
{
$this->search_pattern = array($left, $right);
return $this;
}
public function load_view($mode = '', $file = '')
{
if ($mode && $file)
{
switch ($mode)
{
case 'list':
case 'create':
case 'edit':
case 'view':
$this->load_view[$mode] = $file;
break;
default:
self::error('Incorrect mode.');
}
}
return $this;
}
public function create_action($name = '', $callable = '', $path = 'functions.php')
{
if ($callable && $name)
{
$this->action[$name] = array('callable' => $callable, 'path' => $path);
}
return $this;
}
public function get($name = '')
{
if (!$this->task)
{
self::error('Sorry, but you must use get() only in callbacks');
}
if ($this->_get('key'))
{
return $this->_get($name);
}
else
{
return $this->_post($name);
}
}
public function default_tab($name = false)
{
$this->default_tab = $name;
return $this;
}
public function query($query = '')
{
$this->query = $query;
return $this;
}
public function check()
{
$array = array();
$phpvers = phpversion();
$array['PHP version'] = array('value' => $phpvers, 'state' => ((int)$phpvers >= 5 ? 'passed' : 'error'));
}
public function set_attr($fields = '', array $attr = array())
{
if ($fields && $attr)
{
$fdata = $this->_parse_field_names($fields, 'set_attr');
foreach ($fdata as $fkey => $fitem)
{
if (isset($this->field_attr[$fkey]))
{
$this->field_attr[$fkey] = array_merge((array )$this->field_attr[$fkey], $attr);
}
else
{
$this->field_attr[$fkey] = $attr;
}
}
}
return $this;
}
/** public renderer, final instance method */
public function render($task = false, $primary = false)
{
$this->benchmark_start();
$this->_receive_post($task, $primary);
$this->_regenerate_key();
$this->_remove_and_save_uploads();
$this->_get_language();
$this->_get_theme_config();
if ($this->query)
{
return $this->render_custom_query_task();
}
$this->_get_table_info();
return $this->_run_task();
}
/** main task trigger */
protected function _run_task()
{
if ($this->after && $this->after == $this->task)
{
return self::error('Task recursion!');
}
if (!$this->task)
{
$this->task = 'list';
}
switch ($this->task)
{
case 'create':
$this->_set_field_types('create');
//$this->_sort_defaults();
return $this->_create();
break;
case 'edit':
$this->_set_field_types('edit');
return $this->_entry('edit');
break;
case 'save':
if (!$this->before)
{
return self::error('Restricted task!');
}
$this->_set_field_types($this->before);
return $this->_save();
/*$this->task = $this->after;
$this->after = null;
return $this->_run_task();*/
break;
case 'remove':
$this->_set_field_types('list');
$this->_remove();
return $this->_list();
break;
case 'upload':
return $this->_upload();
break;
case 'remove_upload':
return $this->_remove_upload();
break;
case 'crop_image':
return $this->manual_crop();
break;
case 'unique':
$this->_set_field_types('edit');
return $this->_check_unique_value();
break;
case 'clone':
$this->_set_field_types('list');
$this->_clone_row();
return $this->_list();
break;
case 'print':
if (!$this->is_print)
{
return self::error('Restricted');
}
$this->_set_field_types('list', Xcrud_config::$print_all_fields);
$this->theme = 'printout';
return $this->_list();
break;
case 'depend':
return $this->create_relation($this->_post('name', false, 'base64'), $this->_post('value'), $this->get_field_attr($this->
_post('name', false, 'base64'), 'edit'), $this->_post('dependval'));
break;
case 'view':
$this->_set_field_types('view');
return $this->_entry('view');
break;
case 'query':
break;
case 'external':
break;
case 'action':
return $this->_call_action();
break;
case 'file':
$this->_set_field_types('list');
return $this->_render_file();
break;
case 'csv':
$this->_set_field_types('list', Xcrud_config::$csv_all_fields);
return $this->_csv();
break;
case 'list':
default:
$this->_set_field_types('list');
return $this->_list();
break;
}
}
protected function render_custom_query_task()
{
$this->is_edit = false;
$this->is_remove = false;
$this->is_create = false;
$this->is_view = false;
$this->is_search = false;
switch ($this->task)
{
case 'print':
if (!$this->is_print)
{
return self::error('Restricted');
}
$this->theme = 'printout';
$this->start = 0;
$this->limit = 0;
return $this->render_custom_datagrid();
break;
case 'action':
return $this->_call_action();
break;
case 'csv':
return $this->render_custom_csv();
break;
default:
return $this->render_custom_datagrid();
break;
}
}
protected function render_custom_datagrid()
{
$query = $this->parse_query_params();
$db = Xcrud_db::get_instance($this->connection);
$db->query('SELECT COUNT(*) as `count` FROM (SELECT NULL' . $this->total_query . ') counts');
$this->sum_row = $db->row();
$this->result_total = $this->sum_row['count'];
$order_by = $this->_build_order_by();
$limit = $this->_build_limit($this->result_total);
$db->query($query . ' ' . $order_by . ' ' . $limit);
$this->result_list = $db->result();
$this->columns = reset($this->result_list);
unset($this->columns['primary_key']);
foreach ($this->columns as $key => $tmp)
{
$this->columns[$key] = array('table' => '', 'field' => $key);
if (!isset($this->field_type[$key]))
{
$this->field_type[$key] = 'text';
}
}
$this->fields_list = $this->columns;
$this->_set_column_names();
if (!$this->table_name)
{
$this->table_name = ' ';
}
return $this->_render_list();
}
protected function render_custom_csv()
{
if (!$this->is_csv)
{
return self::error('Restricted');
}
$this->columns = $this->fields_list;
$query = $this->parse_query_params();
$db = Xcrud_db::get_instance($this->connection);
$order_by = $this->_build_order_by();
$this->_set_column_names();
ini_set('auto_detect_line_endings', true);
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-type: application/octet-stream");
$table_name = $this->_clean_file_name(trim(html_entity_decode($this->table_name, ENT_QUOTES, 'utf-8')));
header("Content-Disposition: attachment; filename=\"" . ($table_name ? $table_name : 'table') . ".csv\"");
header("Content-Transfer-Encoding: binary");
$output = fopen('php://output', 'w');
fwrite($output, chr(0xEF) . chr(0xBB) . chr(0xBF)); // bom
fputcsv($output, $this->columns_names, Xcrud_config::$csv_delimiter, Xcrud_config::$csv_enclosure);
$db->query($query . ' ' . $order_by);
while ($row = $db->result->fetch_assoc()) // low level result process, saves memory
{
$out = array();
foreach ($this->columns as $field => $fitem)
{
$out[] = htmlspecialchars_decode(strip_tags($this->_render_export_item($field, $row[$field], $row['primary_key'], $row)),
ENT_QUOTES);
}
fputcsv($output, $out, Xcrud_config::$csv_delimiter, Xcrud_config::$csv_enclosure);
}
}
protected function parse_query_params()
{
$query = preg_replace('/\s+/u', ' ', $this->query);
$query = preg_replace('/[\)`\s]from[\(`\s]/ui', ' FROM ', $query);
if (preg_match('/(limit([0-9\s\,]+)){1}$/ui', $query, $matches))
{
$query = str_ireplace($matches[0], '', $query);
if (!$this->ajax_request)
{
$tmp = explode(',', $matches[2]);
if (isset($tmp[1]))
{
$this->start = (int)trim($tmp[0]);
$this->limit = (int)trim($tmp[1]);
}
else
{
$this->start = 0;
$this->limit = (int)trim($tmp[0]);
}
}
}
if (preg_match('/(order\sby([^\(\)]+)){1}$/ui', $query, $matches))
{
$query = str_ireplace($matches[0], '', $query);
if (!$this->ajax_request)
{
$tmp = explode(',', $matches[2]);
foreach ($tmp as $item)
{
$item = trim($item);
$direct = (mb_strripos($item, ' desc') == (mb_strlen($item) - 5) || mb_strripos($item, '`desc') == (mb_strlen($item) - 5)) ?
'desc' : 'asc';
$item = str_ireplace(array(
' asc',
' desc',
'`asc',
'`desc',
'`'), '', $item);
$this->order_by[$item] = $direct;
}
}
}
$tmp = preg_replace_callback('/\( (?> [^)(]+ | (?R) )+ \)/xui', array($this, 'query_params_callback'), $query);
$from_pos = mb_strpos($tmp, ' FROM ');
$this->total_query = mb_substr($query, $from_pos);
$query = mb_substr($query, 0, $from_pos) . ',(0) AS `primary_key`' . mb_substr($query, $from_pos);
return $query;
}
protected function query_params_callback($matches)
{
return preg_replace('/./Uui', '*', $matches[0]);
}
/** main output */
protected function render_output()
{
if ($this->ajax_request)
{
$contents = $this->render_control_fields() . $this->data;
$this->after_render();
return $contents;
}
else
{
$contents = '';
if (!self::$css_loaded && !Xcrud_config::$manual_load)
{
$contents .= self::load_css();
}
ob_start();
include (XCRUD_PATH . '/' . Xcrud_config::$themes_path . '/' . $this->theme . '/xcrud_container.php');
$contents .= ob_get_contents();
ob_end_clean();
unset($this->data);
if (!self::$js_loaded && !Xcrud_config::$manual_load)
{
$contents .= self::load_js();
}
$this->after_render();
return $contents;
}
}
protected function after_render()
{
switch ($this->task)
{
case 'file':
case 'depend':
case 'print':
case 'csv':
break;
default:
if (self::$instance)
{
foreach (self::$instance as $i)
{
$i->_export_vars();
}
}
break;
}
if (is_callable(Xcrud_config::$after_render))
{
call_user_func(Xcrud_config::$after_render);
}
}
/** returns current view into main container */
protected function render_view()
{
return $this->render_control_fields() . $this->data;
}
/** files and images rendering */
protected function _render_file()
{
$field = str_replace('`', '', $this->_get('field'));
if (!$field)
exit();
$thumb = $this->_get('thumb', false);
$crop = (bool)$this->_get('crop', false);
$settings = $this->upload_config[$field];
$blob = false;
$image = array_search($field, array_reverse($this->upload_to_save));
if (!$image)
{
list($tmp1, $tmp2) = explode('.', $field);
$db = Xcrud_db::get_instance($this->connection);
$this->where_pri($this->primary_key, $this->primary_val);
$where = $this->_build_where();
$table_join = $this->_build_table_join();
$db = Xcrud_db::get_instance($this->connection);
$db->query("SELECT `$tmp1`.`$tmp2`\r\n FROM `{$this->table}`\r\n {$table_join}\r\n {$where}\r\n LIMIT 1");
$row = $db->row();
$image = $row[$tmp2];
if (isset($this->upload_config[$field]['blob']) && $this->upload_config[$field]['blob'] === true)
{
$blob = true;
}
else
{
if ($thumb !== false)
{
if (isset($settings['thumbs'][$thumb]))
{
$thumb_set = $settings['thumbs'][$thumb];
$path = $this->get_thumb_path($image, $field, $thumb_set);
}
else
{
$folder = $this->get_image_folder($field);
$path = $folder . '/' . $image;
}
}
else
{
$folder = $this->get_image_folder($field);
$path = $folder . '/' . $image;
}
//$image = ($thumb ? substr_replace($image, $marker, strrpos($image, '.'), 0) : $image);
//$path = $this->check_folder($folder, 'render_image') . '/' . $image;
if (!is_file($path))
{
die($path);
header("HTTP/1.0 404 Not Found");
exit('Not Found');
}
//$output = file_get_contents($path);
}
}
else
{
//$folder = $this->upload_folder[$field];
if ($crop)
{
$folder = $this->get_image_folder($field);
$tmp_filename = substr($image, 0, strrpos($image, '.')) . '.tmp';
$path = $folder . '/' . $tmp_filename;
}
elseif ($thumb !== false)
{
$thumb_set = $settings['thumbs'][$thumb];
$path = $this->get_thumb_path($image, $field, $thumb_set);
}
else
{
$folder = $this->get_image_folder($field);
$path = $folder . '/' . $image;
}
//$image = ($thumb ? substr_replace($image, $marker, strrpos($image, '.'), 0) : $image);
//$path = $this->check_folder($folder, 'render_image') . '/' . $image;
if (!is_file($path))
{
header("HTTP/1.0 404 Not Found");
exit('Not Found');
}
//$output = file_get_contents($path);
}
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
if ($this->field_type[$field] == 'image' && !$blob)
{
$size = getimagesize($path);
switch ($size[2])
{
case 1:
header("Content-type: image/gif");
break;
case 2:
header("Content-type: image/jpeg");
break;
case 3:
header("Content-type: image/png");
break;
}
}
elseif ($blob && $this->field_type[$field] == 'image')
{
header("Content-type: image/jpeg");
}
elseif ($blob)
{
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"" . (isset($settings['filename']) ? $settings['filename'] :
'binary_data') . "\"");
header("Content-Transfer-Encoding: binary");
}
else
{
if (trim(strtolower(strrchr($path, '.')), '.') == 'pdf')
{
header("Content-type: application/pdf");
}
else
{
header("Content-type: application/octet-stream");
}
header("Content-Disposition: attachment; filename=\"" . (isset($settings['filename']) ? $settings['filename'] : $image) .
"\"");
header("Content-Transfer-Encoding: binary");
}
if ($blob)
header("Content-Length: " . strlen($image));
else
header("Content-Length: " . filesize($path));
@ob_clean();
flush();
if ($blob)
{
return $image;
}
else
{
readfile($path);
}
exit();
}
public function _csv()
{
if (!$this->is_csv)
{
return self::error('Restricted');
}
$db = Xcrud_db::get_instance($this->connection);
$select = $this->_build_select_list(true);
$table_join = $this->_build_table_join();
$where = $this->_build_where();
$order_by = $this->_build_order_by();
$this->_set_column_names();
$headers = array();
foreach ($this->columns as $field => $fitem)
{
if (isset($this->field_type[$field]) && ($this->field_type[$field] == 'password' or $this->field_type[$field] ==
'hidden'))
continue;
$headers[] = $this->columns_names[$field];
}
ini_set('auto_detect_line_endings', true);
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"" . $this->_clean_file_name($this->table_name ? $this->table_name :
$this->table) . ".csv\"");
header("Content-Transfer-Encoding: binary");
$output = fopen('php://output', 'w');
fwrite($output, chr(0xEF) . chr(0xBB) . chr(0xBF)); // bom
fputcsv($output, $headers, Xcrud_config::$csv_delimiter, Xcrud_config::$csv_enclosure);
$db->query("SELECT {$select} FROM `{$this->table}` {$table_join} {$where} {$order_by}");
while ($row = $db->result->fetch_assoc()) // low level result process, saves memory
{
$out = array();
foreach ($this->columns as $field => $fitem)
{
if (isset($this->field_type[$field]) && ($this->field_type[$field] == 'password' or $this->field_type[$field] ==
'hidden'))
continue;
$out[] = htmlspecialchars_decode(strip_tags($this->_render_export_item($field, $row[$field], $row['primary_key'], $row)),
ENT_QUOTES);
}
fputcsv($output, $out, Xcrud_config::$csv_delimiter, Xcrud_config::$csv_enclosure);
}
}
/** returns request variable */
protected function _post($field = '', $default = false, $filter = false)
{
if (isset($_POST['xcrud'][$field]))
{
if (Xcrud_config::$auto_xss_filtering)
{
$xss = $this->load_core_class('xss');
}
else
{
$xss = false;
}
if (($field == 'postdata' or $field == 'unique') && $_POST['xcrud'][$field])
{
$data_keys = array_keys($_POST['xcrud'][$field]);
foreach ($data_keys as $k => $key)
{
$data_keys[$k] = $xss ? $xss->xss_clean($this->fieldname_decode($key)) : $this->fieldname_decode($key);
if ($xss)
{
$_POST['xcrud'][$field][$key] = $xss->xss_clean($_POST['xcrud'][$field][$key]);
}
}
return array_combine($data_keys, $_POST['xcrud'][$field]);
}
elseif ($filter)
{
switch ($filter)
{
case 'key':
return str_replace('`', '', $xss ? $xss->xss_clean($_POST['xcrud'][$field]) : $_POST['xcrud'][$field]);
break;
case 'int':
return (int)$_POST['xcrud'][$field];
break;
case 'trim':
return trim($xss ? $xss->xss_clean($_POST['xcrud'][$field]) : $_POST['xcrud'][$field]);
break;
case 'base64':
return $xss ? $xss->xss_clean($this->fieldname_decode($_POST['xcrud'][$field])) : $this->fieldname_decode($_POST['xcrud'][$field]);
break;
default:
return $xss ? $xss->xss_clean($_POST['xcrud'][$field]) : $_POST['xcrud'][$field];
break;
}
}
else
{
return $xss ? $xss->xss_clean($_POST['xcrud'][$field]) : $_POST['xcrud'][$field];
}
}
else
return $default;
}
protected function _get($field = '', $default = false, $filter = false)
{
if (isset($_GET['xcrud'][$field]))
{
if (Xcrud_config::$auto_xss_filtering)
{
$xss = $this->load_core_class('xss');
}
else
{
$xss = false;
}
if ($filter)
{
switch ($filter)
{
case 'key':
return str_replace('`', '', $xss ? $xss->xss_clean($_GET['xcrud'][$field]) : $_GET['xcrud'][$field]);
break;
case 'int':
return (int)$_GET['xcrud'][$field];
break;
case 'trim':
return trim($xss ? $xss->xss_clean($_GET['xcrud'][$field]) : $_GET['xcrud'][$field]);
break;
default:
return $xss ? $xss->xss_clean($_GET['xcrud'][$field]) : $_GET['xcrud'][$field];
break;
}
}
else
{
return $xss ? $xss->xss_clean($_GET['xcrud'][$field]) : $_GET['xcrud'][$field];
}
}
else
return $default;
}
/** creates fieldlist for adding record */
protected function _create($postdata = array())
{
if (!$this->is_create || $this->table_ro)
return self::error('Forbidden');
$this->_set_field_names();
$this->primary_val = null;
$this->result_row = array_merge($this->defaults, $postdata);
if ($this->before_create)
{
$path = $this->check_file($this->before_create['path'], 'before_create');
include_once ($path);
if (is_callable($this->before_create['callable']))
{
call_user_func_array($this->before_create['callable'], array($this->result_row, $this));
}
}
/** conditions process */
if ($this->condition)
{
foreach ($this->condition as $params)
{
if (!isset($params['mode']['create']))
continue;
$params['value'] = $this->replace_text_variables($params['value'], $this->result_row);
if (array_key_exists($params['field'], $this->result_row) && $this->_compare($this->result_row[$params['field']], $params['operator'],
$params['value']))
{
if (is_array($params['method']) && is_callable($params['method']))
{
call_user_func_array($params['method'], $params['params']);
}
elseif (is_callable(array($this, $params['method'])))
{
$this->condition_backup($params['method']);
call_user_func_array(array($this, $params['method']), $params['params']);
}
elseif (is_callable($params['method']))
{
call_user_func_array($params['method'], $params['params']);
}
}
}
}
return $this->_render_details('create');
}
/** creates fieldlist for editing or viewing record */
protected function _entry($mode = 'edit', $postdata = array())
{
$this->_set_field_names();
$this->where_pri($this->primary_key, $this->primary_val);
$select = $this->_build_select_details($mode);
$where = $this->_build_where();
$table_join = $this->_build_table_join();
$db = Xcrud_db::get_instance($this->connection);
$db->query("SELECT {$select}\r\n FROM `{$this->table}`\r\n {$table_join}\r\n {$where}\r\n LIMIT 1");
$this->result_row = array_merge((array )$db->row(), $postdata);
// moved here to support conditions for buttons
if (((!$this->is_edit($this->result_row) || $this->table_ro) && $mode == 'edit') or (!$this->is_view($this->result_row) &&
$mode == 'view'))
return self::error('Forbidden');
$callback_method = 'before_' . $mode;
if ($this->{$callback_method})
{
$path = $this->check_file($this->{$callback_method}['path'], $callback_method);
include_once ($path);
if (is_callable($this->{$callback_method}['callable']))
{
call_user_func_array($this->{$callback_method}['callable'], array($this->result_row, $this));
}
}
/** conditions process */
if ($this->condition)
{
foreach ($this->condition as $params)
{
if (!isset($params['mode'][$mode]))
continue;
$params['value'] = $this->replace_text_variables($params['value'], $this->result_row);
if (isset($this->result_row[$params['field']]) && $this->_compare($this->result_row[$params['field']], $params['operator'],
$params['value']))
{
if (is_array($params['method']) && is_callable($params['method']))
{
call_user_func_array($params['method'], $params['params']);
}
elseif (is_callable(array($this, $params['method'])))
{
$this->condition_backup($params['method']);
call_user_func_array(array($this, $params['method']), $params['params']);
}
elseif (is_callable($params['method']))
{
call_user_func_array($params['method'], $params['params']);
}
}
}
}
/** hidden fields pass_var_process **/
if ($mode == 'edit' && isset($this->pass_var['edit']))
{
$data = array();
foreach ($this->result_row as $key => $val)
{
if (!isset($this->fields[$key]))
{
foreach ($this->pass_var['edit'] as $pkey => $param)
{
$data[$key] = $val;
}
}
}
if ($data)
$this->pass_var['edit'][$pkey]['tmp_value'] = $this->replace_text_variables($param['value'], $data);
}
return $this->_render_details($mode);
}
/** main insert constructor */
protected function _insert($postdata, $no_processing = false, $no_processing_fields = array())
{
if (!$postdata)
{
self::error('$postdata array is empty');
}
$set = array();
$db = Xcrud_db::get_instance($this->connection);
$fields = array_merge($this->fields, $this->hidden_fields);
$fk_queries = array();
foreach ($postdata as $key => $val)
{
if (isset($fields[$key]) && !isset($this->locked_fields[$key]))
{
if (isset($this->field_type[$key]))
{
switch ($this->field_type[$key])
{
case 'password':
if (trim($val) == '')
{
continue 2;
}
elseif ($this->defaults[$key])
{
$val = hash($this->defaults[$key], $val);
}
break;
/*case 'datetime':
if ($val !== '')
{
if (preg_match('/^\-{0,1}[0-9]+$/u', $val))
{
$val = gmdate('Y-m-d H:i:s', $val);
}
}
else
{
if ($this->field_null[$key])
{
$val = null;
}
else
{
$val = '0000-00-00 00:00:00';
}
}
break;
case 'date':
if ($val !== '')
{
if (preg_match('/^\-{0,1}[0-9]+$/u', $val))
{
$val = gmdate('Y-m-d', $val);
}
}
else
{
if ($this->field_null[$key])
{
$val = null;
}
else
{
$val = '0000-00-00';
}
}
break;
case 'time':
if ($val !== '')
{
if (preg_match('/^\-{0,1}[0-9]+$/u', $val))
{
$val = gmdate('H:i:s', $val);
}
}
else
{
if ($this->field_null[$key])
{
$val = null;
}
else
{
$val = '00:00:00';
}
}
break;*/
case 'fk_relation': //
continue 2;
break;
}
}
if (is_array($val))
{
$set[$fields[$key]['table']]['`' . $fields[$key]['field'] . '`'] = $db->escape(implode(',', $val), false, $this->
field_type[$key], $this->field_null[$key], isset($this->bit_field[$key]));
}
elseif (isset($this->point_field[$key]))
{
$set[$fields[$key]['table']]['`' . $fields[$key]['field'] . '`'] = 'Point(' . $db->escape($val, true, 'point', $this->
field_null[$key], isset($this->bit_field[$key])) . ')';
}
else
$set[$fields[$key]['table']]['`' . $fields[$key]['field'] . '`'] = ((isset($this->no_quotes[$key]) && isset($this->
pass_var['create'][$key])) ? $db->escape($val, true) : $db->escape($val, false, $this->field_type[$key], $this->
field_null[$key], isset($this->bit_field[$key])));
}
elseif ($no_processing)
{
$set[$no_processing_fields[$key]['table']]['`' . $no_processing_fields[$key]['field'] . '`'] =
/*$db->escape($val, false,
$this->field_type[$key], $this->field_null[$key], isset($this->bit_field[$key]))*/((isset($this->no_quotes[$key]) &&
isset($this->pass_var['create'][$key])) ? $db->escape($val, true) : $db->escape($val, false, $this->field_type[$key], $this->
field_null[$key], isset($this->bit_field[$key])));
}
}
//$keys = array_keys($set[$this->table]);
if (!$set)
{
self::error('Nothing to insert');
}
if (!$this->primary_ai && !isset($postdata[$this->table . '.' . $this->primary_key]))
{
self::error('Can\'t insert a row. No primary value.');
}
if (!$this->demo_mode)
$db->query('INSERT INTO `' . $this->table . '` (' . implode(',', array_keys($set[$this->table])) . ') VALUES (' .
implode(',', $set[$this->table]) . ')');
if ($this->primary_ai)
{
$ins_id = $db->insert_id();
$set[$this->table]['`' . $this->primary_key . '`'] = $ins_id;
$postdata[$this->table . '.' . $this->primary_key] = $ins_id;
}
else
{
$ins_id = $postdata[$this->table . '.' . $this->primary_key];
}
if ($this->join)
{
foreach ($this->join as $alias => $param)
{
$set[$alias]['`' . $param['join_field'] . '`'] = $set[$param['table']]['`' . $param['field'] . '`'];
if (!$this->demo_mode)
$db->query("INSERT INTO `{$param['join_table']}` (" . implode(',', array_keys($set[$alias])) . ") VALUES (" . implode(',',
$set[$alias]) . ")");
}
}
if ($this->fk_relation)
{
foreach ($this->fk_relation as $fk)
{
$field = $fk['table'] . '.' . $fk['field'];
if (array_key_exists($fk['alias'], $postdata) && array_key_exists($field, $postdata))
{
$in_val = $db->escape($postdata[$field], false, $this->field_type[$field], $this->field_null[$field], isset($this->
bit_field[$field]));
$db->query('DELETE FROM `' . $fk['fk_table'] . '` WHERE `' . $fk['in_fk_field'] . '` = ' . $in_val);
$fkids = $this->parse_comma_separated($postdata[$fk['alias']]);
if ($fkids)
{
$ins_vals = array();
$ins_keys = array();
$ins_add = array();
if ($fk['add_data'])
{
foreach ($fk['add_data'] as $add_key => $add_val)
{
$ins_keys[] = '`' . $add_key . '`';
$ins_add[] = $db->escape($add_val);
}
}
$ins_add[] = $db->escape($in_val);
$ins_keys[] = '`' . $fk['in_fk_field'] . '`';
$ins_keys[] = '`' . $fk['out_fk_field'] . '`';
foreach ($fkids as $fkid)
{
$ins_vals[] = '(' . implode(',', $ins_add) . ',' . $db->escape($fkid) . ')';
}
$db->query('INSERT INTO `' . $fk['fk_table'] . '` (' . implode(',', $ins_keys) . ') VALUES ' . implode(',', $ins_vals));
}
}
}
}
unset($set, $postdata);
return $ins_id;
}
protected function make_fk_remove($rel, $primary)
{
$db = Xcrud_db::get_instance($this->connection);
}
protected function make_fk_insert($rel, $val, $primary)
{
$db = Xcrud_db::get_instance($this->connection);
}
/** main update constructor */
protected function _update($postdata, $primary)
{
if (!$postdata)
{
self::error('$postdata array is empty');
}
$res = false;
$set = array();
$db = Xcrud_db::get_instance($this->connection);
$fields = array_merge($this->fields, $this->hidden_fields);
foreach ($postdata as $key => $val)
{
if (isset($fields[$key]) && !isset($this->locked_fields[$key]))
{
if (isset($this->field_type[$key]))
{
switch ($this->field_type[$key])
{
case 'password':
if (trim($val) == '')
{
continue 2;
}
elseif ($this->defaults[$key])
{
$val = hash($this->defaults[$key], $val);
}
break;
/*case 'datetime':
if ($val !== '')
{
if (preg_match('/^\-{0,1}[0-9]+$/u', $val))
{
$val = gmdate('Y-m-d H:i:s', $val);
}
}
else
{
if ($this->field_null[$key])
{
$val = null;
}
else
{
$val = '0000-00-00 00:00:00';
}
}
break;
case 'date':
if ($val !== '')
{
if (preg_match('/^\-{0,1}[0-9]+$/u', $val))
{
$val = gmdate('Y-m-d', $val);
}
}
else
{
if ($this->field_null[$key])
{
$val = null;
}
else
{
$val = '0000-00-00';
}
}
break;
case 'time':
if ($val !== '')
{
if (preg_match('/^\-{0,1}[0-9]+$/u', $val))
{
$val = gmdate('H:i:s', $val);
}
}
else
{
if ($this->field_null[$key])
{
$val = null;
}
else
{
$val = '00:00:00';
}
}
break;*/
case 'fk_relation': //
continue 2;
break;
}
}
if (is_array($val))
{
$set[] = '`' . $fields[$key]['table'] . '`.`' . $fields[$key]['field'] . '` = ' . $db->escape(implode(',', $val), false,
$this->field_type[$key], $this->field_null[$key], isset($this->bit_field[$key]));
}
elseif (isset($this->point_field[$key]) && trim($val))
{
$set[] = '`' . $fields[$key]['table'] . '`.`' . $fields[$key]['field'] . '` = Point(' . $db->escape($val, true, 'point',
$this->field_null[$key], isset($this->bit_field[$key])) . ')';
}
else
$set[] = '`' . $fields[$key]['table'] . '`.`' . $fields[$key]['field'] . '` = ' . ((isset($this->no_quotes[$key]) &&
isset($this->pass_var['edit'][$key])) ? $db->escape($val, true) : $db->escape(trim($val), false, $this->field_type[$key],
$this->field_null[$key], isset($this->bit_field[$key])));
}
}
if (!$set)
{
self::error('Nothing to update');
}
if (!$this->join)
{
if (!$this->demo_mode)
$res = $db->query("UPDATE `{$this->table}` SET " . implode(",\r\n", $set) . " WHERE `{$this->primary_key}` = " . $db->
escape($primary) . " LIMIT 1");
}
else
{
//$tables = array('`' . $this->table . '`');
$joins = array();
foreach ($this->join as $alias => $param)
{
//$tables[] = '`' . $alias . '`';
$joins[] = "INNER JOIN `{$param['join_table']}` AS `{$alias}`
ON `{$param['table']}`.`{$param['field']}` = `{$alias}`.`{$param['join_field']}`";
}
if (!$this->demo_mode)
$res = $db->query("UPDATE `{$this->table}` AS `{$this->table}` " . implode(' ', $joins) . " SET " . implode(",\r\n", $set) .
" WHERE `{$this->table}`.`{$this->primary_key}` = " . $db->escape($primary));
}
if (isset($postdata[$this->table . '.' . $this->primary_key]) && $res)
$primary = $postdata[$this->table . '.' . $this->primary_key];
else
{
$postdata[$this->table . '.' . $this->primary_key] = $primary;
}
if ($this->fk_relation)
{
foreach ($this->fk_relation as $fk)
{
$field = $fk['table'] . '.' . $fk['field'];
if (array_key_exists($fk['alias'], $postdata) && array_key_exists($field, $postdata))
{
$in_val = $db->escape($postdata[$field], false, $this->field_type[$field], $this->field_null[$field], isset($this->
bit_field[$field]));
$db->query('DELETE FROM `' . $fk['fk_table'] . '` WHERE `' . $fk['in_fk_field'] . '` = ' . $in_val . ' AND ' . $this->
_build_rel_ins_where($fk['alias']));
$fkids = $this->parse_comma_separated($postdata[$fk['alias']]);
if ($fkids)
{
$ins_vals = array();
$ins_keys = array();
$ins_add = array();
if ($fk['add_data'])
{
foreach ($fk['add_data'] as $add_key => $add_val)
{
$ins_keys[] = '`' . $add_key . '`';
$ins_add[] = $db->escape($add_val);
}
}
$ins_add[] = $db->escape($in_val);
$ins_keys[] = '`' . $fk['in_fk_field'] . '`';
$ins_keys[] = '`' . $fk['out_fk_field'] . '`';
foreach ($fkids as $fkid)
{
$ins_vals[] = '(' . implode(',', $ins_add) . ',' . $db->escape($fkid) . ')';
}
$db->query('INSERT INTO `' . $fk['fk_table'] . '` (' . implode(',', $ins_keys) . ') VALUES ' . implode(',', $ins_vals));
}
}
}
}
unset($set, $postdata);
return $primary;
}
/** main delete */
protected function _remove()
{
$del = false;
if ($this->table_ro)
return self::error('Forbidden');
if ($this->before_remove)
{
$path = $this->check_file($this->before_remove['path'], 'before_remove');
include_once ($path);
if (is_callable($this->before_remove['callable']))
{
call_user_func_array($this->before_remove['callable'], array($this->primary_val, $this));
if ($this->exception)
{
$this->task = 'list';
$this->primary_val = null;
return false;
}
}
}
if ($this->replace_remove)
{
$path = $this->check_file($this->replace_remove['path'], 'replace_remove');
include_once ($path);
if (is_callable($this->replace_remove['callable']))
{
$this->primary_val = call_user_func_array($this->replace_remove['callable'], array($this->primary_val, $this));
}
}
else
{
// remove case
$db = Xcrud_db::get_instance($this->connection);
$del_row = array();
$del = false;
$fields = array();
$this->find_details_text_variables();
if ($this->direct_select_tags) // tags for unset condition
{
foreach ($this->direct_select_tags as $key => $dsf)
{
$fields[$key] = "`{$dsf['table']}`.`{$dsf['field']}` AS `{$key}`";
}
}
if (in_array('image', $this->field_type) or in_array('file', $this->field_type) or in_array('fk_relation', $this->
field_type)) // images && fk
{
foreach ($this->field_type as $key => $type)
{
switch ($type)
{
case 'image':
case 'file':
$tmp = explode('.', $key);
$fields[$key] = '`' . $tmp[0] . '`.`' . $tmp[1] . '` AS `' . $key . '`';
break;
case 'fk_relation':
$fields[$this->fk_relation[$key]['table'] . '.' . $this->fk_relation[$key]['field']] = '`' . $this->fk_relation[$key]['table'] .
'`.`' . $this->fk_relation[$key]['field'] . '` AS `' . $this->fk_relation[$key]['table'] . '.' . $this->fk_relation[$key]['field'] .
'`';
break;
}
if ($type == 'image' or $type == 'file')
{
$tmp = explode('.', $key);
$fields[$key] = "`{$tmp[0]}`.`{$tmp[1]}` AS `{$key}`";
}
}
}
if (!$this->join)
{
if ($fields)
{
$db->query('SELECT ' . implode(',', $fields) . " FROM `{$this->table}` WHERE `{$this->primary_key}` = " . $db->escape($this->
primary_val) . ' LIMIT 1');
$del_row = $db->row();
}
if (!$this->is_remove($del_row))
return self::error('Forbidden');
if (!$this->demo_mode)
$del = $db->query("DELETE FROM `{$this->table}` WHERE `{$this->primary_key}` = " . $db->escape($this->primary_val) .
" LIMIT 1");
}
else
{
$tables = array('`' . $this->table . '`');
$joins = array();
foreach ($this->join as $alias => $param)
{
$tables[] = '`' . $alias . '`';
$joins[] = "INNER JOIN `{$param['join_table']}` AS `{$alias}`
ON `{$param['table']}`.`{$param['field']}` = `{$alias}`.`{$param['join_field']}`";
}
if ($fields)
{
$db->query('SELECT ' . implode(',', $fields) . " FROM `{$this->table}` AS `{$this->table}` " . implode(' ', $joins) .
" WHERE `{$this->table}`.`{$this->primary_key}` = " . $db->escape($this->primary_val));
$del_row = $db->row();
}
if (!$this->is_remove($del_row))
return self::error('Forbidden');
if (!$this->demo_mode)
$del = $db->query("DELETE " . implode(',', $tables) . " FROM `{$this->table}` AS `{$this->table}` " . implode(' ', $joins) .
" WHERE `{$this->table}`.`{$this->primary_key}` = " . $db->escape($this->primary_val));
}
if ($del_row && !$this->demo_mode)
{
foreach ($del_row as $key => $val)
{
if ($val && isset($this->upload_config[$key]) && !isset($this->upload_config[$key]['blob']))
{
$this->remove_file($val, $key);
}
}
}
if ($this->fk_relation) // removing FK relations
{
foreach ($this->fk_relation as $fk)
{
$field = $fk['table'] . '.' . $fk['field'];
if (array_key_exists($field, $del_row))
{
$in_val = $db->escape($del_row[$field], false, $this->field_type[$field], $this->field_null[$field], isset($this->
bit_field[$field]));
$db->query('DELETE FROM `' . $fk['fk_table'] . '` WHERE `' . $fk['in_fk_field'] . '` = ' . $in_val);
}
}
}
// end of remove case
}
if ($this->after_remove)
{
$path = $this->check_file($this->after_remove['path'], 'after_remove');
include_once ($path);
if (is_callable($this->after_remove['callable']))
{
call_user_func_array($this->after_remove['callable'], array($this->primary_val, $this));
}
}
$this->task = 'list';
$this->primary_val = null;
return $del;
}
protected function check_postdata($postdata)
{
foreach ($postdata as $key => $val)
{
if (isset($this->field_type[$key]))
{
switch ($this->field_type[$key])
{
case 'password':
if (trim($val) == '')
{
unset($postdata[$key]);
}
break;
case 'datetime':
if ($val !== '')
{
if (preg_match('/^\-{0,1}[0-9]+$/u', $val))
{
$postdata[$key] = gmdate('Y-m-d H:i:s', $val);
}
}
else
{
if ($this->field_null[$key])
{
$postdata[$key] = null;
}
else
{
$postdata[$key] = '0000-00-00 00:00:00';
}
}
break;
case 'date':
if ($val !== '')
{
if (preg_match('/^\-{0,1}[0-9]+$/u', $val))
{
$postdata[$key] = gmdate('Y-m-d', $val);
}
}
else
{
if ($this->field_null[$key])
{
$postdata[$key] = null;
}
else
{
$postdata[$key] = '0000-00-00';
}
}
break;
case 'time':
if ($val !== '')
{
if (preg_match('/^\-{0,1}[0-9]+$/u', $val))
{
$postdata[$key] = gmdate('H:i:s', $val);
}
}
else
{
if ($this->field_null[$key])
{
$postdata[$key] = null;
}
else
{
$postdata[$key] = '00:00:00';
}
}
break;
}
}
}
return $postdata;
}
/** save events switcher */
protected function _save()
{
$postdata = $this->_post('postdata');
if (!$postdata)
{
self::error('No data to save!');
}
$postdata = $this->check_postdata($postdata);
if ($this->upload_config)
{
foreach ($this->upload_config as $key => $opts)
{
if (isset($opts['blob']) && $opts['blob'] && isset($postdata[$key]) && $postdata[$key] != '')
{
if ($postdata[$key] == 'blob-storage')
{
unset($postdata[$key]);
continue;
}
else
{
$folder = $this->upload_folder[$key];
$path = $folder . '/' . $postdata[$key];
if (is_file($path))
{
$postdata[$key] = file_get_contents($path);
unlink($path);
}
}
}
}
}
if ($this->inner_value !== false) // is nested
{
$field = reset($this->inner_where);
if (!isset($postdata[$field])) // nested table connection field MUST be defined
{
$fdata = $this->_parse_field_names($field, 'build_select_details');
$this->hidden_fields = array_merge($this->hidden_fields, $fdata);
//$this->hidden_fields[$field] = $fdata[0];
$postdata[$field] = $this->inner_value;
}
}
$this->validate_postdata($postdata);
if ($this->exception)
{
return $this->call_exception($postdata);
}
if (!$this->primary_val)
{
if (!$this->is_create || $this->table_ro)
return self::error('Forbidden');
if (isset($this->pass_var['create']))
{
foreach ($this->pass_var['create'] as $field => $param)
{
$postdata[$field] = $this->replace_text_variables($param['value'], $postdata);
$this->hidden_fields[$field] = array('table' => $param['table'], 'field' => $param['field']);
}
}
if ($this->alert_create)
{
foreach ($this->alert_create as $alert)
{
if ($alert['field'] && isset($postdata[$alert['field']]) && $postdata[$alert['field']] != $alert['value'])
continue;
if (!isset($postdata[$alert['column']]) or !preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/',
$postdata[$alert['column']]))
continue;
$alert['message'] = $this->replace_text_variables($alert['message'], $postdata);
if (Xcrud_config::$email_enable_html)
$message = $alert['message'] . '
' . "\r\n" . ($alert['link'] ? '' . $alert['link'] . '' : '');
else
$message = $alert['message'] . "\r\n\r\n" . ($alert['link'] ? $alert['link'] : '');
$this->send_email($postdata[$alert['column']], $alert['subject'], $message, $alert['cc'], Xcrud_config::$email_enable_html);
}
}
if ($this->mass_alert_create)
{
foreach ($this->mass_alert_create as $alert)
{
if ($alert['field'] && isset($postdata[$alert['field']]) && $postdata[$alert['field']] != $alert['value'])
continue;
$alert['message'] = $this->replace_text_variables($alert['message'], $postdata);
$alert['where'] = $this->replace_text_variables($alert['where'], $postdata);
if (Xcrud_config::$email_enable_html)
$message = $alert['message'] . '
' . "\r\n" . ($alert['link'] ? '' . $alert['link'] . '' : '');
else
$message = $alert['message'] . "\r\n\r\n" . ($alert['link'] ? $alert['link'] : '');
$db = Xcrud_db::get_instance($this->connection);
$db->query("SELECT `{$alert['email_column']}` FROM `{$alert['email_table']}`" . ($alert['where'] ? ' WHERE ' . $alert['where'] :
''));
foreach ($db->result() as $row)
{
$this->send_email($row[$alert['email_column']], $alert['subject'], $message, array(), Xcrud_config::$email_enable_html);
}
}
}
$pd = new Xcrud_postdata($postdata, $this);
if ($this->before_insert)
{
$path = $this->check_file($this->before_insert['path'], 'before_insert');
include_once ($path);
if (is_callable($this->before_insert['callable']))
{
call_user_func_array($this->before_insert['callable'], array($pd, $this));
$postdata = $pd->to_array();
if ($this->exception)
{
return $this->call_exception($postdata);
}
}
}
if ($this->replace_insert)
{
$path = $this->check_file($this->replace_insert['path'], 'replace_insert');
include_once ($path);
if (is_callable($this->replace_insert['callable']))
{
$this->primary_val = call_user_func_array($this->replace_insert['callable'], array($pd, $this));
$postdata = $pd->to_array();
if ($this->exception)
{
return $this->call_exception($postdata);
}
}
}
else
{
$this->primary_val = $this->_insert($postdata);
}
if ($this->after_insert)
{
$path = $this->check_file($this->after_insert['path'], 'after_insert');
include_once ($path);
if (is_callable($this->after_insert['callable']))
{
call_user_func_array($this->after_insert['callable'], array(
$pd,
$this->primary_val,
$this));
$postdata = $pd->to_array();
if ($this->exception)
{
return $this->call_exception($postdata);
}
}
}
if ($this->send_external_create)
{
if (!$this->send_external_create['where_field'] or $postdata[$this->send_external_create['where_field']] == $this->
send_external_create['where_val'])
{
foreach ($this->send_external_create['data'] as $key => $value)
{
$this->send_external_create['data'][$key] = $this->replace_text_variables($value, $postdata + array($this->table . '.' .
$this->primary_key => $this->primary_val));
}
switch ($this->send_external_create['method'])
{
case 'include':
$path = $this->check_file($this->send_external_create['path'], 'send_external_create');
ob_start();
extract($this->send_external_create['data']);
include ($path);
ob_end_clean();
break;
case 'get':
case 'post':
$this->send_http_request($this->send_external_create['path'], $this->send_external_create['data'], $this->
send_external_create['method'], false);
break;
}
}
}
}
else
{
if ($this->table_ro)
return self::error('Forbidden');
$fields = array();
$row = array();
$this->find_details_text_variables();
if ($this->direct_select_tags)
{
foreach ($this->direct_select_tags as $key => $dsf)
{
$fields[$key] = "`{$dsf['table']}`.`{$dsf['field']}` AS `{$key}`";
}
}
if ($fields)
{
$db = Xcrud_db::get_instance($this->connection);
if (!$this->join)
{
$db->query('SELECT ' . implode(',', $fields) . " FROM `{$this->table}` WHERE `{$this->primary_key}` = " . $db->escape($this->
primary_val) . " LIMIT 1");
$row = $db->row();
}
else
{
$tables = array('`' . $this->table . '`');
$joins = array();
foreach ($this->join as $alias => $param)
{
$tables[] = '`' . $alias . '`';
$joins[] = "INNER JOIN `{$param['join_table']}` AS `{$alias}`
ON `{$param['table']}`.`{$param['field']}` = `{$alias}`.`{$param['join_field']}`";
}
$db->query('SELECT ' . implode(',', $fields) . " FROM `{$this->table}` AS `{$this->table}` " . implode(' ', $joins) .
" WHERE `{$this->table}`.`{$this->primary_key}` = " . $db->escape($this->primary_val));
$row = $db->row();
}
}
if (!$this->is_edit($row))
return self::error('Forbidden');
if (isset($this->pass_var['edit']))
{
foreach ($this->pass_var['edit'] as $field => $param)
{
if (isset($param['tmp_value']))
{
$param['value'] = $param['tmp_value'];
unset($this->pass_var['edit'][$field]['tmp_value']);
}
$postdata[$field] = $this->replace_text_variables($param['value'], $postdata);
$postdata[$field] = $this->replace_text_variables($param['value'], $row);
$this->hidden_fields[$field] = array('table' => $param['table'], 'field' => $param['field']);
}
}
if ($this->alert_edit)
{
foreach ($this->alert_edit as $alert)
{
if ($alert['field'] && isset($postdata[$alert['field']]) && $postdata[$alert['field']] != $alert['value'])
continue;
if (!isset($postdata[$alert['column']]) or !preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/',
$postdata[$alert['column']]))
continue;
$alert['message'] = $this->replace_text_variables($alert['message'], $postdata);
if (Xcrud_config::$email_enable_html)
$message = $alert['message'] . '
' . "\r\n" . ($alert['link'] ? '' . $alert['link'] . '' : '');
else
$message = $alert['message'] . "\r\n\r\n" . ($alert['link'] ? $alert['link'] : '');
$this->send_email($postdata[$alert['column']], $alert['subject'], $message, $alert['cc'], Xcrud_config::$email_enable_html);
}
}
if ($this->mass_alert_edit)
{
foreach ($this->mass_alert_edit as $alert)
{
if ($alert['field'] && isset($postdata[$alert['field']]) && $postdata[$alert['field']] != $alert['value'])
continue;
$alert['message'] = $this->replace_text_variables($alert['message'], $postdata);
$alert['where'] = $this->replace_text_variables($alert['where'], $postdata);
if (Xcrud_config::$email_enable_html)
$message = $alert['message'] . '
' . "\r\n" . ($alert['link'] ? '' . $alert['link'] . '' : '');
else
$message = $alert['message'] . "\r\n\r\n" . ($alert['link'] ? $alert['link'] : '');
$db = Xcrud_db::get_instance($this->connection);
$db->query("SELECT `{$alert['email_column']}` FROM `{$alert['email_table']}`" . ($alert['where'] ? ' WHERE ' . $alert['where'] :
''));
foreach ($db->result() as $row)
{
$this->send_email($row[$alert['email_column']], $alert['subject'], $message, array(), Xcrud_config::$email_enable_html);
}
}
}
$pd = new Xcrud_postdata($postdata, $this);
if ($this->before_update)
{
$path = $this->check_file($this->before_update['path'], 'before_update');
include_once ($path);
if (is_callable($this->before_update['callable']))
{
call_user_func_array($this->before_update['callable'], array(
$pd,
$this->primary_val,
$this));
$postdata = $pd->to_array();
if ($this->exception)
{
return $this->call_exception($postdata);
}
}
}
if ($this->replace_update)
{
$path = $this->check_file($this->replace_update['path'], 'replace_update');
include_once ($path);
if (is_callable($this->replace_update['callable']))
{
$this->primary_val = call_user_func_array($this->replace_update['callable'], array(
$pd,
$this->primary_val,
$this));
$postdata = $pd->to_array();
if ($this->exception)
{
return $this->call_exception($postdata);
}
}
}
else
$this->primary_val = $this->_update($postdata, $this->primary_val);
if ($this->after_update)
{
$path = $this->check_file($this->after_update['path'], 'after_update');
include_once ($path);
if (is_callable($this->after_update['callable']))
{
call_user_func_array($this->after_update['callable'], array(
$pd,
$this->primary_val,
$this));
$postdata = $pd->to_array();
if ($this->exception)
{
return $this->call_exception($postdata);
}
}
}
if ($this->send_external_edit)
{
if (!$this->send_external_edit['where_field'] or $postdata[$this->send_external_edit['where_field']] == $this->
send_external_edit['where_val'])
{
foreach ($this->send_external_edit['data'] as $key => $value)
{
$this->send_external_edit['data'][$key] = $this->replace_text_variables($value, $postdata);
}
switch ($this->send_external_edit['method'])
{
case 'include':
$path = $this->check_file($this->send_external_edit['path'], 'send_external_edit');
ob_start();
extract($this->send_external_edit['data']);
include ($path);
ob_end_clean();
break;
case 'get':
case 'post':
$this->send_http_request($this->send_external_edit['path'], $this->send_external_edit['data'], $this->
send_external_edit['method'], false);
break;
}
}
}
}
unset($postdata);
$this->task = $this->after;
$this->after = null;
return $this->_run_task();
}
protected function validate_postdata($postdata)
{
foreach ($postdata as $key => $val)
{
if (isset($this->validation_required[$key]) && mb_strlen($val) < $this->validation_required[$key])
{
$this->set_exception($key, 'validation_error', 'error');
}
elseif (isset($this->validation_pattern[$key]) && mb_strlen($val) > 0)
{
switch ($this->validation_pattern[$key])
{
case 'email':
$reg = '/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/u';
break;
case 'alpha':
$reg = '/^([a-z])+$/ui';
break;
case 'alpha_numeric':
$reg = '/^([a-z0-9])+$/ui';
break;
case 'alpha_dash':
$reg = '/^([-a-z0-9_-])+$/ui';
break;
case 'numeric':
$reg = '/^[\-+]?[0-9]*\.?[0-9]+$/u';
break;
case 'integer':
$reg = '/^[\-+]?[0-9]+$/u';
break;
case 'decimal':
$reg = '/^[\-+]?[0-9]+\.[0-9]+$/u';
break;
case 'point':
$reg = '/^[\-+]?[0-9]+\.{0,1}[0-9]*\,[\-+]?[0-9]+\.{0,1}[0-9]*$/u';
break;
case 'natural':
$reg = '/^[0-9]+$/u';
break;
default:
$reg = '/' . $this->validation_pattern[$key] . '/u';
break;
}
if (!preg_match($reg, $val))
{
$this->set_exception($key, 'validation_error', 'error');
}
}
}
}
protected function call_exception($postdata = array())
{
switch ($this->task)
{
case 'upload':
switch ($this->_post('type'))
{
case 'image':
return $this->create_image($this->_post('field'), '') . $this->render_message();
break;
case 'file':
return $this->create_file($this->_post('field'), '') . $this->render_message();
break;
default:
return self::error('Upload Error');
break;
}
break;
}
$this->task = $this->before;
switch ($this->before)
{
case 'create':
return $this->_create($postdata);
break;
case 'edit':
case 'view':
return $this->_entry($this->before, $postdata);
break;
case 'upload':
break;
default:
return $this->_list();
break;
}
}
public function set_exception($fields = '', $message = '', $type = 'note')
{
if ($message)
{
$this->message = array('type' => $type, 'text' => $this->lang($message));
}
if ($fields)
{
$fdata = $this->_parse_field_names($fields, 'set_exception');
foreach ($fdata as $key => $fitem)
{
$this->exception_fields[$key] = $fitem;
}
}
$this->exception = true;
return $this;
}
public function set_message($message = '', $type = 'note')
{
if ($message)
{
$this->message = array('type' => $type, 'text' => $this->lang($message));
}
return $this;
}
/** grid processing */
protected function _list()
{
if (!$this->is_list)
{
return self::error('Forbidden');
}
if (!$this->search_columns)
{
$this->search_columns = $this->columns;
}
$select = $this->_build_select_list();
$table_join = $this->_build_table_join();
$where = $this->_build_where();
$order_by = $this->_build_order_by();
$sum_tmp = array();
if ($this->sum)
{
foreach ($this->sum as $field => $param)
{
if (isset($this->subselect[$field]))
$sum_tmp[$field] = 'SUM(' . $this->subselect_where($field) . ') AS `' . $field . '`';
else
$sum_tmp[$field] = 'SUM(`' . $param['table'] . '`.`' . $param['column'] . '`) AS `' . $field . '`';
}
}
$sum = $sum_tmp ? ', ' . implode(', ', $sum_tmp) : '';
$db = Xcrud_db::get_instance($this->connection);
//$db->query("SELECT COUNT(`{$this->table}`.`{$this->primary_key}`) AS `count` {$sum} \r\n FROM `{$this->table}`\r\n {$table_join}\r\n {$where}");
$db->query("SELECT COUNT(*) AS `count` {$sum} \r\n FROM `{$this->table}`\r\n {$table_join}\r\n {$where}");
$this->sum_row = $db->row();
$this->result_total = $this->sum_row['count'];
$limit = $this->_build_limit($this->result_total);
$db->query("SELECT {$select} \r\n FROM `{$this->table}`\r\n {$table_join}\r\n {$where}\r\n {$order_by}\r\n {$limit}");
$this->result_list = $db->result();
if ($this->before_list)
{
$path = $this->check_file($this->before_list['path'], 'before_list');
include_once ($path);
if (is_callable($this->before_list['callable']))
{
call_user_func_array($this->before_list['callable'], array($this->result_row, $this));
}
}
$this->_set_column_names();
return $this->_render_list();
}
/** defines primary condition for internal usage */
protected function where_pri($fields = false, $where_val = false, $glue = 'AND', $index = false)
{
if ($fields !== false && $where_val !== false)
{
$fdata = $this->_parse_field_names($fields, 'where_pri');
foreach ($fdata as $fitem)
{
if ($index)
{
$this->where_pri[$index] = array(
'table' => $fitem['table'],
'field' => $fitem['field'],
'value' => isset($fitem['value']) ? $fitem['value'] : $where_val,
'glue' => $glue);
}
else
{
$this->where_pri[] = array(
'table' => $fitem['table'],
'field' => $fitem['field'],
'value' => isset($fitem['value']) ? $fitem['value'] : $where_val,
'glue' => $glue);
}
}
unset($fields, $fdata);
}
elseif ($fields)
{
if ($index)
{
$this->where_pri[$index] = array('custom' => $fields, 'glue' => $glue);
}
else
{
$this->where_pri[] = array('custom' => $fields, 'glue' => $glue);
}
unset($where_val);
}
return $this;
}
/** 'select' subquery for grid view */
protected function _build_select_list($csv = false)
{
$this->find_grid_text_variables();
$db = Xcrud_db::get_instance($this->connection);
$columns = array();
//$subselect_before = $this->subselect_before;
foreach ($this->columns as $field_index => $val)
{
if ($val)
{
//$field_index = $key;
if (isset($this->subselect[$field_index]))
{
$columns[] = $this->subselect_query($field_index);
}
elseif (isset($this->point_field[$field_index]))
{
$columns[] = 'CONCAT(X(`' . $val['table'] . '`.`' . $val['field'] . '`),\',\',Y(`' . $val['table'] . '`.`' . $val['field'] .
'`)) AS `' . $val['table'] . '.' . $val['field'] . '`' . "\r\n";
}
elseif (isset($this->relation[$field_index]))
{
if (is_array($this->relation[$field_index]['rel_name']))
{
$tmp_fields = array();
foreach ($this->relation[$field_index]['rel_name'] as $tmp)
{
$tmp_fields[] = "`{$tmp}` \r\n";
}
if ($this->relation[$field_index])
{
$where = "FIND_IN_SET(`{$this->relation[$field_index]['rel_tbl']}`.`{$this->relation[$field_index]['rel_field']}`,`{$this->relation[$field_index]['table']}`.`{$this->relation[$field_index]['field']}`)";
}
else
{
$where = "`{$this->relation[$field_index]['rel_tbl']}`.`{$this->relation[$field_index]['rel_field']}` = `{$this->relation[$field_index]['table']}`.`{$this->relation[$field_index]['field']}`";
}
$columns[] = "(SELECT GROUP_CONCAT(DISTINCT (CONCAT_WS('{$this->relation[$field_index]['rel_separator']}'," . implode(',',
$tmp_fields) . ")) SEPARATOR ', ')
FROM `{$this->relation[$field_index]['rel_tbl']}`
WHERE {$where})
AS `rel.{$val['table']}.{$val['field']}`, \r\n `{$val['table']}`.`{$val['field']}` AS `{$val['table']}.{$val['field']}` \r\n";
}
elseif ($this->relation[$field_index]['multi'])
{
$columns[] = "(SELECT GROUP_CONCAT(DISTINCT `{$this->relation[$field_index]['rel_name']}` SEPARATOR ', ')
FROM `{$this->relation[$field_index]['rel_tbl']}` WHERE
FIND_IN_SET(`{$this->relation[$field_index]['rel_tbl']}`.`{$this->relation[$field_index]['rel_field']}`,`{$this->relation[$field_index]['table']}`.`{$this->relation[$field_index]['field']}`)
ORDER BY `{$this->relation[$field_index]['rel_name']}` ASC)
AS `rel.{$val['table']}.{$val['field']}`, \r\n `{$val['table']}`.`{$val['field']}` AS `{$val['table']}.{$val['field']}` \r\n";
}
else
{
$columns[] = "(SELECT `{$this->relation[$field_index]['rel_alias']}`.`{$this->relation[$field_index]['rel_name']}`
FROM `{$this->relation[$field_index]['rel_tbl']}` AS `{$this->relation[$field_index]['rel_alias']}`
WHERE `{$this->relation[$field_index]['rel_alias']}`.`{$this->relation[$field_index]['rel_field']}` = `{$this->relation[$field_index]['table']}`.`{$this->relation[$field_index]['field']}`
LIMIT 1)
AS `rel.{$val['table']}.{$val['field']}`, \r\n `{$val['table']}`.`{$val['field']}` AS `{$val['table']}.{$val['field']}` \r\n";
}
}
//
elseif (isset($this->fk_relation[$field_index]))
{
$fk = $this->fk_relation[$field_index];
if (is_array($fk['rel_name']))
{
foreach ($fk['rel_name'] as $tmp)
{
$tmp_fields[] = "`{$tmp}`";
$rel_name = 'CONCAT_WS(' . $db->escape($fk['rel_separator']) . ',' . implode(',', $tmp_fields) . ')';
}
}
else
{
$rel_name = '`' . $fk['rel_name'] . '`';
}
$columns[] = '(SELECT GROUP_CONCAT(DISTINCT ' . $rel_name . ' SEPARATOR \', \')
FROM `' . $fk['rel_tbl'] . '`
INNER JOIN `' . $fk['fk_table'] . '` ON `' . $fk['fk_table'] . '`.`' . $fk['out_fk_field'] . '` = `' . $fk['rel_tbl'] .
'`.`' . $fk['rel_field'] . '` WHERE `' . $fk['fk_table'] . '`.`' . $fk['in_fk_field'] . '` = `' . $fk['table'] . '`.`' .
$fk['field'] . '` AND ' . $this->_build_rel_where($field_index) . ')
AS `' . $fk['alias'] . '` ' . "\r\n";
}
elseif (isset($this->bit_field[$field_index]))
{
$columns[] = "CAST(`{$val['table']}`.`{$val['field']}` AS UNSIGNED) AS `{$val['table']}.{$val['field']}` \r\n";
}
else
{
$columns[] = "`{$val['table']}`.`{$val['field']}` AS `{$val['table']}.{$val['field']}` \r\n";
}
}
}
if ($this->hidden_columns)
{
foreach ($this->hidden_columns as $field_index => $val)
{
$columns[] = "`{$val['table']}`.`{$val['field']}` AS `{$field_index}` \r\n";
}
}
if (!$this->primary_key)
{
$columns[] = "(0) AS `primary_key` \r\n";
}
else
{
$columns[] = "`{$this->table}`.`{$this->primary_key}` AS `primary_key` \r\n";
}
return implode(',', $columns);
}
/** creates subselect subquery for grid view */
protected function subselect_query($name)
{
if (isset($this->subselect_query[$name]))
{
$sql = $this->subselect_query[$name];
}
else
{
$sql = preg_replace_callback('/\{(.+)\}/Uu', array($this, 'subselect_callback'), $this->subselect[$name]);
$this->subselect_query[$name] = $sql;
}
return "({$sql}) AS `{$name}`";
}
protected function subselect_where($name)
{
if (isset($this->subselect_query[$name]))
{
return '(' . $this->subselect_query[$name] . ')';
}
else
{
$this->subselect_query($name);
return '(' . $this->subselect_query[$name] . ')';
}
}
protected function subselect_callback($matches)
{
if (strpos($matches[1], '.'))
{
$tmp = explode('.', $matches[1]);
if (isset($this->subselect[$this->prefix . $tmp[0] . '.' . $tmp[1]]))
{
return $this->subselect_where($this->prefix . $tmp[0] . '.' . $tmp[1]);
}
else
return '`' . $this->prefix . $tmp[0] . '`.`' . $tmp[1] . '`';
}
else
{
if (isset($this->subselect[$this->table . '.' . $matches[1]]))
{
return $this->subselect_where($this->table . '.' . $matches[1]);
}
else
return '`' . $this->table . '`.`' . $matches[1] . '`';
}
}
/** 'select' subquery part for edit/details view */
protected function _build_select_details($mode)
{
$this->find_details_text_variables();
$fields = array();
if ($this->inner_table_instance) // nested table
{
foreach ($this->inner_table_instance as $inst_name => $field)
{
if (!isset($this->fields[$field])) // nested table connection field MUST be extracted from DB, even if not defined
{
$fdata = $this->_parse_field_names($field, 'build_select_details');
//$this->hidden_fields[$field] = $fdata[0];
$this->hidden_fields = array_merge($this->hidden_fields, $fdata);
}
}
}
if ($this->fields)
{
foreach ($this->fields as $key => $val)
{
if ($val)
{
if (isset($this->subselect[$key]))
{
$fields[] = $this->subselect_query($key);
}
elseif (isset($this->fk_relation[$key]))
{
$fk = $this->fk_relation[$key];
$fields[] = '(SELECT GROUP_CONCAT(DISTINCT `' . $fk['rel_tbl'] . '`.`' . $fk['rel_field'] . '` SEPARATOR \',\')
FROM `' . $fk['rel_tbl'] . '`
INNER JOIN `' . $fk['fk_table'] . '` ON `' . $fk['fk_table'] . '`.`' . $fk['out_fk_field'] . '` = `' . $fk['rel_tbl'] .
'`.`' . $fk['rel_field'] . '` WHERE `' . $fk['fk_table'] . '`.`' . $fk['in_fk_field'] . '` = `' . $fk['table'] . '`.`' .
$fk['field'] . '` AND ' . $this->_build_rel_where($key) . ')
AS `' . $fk['alias'] . '` ' . "\r\n";
}
elseif (isset($this->point_field[$key]))
{
$fields[] = 'CONCAT(X(`' . $val['table'] . '`.`' . $val['field'] . '`),\',\',Y(`' . $val['table'] . '`.`' . $val['field'] .
'`)) AS `' . $val['table'] . '.' . $val['field'] . '`' . "\r\n";
}
elseif (isset($this->bit_field[$key]))
{
$fields[] = "CAST(`{$val['table']}`.`{$val['field']}` AS UNSIGNED) AS `$key`";
}
else
{
$fields[] = "`{$val['table']}`.`{$val['field']}` AS `$key`";
}
}
}
}
if ($this->hidden_fields)
{
foreach ($this->hidden_fields as $key => $val)
{
if ($val)
$fields[] = "`{$val['table']}`.`{$val['field']}` AS `{$key}`";
}
}
$fields[] = "`{$this->table}`.`{$this->primary_key}` AS `primary_key`";
return implode(',', $fields);
}
protected function _build_table_join()
{
$join = '';
if (count($this->join))
{
$join_arr = array();
foreach ($this->join as $alias => $params)
{
$join_arr[] = "INNER JOIN `{$params['join_table']}` AS `{$alias}`
ON `{$params['table']}`.`{$params['field']}` = `{$alias}`.`{$params['join_field']}`";
}
$join .= implode(' ', $join_arr);
}
return $join;
}
/** builds main where condition for query */
protected function _build_where()
{
$db = Xcrud_db::get_instance($this->connection);
$where_arr = array();
$where_arr_pri = array();
// user defined conditions
if ($this->where)
{
foreach ($this->where as $key => $params)
{
if ($where_arr)
$where_arr[] = $params['glue'];
if (!isset($params['custom']))
{
$fieldkey = $this->_where_fieldkey($params);
if (is_array($params['value']))
{
$in_arr = array();
foreach ($params['value'] as $in_val)
{
$in_arr[] = $db->escape($in_val);
}
if (isset($this->subselect[$fieldkey]))
{
$where_arr[] = $this->subselect_where($fieldkey) . $this->_cond_from_where_in($params['field']) . '(' . implode(',', $in_arr) .
')';
}
else
{
$where_arr[] = $this->_where_field($params) . $this->_cond_from_where_in($params['field']) . '(' . implode(',', $in_arr) .
')';
}
}
else
{
if (isset($this->subselect[$fieldkey]))
{
$where_arr[] = $this->subselect_where($fieldkey) . $this->_cond_from_where($params['field']) . $db->escape($params['value'],
isset($this->no_quotes[$fieldkey]));
}
elseif (isset($this->point_field[$fieldkey]))
{
$where_arr[] = 'CONCAT(X(`' . $this->_where_field($params) . '`),\',\',Y(`' . $this->_where_field($params) . '`))' . $this->
_cond_from_where($params['field']) . $db->escape($params['value'], isset($this->no_quotes[$fieldkey]));
}
else
{
$where_arr[] = $this->_where_field($params) . $this->_cond_from_where($params['field']) . $db->escape($params['value'],
isset($this->no_quotes[$fieldkey]));
}
}
}
else
{
$where_arr[] = '(' . $params['custom'] . ')';
}
}
}
// internal condition
if ($this->where_pri)
{
foreach ($this->where_pri as $params)
{
if ($where_arr_pri)
$where_arr_pri[] = $params['glue'];
if (isset($params['custom']))
{
$where_arr_pri[] = '(' . $params['custom'] . ')';
}
else
{
$where_arr_pri[] = $this->_where_field($params) . $this->_cond_from_where($params['field']) . $db->escape($params['value']);
}
}
}
// search condition
if ($this->search && ($this->task == 'list' or $this->task == 'print' or $this->task == 'csv' or $this->after == 'list'))
{
if ($where_arr)
{
$where_arr[] = 'AND';
}
if ($this->column && isset($this->search_columns[$this->column]))
{
// if relation
if (isset($this->relation[$this->column]))
{
$where_arr[] = $this->_build_relation_subwhere($this->column);
}
// if fk-relation
elseif (isset($this->fk_relation[$this->column]))
{
$where_arr[] = $this->_build_fk_relation_subwhere($this->column);
}
// search in subselect
elseif (isset($this->subselect[$this->column]))
{
$where_arr[] = '(' . $this->subselect_query[$this->column] . ') LIKE ' . $db->escape_like($this->phrase, $this->
search_pattern);
}
elseif (isset($this->point_field[$this->column]))
{
$fdata = $this->_parse_field_names($this->column, 'build_where');
$fitem = reset($fdata);
$where_arr[] = 'CONCAT(X(`' . $fitem['table'] . '`.`' . $fitem['field'] . '`),\',\',Y(`' . $fitem['table'] . '`.`' . $fitem['field'] .
'`))LIKE ' . $db->escape_like($this->phrase, $this->search_pattern);
}
else
{
$fdata = $this->_parse_field_names($this->column, 'build_where');
$fitem = reset($fdata);
// search via fild types
switch ($this->field_type[$this->column])
{
case 'timestamp':
case 'datetime':
case 'date':
case 'time':
switch ($this->field_type[$this->column])
{
case 'date':
$format = 'Y-m-d';
break;
case 'time':
$format = 'H:i:s';
break;
default:
$format = 'Y-m-d H:i:s';
break;
}
if ($this->phrase['from'] && $this->phrase['to'])
{
$where_arr[] = '(`' . $fitem['table'] . '`.`' . $fitem['field'] . '` BETWEEN ' . $db->escape(gmdate($format, (int)$this->
phrase['from'])) . ' AND ' . $db->escape(gmdate($format, (int)$this->phrase['to'])) . ')';
}
elseif ($this->phrase['from'])
{
$where_arr[] = '(`' . $fitem['table'] . '`.`' . $fitem['field'] . '` >= ' . $db->escape(gmdate($format, (int)$this->
phrase['from'])) . ')';
}
elseif ($this->phrase['to'])
{
$where_arr[] = '(`' . $fitem['table'] . '`.`' . $fitem['field'] . '` <= ' . $db->escape(gmdate($format, (int)$this->
phrase['to'])) . ')';
}
break;
case 'select':
case 'radio':
$where_arr[] = '(`' . $fitem['table'] . '`.`' . $fitem['field'] . '` = ' . $db->escape($this->phrase) . ')';
break;
/*case 'multiselect':
case 'checkboxes':
break;*/
case 'bool':
$where_arr[] = '(`' . $fitem['table'] . '`.`' . $fitem['field'] . '` = ' . ((int)$this->phrase) . ')';
break;
default:
$where_arr[] = '(`' . $fitem['table'] . '`.`' . $fitem['field'] . '` LIKE ' . $db->escape_like($this->phrase, $this->
search_pattern) . ')';
break;
}
}
}
else
{
// multicolumn search
//$f_array = array();
$or_array = array();
foreach ($this->search_columns as $key => $fitem)
{
if (isset($this->relation[$key]))
{
$or_array[] = $this->_build_relation_subwhere($key);
}
elseif (isset($this->fk_relation[$key]))
{
$or_array[] = $this->_build_fk_relation_subwhere($key);
}
elseif (isset($this->subselect[$key]))
{
$or_array[] = '(' . $this->subselect_query[$key] . ') LIKE ' . $db->escape_like($this->phrase, $this->search_pattern);
}
else
{
//$f_array[] = '`' . $fitem['table'] . '`.`' . $fitem['field'] . '`';
$or_array[] = '`' . $fitem['table'] . '`.`' . $fitem['field'] . '` LIKE ' . $db->escape_like($this->phrase, $this->
search_pattern);
}
}
$where = '(';
/*if ($f_array)
{
$where .= 'CONCAT_WS(\' \',' . implode(',', $f_array) . ') LIKE ' . $db->escape_like($this->phrase, $this->
search_pattern);
}
if ($f_array && $or_array)
{
$where .= ' OR ';
}*/
if ($or_array)
{
$where .= implode(' OR ', $or_array);
}
$where .= ')';
$where_arr[] = $where;
}
}
// final part
if ($where_arr or $where_arr_pri)
return 'WHERE ' . ($where_arr ? '(' . implode(' ', $where_arr) . ')' : '') . ($where_arr_pri ? ($where_arr ? ' AND ' :
'') . implode(' ', $where_arr_pri) : '');
else
return '';
}
/** relation values will be searched by displayed name (not by id) */
protected function _build_relation_subwhere($key) // multicolumn name
{
$db = Xcrud_db::get_instance($this->connection);
if ($key)
{
$rel = $this->relation[$key];
if (is_array($rel['rel_name']))
{
$tmp_fields = array();
foreach ($rel['rel_name'] as $tmp)
{
$tmp_fields[] = '`' . $tmp . '`' . "\r\n";
}
// multiselect relation
if ($rel['multi'])
{
$where = '`' . $rel['rel_tbl'] . '`.`' . $rel['rel_field'] . '` LIKE `' . $rel['table'] . '`.`' . $rel['field'] . '`';
}
else
{
$where = '`' . $rel['rel_tbl'] . '`.`' . $rel['rel_field'] . '` = `' . $rel['table'] . '`.`' . $rel['field'] . '`';
}
$select = "(SELECT GROUP_CONCAT(DISTINCT (CONCAT_WS('{$rel['rel_separator']}'," . implode(',', $tmp_fields) .
")) SEPARATOR ', ')
FROM `{$rel['rel_tbl']}`
WHERE {$where})\r\n";
}
// multiselect relation
elseif ($rel['multi'])
{
$select = "(SELECT GROUP_CONCAT(DISTINCT `{$rel['rel_name']}` SEPARATOR ', ')
FROM `{$rel['rel_tbl']}` WHERE
FIND_IN_SET(`{$rel['rel_tbl']}`.`{$rel['rel_field']}`,`{$rel['table']}`.`{$rel['field']}`)
ORDER BY `{$rel['rel_name']}` ASC)\r\n";
}
else
{
$select = "(SELECT `{$rel['rel_alias']}`.`{$rel['rel_name']}`
FROM `{$rel['rel_tbl']}` AS `{$rel['rel_alias']}`
WHERE `{$rel['rel_alias']}`.`{$rel['rel_field']}` = `{$rel['table']}`.`{$rel['field']}`
LIMIT 1) \r\n";
}
return "{$select} LIKE " . $db->escape_like($this->phrase, $this->search_pattern);
}
/*
else
{
$or_where = array();
foreach ($this->relation as $column => $param)
{
if (is_array($this->relation[$column]['rel_name']))
{
$tmp_fields = array();
foreach ($this->relation[$column]['rel_name'] as $tmp)
{
$tmp_fields[] = '`' . $tmp . '`' . "\r\n";
}
// multiselect relation
if ($this->relation[$column]['multi'])
{
$where = '`' . $this->relation[$column]['rel_tbl'] . '`.`' . $this->relation[$column]['rel_field'] . '` LIKE `' . $this->
relation[$column]['table'] . '`.`' . $this->relation[$column]['field'] . '`';
}
else
{
$where = '`' . $this->relation[$column]['rel_tbl'] . '`.`' . $this->relation[$column]['rel_field'] . '` = `' . $this->
relation[$column]['table'] . '`.`' . $this->relation[$column]['field'] . '`';
}
$select = "(SELECT GROUP_CONCAT(DISTINCT (CONCAT_WS('{$this->relation[$column]['rel_separator']}'," . implode(',', $tmp_fields) .
")) SEPARATOR ', ')
FROM `{$this->relation[$column]['rel_tbl']}`
WHERE {$where})\r\n";
}
// multiselect relation
elseif ($this->relation[$column]['multi'])
{
$select = "(SELECT GROUP_CONCAT(DISTINCT `{$this->relation[$column]['rel_name']}` SEPARATOR ', ')
FROM `{$this->relation[$column]['rel_tbl']}` WHERE
FIND_IN_SET(`{$this->relation[$column]['rel_tbl']}`.`{$this->relation[$column]['rel_field']}`,`{$this->relation[$column]['table']}`.`{$this->relation[$column]['field']}`)
ORDER BY `{$this->relation[$column]['rel_name']}` ASC)\r\n";
}
else
{
$select = "(SELECT `{$this->relation[$column]['rel_alias']}`.`{$this->relation[$column]['rel_name']}`
FROM `{$this->relation[$column]['rel_tbl']}` AS `{$this->relation[$column]['rel_alias']}`
WHERE `{$this->relation[$column]['rel_alias']}`.`{$this->relation[$column]['rel_field']}` = `{$this->relation[$column]['table']}`.`{$this->relation[$column]['field']}`
LIMIT 1) \r\n";
}
$or_where[] = $select . ' LIKE ' . $db->escape_like($this->phrase, $this->search_pattern);
}
return implode(' OR ', $or_where);
}*/
}
protected function _build_fk_relation_subwhere($key) // multicolumn name
{
$db = Xcrud_db::get_instance($this->connection);
$fk = $this->fk_relation[$key];
if (is_array($fk['rel_name']))
{
foreach ($fk['rel_name'] as $tmp)
{
$tmp_fields[] = "`{$tmp}`";
$rel_name = 'CONCAT_WS(' . $db->escape($fk['rel_separator']) . ',' . implode(',', $tmp_fields) . ')';
}
}
else
{
$rel_name = '`' . $fk['rel_name'] . '`';
}
$select = '(SELECT GROUP_CONCAT(DISTINCT ' . $rel_name . ' SEPARATOR \', \')
FROM `' . $fk['rel_tbl'] . '`
INNER JOIN `' . $fk['fk_table'] . '` ON `' . $fk['fk_table'] . '`.`' . $fk['out_fk_field'] . '` = `' . $fk['rel_tbl'] .
'`.`' . $fk['rel_field'] . '` WHERE `' . $fk['fk_table'] . '`.`' . $fk['in_fk_field'] . '` = `' . $fk['table'] . '`.`' .
$fk['field'] . '` AND ' . $this->_build_rel_where($key) . ')' . "\r\n";
return $select . ' LIKE ' . $db->escape_like($this->phrase, $this->search_pattern);
}
protected function _build_rel_where($name)
{
$where_arr = array();
if ($this->fk_relation[$name]['rel_where'])
{
$db = Xcrud_db::get_instance($this->connection);
if (is_array($this->fk_relation[$name]['rel_where']))
{
foreach ($this->fk_relation[$name]['rel_where'] as $field => $val)
{
$val = preg_replace_callback('/\{(.+)\}/Uu', array($this, 'rel_where_callback'), $val);
$where_arr[] = $this->_field_from_where($field) . $this->_cond_from_where($field) . $db->escape($val);
}
}
else
{
$where_arr[] = preg_replace_callback('/\{(.+)\}/Uu', array($this, 'rel_where_callback'), $this->fk_relation[$name]['rel_where']);
}
return implode(' AND ', $where_arr);
}
else
{
return 1;
}
}
protected function _build_rel_ins_where($name)
{
$where_arr = array();
if ($this->fk_relation[$name]['add_data'])
{
$db = Xcrud_db::get_instance($this->connection);
if (is_array($this->fk_relation[$name]['add_data']))
{
foreach ($this->fk_relation[$name]['add_data'] as $field => $val)
{
$val = preg_replace_callback('/\{(.+)\}/Uu', array($this, 'rel_where_callback'), $val);
$where_arr[] = $this->_field_from_where($field) . $this->_cond_from_where($field) . $db->escape($val);
}
}
else
{
$where_arr[] = preg_replace_callback('/\{(.+)\}/Uu', array($this, 'rel_where_callback'), $this->fk_relation[$name]['add_data']);
}
return implode(' AND ', $where_arr);
}
else
{
return 1;
}
}
protected function rel_where_callback($matches)
{
if (strpos($matches[1], '.'))
{
$tmp = explode('.', $matches[1]);
return '`' . $this->prefix . $tmp[0] . '`.`' . $tmp[1] . '`';
}
else
{
return '`' . $this->table . '`.`' . $matches[1] . '`';
}
}
/** receiving user data */
protected function _receive_post($task = false, $primary = false)
{
if (!$this->table_name && !$this->query)
$this->table_name = $this->_humanize(mb_substr($this->table, mb_strlen($this->prefix)));
if ($task)
{
switch ($task)
{
case 'create':
$this->task = $task;
$this->before = $task;
return;
break;
case 'edit':
case 'view':
if ($primary !== false)
{
$this->task = $task;
$this->before = $task;
$this->primary_val = $primary;
return;
}
break;
case 'list':
$this->task = $task;
return;
break;
}
}
else
{
$this->task = $this->_post('task', 'list');
}
if ($this->is_get)
{
$this->task = $this->_get('task');
$this->primary_val = $this->_get('primary');
}
else
{
$this->order_column = $this->_post('orderby', false, 'key');
$this->order_direct = $this->_post('order') == 'desc' ? 'desc' : 'asc';
if ($this->order_column)
{
if (!$this->query)
$this->order_column = key($this->_parse_field_names($this->order_column, 'receive_post'));
if (isset($this->order_by[$this->order_column]))
unset($this->order_by[$this->order_column]);
$this->order_by = array_merge(array($this->order_column => $this->order_direct), $this->order_by);
}
$this->search = $this->_post('search', $this->search, 'int');
if ($this->search)
{
$this->column = $this->_post('column', false, 'key');
$this->phrase = $this->_post('phrase');
$this->range = $this->_post('range', '');
}
$this->start = $this->_post('start', 0, 'int');
$this->limit = $this->_post('limit', ($this->limit ? $this->limit : Xcrud_config::$limit));
$this->after = $this->_post('after');
$this->primary_val = $this->_post('primary');
}
}
protected function _build_order_by()
{
if (count($this->order_by))
{
$order_arr = array();
foreach ($this->order_by as $field => $direction)
{
if ($direction === false)
{
$order_arr[] = $field;
}
elseif (isset($this->subselect[$field]) or isset($this->columns[$field]) or isset($this->no_select[$field]) or !strpos($field,
'.'))
{
$order_arr[] = '`' . $field . '` ' . $direction;
}
else
{
$tmp = explode('.', $field);
$order_arr[] = '`' . $tmp[0] . '`.`' . $tmp[1] . '` ' . $direction;
}
}
return 'ORDER BY ' . implode(',', $order_arr);
}
else
{
/*if (isset($this->columns[$this->table . '.' . $this->primary_key]))
{
$this->order_by[$this->table . '.' . $this->primary_key] = 'ASC';
return "ORDER BY `{$this->table}.{$this->primary_key}` ASC";
}
else
return "ORDER BY `{$this->table}`.`{$this->primary_key}` ASC";*/
return '';
}
}
protected function _build_limit($total)
{
if ($this->limit != 'all' && $this->theme != 'printout')
{
if ($this->start > 0 && $this->start >= $this->result_total)
{
$this->start = $this->result_total > $this->limit ? $this->result_total - $this->limit : 0;
}
$this->start = floor($this->start / $this->limit) * $this->limit;
return "LIMIT {$this->start},{$this->limit}";
}
else
return '';
}
/** informatiuon about table columns */
protected function _get_table_info()
{
$this->table_info = array();
$db = Xcrud_db::get_instance($this->connection);
$db->query("SHOW COLUMNS FROM `{$this->table}`");
$this->table_info[$this->table] = $db->result();
if ($this->join)
{
foreach ($this->join as $alias => $join)
{
$db->query("SHOW COLUMNS FROM `{$join['join_table']}`");
$this->table_info[$alias] = $db->result();
}
}
return true;
}
protected function _set_field_types($mode = 'create', $all_fields = false)
{
if (is_array($this->table_info) && count($this->table_info))
{
$uni = false;
$this->primary_ai = false;
$fields = array();
foreach ($this->table_info as $table => $types)
{
foreach ($types as $row)
{
$field_index = $table . '.' . $row['Field'];
if (!$all_fields)
{
$fields_object_name = 'fields_' . $mode;
$fields_object = $this->$fields_object_name;
}
else
{
$fields_object = array();
}
$this->field_null[$field_index] = $row['Null'] == 'YES' ? true : false;
if ($row['Type'] == 'point')
{
$this->point_field[$field_index] = true;
}
if ($row['Key'] == 'PRI' or $row['Key'] == 'UNI')
{
$this->unique[$field_index] = true;
if ($table == $this->table && !$uni)
{
$uni = $row['Field'];
}
}
if ($row['Key'] == 'PRI' && $row['Extra'] == 'auto_increment')
{
if ($table == $this->table)
{
$this->primary_ai = true;
if (!$this->primary_key)
{
$this->primary_key = $row['Field'];
}
}
if (((!$this->show_primary_ai_column && $mode == 'list') or (!$this->show_primary_ai_field && $mode != 'list')) && !
isset($fields_object[$field_index]))
{
if (!isset($this->field_type[$field_index]))
{
$this->_define_field_type($row, $field_index);
}
continue;
}
else
{
$this->disabled[$field_index] = $this->parse_mode(false);
}
}
if ($this->join && isset($this->join[$table]) && $this->join[$table]['join_field'] == $row['Field'])
{
if (!isset($this->field_type[$field_index]))
{
$this->_define_field_type($row, $field_index);
}
continue;
}
if (!$fields_object)
{
$fields[$field_index] = array(
'table' => $table,
'field' => $row['Field'],
'tab' => '');
}
elseif ($fields_object && isset($this->reverse_fields[$mode]) && $this->reverse_fields[$mode])
{
if (!isset($fields_object[$field_index]))
{
$fields[$field_index] = array(
'table' => $table,
'field' => $row['Field'],
'tab' => '');
}
}
elseif (isset($fields_object[$field_index]))
{
$fields[$field_index] = $fields_object[$field_index];
}
if (isset($this->relation[$field_index]))
{
$this->field_type[$field_index] = 'relation';
if (!isset($this->defaults[$field_index]))
{
$this->defaults[$field_index] = $row['Default'];
}
$this->_define_field_type($row, $field_index);
continue;
}
$this->_define_field_type($row, $field_index);
}
}
// resorting
if ($fields_object && (!isset($this->reverse_fields[$mode]) || !$this->reverse_fields[$mode]))
{
$fields = array_merge($fields_object, $fields);
if ($mode == 'list')
{
$this->columns = $fields;
}
else
{
$this->fields = $fields;
}
}
else
{
$fk_before = array();
if ($this->fk_relation)
{
foreach ($this->fk_relation as $fk)
{
$fk_before[$fk['alias']] = $fk['before'];
}
}
if ($mode == 'list')
{
$subselect_before = $this->subselect_before;
foreach ($fields as $field_index => $field)
{
// subselect
if ($name = array_search($field_index, $subselect_before))
{
if (!isset($fields_object[$name]))
{
$fdata = $this->_parse_field_names($name, 'set_field_types');
$this->columns[$name] = reset($fdata);
}
unset($subselect_before[$name]);
}
if ($name = array_search($field_index, $fk_before))
{
if (!isset($fields_object[$name]))
{
$fdata = $this->_parse_field_names($name, 'set_field_types');
$this->columns[$name] = reset($fdata);
}
unset($fk_before[$name]);
}
$this->columns[$field_index] = $field;
}
if (count($subselect_before))
{
foreach ($subselect_before as $name => $before)
{
if (!isset($fields_object[$name]))
{
$fdata = $this->_parse_field_names($name, 'set_field_types');
$this->columns[$name] = reset($fdata);
}
unset($subselect_before[$name]);
}
}
if (count($fk_before))
{
foreach ($fk_before as $name => $before)
{
if (!isset($fields_object[$name]))
{
$fdata = $this->_parse_field_names($name, 'set_field_types');
$this->columns[$name] = reset($fdata);
}
unset($fk_before[$name]);
}
}
}
elseif ($mode != 'create')
{
$subselect_before = $this->subselect_before;
foreach ($fields as $field_index => $field)
{
// subselect
if ($name = array_search($field_index, $subselect_before))
{
if (!isset($fields_object[$name]))
{
$fdata = $this->_parse_field_names($name, 'set_field_types');
$this->fields[$name] = reset($fdata);
}
unset($subselect_before[$name]);
}
if ($name = array_search($field_index, $fk_before))
{
if (!isset($fields_object[$name]))
{
$fdata = $this->_parse_field_names($name, 'set_field_types');
$this->fields[$name] = reset($fdata);
}
unset($fk_before[$name]);
}
$this->fields[$field_index] = $field;
}
if (count($subselect_before))
{
foreach ($subselect_before as $name => $before)
{
if (!isset($fields_object[$name]))
{
$fdata = $this->_parse_field_names($name, 'set_field_types');
$this->fields[$name] = reset($fdata);
}
unset($subselect_before[$name]);
}
}
if (count($fk_before))
{
foreach ($fk_before as $name => $before)
{
if (!isset($fields_object[$name]))
{
$fdata = $this->_parse_field_names($name, 'set_field_types');
$this->fields[$name] = reset($fdata);
}
unset($fk_before[$name]);
}
}
}
elseif ($fk_before)
{
foreach ($fields as $field_index => $field)
{
if ($name = array_search($field_index, $fk_before))
{
if (!isset($fields_object[$name]))
{
$fdata = $this->_parse_field_names($name, 'set_field_types');
$this->fields[$name] = reset($fdata);
}
unset($fk_before[$name]);
}
$this->fields[$field_index] = $field;
}
if (count($fk_before))
{
foreach ($fk_before as $name => $before)
{
if (!isset($fields_object[$name]))
{
$fdata = $this->_parse_field_names($name, 'set_field_types');
$this->fields[$name] = reset($fdata);
}
unset($fk_before[$name]);
}
}
}
else
{
$this->fields = $fields;
}
}
//echo'
'.print_r($fields,true).''; if (!$this->primary_key) { if ($uni) $this->primary_key = $uni; else { // changed to prevent data rewriting //$this->primary_key = $this->table_info[$this->table][0]['Field']; switch ($this->task) { case 'list': case 'action': case 'print': case 'csv': $this->is_edit = false; $this->is_remove = false; $this->is_create = false; $this->is_view = false; //$this->is_search = false; break; default: self::error('Table "' . $this->table . '" has no any primary or unique key!