Example #1
0
 function is_valid($value)
 {
     assert('is_string($value)');
     $pattern = '/^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})$/';
     if (!preg_match($pattern, $value, $matches)) {
         return false;
     }
     return AnewtDateTime::is_valid_date_ymd($matches[1], $matches[2], $matches[3]);
 }
Example #2
0
function f($d)
{
    printf("%s\n", $d);
    $d = AnewtDateTime::parse($d);
    printf("%s\n", AnewtDateTime::iso8601($d));
    printf("%s\n", AnewtDateTime::iso8601_week($d));
    printf("%s\n", AnewtDateTime::iso8601_week_day($d));
    printf("%s\n", AnewtDateTime::iso8601_day_of_year($d));
    printf("\n");
}
Example #3
0
 /**
  * Formats a date, using an alternative format if the given date is the same
  * day as today.
  *
  * \param $format_if_today
  *   A format specifier in strftime() syntax, used if the date is today.
  * \param $format_if_not_today
  *   A format specifier in strftime() syntax, used if the date is not today.
  * \param $date
  *   A date-like object (optional).
  *
  * \return
  *   A formatted date representation.
  *
  * \see AnewtDateTime::format
  * \see AnewtDateTime::format_if_current_year
  */
 static function format_if_today($format_if_today, $format_if_not_today, $date)
 {
     if (is_null($date)) {
         return null;
     }
     assert('$date instanceof AnewtDateTimeAtom;');
     assert('is_string($format_if_today)');
     assert('is_string($format_if_not_today)');
     if (AnewtDateTime::is_today($date)) {
         return strftime($format_if_today, $date->timestamp());
     } else {
         return strftime($format_if_not_today, $date->timestamp());
     }
 }
Example #4
0
 /**
  * \private
  *
  * Helper function to create RSS XML elements.
  *
  * This is only for internal use.
  *
  * \param $obj
  *   The object from which to retrieve the value
  *
  * \param $property
  *   The property name
  *
  * \param $tagname
  *   The XML tag name
  *
  * \param $status
  *   Status of the element
  *
  * \param $type
  *   Data type of the element
  *
  * \return
  *   An AnewtXMLDomElement instance, or null.
  */
 public static function _build_rss_element($obj, $property, $tagname, $status, $type)
 {
     if (!$obj->_isset($property)) {
         /* If an optional element not provided it's not a problem... */
         if ($status == ANEWT_RSS_ELEMENT_STATUS_OPTIONAL) {
             return null;
         }
         /* ...but required means required! */
         throw new AnewtException('AnewtRssItem::render(): Required property "%s" not set.', $property);
     }
     $value = $obj->_get($property);
     switch ($type) {
         case ANEWT_RSS_ELEMENT_TYPE_STRING:
             assert('is_string($value);');
             break;
         case ANEWT_RSS_ELEMENT_TYPE_CANONICAL_URL:
             assert('is_string($value);');
             if (str_has_prefix($value, '/')) {
                 /* Fixup relative URL's without a http://hostname.ext/ part */
                 $value = AnewtRequest::canonical_base_url() . $value;
             }
             break;
         case ANEWT_RSS_ELEMENT_TYPE_INTEGER:
             assert('is_int($value);');
             $value = (string) $value;
             break;
         case ANEWT_RSS_ELEMENT_TYPE_DATE:
             assert('$value instanceof AnewtDateTimeAtom;');
             $value = AnewtDateTime::rfc2822($value);
             break;
         default:
             assert('false; // not reached');
             break;
     }
     $element = new AnewtXMLDomElement($tagname);
     $element->append_child(new AnewtXMLDomText($value));
     return $element;
 }
Example #5
0
<?php

