Esempio n. 1
0
 function build_widget()
 {
     $id = $this->get('id');
     $attr = array('name' => $this->get('name'), 'id' => $id, 'type' => 'checkbox');
     if ($this->_get('disabled')) {
         $attr['disabled'] = 'disabled';
     }
     if ($this->_get('value')) {
         $attr['checked'] = 'checked';
     }
     /* Note: Checkboxes cannot be set readonly (only from JavaScript) */
     $help = $this->_get('help');
     if (!is_null($help)) {
         $help_text = to_string($help);
         $attr['title'] = $help_text;
         $attr['class'] = 'with-help';
     }
     /* Output */
     $input = new AnewtXHTMLInput(null, $attr);
     $secondary_label = $this->_get('secondary-label');
     if (is_null($secondary_label)) {
         $out = $input;
     } else {
         $label_attr = array();
         if (!is_null($help)) {
             $label_attr['title'] = $help_text;
             $label_attr['class'] = 'with-help';
         }
         $out = new AnewtXHTMLLabel($input, $secondary_label, $label_attr);
     }
     return $out;
 }
/**
 * Formats and simplifies the call stack backtrace log
 *
 * @param  array $backtrace The call stack to simplify
 * @return array            Formatted and simplified backtrace log
 */
function debug($arg1 = null, $arg2 = null)
{
    $vars = func_get_args();
    $bt = array_reverse(debug_backtrace($arg1));
    $c = $bt[count($bt) - 1];
    $call_line = str_replace(DIR_ROOT, '', $c['file']) . ':' . $c['line'];
    print <<<CSS
<style type="text/css">
.Debug     { font-family:sans-serif; border:2px solid #DDD; background-color:#DDD; padding:5px; font-size:13px; }
.Debug H3  { font-size:13px; margin:0 0 10px; padding:0; background-color:#DDD; color:#000; }
.Debug P   { margin:10px 0 0 0; }
.Debug PRE { font-size:14px; padding:3px 4px; margin:5px 0 0 0; background-color:#FFF; font-family:Consolas, monospace; }
</style>
CSS;
    print "<div class=\"Debug\">\n<h3>Debug at {$call_line}</h3>\n";
    foreach ($vars as $var) {
        print "<pre>" . nl2br(to_string($var, true)) . '</pre>';
    }
    $c = 0;
    print "<p>\n";
    foreach ($bt as $step) {
        $file = str_replace(DIR_ROOT, '', $step['file']);
        $line = $step['line'];
        $call = "<strong>" . $step['function'] . '</strong>(' . join(', ', array_map('to_string', $step['args'])) . ')';
        print "#{$c} <strong>{$file}</strong> called {$call} at line <strong>{$line}</strong><br/>\n";
        $c++;
    }
    print '</p>';
    print "</div>";
}
Esempio n. 3
0
 /**
  * Build widget HTML for this form control.
  */
 function build_widget()
 {
     /* Output <input ... /> */
     $attr = array('id' => $this->get('id'), 'type' => $this->_get('input-type'), 'class' => sprintf('button %s', $this->_get('extra-class')));
     if ($this->_get('render-name')) {
         $attr['name'] = $this->get('name');
     }
     $label = $this->get('label');
     if (!is_null($label)) {
         $attr['value'] = $label;
     }
     if ($this->get('disabled')) {
         $attr['disabled'] = 'disabled';
     }
     $widget = new AnewtXHTMLInput($attr);
     /* Optional extra class value */
     $class = $this->_get('class');
     if (!is_null($class)) {
         $widget->add_class($class);
     }
     /* Help text, if any */
     $help = $this->_get('help');
     if (!is_null($help)) {
         $help_text = to_string($help);
         $widget->set_attribute('title', $help_text);
         $widget->add_class('with-help');
     }
     return $widget;
 }
Esempio n. 4
0
 /**
  * Render this fragment into a string.
  *
  * This method renders all children and concenates those strings into one
  * single value. Usually XHTML fragments are not rendered directly, but
  * added to a DOM tree instead. When that happens, all child nodes of the
  * fragment are added to the DOM tree, and the document fragment instance
  * itself is no longer of any use. This means that this method is not
  * invoked if document fragments are used in combination with a proper DOM
  * document (e.g. as used by AnewtPage).
  *
  * \return
  *   Rendered XML output or an empty string if the fragment was empty.
  */
 function render()
 {
     $out = array();
     foreach ($this->child_nodes as $child_node) {
         $out[] = $child_node->render();
     }
     return to_string($out);
 }
Esempio n. 5
0
 function init($args)
 {
     $this->source = $args[0] === null ? '(?:)' : to_string($args[0]);
     $flags = array_key_exists('1', $args) ? to_string($args[1]) : '';
     $this->ignoreCaseFlag = strpos($flags, 'i') !== false;
     $this->globalFlag = strpos($flags, 'g') !== false;
     $this->multilineFlag = strpos($flags, 'm') !== false;
 }
Esempio n. 6
0
 function __construct($str = null)
 {
     parent::__construct();
     $this->proto = self::$protoObject;
     if (func_num_args() === 1) {
         $this->set('message', to_string($str));
     }
 }
Esempio n. 7
0
 public function update_core_settings($setting_key, $setting_value)
 {
     $this->db->where('key', $setting_key);
     $input = array('value' => $setting_value);
     $return = $this->db->update('settings', $input);
     ci()->cfg->{$setting_key} = to_string($setting_value);
     return $return;
 }
Esempio n. 8
0
 function __construct($value)
 {
     if ($value instanceof Error) {
         $message = $value->getMessage();
     } else {
         $message = to_string($value);
     }
     parent::__construct($message);
     $this->value = $value;
 }
Esempio n. 9
0
/**
 * Returns a string representation of an array
 * 
 * @param  array  $array  Array to be stringified
 * @param  bool   $html   Whether to prettify output with HTML and CSS
 * @return string         String representation of input array
 */
function array_to_string($array, $html = false)
{
    $fn = formatter($html ? '<em>%s</em>' : '%s');
    $s1 = $html ? "\n" : '';
    $s2 = $html ? "&nbsp;&nbsp;&nbsp;" : ' ';
    $OUT = array();
    $MAX = array_reduce(array_map('strlen', array_keys($array)), 'max');
    foreach ($array as $key => $val) {
        $SPACER = str_repeat('&nbsp;', max($MAX - strlen($key), 0));
        $OUT[] = to_string($key) . $SPACER . $fn(' = ') . str_replace("\n", $s2, to_string($val));
    }
    return $fn("[{$s2}") . join(",{$s2}", $OUT) . $fn("{$s1}]");
}
Esempio n. 10
0
 function to_string($arr)
 {
     $values = [];
     foreach ($arr as $k => $v) {
         if (is_array($v)) {
             $v = to_string($v);
         }
         if (is_string($v)) {
             $v = htmlspecialchars($v);
         }
         $v = Database::format($v);
         $values[] = "<b><i>{$k}</i></b>: {$v}";
     }
     return '{' . implode(', ', $values) . '}';
 }
Esempio n. 11
0
 /**
  * Creates the global constructor used in user-land
  * @return Func
  */
 static function getGlobalConstructor()
 {
     $String = new Func(function ($value = '') {
         $self = Func::getContext();
         if ($self instanceof Str) {
             $self->value = to_string($value);
             return $self;
         } else {
             return to_string($value);
         }
     });
     $String->instantiate = function () {
         return new Str();
     };
     $String->set('prototype', Str::$protoObject);
     $String->setMethods(Str::$classMethods, true, false, true);
     return $String;
 }
Esempio n. 12
0
 function init($args)
 {
     global $Buffer;
     list($subject, $encoding, $offset) = array_pad($args, 3, null);
     $type = gettype($subject);
     if ($type === 'integer' || $type === 'double') {
         $this->raw = str_repeat("", (int) $subject);
     } else {
         if ($type === 'string') {
             $encoding = $encoding === null ? 'utf8' : to_string($encoding);
             if ($encoding === 'hex') {
                 $this->raw = hex2bin($subject);
             } else {
                 if ($encoding === 'base64') {
                     $this->raw = base64_decode($subject);
                 } else {
                     $this->raw = $subject;
                 }
             }
         } else {
             if (_instanceof($subject, $Buffer)) {
                 $this->raw = $subject->raw;
             } else {
                 if ($subject instanceof Arr) {
                     $this->raw = $util['arrToRaw']($subject);
                 } else {
                     throw new Ex(Error::create('Invalid parameters to construct Buffer'));
                 }
             }
         }
     }
     $len = strlen($this->raw);
     //save an integer copy of length for performance
     $this->length = $len;
     $this->set('length', (double) $len);
 }
Esempio n. 13
0
 /**
  * Render this node to a string.
  *
  * \return
  *   Rendered string with XML data.
  */
 public function render()
 {
     $node_value_escaped = to_string($this->node_value);
     assert('is_string($node_value_escaped);');
     return $node_value_escaped;
 }
Esempio n. 14
0
 /**
  * Processes the text. This method will transform the input text into XHTML,
  * thereby converting headers, paragraphs, lists, block quotes and other
  * block elements into their corresponding XHTML tags. Hyperlinks, inline
  * markup (like emphasized or strong words), images and code is also
  * converted. Additionally, several typographic enhancements are made to
  * inline text (curly quotes, em dashes, entity replacements, etc).
  *
  * \param $text
  *   Input text in Textile format
  *
  * \return
  *   Processed text in XHTML format
  */
 function process($text)
 {
     /* Normalize */
     $text = $this->_normalize_text($text);
     /* Split into blocks */
     $blocks = $this->_split_into_blocks($text);
     /* Process each block */
     $out = array();
     foreach ($blocks as $block) {
         $out[] = $this->_process_block($block);
     }
     /* Result */
     return to_string($out);
 }
Esempio n. 15
0
/**
 * Join array elements with a string or DOM node.
 *
 * This is an XHTML-aware version of the built-in join() function.
 * 
 * \param $glue
 *   The glue string (or DOM node) to insert between each subsequent pair of
 *   values.
 *
 * \param $values
 *   The values to join together. These can be strings or DOM nodes.
 *
 * \return
 *   A DOM node instance containing the joined values.
 */
function ax_join($glue, $values)
{
    assert('is_numeric_array($values);');
    /* Make sure the glue is escaped properly */
    if ($glue instanceof AnewtXMLDomNode) {
        $glue = to_string($glue);
    } else {
        assert('is_string($glue)');
        $glue = htmlspecialchars($glue);
    }
    /* Build a format string so that ax_vsprintf() can do the real work */
    $glue = str_replace('%', '%%', $glue);
    $format = join($glue, array_fill(0, count($values), '%s'));
    return ax_vsprintf(ax_raw($format), $values);
}
Esempio n. 16
0
 static function checkInt($s)
 {
     if (is_int($s) && $s >= 0) {
         return (double) $s;
     }
     $s = to_string($s);
     $match = preg_match('/^\\d+$/', $s);
     return $match !== false ? (double) $s : null;
 }
Esempio n. 17
0
 /**
  * Build XHTML for a form control.
  *
  * \param $control
  *   An AnewtFormControl instance.
  */
 protected function _build_form_control_node($control)
 {
     $control_div = ax_div_class(null, 'form-control');
     $control_div->append_child($this->_build_description_node($control));
     $control_div->append_child($this->_build_error_node($control));
     /* Label and the widget itself are combined. Buttons do not have
      * explicit labels, since the label text is on the button itself. */
     $widget = $control->build_widget();
     $label_text = $control->_get('label');
     if (is_null($label_text) || $control instanceof AnewtFormControlButton) {
         /* No label (none set or this is a button) */
         $control_div->append_child($widget);
     } else {
         /* This control has a label */
         assert('is_string($label_text) || $label_text instanceof AnewtXMLDomNode');
         $label = new AnewtXHTMLLabel($label_text, array('class' => 'form-control'));
         /* Some composite widgets support allow the 'for=' attribute to be
          * filled in, even though they consist of multiple html widgets. */
         if ($control->get('composite')) {
             $composite_for = $control->get('composite-for');
             if (!is_null($composite_for)) {
                 $label->set_attribute('for', $composite_for);
             }
         } else {
             $label->set_attribute('for', $control->get('id'));
         }
         /* Help text */
         $help = $control->_get('help');
         if (!is_null($help)) {
             $help_text = to_string($help);
             $label->set_attribute('title', $help_text);
             $label->add_class('with-help');
         }
         $control_div->append_child($label);
         $control_div->append_child($widget);
         unset($label);
     }
     unset($widget);
     return $control_div;
 }
Esempio n. 18
0
 function build_widget()
 {
     $value = $this->_get('value');
     if (is_null($value)) {
         $value = "";
     }
     assert('is_string($value); // only plain strings can be used as field value: type: ' . gettype($value));
     $name = $this->get('name');
     $widgets = array();
     if ($this->get('show-img-preview') && $value) {
         $widgets[] = ax_div_class(ax_img_src($this->get('preview-dir') . $value), 'preview');
     } elseif ($this->get('show-link-preview') && $value) {
         $widgets[] = ax_div_class(ax_a_href($value, $this->get('preview-dir') . $value), 'preview');
     }
     $remove_label = $this->_get('remove-label');
     if ($remove_label && $value) {
         $subattr = array('type' => 'checkbox', 'name' => $name . '-remove');
         $widgets[] = new AnewtXHTMLInput(null, $subattr);
         $subattr = array('for' => $name . '-remove');
         $widgets[] = new AnewtXHTMLLabel($remove_label, $subattr);
         $widgets[] = ax_br();
     }
     /* XML tag attributes used both for single line and multiline */
     $attr = array('name' => $this->get('name'), 'id' => $this->get('id'), 'type' => 'file');
     if ($this->_get('readonly')) {
         $attr['readonly'] = 'readonly';
     }
     if ($this->_get('disabled')) {
         $attr['disabled'] = 'disabled';
     }
     $size = $this->_get('size');
     if (!is_null($size)) {
         assert('is_int($size);');
         $attr['size'] = (string) $size;
     }
     $maxlength = $this->_get('maxlength');
     if (!is_null($maxlength)) {
         assert('is_int($maxlength);');
         $attr['maxlength'] = (string) $maxlength;
     }
     $max_file_size = $this->_get('max_file_size');
     if (!is_null($max_file_size)) {
         $subattr = array('type' => 'hidden', 'name' => 'MAX_FILE_SIZE', 'value' => (string) $max_file_size);
         $widgets[] = new AnewtXHMTLInput(null, $subattr);
     }
     $widget = new AnewtXHTMLInput(null, $attr);
     /* Styling */
     $widget->add_class('fileupload');
     if (!$this->_get('required')) {
         $widget->add_class('optional');
     }
     /* Optional extra class value */
     $class = $this->_get('class');
     if (!is_null($class)) {
         $widget->add_class($class);
     }
     /* Help text, if any */
     $help = $this->_get('help');
     if (!is_null($help)) {
         $help_text = to_string($help);
         $widget->set_attribute('title', $help_text);
         $widget->add_class('with-help');
     }
     $widgets[] = $widget;
     /* Add secondary label, if any */
     $secondary_label = $this->_get('secondary-label');
     if (!is_null($secondary_label)) {
         $widgets[] = $secondary_label;
     }
     $out = ax_fragment($widgets);
     return $out;
 }
Esempio n. 19
0
<?php

// implicitly weak mode code
function to_int(int &$x)
{
}
function to_float(float &$x)
{
}
function to_string(string &$x)
{
}
function to_bool(bool &$x)
{
}
$x = 1.0;
var_dump($x);
to_int($x);
// because $x is by-reference, the weak type hint converts it
var_dump($x);
to_float($x);
var_dump($x);
to_string($x);
var_dump($x);
to_bool($x);
var_dump($x);
Esempio n. 20
0
/**
 * Format a text node using a format specifier and supplied values.
 *
 * This method acts like sprintf(), but supports DOM nodes and takes care of XML
 * escaping. This function formats its arguments into a (raw) DOM node instead
 * of a string. The supplied values may regular values such as strings and
 * numbers, but may be XML nodes as well. This means you can pass XML node
 * instances created by the functions in the xhtml module as values. The format
 * specifier will be escaped for XML, and XML nodes will be rendered into
 * escaped strings before substitution into the format specifier.
 *
 * This example results in a valid XHTML paragraph:
 *
 * <code>
 * ax_p(ax_sprintf('%s & %s', ax_span_class('Sugar', 'sweet'), 'Spice'));
 * </code>
 *
 * \param $format
 *   A format specifier in sprintf syntax.
 *
 * \param $values
 *   One or more values to be substituted into the format string.
 *
 * \return
 *   An AnewtXHTMLRaw instance that can be added to a DOM tree (or page).
 */
function ax_sprintf($format, $values)
{
    /* Accept multiple parameters, just like sprintf */
    $values = func_get_args();
    /* First parameter is the format */
    $format = array_shift($values);
    if ($format instanceof AnewtXMLDomNode) {
        $format = to_string($format);
    } else {
        assert('is_string($format)');
        $format = htmlspecialchars($format);
    }
    /* Render DOM nodes into strings. The $values array is modified in-place. */
    foreach (array_keys($values) as $key) {
        if (is_string($values[$key])) {
            $values[$key] = htmlspecialchars($values[$key]);
        } elseif ($values[$key] instanceof AnewtXMLDomNode) {
            $values[$key] = to_string($values[$key]);
        }
    }
    /* Everything is already escaped, so return a raw node */
    return ax_raw(vsprintf($format, $values));
}
Esempio n. 21
0
                }
            }
        }
        return $headers;
    }, 'getRemoteAddress' => function () use(&$SERVER) {
        return isset($SERVER['REMOTE_ADDR']) ? $SERVER['REMOTE_ADDR'] : '127.0.0.1';
    }, 'read' => function ($bytes) {
        throw new Ex(Error::create('not implemented: Request.read()'));
    });
    $request = new Object();
    $request->setMethods($methods, true, false, true);
    return $request;
});
Module::define('response', function () {
    $methods = array('writeHead' => function ($statusCode, $statusReason, $headers) {
        http_response_code($statusCode);
        $keys = $headers->getOwnKeys(true);
        foreach ($keys as $key) {
            $value = $headers->get($key);
            header($key . ": " . $value);
        }
    }, 'write' => function ($data) {
        $data = $data instanceof Buffer ? $data->raw : to_string($data);
        echo $data;
    }, 'end' => function () {
        exit;
    });
    $response = new Object();
    $response->setMethods($methods, true, false, true);
    return $response;
});
Esempio n. 22
0
    }
    if (str_has_prefix($arg, '--')) {
        continue;
    }
    $fd = fopen($arg, 'r');
    $title = $arg;
    break;
}
/* Input */
$input_chunks = array();
while (!feof($fd)) {
    $input_chunks[] = fread($fd, 16384);
}
$input = join('', $input_chunks);
fclose($fd);
/* Output */
$output = TextFormatter::format($input, 'textile');
$output = trim($output);
if ($use_page) {
    anewt_include('page');
    $page = new AnewtPage();
    $page->enable_dublin_core = false;
    $page->content_type = 'application/xhtml+xml';
    $page->charset = 'UTF-8';
    $page->title = $title;
    $page->add_stylesheet_href_media('style.css', 'screen');
    $page->append(ax_raw($output));
    echo to_string($page), NL;
} else {
    echo $output, NL;
}
Esempio n. 23
0
$form = new AnewtXHTMLForm(null, array('method' => 'GET'));
$input_fragment = new AnewtXHTMLFragment();
$input_fragment->append_child(new AnewtXHTMLLabel('Label: ', array('for' => 'test')));
$input_fragment->append_child(new AnewtXHTMLInput(null, array('name' => 'test', 'id' => 'test', 'type' => 'text')));
$form->append_child(new AnewtXHTMLParagraph($input_fragment));
$select = new AnewtXHTMLSelect(null, array('name' => 'select'));
$select->append_child(new AnewtXHTMLOption('First', array('value' => 'first')));
$select->append_child(new AnewtXHTMLOption('Second', array('value' => 'second')));
$select->append_child(new AnewtXHTMLOption('Third', array('value' => 'third')));
$form->append_child(new AnewtXHTMLParagraph($select));
$fragment->append_child($form);
$form->append_child(new AnewtXHTMLParagraph(new AnewtXHTMLInput(null, array('type' => 'submit'))));
/* Convenience API */
$r = array();
$r[] = ax_h2('Convenience API');
$r[] = ax_p('Test with some <& special characters.', array('style' => 'color: #ccc;'));
$r[] = ax_p_class(ax_raw('This is <strong>strong</strong>'), 'someclass');
$r[] = ax_p(ax_abbr('ICE', 'InterCity Express'));
$r[] = ax_p(array('Test', ax_br(), 'after the break'));
$p = ax_p(array('testje', array('1', '2'), ax_strong('blablabla')));
$p->set_attribute('id', 'paragraph-id');
$p->set_class('foo bar baz');
$p->remove_class('bar');
$p->add_class('quux');
$p->append_child(ax_a_href('name', '/url/'));
$r[] = $p;
$r[] = ax_p(ax_sprintf('%s & %s', ax_span_class('Sugar', 'sweet'), 'Spice'));
$fragment->append_child(ax_fragment($r, ax_p('final paragraph')));
/* Final output */
echo to_string($fragment), NL;
Esempio n. 24
0
/**
 * @param Object $obj
 * @param string $name
 * @return mixed
 * @throws Exception
 */
