function display($args) { $show = array_get_default($args, 'show', 'home'); $page = null; foreach ($this->pages as $page) { if ($page['name'] == $show) { break; } } if (!$page) { $show = 'home'; $main_show = 'home'; } else { $main_show = array_key_exists('parent', $page) ? $page['parent'] : $show; } $args['show'] = $show; // Go to monitor if no id is specified $id = array_get_default($args, 'id', ''); if ($id == '') { header('Location: ../?' . http_build_query($args)); exit; } // Display menu $menu = $this->display_menu($main_show); $this->append(ax_ul_items($menu, array('id' => 'tablist'))); foreach ($this->forms as $form) { if ($form['name'] == $show) { break; } } if (!$form or $form['name'] != $show) { return; } $title = $form['descr']; $form = new $form['class']($args); if ($form->get_data($id)) { // Editing existing entity $title .= " {$id}"; } else { // Adding new entity $form->set_control_value('id', ''); $id = ""; unset($args['id']); $title .= " (new)"; } if (Request::is_post()) { $form->fill($_POST); $msg = $form->save_data(); $id = $form->get_control_value('id'); $form->get_data($id); if ($msg != "") { $this->append(ax_p($msg)); } } $fr = new AnewtFormRendererDefault(); $fr->set_form($form); $this->append(ax_h2($title)); $this->append($fr); }
/** * This function redirects the browser and stops further processing. There's no * need to call die()/exit() after calling this function, because execution * stops at the end of this method. * * \param $location An optional parameter specifying the url to redirect to. * This defaults to / (used if omitted). You can also use a numeric -1 to use * the HTTP referrer if available (will default to / if no referrer was sent). * * \param $http_status An optional parameter specifying the http status to be * sent back to the browser. If omitted, HTTP/1.1 302: Found will be used. * * Examples: * * \code * redirect(); // redirect to / * redirect('/foo'); // redirect to /foo * redirect('/bar', HTTP_STATUS_MOVED_PERMANENTLY); * // redirect to /bar with a * // permanent redirect (i.e. client should remember * // the new address instead of the old one) * redirect(-1); // redirect to the referring page * \endcode */ function redirect($location = '/', $http_status = HTTP_STATUS_FOUND) { /* Use the referring page (or the root url if not available) when the * special value -1 was specified */ if ($location === -1) { $location = array_get_default($_SERVER, 'HTTP_REFERER', '/'); } assert('is_string($location)'); assert('is_int($http_status)'); assert('($http_status == HTTP_STATUS_FOUND) || ($http_status == HTTP_STATUS_MOVED_PERMANENTLY)'); /* Only send custom HTTP header if it's not the default */ if ($http_status != HTTP_STATUS_FOUND) { header(sprintf('HTTP/1.1 %03d', $http_status)); } header('Location: ' . $location); die; }
/** * Returns a boolean value from an array specified by a given key or the default * value if the key does not exist. If the value is a string, it will be * validated and converted to a boolean. Recognized strings: 1, 0, true, false, * yes, no, on, off. * * \param $arr * The array containing the data. * * \param $key * The key, given as int or string. * * \param $default * The default return value if no value was found. * * \return * A boolean value or null if no default value was specified. * * \see * array_get_default * * \todo * Write tests for this method */ function array_get_bool($arr, $key, $default = null) { $value = array_get_default($arr, $key, $default); if (is_bool($value)) { return $value; } if (preg_match('/^(1|true|yes|on)$/', $value)) { return true; } if (preg_match('/^(0|false|no|off)$/', $value)) { return false; } assert('is_null($default) || is_bool($default)'); return $default; }
/** * \protected * * Fetch default value from the row data, based on the cell renderer id. * This method is used internally to fetch the cell data from the row data * object. Both associative arrays and Container objects are handled. Which * value is retrieved depends on the <code>id</code> of the cell renderer; * if you did not instantiate an AnewtGridCellRenderer yourself, this is * will be the same as the column <code>id</code>. * * Custom AnewtGridCellRenderer subclasses may use this method as * a convenience method to get data from the row object prior to further * processing or formatting. * * \param $data * Row data * * \return * Value extracted from row data, based on the <code>id</code> */ function fetch_value_from_data($data) { /* Handle arrays, */ if (is_assoc_array($data)) { $value = array_get_default($data, $this->id, null); } elseif ($data instanceof Container) { $value = $data->getdefault($this->id, null); } else { trigger_error('AnewtGridCellRenderer::render_cell(): This cell renderer can only render associative arrays and Container objects.', E_USER_ERROR); } return $value; }
/** * Adds a mapping to the list of url mappings. * * \param $command_name * The name of the command to invoke when this url mapping matches. This * should be a simple string, eg. "archive". This string will be prefixed * with "command_" and called if the url matches, eg. the method * command_archive() will be called. This callback method needs to handle * the url. * * \param $url * The url pattern to match. Variable url parts should have a colon * prefix. Example: /news/:year/:month/:slug/comments. The year, month and * slug variables will be passed in an array to the method handling the * request if the url matches. * * \param $requirements * Optional parameter with regular expressions to match against the * variables in the url. Only variables matching the regular expression * will be handled by this mapping. This way you can be sure your method * will always be called with valid parameters (so you don't need to * repeat the input checking in your handler methods). Example: * array('year' => '/^\\d{4}$/', 'month' => '/^\\d{2}$/') * */ function add_urlmap($command_name, $url, $requirements = null) { /* Requirements are optional */ if (is_null($requirements)) { $requirements = array(); } /* Sanity checks */ assert('is_string($command_name) && strlen($command_name)'); assert('is_assoc_array($requirements)'); /* Split the url into smaller pieces. We split on the forward slash * character and put the parts in a list after stripping of leading and * trailing slashes. Eg. /foo/bar/baz/ is split in (foo, bar, baz). */ if (is_string($url)) { $url = str_strip_prefix($url, '/'); $url = str_strip_suffix($url, '/'); /* Special case for top level urls */ if (strlen($url) == 0) { $parts = array(); // no parts } else { $parts = split('/', $url); } } else { assert('is_array($url)'); $parts = array_trim_strings($url, '/'); } /* Parse the pieces and parameters */ $map = array(); foreach ($parts as $part) { /* Handle variables */ if (str_has_prefix($part, ':')) { $part = substr($part, 1); $requirement = array_get_default($requirements, $part, null); $map[] = array($part, $requirement); /* No variable */ } else { $map[] = $part; } } /* Add the url map to the list of registered url maps */ $urlmap = array($command_name, $map); $this->urlmaps[] = $urlmap; }
/** \{ * \name Methods for getting and setting values */ function fill($values) { /* See AnewtFormControl::fill() for why: */ if (!$this->_get('can-be-filled')) { return true; } if ($this->_get('disabled')) { return true; } /* If none of the values in the choice control are selected, there is no * value for this control in $values (just like for checkboxes). */ $name = $this->get('name'); $value = array_get_default($values, $name, null); parent::fill(array($name => $value)); /* Filling succeeds if... */ return $this->get('multiple') || array_has_key($values, $name) || $this->all_disabled(); /* (3) if all options are disabled */ }
/** * Gets a string from the COOKIE data. * * \param $key The name of the string. * \param $default The default value to return if no string was found. If * you omit this parameter, null is used. * * \return A string or the default value. */ public static function cookie_string($key, $default = null) { return array_get_default($_COOKIE, $key, $default); }
function prepare_query($q, $field_name = null) { $where = array(); foreach ($this->fields as $f) { if (isset($this->params[$f])) { $val = $this->params[$f]; $f = array_get_default($this->field_opts[$f], 'sql-name', $f); if (str_has_prefix($val, 'HAS:')) { $val = preg_replace('/^HAS:/', '', $val); array_push($where, sprintf("FIND_IN_SET('%s', %s)", mysql_real_escape_string($val), $f)); } elseif (str_has_prefix($val, 'LIKE:')) { $val = preg_replace('/^LIKE:/', '', $val); array_push($where, sprintf("%s LIKE '%s'", $f, mysql_real_escape_string($val))); } else { if (!is_numeric($val)) { $val = "'" . mysql_real_escape_string($val) . "'"; } array_push($where, sprintf("%s=%s", $f, $val)); } } } if ($this->time_field and $this->interval != '' and $this->interval != '*') { array_push($where, sprintf("(`%s` > NOW() - INTERVAL %s)", $this->time_field, $this->interval)); } $where = implode(' AND ', $where); $this->query_restriction = $where; if (str_contains($q, '?where?')) { if ($where) { $where = "WHERE {$where}"; } $q = str_replace('?where?', $where, $q); #$q = str_replace('?where?', '', $q); #die($qqq); } elseif (str_contains($q, '?where-and?')) { if ($where) { $where = "AND {$where}"; } $q = str_replace('?where-and?', $where, $q); } if (str_contains($q, '?temp-constraint?')) { $q = str_replace('?temp-constraint?', sprintf("(`%s` > NOW() - INTERVAL %s)", $field_name, $this->interval), $q); } $order_by = array_get_default($this->field_opts[$this->order_by], 'sql-name', $this->order_by); //$order_by = $this->order_by; $q = $q . " ORDER BY " . $order_by . " " . $this->order_dir . " LIMIT " . ($this->limit + 1) . " OFFSET " . $this->offset; return $q; }
/** * Return the HTTP referer of the current request, if any. This method uses * the HTTP_REFERER header in the HTTP request, and will return null if no * referer was set. * * \return * The refererring url of the current request, or null. */ static function referer() { return array_get_default($_SERVER, 'HTTP_REFERER', null); }
/** * Find one or more records by providing a part of the SQL query. * * \param $class Class name * * \param $just_one_result * Whether to return just one instance (or null) or an array of instances * * \param $sql The constraints of the SQL query * \param $values Array with placeholder values * * \param $connection AnewtDatabaseConnection instance */ protected static final function _db_find_by_sql($class, $just_one_result = false, $sql = null, $values = array(), $connection) { assert('is_string($class)'); assert('is_bool($just_one_result)'); assert('is_null($sql) || is_string($sql) || is_assoc_array($sql)'); assert('is_array($values)'); assert('$connection instanceof AnewtDatabaseConnection'); /* Table alias. * * Several possibilities exist: * - no alias, * - alias provided explicitly, or * - not specified but still needed. */ $table_alias = null; if (is_assoc_array($sql)) { /* Table alias might be provided explicitly */ $table_alias = array_get_default($sql, 'table-alias', null); /* If JOINs are used, a table alias must be used for all columns in * the SELECT clause to avoid ambiguous column names if the same * column names are used in one of the JOINed tables. If no * table-alias is provided explicitly, the table name is reused. */ if (is_null($table_alias) && array_key_exists('join', $sql)) { $table_alias = call_user_func(array($class, 'db_table')); } } /* Standard query parts */ $sql_select = AnewtAutoRecord::_db_sql_select($class, $table_alias, $connection); $sql_from = AnewtAutoRecord::_db_sql_from($class, $table_alias, $connection); $sql_order_by = AnewtAutoRecord::_db_sql_order_by($class, $table_alias, $connection); /* Build the SQL query. * * There are three possibilities for the $sql parameter: * 1. null * 2. a string * 3. an associative array */ if (is_null($sql)) { /* No SQL: find all records */ $sql_order_by_full = is_null($sql_order_by) ? '' : sprintf('ORDER BY %s', $sql_order_by); $sql_full = $connection->create_sql_template('SELECT ?raw? FROM ?raw? ?raw?;')->fill($sql_select, $sql_from, $sql_order_by_full); } elseif (is_string($sql)) { /* SQL string */ $sql_with_values = $connection->create_sql_template($sql)->fillv($values); $sql_full = $connection->create_sql_template('SELECT ?raw? FROM ?raw? ?raw?;')->fill($sql_select, $sql_from, $sql_with_values); } else { /* Associative array with SQL */ $sql_parts = array(); /* SELECT and possible additions */ $sql_select_addition = array_get_default($sql, 'select', null); if ($sql_select_addition) { $sql_select = sprintf('%s, %s', $sql_select, $sql_select_addition); } /* WHERE */ $sql_where = array_get_default($sql, 'where', null); if (!is_null($sql_where)) { $sql_parts[] = sprintf('WHERE %s', $sql_where); } /* JOIN */ $sql_join = array_get_default($sql, 'join', null); if (!is_null($sql_join)) { $sql_from = sprintf('%s %s', $sql_from, $sql_join); } /* ORDER BY */ $sql_order_by = array_get_default($sql, 'order-by', $sql_order_by); if (!is_null($sql_order_by)) { $sql_parts[] = sprintf('ORDER BY %s', $sql_order_by); } /* LIMIT. Note that "optimizing" this depending on the value of * $just_one_result is impossible since it may contain a placeholder * string and not a literal value. We take care of $just_one_result * when fetching the result rows. */ $sql_limit = array_get_default($sql, 'limit', null); if (!is_null($sql_limit)) { $sql_parts[] = sprintf('LIMIT %s', $sql_limit); } /* OFFSET */ $sql_offset = array_get_default($sql, 'offset', null); if (!is_null($sql_offset)) { $sql_parts[] = sprintf('OFFSET %s', $sql_offset); } /* Combine */ $sql_parts_combined = $connection->create_sql_template(join(' ', $sql_parts))->fillv($values); $sql_full = $connection->create_sql_template('SELECT ?raw? FROM ?raw? ?raw?;')->fill($sql_select, $sql_from, $sql_parts_combined); } /* Fetch resulting row(s) and create AnewtAutoRecord instances. * * The generated SQL query may contain placeholders (e.g. the string * '?int?' could be somewhere in a value), but those must not be parsed * by AnewtDatabaseSQLTemplate. Since the generated SQL is already fully * escaped, it is passed as a single value for a ?raw? query. See * bug:502916 for more information. */ if ($just_one_result) { $row = $connection->prepare_execute_fetch_one('?raw?', $sql_full); if (!$row) { return null; } return AnewtAutoRecord::_db_object_from_array($class, $row); } else { $rows = $connection->prepare_execute_fetch_all('?raw?', $sql_full); return AnewtAutoRecord::_db_objects_from_arrays($class, $rows); } }
/** * Opens the SQLite database. * * \param settings An associative array with connection settings: the * 'filename' and 'mode' indices will be used (but mode is optional). */ function connect(array $settings) { is_array($settings) && array_has_key($settings, 'filename') or trigger_error('Invalid parameters to connect()', E_USER_ERROR); $mode = array_get_default($settings, 'mode', 0666); $this->handle = sqlite_open($settings['filename'], $mode, $error) or trigger_error(sprintf('Could not open database (%s)', $error), E_USER_ERROR); }
/** * Convert HTTP error code into a string. * * Returns the appropriate human readable status string for the given status * code as per rfc2616. * * \param $http_status * The HTTP status ok, e.g. \c 200 * * \return * A string with the status code */ function http_status_to_string($http_status) { assert('is_int($http_status)'); global $__anewt_http_status_strings; return array_get_default($__anewt_http_status_strings, $http_status, 'Unknown HTTP status code'); }
/** * Escapes a column name for SQL queries. * * \param $str The string to escape. * * \return The escaped string. */ function escape_column_name($str) { assert('is_string($str)'); if (!array_get_default($this->settings, 'escape_column_names', true)) { return $str; } return $this->_escape_column_or_table_name($str); }
function display($args) { $show = array_get_default($args, 'show', 'home'); $page = null; foreach ($this->pages as $page) { if ($page['name'] == $show) { break; } } if (!$page) { $show = 'home'; $main_show = 'home'; } else { $main_show = array_key_exists('parent', $page) ? $page['parent'] : $show; } $args['show'] = $show; $menu = $this->display_menu($main_show); $this->append(ax_ul_items($menu, array('id' => 'tablist'))); foreach ($this->pages as $page) { if ($page['name'] == $show) { // show header first $this->append(ax_h2($page['descr'])); // then submenu $submenu = $this->display_menu($show, $main_show); $this->append(ax_ul_items($submenu, array('id' => 'subtablist'))); // and finally the page $display = new $page['class']($this, $args, $this->pages); $display->show(); } } }
/** * Return a variable from the configuration data, returning a default value * if the value is not available. * * \param $name * The variable name. * * \param $default * The default value returned if the value was not found. * * \return * The value of the variable. * * \see array_get_default */ public static function getdefault($name, $default) { assert('is_string($name)'); global $_anewt_config; return array_get_default($_anewt_config, $name, $default); }
#!/usr/bin/php -q <?php require_once '../anewt.lib.php'; anewt_include('mail'); $m = new AnewtMailMessage(); function usage() { printf("Usage: %s address\n", $_SERVER['argv'][0]); exit(1); } $address = array_get_default($_SERVER['argv'], 1, null); if (is_null($address)) { echo 'Error: no address specified', NL; usage(); } $m->add_header('To', $address); $m->add_header('Subject', 'Test'); $m->add_header('From', $address); $m->set('body', 'This is a test message sent using the AnewtMailMessage class.'); $result = $m->send(); if ($result) { echo 'Mail sent successfully.', NL; } else { echo 'Sending mail failed.', NL; }
/** * Connects to the database using the specified connection settings. * * \param $settings * An associative array of connection settings. Set the \c debug and * \c debug_print keys to true if you want to debug your queries. */ function connect($settings = null) { /* Connect only once */ if (!$this->connected) { if (is_null($settings)) { if (is_null($this->settings)) { trigger_error('Cannot connect to database, no settings are specified.', E_USER_ERROR); } $settings = $this->settings; } assert('is_assoc_array($settings)'); $this->backend->connect($settings); $this->connected = true; $this->debug = array_get_default($settings, 'debug', false); $this->debug_print = array_get_default($settings, 'debug_print', false); unset($this->settings); } }