require_once dirname(__FILE__) . '/../anewt.lib.php';
anewt_include('calendar');
$calendar = new AnewtCalendar();
$event = new AnewtCalendarEvent('Title');
$event->date_start = AnewtDateTime::parse_string('2009-01-01 12:00');
$event->date_end = AnewtDateTime::parse_string('2009-01-01 14:00');
$event->summary = 'This is the summary';
$event->location = 'This is the location';
$event->url = 'http://example.org/foo';
$event->uid = 'abc1234567890';
$calendar->add_event($event);
$event = new AnewtCalendarEvent('Another event', AnewtDateTime::now());
$event->summary = "This is a multiline\nsummary";
$event->summary = "This is a multiline\ndescription";
$calendar->add_event($event);
$calendar->flush();
Example #6
0
 /**
  * Return a string representing this event.
  *
  * \return
  *   String with iCalender data.
  */
 function to_ical()
 {
     $r = array();
     $r[] = 'BEGIN:VEVENT';
     /* Generation date */
     $r[] = sprintf('DTSTAMP;VALUE=DATE:%s', AnewtDateTime::iso8601_compact(AnewtDateTime::now()));
     /* Summary */
     $r[] = sprintf('SUMMARY:%s', $this->get('summary'));
     /* Description */
     if (!$this->is_set('description')) {
         $this->set('description', $this->get('summary'));
     }
     $r[] = sprintf('DESCRIPTION:%s', $this->get('description'));
     /* Unique ID */
     if (!$this->is_set('uid')) {
         /* Generate a unique id */
         $uid = strtoupper(sprintf('%s-%s', md5($this->get('summary')), md5(AnewtDateTime::iso8601_compact($this->get('datestart')))));
         $this->set('uid', $uid);
     }
     $r[] = sprintf('UID:%s', $this->get('uid'));
     /* All day event? */
     $all_day = $this->get('all-day');
     assert('is_bool($all_day)');
     /* Start date */
     $datestart = $this->get('datestart');
     $datestart_str = $all_day ? AnewtDateTime::iso8601_date_compact($datestart) : AnewtDateTime::iso8601_compact($datestart);
     /* with time */
     $r[] = sprintf('DTSTART;VALUE=DATE:%s', $datestart_str);
     /* End date */
     if ($this->is_set('dateend')) {
         $dateend = $this->get('dateend');
         assert('$dateend instanceof AnewtDateTimeAtom');
         $dateend_str = $all_day ? AnewtDateTime::iso8601_date_compact($dateend) : AnewtDateTime::iso8601_compact($dateend);
         /* with time */
         $r[] = sprintf('DTEND;VALUE=DATE:%s', $dateend_str);
     }
     /* Transparency */
     $transparent = $this->getdefault('transparent', false);
     assert('is_bool($transparent)');
     $r[] = sprintf('TRANSP:%s', $transparent ? 'TRANSPARENT' : 'OPAQUE');
     /* Location  */
     if ($this->is_set('location')) {
         $r[] = sprintf('LOCATION:%s', $this->get('location'));
     }
     /* URL  */
     if ($this->is_set('url')) {
         $r[] = sprintf('URL:%s', $this->get('url'));
     }
     $r[] = 'END:VEVENT';
     $r[] = '';
     return implode("\r\n", $r);
 }
 protected function cast_row(&$row)
 {
     assert('is_assoc_array($row)');
     foreach ($row as $name => $value) {
         /* Don't cast null values */
         if (is_null($value)) {
             continue;
         }
         switch ($this->field_types[$name]) {
             case 'int2':
             case 'int4':
             case 'int8':
                 $value = (int) $value;
                 break;
             case 'float4':
             case 'float8':
             case 'numeric':
             case 'money':
                 $value = (double) $value;
                 break;
             case 'varchar':
             case 'bpchar':
                 $value = (string) $value;
                 break;
             case 'bool':
                 $value = $value === 't';
                 break;
             case 'timestamp':
             case 'date':
             case 'time':
             case 'datetime':
                 $value = AnewtDateTime::parse_string($value);
                 break;
             case 'inet':
                 /* FIXME: What to do with these? */
             /* FIXME: What to do with these? */
             default:
                 /* No conversion, leave as string */
                 break;
         }
         $row[$name] = $value;
     }
 }