function call_method($obj, $name)
{
    if ($obj === null || $obj === Object::$null) {
        throw new Ex(Error::create("Cannot read property '" . $name . "' of " . to_string($obj)));
    }
    $obj = objectify($obj);
    $fn = $obj->get($name);
    if (!$fn instanceof Func) {
        throw new Ex(Error::create(_typeof($fn) . " is not a function"));
    }
    $args = array_slice(func_get_args(), 2);
    return $fn->apply($obj, $args);
}
Esempio n. 25
0
 /**
  * Escape a field for embedding in an SQL query.
  *
  * This method does rigid sanity checking and throws errors when the
  * supplied value is not suitable for the specified field type.
  *
  * \param $field_type
  *   The field type (one of the \c ANEWT_DATABASE_SQL_FIELD_TYPE_* constants)
  * \param $value
  *   The value to escape
  *
  * \return
  *   The escaped value
  *
  * \see escape_field_array
  */
 private function escape_field($field_type, $value)
 {
     /* Escaping is not needed for NULL values. */
     if (is_null($value)) {
         return 'NULL';
     }
     /* The value is non-null. Perform very restrictive input sanitizing
      * based on the field type. */
     switch ($field_type) {
         case ANEWT_DATABASE_SQL_FIELD_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->connection->escape_boolean($value);
                 break;
             }
             throw new AnewtDatabaseQueryException('Invalid boolean value: "%s"', $value);
         case ANEWT_DATABASE_SQL_FIELD_TYPE_INTEGER:
             if (is_int($value)) {
                 $value = (string) $value;
                 break;
             }
             if (is_string($value) && preg_match('/^-?\\d+$/', $value)) {
                 break;
             }
             throw new AnewtDatabaseQueryException('Invalid integer value: "%s"', $value);
         case ANEWT_DATABASE_SQL_FIELD_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;
             } elseif (is_int($value) || is_float($value)) {
                 /* Locale-agnostic float formatting */
                 $value = number_format($value, 10, '.', '');
                 if (str_has_suffix($value, '.')) {
                     $value .= '0';
                 }
                 break;
             }
             throw new AnewtDatabaseQueryException('Invalid float value: "%s"', $value);
         case ANEWT_DATABASE_SQL_FIELD_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 = to_string($value);
             }
             /* From this point on only strings are accepted. */
             if (is_string($value)) {
                 $value = $this->connection->escape_string($value);
                 break;
             }
             throw new AnewtDatabaseQueryException('Invalid string value: "%s"', $value);
         case ANEWT_DATABASE_SQL_FIELD_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->connection->escape_date($value);
                 break;
             }
             if (is_string($value) && strtoupper($value) == 'NOW') {
                 $value = 'NOW()';
                 break;
             }
             throw new AnewtDatabaseQueryException('Invalid date value: "%s"', $value);
         case ANEWT_DATABASE_SQL_FIELD_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->connection->escape_time($value);
                 break;
             }
             if (is_string($value) && strtoupper($value) == 'NOW') {
                 $value = 'NOW()';
                 break;
             }
             throw new AnewtDatabaseQueryException('Invalid time value: "%s"', $value);
         case ANEWT_DATABASE_SQL_FIELD_TYPE_DATETIME:
         case ANEWT_DATABASE_SQL_FIELD_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->connection->escape_datetime($value);
                 break;
             }
             if (is_string($value) && strtoupper($value) == 'NOW') {
                 $value = 'NOW()';
                 break;
             }
             throw new AnewtDatabaseQueryException('Invalid datetime or timestamp value: "%s"', $value);
         case ANEWT_DATABASE_SQL_FIELD_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_SQL_FIELD_TYPE_COLUMN:
             if (is_string($value) && preg_match('/^([a-z0-9_-]+\\.)*[a-z0-9_-]+$/i', $value)) {
                 $value = $this->connection->escape_column_name($value);
                 break;
             }
             throw new AnewtDatabaseQueryException('Invalid column name: "%s"', $value);
         case ANEWT_DATABASE_SQL_FIELD_TYPE_TABLE:
             if (is_string($value) && preg_match('/^([a-z0-9_-]+\\.)*[a-z0-9_-]+$/i', $value)) {
                 $value = $this->connection->escape_table_name($value);
                 break;
             }
             throw new AnewtDatabaseQueryException('Invalid table name: "%s"', $value);
         default:
             throw new AnewtDatabaseQueryException('Unsupported field type! Please file a bug.');
             break;
     }
     assert('is_string($value)');
     return $value;
 }
