/** * Creates and executes a prepared statement. * * The purpose of prepared statements is to execute a single query multiple times quickly using different variables. * However, we are using them here for security purposes, aware of the fact that preparing and executing single statements * one at a time goes against the intention of prepared statements. See "Escaping and SQL Injection" at * http://php.net/manual/en/mysqli.quickstart.prepared-statements.php * * For insert and update queries, passing an associative array of column names and values along with the first few * words of the query, up to and including the table name, is sufficient. * * Example: * $my_table_values = array( * 'Person' => 'Bob Jones', * 'Company => 'BJ Manufacturing' * ); * $query_fragment = "INSERT INTO `my_table`"; * database->query( $query_fragment, $my_table_values ); * * @param string [$query] Either a valid SQL query or the start of one accompanied by an associative array * @param array [$params] Optional. Either a list of values that will be bound to the prepared statement or an associative * array whose keys match the table's column names. * @return mixed [$result or $success] The result of a SQL SELECT, else boolean. */ public function query($query, $params = null) { if (mysqli_connect_error()) { throw new Exception('Failed to connect(' . mysqli_connect_errno() . '): ' . mysqli_connect_error()); } //var_dump( 'before: ', $query, $params ); if (empty($params)) { $statement = $this->prepare($query); return $this->execute($statement); } else { if (!is_array($params)) { $params = array($params); // convert to array because $this->bind_params requires it } else { if (is_assoc($params)) { // @todo finish reduce_params( $table_name, $params ); // stick $params keys into $query $query = $this->build_query_from_associative_array($query, array_keys($params)); // Because we've just filled in the keys (column names), we only need to pass the values $params = array_values($params); } } //var_dump( 'after: ', $query, $params ); $statement = $this->prepare($query); return $this->execute($statement, $params); } }
public function init() { parent::init(); $this->current_index = 0; // make sure $field was specified if (!$this->field) throw new Exception("field must be specified in resultfilter control"); $this->filter_definition = $this->controller->appmeta->filter->{$this->field}; if (!$this->datasource) /* Default to the datasource definition in the config file */ $this->datasource = $this->filter_definition->datasource; $filter_type = $this->filter_definition->type; // Set container and item templates from config file if not passed into tag if (!$this->item_template) $this->item_template = $this->controller->appmeta->renderer_map->{$filter_type}->item; if (!$this->container_template) $this->container_template = $this->controller->appmeta->renderer_map->{$filter_type}->container; // dig specific facet counts out of facets if (is_assoc($this->datasource)) { $facet = $this->datasource[$this->filter_definition->facet->field]; $this->datasource = array(); foreach($facet as $value => $count) $this->datasource[] = array('value' => $value, 'count' => $count); } }
public function testIsAssoc() { $arr = ['a' => 0, 'b' => 1]; $this->assertTrue(is_assoc($arr)); $arr = ['a', 'b', 'c']; $this->assertFalse(is_assoc($arr)); }
function recursive($array, $level = 1) { $cur = 1; foreach ($array as $key => $value) { //If $value is an array. if (is_array($value)) { if (!is_numeric($key)) { echo '"' . $key . '": '; } if (is_assoc($value)) { echo '{ '; } else { echo '[ '; } //We need to loop through it. recursive($value, $level + 1); if (is_assoc($value)) { echo ' }'; } else { echo ' ]'; } } else { //It is not an array, so print it out. echo '"' . $key . '": "' . $value, '"'; } if ($cur != count($array)) { echo ', '; } $cur++; } }
/** * __construct method * @param array $array * @array array $args * */ public function __construct($array, $args) { $this->array = $array; $this->args = $args; is_assoc($this->array) ? $this->assocArray() : $this->sequentArray(); $this->setRouting(implode('/', $this->array) . '/' . $this->args); }
function array_str($arr, $var_export_all = false) { $is_assoc = is_assoc($arr); $result = '['; foreach ($arr as $key => $value) { if ($is_assoc) { $result .= $key . '='; } if (is_array($value)) { $result .= array_str($value); } else { if ($var_export_all) { $result .= var_export($value, true); } else { if (is_bool($value)) { $result .= bool_str($value); } else { if (is_string($value)) { $result .= '"' . $value . '"'; } else { if (is_string_convertable($value)) { $result .= $value; } else { $result .= var_export($value, true); } } } } } $result .= ', '; } return remove_last($result, ', ') . ']'; }
/** * Constructor * * @param array $array multidimensional associative array * @param string $separator [optional] default '.' * * @throws NonAssocException */ public function __construct(array $array, $separator = '.') { if (!is_assoc($array)) { throw new NonAssocException(); } $this->storage = $array; $this->separator = $separator; }
/** * @return $this */ public function _refresh() { if (!is_assoc($this->_result)) { return $this; } DB::_getInstance()->query("UPDATE `Token` SET `Created` = NULL WHERE `ID` = {$this->_result['ID']};"); return $this; }
/** * Copy nodes * * @param array $keys associative array * * @throws NonAssocException * * @return $this */ public function copyKeys(array $keys) { if (!is_assoc($keys)) { throw new NonAssocException(); } foreach ($keys as $existingKey => $newKey) { $this->array->offsetSet($newKey, $this->array->offsetGet($existingKey)); } return $this; }
function parseMatch($match, $MAJOR_ITEMS) { //Strip fields from participants // $support_1; // $support_2; $counter = 0; foreach ($match['participants'] as $participant) { // if ($participant['timeline']['role'] == 'DUO_SUPPORT' && $participant['teamId'] == 100) // $support_1 = $participant['participantId']; // if ($participant['timeline']['role'] == 'DUO_SUPPORT' && $participant['teamId'] == 200) // $support_2 = $participant['participantId']; unset($match['participants'][$counter]['masteries']); unset($match['participants'][$counter]['runes']); foreach ($participant['stats'] as $key => $value) { if ($key != 'deaths' && $key != 'kills' && $key != 'assists' && $key != 'winner') { unset($match['participants'][$counter]['stats'][$key]); } } $counter++; } unset($match['participantIdentities']); unset($match['teams']); //Strip events $frame_counter = 0; if (is_assoc($match['timeline']['frames'])) { return $match; //don't change doc at all } foreach ($match['timeline']['frames'] as $frame) { unset($match['timeline']['frames'][$frame_counter]['participantFrames']); if (isset($frame['events'])) { $counter = 0; foreach ($frame['events'] as $event) { if ($event['eventType'] != 'ITEM_PURCHASED') { unset($match['timeline']['frames'][$frame_counter]['events'][$counter]); } else { // if ($event['participantId'] != $support_1 && $event['participantId'] != $support_2 && !in_array($event['itemId'], $MAJOR_ITEMS['items'])) if (!in_array($event['itemId'], $MAJOR_ITEMS['items'])) { unset($match['timeline']['frames'][$frame_counter]['events'][$counter]); } //remove event if not a major purchase by non-support } $counter++; } if (count($match['timeline']['frames'][$frame_counter]['events']) == 0) { unset($match['timeline']['frames'][$frame_counter]); } } $frame_counter++; } return $match; }
public static function replace($subject, $variables) { if (is_array($variables) && is_assoc($variables)) { foreach ($variables as $key => $value) { $key = str_replace("[", "\\[", $key); $key = str_replace("]", "\\]", $key); $subject = preg_replace("/\\{\\{{$key}\\}\\}/", $value, $subject); } /* Remove any variables remaining */ $subject = preg_replace("/\\{\\{[^}]*\\}\\}/", "", $subject); } return $subject; }
public function setProperties($properties) { if (!is_array($properties)) { $properties = func_get_args(); } elseif (is_assoc($properties)) { foreach ($properties as $key => $value) { $this->settable_properties[$key] = $value; } return; } foreach ($properties as $property) { $this->settable_properties[$property] = ""; } }
function is_red($ob) { if (!is_array($ob)) { return false; } if (!is_assoc($ob)) { return false; } foreach ($ob as $val) { if ($val === 'red') { return true; } } return false; }
function recursive_add($obj) { $total = 0; foreach ($obj as $k => $v) { if (is_scalar($v)) { $total += $v; if ($v === "red" && is_assoc($obj)) { // part 2 return 0; } } else { $total += recursive_add($obj[$k]); } } return $total; }
public function parse() { if (!$this->map) { throw new CSVParserException('$map must be defined.'); } if (!is_assoc($this->map)) { throw new CSVParserException('$map must be associative.'); } if (!$this->delimiter) { throw new CSVParserException('$delimiter must be defined.'); } if (!$this->path) { throw new CSVParserException('$path must be defined.'); } $csv = $this->remote ? $this->_getRemoteCSV() : $this->_getLocalCSV(); return $csv; }
function print_select($name, $options = array(), $selected = NULL) { echo "<select name=\"{$name}\">"; if (!is_assoc($options)) { $new_options = array(); foreach ($options as $option) { $new_options[$option] = $option; } } foreach ($options as $option => $text) { $setxt = ""; if (!is_null($selected) && $selected == $option) { $setxt = " selected"; } echo "<option value=\"{$option}\"{$setxt}>{$text}</option>"; } echo "</select>"; }
function icon_switch($case, $icons) { $icon = ''; if (is_numeric($case) && !is_assoc($icons)) { $case %= count($icons); } if (isset($icons[$case])) { if (is_array($icons[$case])) { $icon = $icons[$case]['icon']; $url = isset($icons[$case]['url']) ? $icons[$case]['url'] : FALSE; $attr = isset($icons[$case]['attr']) ? $icons[$case]['attr'] : array(); $icon = icon($icon, $url, $attr); } else { $icon = icon($icons[$case]); } } return $icon; }
function convert($currency_value, $your_currencies) { global $exchangeRates, $currencies; if (isset($your_currencies)) { $list_currencies = $your_currencies; } elseif (isset($currencies)) { $list_currencies = $currencies; } else { $list_currencies = (array) $exchangeRates->rates; } foreach ($list_currencies as $key => $value) { if (is_assoc($list_currencies)) { $return_list[$key] = convert_to($currency_value, $key); } else { $return_list[$value] = convert_to($currency_value, $value); } } return $return_list; }
public function package_maintainers() { $this->package = Package::find_by_name($_GET['name']); $data = unserialize(Version::find('first', array('conditions' => array('package_id' => $this->package->id)))->meta); $this->maintainers = array(); foreach (array('lead', 'developer', 'contributor', 'helper') as $role) { if (isset($data[$role]) && !empty($data[$role])) { if (!is_assoc($data[$role])) { foreach ($data[$role] as $node) { $node['role'] = $role; $this->maintainers[] = $node; } } else { $data[$role]['role'] = $role; $this->maintainers[] = $data[$role]; } } } }
public function __construct($o = array()) { if (!$o) { throw new \Exception('Constructor arguments required.'); } if (!\is_assoc($o)) { throw new \Exception('Contsructor argument needs to be associative.'); } $o = (object) $o; $this->codebase_paths = $o->codebase_paths; $this->db = $o->db; if ($o->page_path_default) { $this->page_path_default = $o->page_path_default; } if ($o->page_path_404) { $this->page_path_404 = $o->page_path_404; } $this->uri = $o->uri; }
function toXml(&$xml, $parentnode, $tag, $data) { if (is_assoc($data)) { $node = $xml->createElement($tag); foreach ($data as $key => $val) { toXml($xml, $node, $key, $val); } } else { if (is_array($data)) { $node = $xml->createElement($tag); foreach ($data as $val) { toXml($xml, $node, 'item', $val); } } else { $node = $xml->createElement($tag, $data); } } $parentnode->appendChild($node); }
function ws_confidence($prediction, $distribution, $ws_z = 1.96, $ws_n = null) { /* Wilson score interval computation of the distribution for the prediction expected arguments: prediction: the value of the prediction for which confidence is computed distribution: a distribution-like structure of predictions and the associated weights. (e.g. array(('Iris-setosa', 10), ('Iris-versicolor', 5)) ws_z: percentile of the standard normal distribution ws_n: total number of instances in the distribution. If absent, the number is computed as the sum of weights in the provided distribution */ if (!is_assoc($distribution)) { $new_distribution = array(); foreach ($distribution as $item) { $new_distribution[$item[0]] = $item[1]; } $distribution = $new_distribution; } $ws_p = $distribution[$prediction]; if ($ws_p < 0) { throw new Exception("The distribution weight must be a positive value"); } $ws_norm = floatval(array_sum($distribution)); if ($ws_norm != 1.0) { $ws_p = $ws_p / $ws_norm; } if ($ws_n == null) { $ws_n = $ws_norm; } else { $ws_n = floatval($ws_n); } if ($ws_n < 1) { throw new Exception("The total of instances in the distribution must be a positive integer"); } $ws_z = floatval($ws_z); $ws_z2 = $ws_z * $ws_z; $ws_factor = floatval($ws_z2) / floatval($ws_n); $ws_sqrt = sqrt(($ws_p * (1.0 - $ws_p) + $ws_factor / 4.0) / $ws_n); return ($ws_p + $ws_factor / 2 - $ws_z * $ws_sqrt) / (1 + $ws_factor); }
/** * Sky Mustache Constructor * @param string $mustache mustache filename (relative to calling php file or codebase) OR mustache markup string containing at least one {{tag}} * @param mixed $data object with properties/methods or array of values/functions * @param mixed $partials see usage notes above * @param mixed $path see usage notes above * @return string */ public function __construct($mustache, $data, $partials = null, $path = null) { // if $partials is not an associative array, assume it is $path if (!\is_assoc($partials)) { // $path was provided as the 3rd param // ignore the 4th param $path = $partials; $partials = null; } $paths = \arrayify($path); // get the mustache markup $markup = $this->getMarkup($mustache); if (!$markup) { // the requested mustache file is not in the include path // so let's try to find it relative to the path(s) provided $markup = $this->getMarkup($mustache, $paths); } $this->markup = $markup; $this->data = $data; $this->partials = $this->getPartials($markup, $paths, $partials); }
function print_as_json($arr_key, $arr, $level = 0) { if (!is_array($arr)) { echo_line($arr_key . ' : ' . $arr . ',', $level); return; } $is_assoc = is_assoc($arr); if ($arr_key !== '' && !is_int($arr_key)) { $arr_key .= ' : '; } if (is_int($arr_key)) { $arr_key = !$is_assoc ? '[' : '{'; } else { $arr_key = $arr_key . (!$is_assoc ? '[' : '{'); } echo_line($arr_key, $level); foreach ($arr as $key => $value) { print_as_json($key, $value, $level + 1); } echo_line(!$is_assoc ? '],' : '},', $level); }
public function package_maintainers() { $this->package = Package::find_by_name($_GET['name']); $date = DateHelper::from_db($this->package->updated_at); $date = date(DATE_RFC822, $date); $this->header("Last-Modified: {$date}"); $data = unserialize(Version::find('first', array('conditions' => array('package_id' => $this->package->id)))->meta); $this->maintainers = array(); foreach (array('lead', 'developer', 'contributor', 'helper') as $role) { if (isset($data[$role]) && !empty($data[$role])) { if (!is_assoc($data[$role])) { foreach ($data[$role] as $node) { $node['role'] = $role; $this->maintainers[] = $node; } } else { $data[$role]['role'] = $role; $this->maintainers[] = $data[$role]; } } } }
private function normalizeCollection($collection_name, $collection) { $normalized_collections = []; if (is_assoc($collection)) { #inspect($collection, True); #$var_data = [$collection_name => $collection]; #$normalized_collections = $this->mergeCollections($normalized_collections, $var_data); #inspect($collection, $var_data, $normalized_collections, True); } else { foreach ($collection as $object) { if (is_array($object)) { if (array_key_exists('id', $object)) { $result = $this->normalizeObject($object); $normalized_collections = $this->mergeCollections($normalized_collections, $result['collections'], [$collection_name => [$result['object']]]); } } else { #inspect($collection_name, [$collection_name => $object]); #$normalized_collections = $this->mergeCollections($normalized_collections, [$collection_name => $object]); } } } return $normalized_collections; }
function array2object($data) { if (!is_array($data)) { return $data; } $is_assoc = is_assoc($data); $object = new stdClass(); if (count($data) == 0) { return $data; } if (is_array($data) && count($data) > 0) { foreach ($data as $name => $value) { if ($name !== '') { $object->{$name} = array2object($value); $data[$name] = array2object($value); } } } if ($is_assoc) { return $object; } else { return $data; } }
public function load_by_image_id_and_actions($image_id, $actions) { $this->initialise(); if (is_assoc($actions)) { $sql = $this->data_source->sql; $sql->select('*')->from($this->table_name); $where = new sql_and(new sql_cond('image_id', sql::EQUALS, sql::q($image_id)), new sql_cond('date_deleted', sql::IS, new sql_null())); $key_pairs = ['action_resized_to_height' => 'No', 'action_resized_to_width' => 'No', 'action_resized' => 'No', 'action_scaled' => 'No', 'action_gaussian_blur' => 'No', 'action_cropped' => 'No', 'action_cropped_from_center' => 'No', 'action_squared' => 'No']; if (isset($actions['actions'])) { $actions['actions'] = explode(",", $actions['actions']); foreach ($actions['actions'] as $action) { switch ($action) { case "resize_to_height": $key_pairs['action_resized_to_height'] = 'Yes'; $key_pairs['height'] = $actions['height']; break; case "resize_to_width": $key_pairs['action_resized_to_width'] = 'Yes'; $key_pairs['width'] = $actions['width']; break; case "resize": $key_pairs['action_resized'] = 'Yes'; $key_pairs['height'] = $actions['height']; $key_pairs['width'] = $actions['width']; break; case "scale": $key_pairs['action_scaled'] = 'Yes'; $key_pairs['scale'] = $actions['scale']; break; case "gaussian_blur": $key_pairs['action_gaussian_blur'] = 'Yes'; break; case "crop": $key_pairs['action_cropped'] = 'Yes'; $key_pairs['height'] = $actions['height']; $key_pairs['width'] = $actions['width']; $key_pairs['start_x'] = $actions['x']; $key_pairs['start_y'] = $actions['y']; break; case "crop_from_center": $key_pairs['action_cropped_from_center'] = 'Yes'; $key_pairs['height'] = $actions['height']; $key_pairs['width'] = $actions['width']; break; case "square": $key_pairs['action_squared'] = 'Yes'; $key_pairs['size'] = $actions['size']; break; } } } foreach ($key_pairs as $key => $value) { if ($value) { $where->add(new sql_cond($key, sql::EQUALS, sql::q($value))); } } $sql->where($where); $results = $sql->execute()->results(); if (count($results)) { return $this->load_by_data($results[0]); } } else { $this->error('No actions provided'); } return false; }
function report_row(&$rows, &$data) { global $output_format, $ajax, $ajax_capable; global $csv_row_sep, $csv_col_sep; global $custom_fields, $field_natures, $field_lengths, $tbl_entry; global $approval_somewhere, $confirmation_somewhere; global $strftime_format; global $select_options; global $field_order_list; // If we're capable of delivering an Ajax request and this is not Ajax request, // then don't do anything. We're going to save sending the data until we actually // get the Ajax request; we just send the rest of the page at this stage. if ($output_format == OUTPUT_HTML && $ajax_capable && !$ajax) { return; } $values = array(); foreach ($field_order_list as $field) { $value = $data[$field]; // Some fields need some special processing to turn the raw value into something // more meaningful switch ($field) { case 'end_time': // Calculate the duration and then fall through to calculating the end date // Need the duration in seconds for sorting. Have to correct it for DST // changes so that the user sees what he expects to see $duration_seconds = $data['end_time'] - $data['start_time']; $duration_seconds -= cross_dst($data['start_time'], $data['end_time']); $d = get_duration($data['start_time'], $data['end_time'], $data['enable_periods']); $d_string = $d['duration'] . ' ' . $d['dur_units']; $d_string = escape($d_string); case 'start_time': $mod_time = $field == 'start_time' ? 0 : -1; if ($data['enable_periods']) { list(, $date) = period_date_string($value, $mod_time); } else { $date = time_date_string($value); } $value = $date; break; case 'type': $value = get_type_vocab($value); break; case 'confirmation_enabled': // Translate the status field bit into meaningful text if ($data['confirmation_enabled']) { $value = $data['status'] & STATUS_TENTATIVE ? get_vocab("tentative") : get_vocab("confirmed"); } else { $value = ''; } break; case 'approval_enabled': // Translate the status field bit into meaningful text if ($data['approval_enabled']) { $value = $data['status'] & STATUS_AWAITING_APPROVAL ? get_vocab("awaiting_approval") : get_vocab("approved"); } else { $value = ''; } break; case 'last_updated': $value = time_date_string($value); break; default: // Custom fields if (array_key_exists($field, $custom_fields)) { // Output a yes/no if it's a boolean or integer <= 2 bytes (which we will // assume are intended to be booleans) if ($field_natures[$field] == 'boolean' || $field_natures[$field] == 'integer' && isset($field_lengths[$field]) && $field_lengths[$field] <= 2) { $value = empty($value) ? get_vocab("no") : get_vocab("yes"); } elseif (isset($value)) { // If the custom field is an associative array then we want // the value rather than the array key (provided the key is not // an empty string) if (isset($select_options["entry.{$field}"]) && is_assoc($select_options["entry.{$field}"]) && array_key_exists($value, $select_options["entry.{$field}"]) && $value !== '') { $value = $select_options["entry.{$field}"][$value]; } } else { $value = ''; } } break; } $value = escape($value); // For HTML output we take special action for some fields if ($output_format == OUTPUT_HTML) { switch ($field) { case 'name': // Add a link to the entry and also a data-id value for the Bulk Delete JavaScript $value = "<a href=\"view_entry.php?id=" . $data['id'] . "\"" . " data-id=\"" . $data['id'] . "\"" . " title=\"{$value}\">{$value}</a>"; break; case 'end_time': // Process the duration and then fall through to the end_time // Include the duration in a seconds as a title in an empty span so // that the column can be sorted and filtered properly $d_string = "<span title=\"{$duration_seconds}\"></span>{$d_string}"; case 'start_time': case 'last_updated': // Include the numeric time as a title in an empty span so // that the column can be sorted and filtered properly $value = "<span title=\"{$data[$field]}\"></span>{$value}"; break; default: break; } } // Add the value to the array. We don't bother with some fields if // they are going to be irrelevant if (($confirmation_somewhere || $field != 'confirmation_enabled') && ($approval_somewhere || $field != 'approval_enabled')) { $values[] = $value; } // Special action for the duration if ($field == 'end_time') { $values[] = $d_string; } } // foreach $rows[] = $values; }
/** * loads the document into DOM recursively from an array or object/SimpleXMLelement. It's supposed to be private, but * due to PHP not supporting friend classes it's made public * @param DOMDocument &$subdoc into which the nodes are being loaded * @param DOMNode &$destNode destination node * @param string|array|object|SimpleXMLElement &$srcNode source node */ public static function _loadIntoDom(&$subdoc, &$destNode, &$srcNode) { foreach ($srcNode as $key => $value) { $newDestNode = $subdoc->createElement($key); $destNode->appendChild($newDestNode); if (is_array($value)) { // array - associative or not? if (is_assoc($value)) { self::_loadIntoDom($subdoc, $newDestNode, $value); } else { $c = 0; foreach ($value as &$v) { if ($c) { $newDestNode = $subdoc->createElement($key); $destNode->appendChild($newDestNode); } if (is_string($v) || is_float($v) || is_int($v) || $v instanceof SimpleXMLElement && count($v->children()) == 0) { if (!CPS_Request::isValidUTF8((string) $v)) { throw new CPS_Exception(array(array('long_message' => 'Invalid UTF-8 encoding in key = \'' . $key . '\'', 'code' => ERROR_CODE_INVALID_UTF8, 'level' => 'ERROR', 'source' => 'CPS_API'))); } $textNode = $subdoc->createTextNode((string) self::getValidXmlValue($v)); $newDestNode->appendChild($textNode); } else { self::_loadIntoDom($subdoc, $newDestNode, $v); } /* $textNode = $subdoc->createTextNode($v); $newDestNode->appendChild($textNode);*/ ++$c; } } } else { if (is_object($value) && $value instanceof SimpleXMLElement) { $domNode = dom_import_simplexml($value); $domNode2 = $subdoc->importNode($domNode, true); $destNode->replaceChild($domNode2, $newDestNode); } else { if (is_object($value)) { self::_loadIntoDom($subdoc, $newDestNode, $value); } else { if (is_string($value) || is_float($value) || is_int($value)) { if (!CPS_Request::isValidUTF8((string) $value)) { throw new CPS_Exception(array(array('long_message' => 'Invalid UTF-8 encoding in key = \'' . $key . '\'', 'code' => ERROR_CODE_INVALID_UTF8, 'level' => 'ERROR', 'source' => 'CPS_API'))); } $textNode = $subdoc->createTextNode((string) self::getValidXmlValue($value)); $newDestNode->appendChild($textNode); } } } } } }