Example #8
0
 /**
  * Log a message.
  *
  * \param $domain
  * \param $level
  * \param $message
  *
  * \see AnewtLogHandlerBase::log
  */
 public function log($domain, $level, $message)
 {
     $name = AnewtLog::loglevel_to_string($level);
     $output = $this->format_log_message($domain, $level, $message);
     /* Optionally prefix with timestamp */
     if ($this->timestamps) {
         $date = AnewtDateTime::iso8601(AnewtDateTime::now());
         $output = sprintf('[%s] %s', $date, $output);
     }
     /* Make sure there is a trailing newline */
     if (!str_has_prefix($output, NL)) {
         $output .= NL;
     }
     fwrite($this->fp, $output);
 }
Example #9
0
 function valid_values_provider()
 {
     return array(array(null, null, null, null, null, null, null, null, null), array(true, null, null, null, null, null, null, null, null), array(false, null, null, null, null, null, null, null, null), array(null, 2, null, null, null, null, null, null, null), array(null, '3', null, null, null, null, null, null, null), array(null, null, 2.0, null, null, null, null, null, null), array(null, null, 1.234, null, null, null, null, null, null), array(null, null, 3, null, null, null, null, null, null), array(null, null, null, 'Test', null, null, null, null, null), array(null, null, null, 'Te\';st', null, null, null, null, null), array(null, null, null, "\t\n;--'", null, null, null, null, null), array(null, null, null, 2, null, null, null, null, null), array(null, null, null, new StringWrap(), null, null, null, null, null), array(null, null, null, null, '2006-06-06', null, null, null, null), array(null, null, null, null, AnewtDateTime::now(), null, null, null, null), array(null, null, null, null, null, '2006-06-06 06:06:06', null, null, null), array(null, null, null, null, null, AnewtDateTime::now(), null, null, null), array(null, null, null, null, null, AnewtDateTime::sql(AnewtDateTime::now()), null, null, null), array(null, null, null, null, null, null, '2006-06-06 06:06:06', null, null), array(null, null, null, null, null, null, AnewtDateTime::now(), null, null), array(null, null, null, null, null, null, AnewtDateTime::sql(AnewtDateTime::now()), null, null), array(null, null, null, null, null, null, null, '06:06:06', null), array(null, null, null, null, null, null, null, AnewtDateTime::now(), null), array(null, null, null, null, null, null, null, AnewtDateTime::sql_time(AnewtDateTime::now()), null), array(null, null, null, null, null, null, null, null, "'?int?'"), array(true, 3, 2.0, 'Test', '2006-06-06', '2006-06-06 06:06:06', '2006-06-06 06:06:06', '06:06:06', "'?raw?'"));
 }
Example #10
0
 function get_data($id)
 {
     $q = "SELECT * FROM ssscrape.ssscrape_feed WHERE id=?str?";
     $db = DB::get_instance();
     $data = $db->prepare_execute_fetch($q, $id);
     if ($data) {
         $data['pub_date'] = AnewtDateTime::sql($data['pub_date']);
         $data['mod_date'] = AnewtDateTime::sql($data['mod_date']);
         $q = "SELECT * FROM ssscrape.ssscrape_feed_metadata WHERE feed_id=?str?";
         $metadata = $db->prepare_execute_fetch($q, $id);
         if ($metadata) {
             foreach ($metadata as $name => $value) {
                 $data['m_' . $name] = $value;
             }
         }
         $q = "SELECT * FROM ssscrapecontrol.ssscrape_task WHERE LOCATE(?str?, args) AND type in ('fetch', 'peilendfetch')";
         $task_data = $db->prepare_execute_fetch($q, "'" . $data['url'] . "'");
         if ($task_data) {
             $task_data['periodicity'] = AnewtDateTime::time($task_data['periodicity']);
             $task_data['latest_run'] = AnewtDateTime::sql($task_data['latest_run']);
             foreach ($task_data as $name => $value) {
                 $data['t_' . $name] = $value;
             }
         }
         $q = "SELECT * FROM ssscrapecontrol.ssscrape_task WHERE LOCATE(?str?, args) AND type='modelupdate'";
         $task_data = $db->prepare_execute_fetch($q, "'" . $data['url'] . "'");
         if ($task_data) {
             if ($task_data['periodicity']) {
                 $task_data['periodicity'] = AnewtDateTime::time($task_data['periodicity']);
             } else {
                 # In case periodicity cannot be read from the DB
                 $task_data['periodicity'] = "24:00:00";
             }
             $task_data['latest_run'] = AnewtDateTime::sql($task_data['latest_run']);
             foreach ($task_data as $name => $value) {
                 $data['ct_' . $name] = $value;
             }
         }
         $this->fill($data);
         return true;
     }
     return false;
 }
