private function &_value_to_has_many_object($model, &$value) { $object = NULL; if (!isset($value) || is_mdinull($value)) { $object = new $model(); } else { if (is_object($value)) { if ($value->model != $model) { mdi::error(get_class($this) . '::_value_to_has_many_object' . ' - model type of value is different(' . $value->model . ')'); /// } $object =& $this->_modelarray_to_object($model, array($value)); } else { if (is_array($value)) { if (empty($value)) { $object = new $model(); } else { if (is_numeric_array($value)) { $object = new $model(); $object->where_in('id', $value)->get(); } else { $object =& $this->_modelarray_to_object($model, $value); } } } else { if (is_numeric($value)) { $object = new $model(); $object->where_in('id', array($value))->get(); } else { mdi::error(get_class($this) . '::_value_to_has_many_object' . ' - type that is not allowed in related field(' . gettype($value) . ')'); /// } } } } return $object; }
/** * Test is_numeric_array and is_assoc_array */ function test_is_functions() { $this->assertTrue(is_numeric_array(array())); $this->assertTrue(is_assoc_array(array())); $data = array('a', 'b', 'c'); $this->assertTrue(is_numeric_array($data)); $this->assertTrue(is_numeric_array($data, true)); $this->assertFalse(is_assoc_array($data)); $this->assertFalse(is_assoc_array($data, true)); $data = array(1, 2, 3); $this->assertTrue(is_numeric_array($data)); $this->assertTrue(is_numeric_array($data, true)); $this->assertFalse(is_assoc_array($data)); $this->assertFalse(is_assoc_array($data, true)); $data = array('a' => 'aa', 'b' => 'bb', 'c' => 'cc'); $this->assertFalse(is_numeric_array($data)); $this->assertTrue(is_assoc_array($data)); $data = array('a', 'b' => 'bb', 'c' => 'cc', 'd' => 'dd'); $this->assertTrue(is_numeric_array($data)); $this->assertFalse(is_numeric_array($data, true)); $this->assertFalse(is_assoc_array($data)); $this->assertTrue(is_assoc_array($data, true)); $data = array('a' => 'aa', 'b', 'c'); $this->assertFalse(is_numeric_array($data)); $this->assertFalse(is_numeric_array($data, true)); $this->assertTrue(is_assoc_array($data)); $this->assertTrue(is_assoc_array($data, true)); }
function dump_results($a) { print_r($a); is_numeric_array($a) ? printf("%s\n", 'This array is numeric') : printf("%s\n", 'This array is not numeric'); is_assoc_array($a) ? printf("%s\n", 'This array is associative') : printf("%s\n", 'This array is not associative'); print "\n\n"; }
/** * Test if the supplied argument is an associative array (dictionary, hash). * * For performance reasons, this function only checks the first element of the * array by default. * * \param $arr * The array to test * \param $check_all * Whether to check all elements instead of just the first (optional, defaults * to false) * * \return * Returns true if $arr is an associative array, false otherwise. */ function is_assoc_array($arr, $check_all = false) { if (!is_array($arr)) { return false; } if (count($arr) == 0) { return true; } return !is_numeric_array($arr, $check_all); }
public function where($where, $params = array()) { // '$where' is empty? if (!is_array($where) && is_blank($where)) { return; } // '$where' is id? if (is_numeric($where) || is_numeric_array($where)) { $this->where = "{$this->from}.id" . self::id_condition($where); return; } // etc $this->where = Context::get('db')->bind_params($where, $params); }
/** * Join all parameters into a URL path with an extension. This function does * the same as URL::join, but uses the last parameter as a file extension. * * \param $parts * Any number of string parameters (or an array) * * \param $ext * The extension to append to the path. All strings are accepted and * a leading dot is taken care of, so that both "txt" and ".txt" work * correctly. * * \return * The resulting URL path * * \see URL::join */ static function join_ext($parts, $ext = null) { $args = func_get_args(); $num_args = func_num_args(); /* Accept one single array argument too */ if ($num_args == 1 && is_numeric_array($args[0])) { $args = $args[0]; } /* Require at least 2 parameters */ assert('is_numeric_array($args)'); assert('count($args) >= 2'); $ext = array_pop($args); assert('is_string($ext)'); $ext = str_strip_prefix($ext, '.'); $path = URL::join($args); return sprintf('%s.%s', $path, $ext); }
/** * \private * * Setter method to enable the correct options. * * External callers should use <code>set('value', 'the-value-here')</code> * instead. * * \param $value * The value to set */ function set_value($value) { /* Now set the new value(s). It's easier if we treat the values as an * array of values, even if only one value was provided. */ $this->at_least_one_selected = false; $multiple = $this->_get('multiple'); if (is_numeric_array($value)) { /* Multiple values provided. This only works for multiple select * choice controls; for single select control just use the first * value. */ $values = $value; if (!$multiple) { $values = array_slice($values, 0, 1); } } else { /* Only a single value was provided. Make a 1-item array for it. */ $values = array($value); } /* Iterate over the options and select the right ones */ foreach ($this->_options as $option_or_option_group) { $option_or_option_group->set('value', $values); if ($option_or_option_group->at_least_one_selected) { $this->at_least_one_selected = true; /* Don't set any other values if this is a single select control */ if (!$multiple) { $values = array(); } } } /* Make sure there's always at least one value selected for single * select choice controls. FIXME: this is controversial... */ if (!$multiple && !$this->at_least_one_selected) { $this->_ensure_selection(); } }
/** * Render various objects to a string. This function creates a string from * various types of objects by applying various conversion methods. Supported * data types: * * - Simple values: strings, integers, floats, boolean (0 or 1). * - Any object implementing a render(), to_xhtml(), to_string() or toString() method. * - Numerical arrays containing any of the supported types are recursively * converted to string values, separated by newlines. * * An error is thrown if the passed object cannot be handled. * * \param $args * Any value supported by this function. You can also pass multiple * parameters. * * \return * String representation of the renderered object. */ function to_string($args) { $args = func_get_args(); $r = array(); foreach ($args as $arg) { /* Strings are left as-is. Easy enough. */ if (is_string($arg)) { $r[] = $arg; continue; } /* Null values are skipped */ if (is_null($arg)) { continue; } /* Numbers are converted to strings. */ if (is_integer($arg) || is_float($arg)) { $r[] = (string) $arg; continue; } /* Boolean values are converted to 1 or 0. */ if (is_bool($arg)) { $r[] = $arg ? '1' : '0'; continue; } /* Numerical arrays: recursively iterate over the items */ if (is_numeric_array($arg)) { $tmp = array(); foreach (array_keys($arg) as $key) { $tmp[] = to_string($arg[$key]); } $r[] = implode(NL, $tmp); continue; } /* Handle objects */ if (is_object($arg)) { $found = false; foreach (array('render', 'to_string', 'toString') as $func) { if (method_exists($arg, $func)) { /* Call to_string() again because the method may not return * a string but (for instance) an array. */ $r[] = to_string($arg->{$func}()); $found = true; break; /* break out of inner loop */ } } if ($found) { continue; } /* continue outer loop */ } /* All our attempts failed... throw an error */ throw new AnewtException('Could not convert value to string: "%s"', $arg); } /* Yay, done. */ return implode(NL, $r); }
function is_numeric_array($array) { $r = false; if (is_array($array)) { foreach($array as $n=>$v) { if (is_array( $array[$n] )) { $r = is_numeric_array( $array[$n] ); if ($r==false) break; } else { if (!is_numeric($v)) { $r = false; break; } else { $r = true; } } } } return $r; }
/** * Fill the SQL template using the values passed as a single parameter. * * This method will check all values for correctness to avoid nasty SQL * injection vulnerabilities. * * \param $values * Array with values to use for substitution. For positional placeholders * this should be a numeric array. For named placeholders an associative * array or AnewtContainer instance should be passed. * * \return * The query containing all values, quoted correctly. * * \see AnewtDatabaseSQLTemplate::fill */ public function fillv($values = null) { $n_placeholders = count($this->placeholders); $escaped_values = array(); /* I. Named mode */ if ($this->named_mode) { /* Sanity checks */ $values_is_container = $values instanceof AnewtContainer; if (!is_assoc_array($values) && !$values_is_container) { throw new AnewtDatabaseQueryException('SQL templates in named mode require a single associative array or AnewtContainer instance when filled.'); } /* Fill the placeholders */ for ($i = 0; $i < $n_placeholders; $i++) { list($field_name, $field_type, $multiple) = $this->placeholders[$i]; if ($values_is_container) { $value = $values->get($field_name); } else { if (!array_key_exists($field_name, $values)) { throw new AnewtDatabaseQueryException('No value specified for field "%s".', $field_name); } $value = $values[$field_name]; } /* Multiple values */ if ($multiple) { if (!is_numeric_array($value)) { throw new AnewtDatabaseQueryException('Value for field "%s[]:%s" is not a numeric array.', $field_type, $field_name); } $escaped_values[] = $this->escape_field_array($field_type, $value); } else { $escaped_values[] = $this->escape_field($field_type, $value); } } } else { /* Sanity checks */ if (!is_numeric_array($values)) { throw new AnewtDatabaseQueryException('SQL templates in positional mode can only be filled using a numeric array'); } $n_values = count($values); if ($n_placeholders != $n_values) { throw new AnewtDatabaseQueryException('Expected %d placeholder values, but %d values were provided.', $n_placeholders, $n_values); } /* Fill the placeholders */ foreach ($this->placeholders as $placeholder) { list($field_name, $field_type, $multiple) = $placeholder; $value = array_shift($values); /* Multiple values */ if ($multiple) { if (!is_numeric_array($value)) { throw new AnewtDatabaseQueryException('Value for field "%s[]" is not a numeric array.', $field_type); } $escaped_values[] = $this->escape_field_array($field_type, $value); } else { $escaped_values[] = $this->escape_field($field_type, $value); } } } /* Now that all supplied values are validated and escaped properly, we * can easily substitute them into the query template. The %s * placeholders were already prepared during initial parsing. */ $query = vsprintf($this->sql, $escaped_values); return $query; }
/** * (Really) dispatch an URL to the correct handlers. * * This method does the actual magic, such as URL parsing, matching and * command invocation. You can optionally provide a custom URL and tell the * dispatcher that some parts of the URL should be skipped when handling * this request. * * \param $url * \param $prefix * \see AnewtURLDispatcher::dispatch */ private function real_dispatch($url = null, $prefix = null) { /* Use the current URL if no explicit url was given */ if (is_null($url)) { $url = AnewtRequest::relative_url(); } /* Figure out the right base location if no prefix was given. If the URL * starts with the PHP script name, we assume no htaccess file has been * setup to beautify the website URLs. In this case the relevant parts * of the URL are added after the PHP script name. Example URL of such * a setup is http://.../dispatch.php/a/b/c/. Otherwise, it is quite * likely a htaccess file is used to point all requests to a script that * invokes the dispatcher. We assume this script is placed in the * toplevel directory, so we use that directory as the prefix. */ if (is_null($prefix)) { if (str_has_prefix($url, $_SERVER['SCRIPT_NAME'])) { $prefix = $_SERVER['SCRIPT_NAME']; } else { $prefix = dirname($_SERVER['SCRIPT_NAME']); } } assert('is_string($url)'); assert('is_string($prefix)'); /* Strip off the GET parameters from the URL */ $get_params = ''; $question_mark_pos = strpos($url, '?'); if ($question_mark_pos !== false) { $get_params = substr($url, $question_mark_pos); $url = substr($url, 0, $question_mark_pos); } /* Redirect GET requests when trailing slash is required but missing */ if (!str_has_suffix($url, '/') && $this->force_trailing_slash && AnewtRequest::is_get() && !preg_match('#^.*\\.[^\\/]*$#', $url)) { redirect(sprintf('%s/%s', $url, $get_params), HTTP_STATUS_MOVED_PERMANENTLY); } /* Strip off prefix and slashes */ $this->request_url_full = $url; $url = str_strip_prefix($url, $prefix); $url = str_strip_prefix($url, '/'); $url = str_strip_suffix($url, '/'); $this->request_url = $url; /* Try to find a matching route and extract the parameters */ $found_route = false; $command = null; $parameters = array(); $url_parts = strlen($url) > 0 ? explode('/', $url) : array(); foreach ($this->routes as $route) { $route_type = array_shift($route); $route_command = array_shift($route); $route_parameters = array(); /* Type I: Routes using regular expression */ if ($route_type == ANEWT_URL_DISPATCHER_ROUTE_TYPE_REGEX) { list($pattern) = $route; /* Try both with and without trailing slash */ if (preg_match($pattern, $url, $route_parameters) || preg_match($pattern, sprintf('%s/', $url), $route_parameters)) { /* We don't care about $parameters[0] (it contains the full match) */ array_shift($route_parameters); $route_parameters = array_map('urldecode', $route_parameters); $command = $route_command; $parameters = $route_parameters; $found_route = true; break; } } elseif ($route_type == ANEWT_URL_DISPATCHER_ROUTE_TYPE_URL_PARTS) { list($route_url, $additional_constraints) = $route; /* Route URL can be a string or an array */ if (is_string($route_url)) { $route_url = str_strip_prefix($route_url, '/'); $route_url = str_strip_suffix($route_url, '/'); $route_url_parts = strlen($route_url) > 0 ? explode('/', $route_url) : array(); } elseif (is_numeric_array($route_url)) { $route_url_parts = $route_url; } else { throw new AnewtException('Invalid url route: %s', $route_url); } /* Match the URL parts against the route URL parts */ if (count($url_parts) != count($route_url_parts)) { continue; } $constraints = array_merge($this->url_part_constraints, $additional_constraints); for ($i = 0; $i < count($url_parts); $i++) { /* If the URL starts with a ':' character it is * a parameter... */ if ($route_url_parts[$i][0] === ':') { $parameter_name = substr($route_url_parts[$i], 1); $parameter_value = $url_parts[$i]; /* If there is a constraint for this parameter, the * value must match the constraint. If not, this route * cannot be used. */ if (array_key_exists($parameter_name, $constraints)) { $pattern = $constraints[$parameter_name]; if (!preg_match($pattern, $parameter_value)) { continue 2; } } $route_parameters[$parameter_name] = urldecode($parameter_value); } elseif ($url_parts[$i] !== $route_url_parts[$i]) { continue 2; } } /* If this code is reached, we found a matching route with all * the constraints on the URL parts satisfied. */ $command = $route_command; $parameters = $route_parameters; $found_route = true; break; } else { assert('false; // not reached'); } } /* If no route matches, try an automatic route. Only the first URL part * is considered for this. */ if (!$found_route && $this->use_automatic_commands) { $url_parts = explode('/', $url, 2); if ($url_parts) { $command = array($this, sprintf('command_%s', $url_parts[0])); list($found_route, $error_message_to_ignore) = $this->is_valid_command($command); } } /* As a last resort try the default handler, if one was set. */ $default_command = $this->default_command; if (!$found_route && !is_null($default_command)) { $command = $default_command; $command = $this->validate_command($command); $found_route = true; } /* If we still don't have a command, we give up. Too bad... not found */ if (!$found_route) { throw new AnewtHTTPException(HTTP_STATUS_NOT_FOUND); } /* Check the command for validity. In most cases we already know the * command exists since that is already checked in the add_route_*() * methods or in the code above, except for lazily loaded commands, so * we try to load them and check for validity afterwards. */ if (is_array($command) && is_string($command[0])) { $this->include_command_class($command[0]); $command = $this->validate_command($command); } /* Finally... run the command and the pre and post command hooks. */ $this->pre_command($parameters); call_user_func($command, $parameters); $this->post_command($parameters); }
function getLegend($filter,$layer){ // create a new XML document $responseDoc = new DomDocument('1.0'); // create root node $rootNode = $responseDoc->createElement('response'); $rootNode = $responseDoc->appendChild($rootNode); $query = "select count(*) as total from lut_color where color_by_column ='". $filter ."' and layer_id = ( select layer_id from \"Meta_Layer\" where layer_tablename ='".$layer."' )"; $data = db_query($query); if ($obj = db_fetch_object($data)) { if ($obj->total > 0) { setNoError($responseDoc, $rootNode); $layerNode = addXMLChildNode($responseDoc, $rootNode, "layer", null, array('color_by_column' => $filter)); $query = "select color_by_value, color from lut_color where layer_id = ( select layer_id from \"Meta_Layer\" where layer_tablename ='".$layer."') and color_by_column ='". $filter ."' order by color_by_value"; $data = db_query($query); $categories = array(); $colors = array(); while ($obj = db_fetch_object($data)) { $categories[] = $obj->color_by_value; $colors[] = $obj->color; } if (is_numeric_array($categories)) { array_multisort($categories, $colors); } elseif (is_range_array($categories)) { rangearray_multisort($categories, $colors); } $len = sizeof($categories); for ($i = 0; $i < $len; $i++) { addXMLChildNode($responseDoc, $layerNode, "category", null, array('category_name' => $categories[$i], 'category_color' => $colors[$i])); } } else { setError($responseDoc, $rootNode, "Color by column not set for this layer"); } } return $responseDoc->saveXML(); }
/** * addChild(string $element[, array|string|null $data [, array|null $attributes [, bool $write_raw_xml ]]]) * * 88mph * * @access: private */ private function addChild($element, $data = null, $attributes = null) { $this->startElement((string) $element); // Apparently writeAttribute() has issues. if (is_array($attributes)) { foreach ($attributes as $key => $value) { $this->startAttribute($key); $this->text($value); $this->endAttribute(); } } $write_raw_xml = $this->isRawXML($data); // 1.1 jigawatts if (is_array($data)) { foreach ($data as $child => $value) { // Lets check if this current value has attributes // and if so, let's take care of that now. $attributes = $this->getAttributes($value); // this function is not included in php, but it should be :) if (is_numeric_array($value)) { // so let's go through these similiarly named tags foreach ($value as $v) { // and again, let's take care of attributes asap $a = $this->getAttributes($v); // and recurse $this->addChild($child, $v, $a); } } else { $this->addChild($child, $value, $attributes); } } /** * edit 10/5/2014 6:04:15 AM * edit 10/6/2014 7:46:24 PM * previously used is_string(), which causes numbers not to print * * numbers are useful. * * Scalar variables are those containing an integer, float, string or boolean. Types array, object and resource are not scalar. * * is_scalar() does not consider NULL to be scalar. */ } elseif (is_scalar($data)) { $write_raw_xml ? $this->writeRaw($data) : $this->text($data); } // And if $data was null? Well this will make sure we have a nice closed <tag/> $this->endElement(); }
/** * Fills in the valus in the SQL template. This method will check all values * for correctness to avoid nasty SQL injection vulnerabilities. * * \param $args * Array with values to use for substitution. * * \return * The query containing all values, quoted correctly. */ function fill($args = null) { /* We accept either: * - no parameters * - multiple scalar parameters * - 1 array parameter with scalar elements * - 1 associative array parameter * - 1 container parameter */ $args = func_get_args(); if ($this->named_mode) { if (count($args) != 1) { trigger_error('associative array or Container expected', E_USER_ERROR); } if ($args[0] instanceof Container) { $args = $args[0]->to_array(); } elseif (is_array($args[0])) { $args = $args[0]; } else { trigger_error('associative array or Container expected', E_USER_ERROR); } $numargs = count($this->named_placeholders); } else { if (count($args) == 1 && is_numeric_array($args[0])) { $args = $args[0]; } assert('is_numeric_array($args)'); if (count($args) != count($this->placeholders)) { trigger_error(sprintf('Incorrect number of parameters to SQLTemplate::fill(): expected %d, got %d', count($this->placeholders), count($args)), E_USER_ERROR); } $numargs = count($args); } /* Note: don't use foreach() here, because it copies the values in * memory and leaves the original values untouched! */ for ($i = 0; $i < $numargs; $i++) { if ($this->named_mode) { $fieldtype = $this->named_placeholders[$i]['type']; $var = $this->named_placeholders[$i]['var']; if (!isset($args[$var])) { $var = str_replace('-', '_', $var); // Container replaces '-' with '_' if (!array_key_exists($var, $args)) { trigger_error(sprintf('SQLTemplate::fill(): missing expected parameter "%s"', $this->named_placeholders[$i]['var']), E_USER_ERROR); } } $value = $args[$var]; $argname = "`" . $var . "'"; } else { $fieldtype = $this->placeholders[$i]; $value =& $args[$i]; $argname = $i + 1; } /* Handle NULL values here. Escaping is not needed for NULL values. */ if (is_null($value)) { $value = 'NULL'; if ($this->named_mode) { $arglist[$i] = $value; } continue; } /* The value is non-null. Perform very restrictive input sanitizing * based on the field type. */ switch ($fieldtype) { case ANEWT_DATABASE_TYPE_BOOLEAN: /* Integers: only accept 0 and 1 (no type juggling!) */ if (is_int($value)) { if ($value === 0) { $value = false; } elseif ($value === 1) { $value = true; } } /* Strings: only accept literal "0" and "1" (no type juggling!) */ if (is_string($value)) { if ($value === "0") { $value = false; } elseif ($value === "1") { $value = true; } } if (is_bool($value)) { $value = $this->db->backend->escape_boolean($value); break; } trigger_error(sprintf('Invalid boolean value: "%s" on argument %s', $value, $argname), E_USER_ERROR); case ANEWT_DATABASE_TYPE_INTEGER: if (is_int($value)) { $value = (string) $value; break; } if (is_string($value) && preg_match('/^-?\\d+$/', $value)) { break; } trigger_error(sprintf('Invalid integer value: "%s" on argument %s', $value, $argname), E_USER_ERROR); case ANEWT_DATABASE_TYPE_FLOAT: // FIXME: this does not accept .123 (without a leading zero) if (is_string($value) && preg_match('/^-?\\d+(\\.\\d*)?$/', $value)) { /* Enough checks done by the regex, no need to do any * formatting/escaping */ break; /* Locale-agnostic float formatting */ } elseif (is_int($value) || is_float($value)) { $value = number_format($value, 10, '.', ''); if (str_has_suffix($value, '.')) { $value .= '0'; } break; } trigger_error(sprintf('Invalid float value: "%s" on argument %s', $value, $argname), E_USER_ERROR); case ANEWT_DATABASE_TYPE_STRING: /* Accept integers and objects with a render() method. */ if (is_int($value)) { $value = (string) $value; } elseif (is_object($value) && method_exists($value, 'render')) { $value = $value->render(); } /* From this point on, only strings are accepted. */ if (is_string($value)) { $value = $this->db->backend->escape_string($value); break; } trigger_error(sprintf('Invalid string value: "%s" on argument %s', $value, $argname), E_USER_ERROR); case ANEWT_DATABASE_TYPE_DATE: if ($value instanceof AnewtDateTimeAtom) { $value = AnewtDateTime::sql_date($value); } if (is_string($value) && preg_match('/^\\d{2,4}-\\d{2}-\\d{2}$/', $value)) { $value = $this->db->backend->escape_date($value); break; } if (is_string($value) && strtoupper($value) == "NOW") { $value = "NOW()"; break; } if (is_string($value) && strtoupper($value) == 'NOW') { $value = 'NOW()'; break; } trigger_error(sprintf('Invalid date value: "%s" on argument %s', $value, $argname), E_USER_ERROR); case ANEWT_DATABASE_TYPE_TIME: if ($value instanceof AnewtDateTimeAtom) { $value = AnewtDateTime::sql_time($value); } if (is_string($value) && preg_match('/^\\d{2}:\\d{2}(:\\d{2})?$/', $value)) { $value = $this->db->backend->escape_time($value); break; } if (is_string($value) && strtoupper($value) == "NOW") { $value = "NOW()"; break; } if (is_string($value) && strtoupper($value) == 'NOW') { $value = 'NOW()'; break; } trigger_error(sprintf('Invalid time value: "%s" on argument %s', $value, $argname), E_USER_ERROR); case ANEWT_DATABASE_TYPE_DATETIME: case ANEWT_DATABASE_TYPE_TIMESTAMP: if ($value instanceof AnewtDateTimeAtom) { $value = AnewtDateTime::sql($value); } if (is_string($value) && preg_match('/^\\d{2,4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$/', $value)) { $value = $this->db->backend->escape_datetime($value); break; } if (is_string($value) && strtoupper($value) == "NOW") { $value = "NOW()"; break; } if (is_string($value) && strtoupper($value) == 'NOW') { $value = 'NOW()'; break; } trigger_error(sprintf('Invalid datetime or timestamp value: "%s" on argument %s', $value, $argname), E_USER_ERROR); case ANEWT_DATABASE_TYPE_RAW: /* No checking, no escaping... use at your own risk ;-) */ break; /* The column and table type are mostly for internal usage, it's * a BAD idea to use user data for these fields! */ /* The column and table type are mostly for internal usage, it's * a BAD idea to use user data for these fields! */ case ANEWT_DATABASE_TYPE_COLUMN: if (is_string($value) && preg_match('/^([a-z0-9_-]+\\.)*[a-z0-9_-]+$/i', $value)) { $value = $this->db->backend->escape_column_name($value); break; } trigger_error(sprintf('Invalid column value: "%s" on argument %s', $value, $argname), E_USER_ERROR); case ANEWT_DATABASE_TYPE_TABLE: if (is_string($value) && preg_match('/^([a-z0-9_-]+\\.)*[a-z0-9_-]+$/i', $value)) { $value = $this->db->backend->escape_table_name($value); break; } trigger_error(sprintf('Invalid table value: "%s" on argument %s', $value, $argname), E_USER_ERROR); default: trigger_error('This is a bug! Fieldtype unknown', E_USER_ERROR); break; } assert('is_string($value)'); if ($this->named_mode) { $arglist[$i] = $value; } } /* Now that all supplied values are validated and escaped properly, we * can easily substitute them into the query template. The %s * placeholders were already prepared during initial parsing. */ if ($this->named_mode) { $query = vsprintf($this->sql_template, $arglist); } else { $query = vsprintf($this->sql_template, $args); } return $query; }
function kvwriteSegment(&$str, $arr, $tier = 0, $tree = array()) { global $ordered_fields; $indent = str_repeat(chr(9), $tier); // TODO check for a certain key to keep it in the same tier instead of going into the next? foreach ($arr as $key => $value) { if (is_array($value)) { $tree[$tier] = $key; $key = '"' . $key . '"'; $str .= $indent . $key . "\n" . $indent . "{\n"; $path = implode("/", $tree); // If this item is an ordered array, deserialize it if (matchTheaterPath($path, $ordered_fields) && is_numeric_array(array_keys($value))) { // echo "Ordered<br>\n"; foreach ($value as $idx => $item) { foreach ($item as $k => $v) { $str .= chr(9) . $indent . QuoteAndTabKeyValue($k, $v) . "\n"; } } } else { // echo "Array<br>\n"; kvwriteSegment($str, $value, $tier + 1, $tree); } $str .= $indent . "}\n"; unset($tree[$tier]); } else { // echo "String<br>\n"; $str .= $indent . QuoteAndTabKeyValue($key, $value) . "\n"; } } return $str; }
if ("directus_users" === $table && in_array($app->request()->getMethod(), array('POST')) && array_key_exists('email', $requestPayload)) { $avatar = DirectusUsersTableGateway::get_avatar($requestPayload['email']); $requestPayload['avatar'] = $avatar; } switch ($app->request()->getMethod()) { // POST one new table entry case 'POST': $activityLoggingEnabled = !(isset($_GET['skip_activity_log']) && 1 == $_GET['skip_activity_log']); $activityMode = $activityLoggingEnabled ? TableGateway::ACTIVITY_ENTRY_MODE_PARENT : TableGateway::ACTIVITY_ENTRY_MODE_DISABLED; $newRecord = $TableGateway->manageRecordUpdate($table, $requestPayload, $activityMode); $params[$TableGateway->primaryKeyFieldName] = $newRecord[$TableGateway->primaryKeyFieldName]; break; // PUT a change set of table entries // PUT a change set of table entries case 'PUT': if (!is_numeric_array($requestPayload)) { $params[$TableGateway->primaryKeyFieldName] = $requestPayload[$TableGateway->primaryKeyFieldName]; $requestPayload = array($requestPayload); } $TableGateway->updateCollection($requestPayload); break; } // GET all table entries $Table = new TableGateway($acl, $table, $ZendDb); $entries = $Table->getEntries($params); JsonView::render($entries); })->via('GET', 'POST', 'PUT'); $app->get("/{$v}/tables/:table/typeahead/?", function ($table, $query = null) use($ZendDb, $acl, $params, $app) { $Table = new TableGateway($acl, $table, $ZendDb); if (!isset($params['columns'])) { $params['columns'] = '';
/** * Update a collection of records within this table. * @param array $entries Array of records. * @return void */ public function updateCollection($entries) { $entries = is_numeric_array($entries) ? $entries : array($entries); foreach ($entries as $entry) { $entry = $this->manageRecordUpdate($this->table, $entry); $entry->save(); } }
/** * Recursively appends children to this element. * * Strings are converted into text nodes. This method expands numerical * arrays and ignores null values. * * \param $new_children * Array of children elements */ public function append_children($new_children) { assert('is_numeric_array($new_children);'); foreach ($new_children as $new_child) { /* Skip null values. This may happen if a constructor was called by * the convenience API with attributes=null, or if consuming code * passes null instances. */ if (is_null($new_child)) { continue; } elseif (is_numeric_array($new_child)) { $this->append_children($new_child); continue; } $this->append_child($new_child); unset($new_child); } }
/** * Append new content to a block on this page. * * This method can only be used for block-based pages. * * Note that the specified block is not required to be specified in the * <code>blocks</code> property, though in most cases it will be (if you * want it to be rendered at least). In some custom situations where you * build blocks by other means, i.e. using <code>build_*</code> methods on * your page subclass, it might be helpful to use custom block names to act * as temporary containers for the page content. The <code>build_*</code> * methods can then retrieve the value and do something smart with it. * * \param $name * The name of the block to which the content should be added. * * \param $new_child * The content to add. This is most likely an Anewt XHTML element * instance, e.g. created by the <code>ax_*</code> functions from the * XHTML module. Numerical arrays are also accepted. * * \see append */ public function append_to($name, $new_child) { assert('is_string($name);'); /* Initialize when needed */ if (!array_key_exists($name, $this->_blocks)) { $this->_init_block($name); } if (is_numeric_array($new_child)) { $this->_blocks[$name]->append_children($new_child); } else { $this->_blocks[$name]->append_child($new_child); } }
/** * Get Fields from request. * * @param string $fields_data * * @return array */ protected function getFields($fields_data) { $list_fields = []; if ($fields_data == null) { return []; } $_fields_data = array_filter(explode('f', $fields_data)); foreach ($_fields_data as $fields) { $_fields = explode('a', $fields); if (count($_fields) == 2 && is_numeric($_fields[0])) { $minmax = explode('b', $_fields[1]); $checkbox = explode('|', $_fields[1]); if (count($minmax) == 2 && (is_numeric($minmax[0]) || $minmax[0] == '*') && (is_numeric($minmax[1]) || $minmax[1] == '*')) { $list_fields[$_fields[0]] = $this->constructNumericInput($_fields, $minmax); } elseif (count($checkbox) > 1 && is_numeric_array($checkbox)) { $list_fields[$_fields[0]] = $this->constructCheckbox($_fields, $checkbox); } elseif (is_numeric($_fields[1])) { $list_fields[$_fields[0]] = $this->constructSelect($_fields, $_fields[1]); } } } return $list_fields; }