Esempio n. 26
0
 /**
  * Group AnewtAutoRecord instances by the value of a column.
  *
  * This method can be used to group an array of AnewtAutoRecord instances by
  * the value of a column. It handles both unique and non-unique column
  * values, based on the \c $unique parameter.
  *
  * Note that the column value should be a string, or convertable to
  * a string.
  *
  * The resulting array uses the column values as keys. If \c $unique is \c
  * true, each array value is an object instance. If \c $unique is \c false,
  * each array value is an array of object instances.
  *
  *   the column value as the key and the
  *   instance itself as the value (if \c $unique is true)
  *
  * \param $instances
  *   A list of AnewtAutoRecord instances
  *
  * \param $column
  *   The name of the (unique) column to use as the associative array.
  *
  *  \param $unique
  *    Whether the column value should be unique. This influences the
  *    structure of the resulting array.
  *
  * \return
  *   Associative array with instances by column value
  *
  * \see array_by_primary_key_value
  */
 public static final function array_by_column_value($instances, $column, $unique)
 {
     assert('is_numeric_array($instances)');
     assert('is_string($column)');
     assert('is_bool($unique)');
     if (!$instances) {
         return array();
     }
     $out = array();
     foreach ($instances as $instance) {
         assert('$instance instanceof AnewtAutoRecord;');
         $key_value = to_string($instance->get($column));
         if ($unique) {
             if (array_key_exists($key_value, $out)) {
                 throw new AnewtException('Values for column "%s" are not unique.', $column);
             }
             $out[$key_value] = $instance;
         } else {
             if (!array_key_exists($key_value, $out)) {
                 $out[$key_value] = array();
             }
             $out[$key_value][] = $instance;
         }
     }
     return $out;
 }