Example #11
0
 /**
  * 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;
 }
Example #12
0
 function display_periodicity($value, $row)
 {
     return AnewtDateTime::time($value);
 }
Example #13
0
 protected function cast_row(&$row)
 {
     assert('is_assoc_array($row)');
     foreach ($row as $name => $value) {
         $type = $this->field_types[$name];
         /* Don't cast null values */
         if (is_null($value)) {
             continue;
         }
         switch ($type) {
             case MYSQLI_TYPE_DECIMAL:
             case MYSQLI_TYPE_NEWDECIMAL:
             case MYSQLI_TYPE_BIT:
             case MYSQLI_TYPE_TINY:
             case MYSQLI_TYPE_SHORT:
             case MYSQLI_TYPE_LONG:
             case MYSQLI_TYPE_INT24:
             case MYSQLI_TYPE_YEAR:
                 $value = (int) $value;
                 break;
             case MYSQLI_TYPE_LONGLONG:
                 /* Only cast BIGINTs on 64 bit platforms that can actually
                    hold the values in an integer data type. */
                 if (PHP_INT_SIZE >= 8) {
                     $value = (int) $value;
                 }
                 break;
             case MYSQLI_TYPE_FLOAT:
             case MYSQLI_TYPE_DOUBLE:
                 $value = (double) $value;
                 break;
             case MYSQLI_TYPE_TINY_BLOB:
             case MYSQLI_TYPE_MEDIUM_BLOB:
             case MYSQLI_TYPE_LONG_BLOB:
             case MYSQLI_TYPE_BLOB:
             case MYSQLI_TYPE_VAR_STRING:
             case MYSQLI_TYPE_STRING:
             case MYSQLI_TYPE_CHAR:
                 $value = (string) $value;
                 break;
             case MYSQLI_TYPE_TIMESTAMP:
             case MYSQLI_TYPE_DATE:
             case MYSQLI_TYPE_TIME:
             case MYSQLI_TYPE_DATETIME:
             case MYSQLI_TYPE_NEWDATE:
                 $value = AnewtDateTime::parse_string($value);
                 break;
             case MYSQLI_TYPE_ENUM:
             case MYSQLI_TYPE_INTERVAL:
             case MYSQLI_TYPE_ENUM:
             case MYSQLI_TYPE_SET:
             case MYSQLI_TYPE_GEOMETRY:
                 /* XXX: Fall-through: what should be done with these? */
             /* XXX: Fall-through: what should be done with these? */
             default:
                 /* No conversion, leave as string */
                 break;
         }
         $row[$name] = $value;
     }
 }
Example #14
0
$values->set('datetime_var', '2006-06-06 06:06:06');
$pq->execute($values);
$values->set('datetime_var', AnewtDateTime::now());
$pq->execute($values);
$values->set('datetime_var', AnewtDateTime::sql(AnewtDateTime::now()));
$pq->execute($values);
$values->set('datetime_var', null);
/* Test timestamps */
$values->set('timestamp_var', '2006-06-06 06:06:06');
$pq->execute($values);
$values->set('timestamp_var', AnewtDateTime::now());
$pq->execute($values);
$values->set('timestamp_var', AnewtDateTime::sql(AnewtDateTime::now()));
$pq->execute($values);
$values->set('timestamp_var', null);
/* Test times */
$values->set('time_var', '06:06:06');
$pq->execute($values);
$values->set('time_var', AnewtDateTime::now());
$pq->execute($values);
$values->set('time_var', null);
/* Test raw */
$values->set('raw_var', '"?int?"');
$pq->execute($values);
$values->set('raw_var', null);
/* Test all at once */
$values->seed(array('bool_var' => true, 'int_var' => 3, 'float_var' => 2.0, 'string_var' => 'Test', 'date_var' => '2006-06-06', 'datetime_var' => '2006-06-06 06:06:06', 'timestamp_var' => '2006-06-06 06:06:06', 'time_var' => '06:06:06', 'raw_var' => '"?raw?"'));
$pq->execute($values);
$db->transaction_commit();
/* TODO: test column and table types */
$db->disconnect();
 protected function cast_row(&$row)
 {
     assert('is_assoc_array($row)');
     foreach ($row as $name => $value) {
         $type = $this->field_types[$name];
         /* Don't cast null values */
         if (is_null($value)) {
             continue;
         }
         switch ($type) {
             case 'int':
                 $value = (int) $value;
                 break;
             case 'real':
                 $value = (double) $value;
                 break;
             case 'string':
             case 'blob':
                 $value = (string) $value;
                 break;
             case 'date':
             case 'datetime':
             case 'time':
             case 'timestamp':
                 $value = AnewtDateTime::parse_string($value);
                 break;
             default:
                 /* No conversion, leave as string */
                 break;
         }
         $row[$name] = $value;
     }
 }
Example #16
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;
 }
Example #17
0
<?php

error_reporting(E_ALL | E_STRICT);
require_once dirname(__FILE__) . '/../anewt.lib.php';
anewt_include('rss');
$channel = new AnewtRssChannel('Title', 'http://example.com', 'This is a test');
$channel->set('author', 'Anewt test');
$channel->set('build-date', AnewtDateTime::now());
$item = new AnewtRssItem('test', 'http://example.com/some-item');
$item->set('description', 'The description goes here.');
$item->set('guid', 'http://example.com/some-item');
$item->set('date', AnewtDateTime::now());
$channel->add_item($item);
$item = new AnewtRssItem('another test');
$item->set('description', 'The description goes here.');
$item->set('link', 'http://example.com/another-item');
$item->set('guid', 'http://example.com/another-item');
$item->set('date', AnewtDateTime::now());
$channel->add_item($item);
$channel->flush();
Example #18
0
 function display_latest_run($value, $row)
 {
     return AnewtDateTime::format_if_today("%H:%M:%S", "%H:%M:%S (%d-%m-%Y)", $value);
 }
Example #19
0
 /**
  * Render data as formatted date.
  *
  * \param $data
  *   Data to pack into the cell
  *
  * \return
  *   Rendered cell
  */
 function render_cell($data)
 {
     $dt = $this->fetch_value_from_data($data);
     if (is_null($dt)) {
         $str = null;
     } else {
         assert('$dt instanceof AnewtDateTimeAtom;');
         $str = AnewtDateTime::format($this->_format, $dt);
     }
     return $this->create_td($str);
 }
Example #20
0
 /**
  * Construct a new AnewtCalendarEvent instance.
  *
  * If you don't specify \c $summary or \c $date_start these values need to
  * be set later.
  *
  * \param $summary
  *   A summary line for this event (optional).
  *
  * \param $date_start
  *   A AnewtDateTimeAtom instance describing the start date for this event
  *   (optional).
  */
 function __construct($summary = null, $date_start = null)
 {
     parent::__construct();
     $now = AnewtDateTime::now();
     $this->_seed(array('uid' => null, 'summary' => null, 'description' => null, 'location' => null, 'url' => null, 'date-start' => $now, 'date-end' => $now, 'all-day' => false, 'transparent' => false));
     if (!is_null($summary)) {
         assert('is_string($summary)');
         $this->summary = $summary;
     }
     if (!is_null($date_start)) {
         assert('$date_start instanceof AnewtDateTimeAtom');
         $this->date_start = $date_start;
     }
 }