Esempio n. 27
0
 static function parse($str)
 {
     $str = to_string($str);
     $d = date_parse($str);
     //todo: validate $d for errors array and false values
     return array($d['year'], $d['month'] - 1, $d['day'], $d['hour'], $d['minute'], $d['second'], floor($d['fraction'] * 1000));
 }
Esempio n. 28
0
 /**
  * Output the calendar to a browser.
  *
  * This renders the calendar and all its asssociated events, and sends the
  * output to the browser with the correct HTTP headers for the MIME type and
  * (optionally) the downoad filename.
  */
 function flush()
 {
     header('Content-Type: text/calendar');
     $filename = $this->filename;
     if (!is_null($filename)) {
         /* Make sure the filename ends with .ics */
         if (!str_has_prefix($filename, 'ics')) {
             $filename = sprintf('%s.ics', $filename);
         }
         header(sprintf('Content-Disposition: inline; filename=%s', $filename));
     }
     echo to_string($this), NL;
 }
Esempio n. 29
0
 /**
  * Flush this page to the browser.
  *
  * This method renders the page into a XHTML string and outputs it to the
  * browser along with the correct HTTP headers.
  *
  * \see AnewtPage::render
  */
 public function flush()
 {
     header(sprintf('Content-type: %s', $this->build_content_type_charset()));
     echo to_string($this->render()), NL;
 }
Esempio n. 30
0
     * @return Func
     */
    static function getGlobalConstructor()
    {
        $Boolean = new Func(function ($value = false) {
            $self = Func::getContext();
            if ($self instanceof Bln) {
                $self->value = $value ? true : false;
                return $self;
            } else {
                return $value ? true : false;
            }
        });
        $Boolean->instantiate = function () {
            return new Bln();
        };
        $Boolean->set('prototype', Bln::$protoObject);
        $Boolean->setMethods(Bln::$classMethods, true, false, true);
        return $Boolean;
    }
}
Bln::$classMethods = array();
Bln::$protoMethods = array('valueOf' => function () {
    $self = Func::getContext();
    return $self->value;
}, 'toString' => function () {
    $self = Func::getContext();
    return to_string($self->value);
});
Bln::$protoObject = new Object();
Bln::$protoObject->setMethods(Bln::$protoMethods, true, false, true);