Example #21
0
 function get_data($id)
 {
     $q = "SELECT * FROM ssscrapecontrol.ssscrape_task WHERE id=?str?";
     $db = DB::get_instance();
     $data = $db->prepare_execute_fetch($q, $id);
     if ($data) {
         $data['periodicity'] = AnewtDateTime::time($data['periodicity']);
         $data['latest_run'] = AnewtDateTime::sql($data['latest_run']);
         $this->fill($data);
         return true;
     }
     return false;
 }
Example #22
0
 function make_one_cell($field, $value, &$row)
 {
     $classes = array();
     if (method_exists($this, "check_" . $field)) {
         if (!call_user_func(array($this, "check_" . $field), $value, $row)) {
             $classes['error'] = 1;
         }
     }
     if (isset($this->field_opts[$field]['truncate'])) {
         $value = str_truncate($value, $this->field_opts[$field]['truncate']);
     }
     if (isset($this->field_opts[$field]['datetime']) and $value) {
         $value = AnewtDateTime::sql($value);
     }
     if (isset($this->field_opts[$field]['time']) and $value) {
         $value = AnewtDateTime::time($value);
     }
     if (isset($this->field_opts[$field]['num'])) {
         $this->stat[$field]['sum'] += intval($value);
     }
     if (preg_match('/^[\\d\\+\\-\\.eE]+$/', $value) || isset($this->field_opts[$field]['flushright'])) {
         $classes['number'] = 1;
     }
     $display_value = $value;
     if (method_exists($this, "display_" . $field)) {
         $display_value = call_user_func(array($this, "display_" . $field), $value, &$row);
     }
     $expand = array_get_default($this->field_opts[$field], 'expand', "0");
     $dynamic = array_get_default($this->field_opts[$field], 'dynamic', FALSE);
     if ($dynamic || $expand > 0 && is_string($value) && strlen($value) > 0 && strlen($value) > $expand) {
         $display_value = ax_a(array(str_truncate($value, $expand, "...", true), ax_span($display_value, array('class' => 'expanded'))), array('class' => 'expand'));
     }
     $c =& ax_td($display_value);
     foreach ($classes as $class => $val) {
         $c->add_class($class);
     }
     return $c;
 }
Example #23
0
 /**
  * Render this page into XHTML.
  *
  * This methods renders the whole page into a complete XHTML page. Usually
  * you want to use flush() to output the page to the browser.
  *
  * \return
  *   The rendered page as a string.
  *
  * \see AnewtPage::flush
  */
 public function render()
 {
     /* Create basic element nodes */
     $head = new AnewtXMLDomElement('head');
     $body = new AnewtXMLDomElement('body');
     $head->always_render_closing_tag = true;
     $body->always_render_closing_tag = true;
     /* Content-type in meta tag. This must be the first element inside the
      * <head>...</head> element. */
     $head->append_child(ax_meta(array('http-equiv' => 'Content-type', 'content' => $this->build_content_type_charset())));
     /* Base URI */
     $base_uri = $this->_get('base-uri');
     if (!is_null($base_uri)) {
         assert('is_string($base_uri); // base-uri must be a simple string');
         /* Employ a simple heuristic to make sure we use an absolute URI, as
          * is required by the HTML specification. */
         if (!str_contains($base_uri, '://')) {
             $base_uri = AnewtRequest::canonical_base_url() . $base_uri;
         }
         $base = new AnewtXHTMLBase();
         $base->set_attribute('href', $base_uri);
         $head->append_child($base);
     }
     /* Page title (always include, even if empty, since this is required by
      * the HTML specification) */
     $title = $this->_get('title');
     $head->append_child(ax_title($title));
     /* Dublin Core metadata. See http://dublincore.org/documents/dcq-html/ * */
     if ($this->_get('show-dublin-core')) {
         $head->append_child(ax_link(array('rel' => 'schema.DC', 'href' => 'http://purl.org/dc/elements/1.1/')));
         $head->append_child(ax_meta_name_content('DC.language', $this->_get('language')));
         if (!is_null($title)) {
             $head->append_child(ax_meta_name_content('DC.title', $title));
         }
         if ($this->_isset('creator')) {
             $head->append_child(ax_meta_name_content('DC.creator', $this->_get('creator')));
         }
         if ($this->_isset('description')) {
             $head->append_child(ax_meta_name_content('DC.description', $this->_get('description')));
         }
         if ($this->_isset('date')) {
             $date = $this->get('date');
         } else {
             $date = AnewtDateTime::now();
         }
         $head->append_child(ax_meta_name_content('DC.date', AnewtDateTime::date($date)));
     }
     /* Powered by Anewt! */
     $generator = $this->_get('generator');
     if (!is_null($generator)) {
         assert('is_string($generator);');
         $head->append_child(ax_meta_name_content('generator', $generator));
     }
     /* Robots */
     $robots = $this->_get('robots');
     if (!is_null($robots)) {
         assert('is_string($robots);');
         $head->append_child(ax_meta(array('name' => 'robots', 'content' => $robots)));
     }
     /* Links (including stylesheets) and JavaScripts */
     $head->append_children($this->_links);
     $head->append_children($this->_javascripts);
     /* Favicon */
     $favicon = $this->_get('favicon');
     if (!is_null($favicon)) {
         assert('is_string($favicon);');
         $head->append_child(ax_link_favicon($favicon));
     }
     /* Body content */
     if ($this->_get('blocks')) {
         /* This is a page using div blocks */
         if ($this->_content && $this->_content->has_child_nodes()) {
             throw new AnewtException('Pages using blocks should not have content outside blocks.');
         }
         /* The buffer holding all content is either a wrapper div or an
          * invisible fragment (both XML nodes, so the API is the same). */
         if ($this->_get('use-wrapper-div')) {
             $buffer = ax_div_id(null, $this->_get('wrapper-div-id'));
         } else {
             $buffer = ax_fragment();
         }
         /* Add the content */
         foreach ($this->_get('blocks') as $block_name) {
             $block = $this->get_block($block_name);
             $buffer->append_child(ax_div_id($block, $block_name));
             unset($block);
             unset($div);
         }
         $body->append_child($buffer);
     } else {
         /* This page has no blocks, so we use the nodes in _content instead
          * (if any) */
         if ($this->_blocks) {
             throw new AnewtException('Pages not using blocks should not have content in blocks');
         }
         if ($this->_content) {
             $body->append_child($this->_content);
         }
     }
     /* Assemble the top level elements */
     $document = new AnewtXMLDomDocument();
     $document->set_document_type($this->_get('document-type'));
     $document->set_content_type($this->_get('content-type'));
     $document->set_encoding($this->_get('encoding'));
     $html = new AnewtXMLDomElement('html', array('xmlns' => 'http://www.w3.org/1999/xhtml', 'xml:lang' => $this->_get('language'), 'lang' => $this->_get('language')));
     $html->append_child($head);
     $html->append_child($body);
     $document->append_child($html);
     return $document;
 }
 protected function cast_row(&$row)
 {
     assert('is_assoc_array($row)');
     foreach ($row as $name => $value) {
         $type = $this->field_types[$name];
         /* Don't cast null values */
         if (is_null($value)) {
             continue;
         }
         switch ($type) {
             case 'int':
                 /* Issue: this doesn't work for BIGINTs on 32 bits
                  * platforms, but there is no way to find out when this
                  * happens (both have a 'int' field type). :(  The solution
                  * is to use MySQLi instead. */
                 $value = (int) $value;
                 break;
             case 'real':
                 $value = (double) $value;
                 break;
             case 'string':
             case 'blob':
                 $value = (string) $value;
                 break;
             case 'date':
             case 'datetime':
             case 'time':
             case 'timestamp':
                 $value = AnewtDateTime::parse_string($value);
                 break;
             default:
                 /* No conversion, leave as string */
                 break;
         }
         $row[$name] = $value;
     }
 }