- */
-class MDB2_Driver_Reverse_Common extends MDB2_Module_Common
-{
- // {{{ splitTableSchema()
-
- /**
- * Split the "[owner|schema].table" notation into an array
- *
- * @param string $table [schema and] table name
- *
- * @return array array(schema, table)
- * @access private
- */
- function splitTableSchema($table)
- {
- $ret = array();
- if (strpos($table, '.') !== false) {
- return explode('.', $table);
- }
- return array(null, $table);
- }
-
- // }}}
- // {{{ getTableFieldDefinition()
-
- /**
- * Get the structure of a field into an array
- *
- * @param string $table name of table that should be used in method
- * @param string $field name of field that should be used in method
- * @return mixed data array on success, a MDB2 error on failure.
- * The returned array contains an array for each field definition,
- * with all or some of these indices, depending on the field data type:
- * [notnull] [nativetype] [length] [fixed] [default] [type] [mdb2type]
- * @access public
- */
- function getTableFieldDefinition($table, $field)
- {
- $db =$this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ getTableIndexDefinition()
-
- /**
- * Get the structure of an index into an array
- *
- * @param string $table name of table that should be used in method
- * @param string $index name of index that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * The returned array has this structure:
- *
- * array (
- * [fields] => array (
- * [field1name] => array() // one entry per each field covered
- * [field2name] => array() // by the index
- * [field3name] => array(
- * [sorting] => ascending
- * )
- * )
- * );
- *
- * @access public
- */
- function getTableIndexDefinition($table, $index)
- {
- $db =$this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ getTableConstraintDefinition()
-
- /**
- * Get the structure of an constraints into an array
- *
- * @param string $table name of table that should be used in method
- * @param string $index name of index that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * The returned array has this structure:
- *
- * array (
- * [primary] => 0
- * [unique] => 0
- * [foreign] => 1
- * [check] => 0
- * [fields] => array (
- * [field1name] => array() // one entry per each field covered
- * [field2name] => array() // by the index
- * [field3name] => array(
- * [sorting] => ascending
- * [position] => 3
- * )
- * )
- * [references] => array(
- * [table] => name
- * [fields] => array(
- * [field1name] => array( //one entry per each referenced field
- * [position] => 1
- * )
- * )
- * )
- * [deferrable] => 0
- * [initiallydeferred] => 0
- * [onupdate] => CASCADE|RESTRICT|SET NULL|SET DEFAULT|NO ACTION
- * [ondelete] => CASCADE|RESTRICT|SET NULL|SET DEFAULT|NO ACTION
- * [match] => SIMPLE|PARTIAL|FULL
- * );
- *
- * @access public
- */
- function getTableConstraintDefinition($table, $index)
- {
- $db =$this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ getSequenceDefinition()
-
- /**
- * Get the structure of a sequence into an array
- *
- * @param string $sequence name of sequence that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * The returned array has this structure:
- *
- * array (
- * [start] => n
- * );
- *
- * @access public
- */
- function getSequenceDefinition($sequence)
- {
- $db =$this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $start = $db->currId($sequence);
- if (PEAR::isError($start)) {
- return $start;
- }
- if ($db->supports('current_id')) {
- $start++;
- } else {
- $db->warnings[] = 'database does not support getting current
- sequence value, the sequence value was incremented';
- }
- $definition = array();
- if ($start != 1) {
- $definition = array('start' => $start);
- }
- return $definition;
- }
-
- // }}}
- // {{{ getTriggerDefinition()
-
- /**
- * Get the structure of a trigger into an array
- *
- * EXPERIMENTAL
- *
- * WARNING: this function is experimental and may change the returned value
- * at any time until labelled as non-experimental
- *
- * @param string $trigger name of trigger that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * The returned array has this structure:
- *
- * array (
- * [trigger_name] => 'trigger name',
- * [table_name] => 'table name',
- * [trigger_body] => 'trigger body definition',
- * [trigger_type] => 'BEFORE' | 'AFTER',
- * [trigger_event] => 'INSERT' | 'UPDATE' | 'DELETE'
- * //or comma separated list of multiple events, when supported
- * [trigger_enabled] => true|false
- * [trigger_comment] => 'trigger comment',
- * );
- *
- * The oci8 driver also returns a [when_clause] index.
- * @access public
- */
- function getTriggerDefinition($trigger)
- {
- $db =$this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ tableInfo()
-
- /**
- * Returns information about a table or a result set
- *
- * The format of the resulting array depends on which $mode
- * you select. The sample output below is based on this query:
- *
- * SELECT tblFoo.fldID, tblFoo.fldPhone, tblBar.fldId
- * FROM tblFoo
- * JOIN tblBar ON tblFoo.fldId = tblBar.fldId
- *
- *
- *
- * -
- *
- * null (default)
- *
- * [0] => Array (
- * [table] => tblFoo
- * [name] => fldId
- * [type] => int
- * [len] => 11
- * [flags] => primary_key not_null
- * )
- * [1] => Array (
- * [table] => tblFoo
- * [name] => fldPhone
- * [type] => string
- * [len] => 20
- * [flags] =>
- * )
- * [2] => Array (
- * [table] => tblBar
- * [name] => fldId
- * [type] => int
- * [len] => 11
- * [flags] => primary_key not_null
- * )
- *
- *
- * -
- *
- * MDB2_TABLEINFO_ORDER
- *
- *
In addition to the information found in the default output,
- * a notation of the number of columns is provided by the
- * num_fields element while the order
- * element provides an array with the column names as the keys and
- * their location index number (corresponding to the keys in the
- * the default output) as the values.
- *
- * If a result set has identical field names, the last one is
- * used.
- *
- *
- * [num_fields] => 3
- * [order] => Array (
- * [fldId] => 2
- * [fldTrans] => 1
- * )
- *
- *
- * -
- *
- * MDB2_TABLEINFO_ORDERTABLE
- *
- *
Similar to MDB2_TABLEINFO_ORDER but adds more
- * dimensions to the array in which the table names are keys and
- * the field names are sub-keys. This is helpful for queries that
- * join tables which have identical field names.
- *
- *
- * [num_fields] => 3
- * [ordertable] => Array (
- * [tblFoo] => Array (
- * [fldId] => 0
- * [fldPhone] => 1
- * )
- * [tblBar] => Array (
- * [fldId] => 2
- * )
- * )
- *
- *
- *
- *
- *
- * The flags element contains a space separated list
- * of extra information about the field. This data is inconsistent
- * between DBMS's due to the way each DBMS works.
- * + primary_key
- * + unique_key
- * + multiple_key
- * + not_null
- *
- * Most DBMS's only provide the table and flags
- * elements if $result is a table name. The following DBMS's
- * provide full information from queries:
- * + fbsql
- * + mysql
- *
- * If the 'portability' option has MDB2_PORTABILITY_FIX_CASE
- * turned on, the names of tables and fields will be lower or upper cased.
- *
- * @param object|string $result MDB2_result object from a query or a
- * string containing the name of a table.
- * While this also accepts a query result
- * resource identifier, this behavior is
- * deprecated.
- * @param int $mode either unused or one of the tableInfo modes:
- * MDB2_TABLEINFO_ORDERTABLE,
- * MDB2_TABLEINFO_ORDER or
- * MDB2_TABLEINFO_FULL (which does both).
- * These are bitwise, so the first two can be
- * combined using |.
- *
- * @return array an associative array with the information requested.
- * A MDB2_Error object on failure.
- *
- * @see MDB2_Driver_Common::setOption()
- */
- function tableInfo($result, $mode = null)
- {
- $db =$this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if (!is_string($result)) {
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- $db->loadModule('Manager', null, true);
- $fields = $db->manager->listTableFields($result);
- if (PEAR::isError($fields)) {
- return $fields;
- }
-
- $flags = array();
-
- $idxname_format = $db->getOption('idxname_format');
- $db->setOption('idxname_format', '%s');
-
- $indexes = $db->manager->listTableIndexes($result);
- if (PEAR::isError($indexes)) {
- $db->setOption('idxname_format', $idxname_format);
- return $indexes;
- }
-
- foreach ($indexes as $index) {
- $definition = $this->getTableIndexDefinition($result, $index);
- if (PEAR::isError($definition)) {
- $db->setOption('idxname_format', $idxname_format);
- return $definition;
- }
- if (count($definition['fields']) > 1) {
- foreach ($definition['fields'] as $field => $sort) {
- $flags[$field] = 'multiple_key';
- }
- }
- }
-
- $constraints = $db->manager->listTableConstraints($result);
- if (PEAR::isError($constraints)) {
- return $constraints;
- }
-
- foreach ($constraints as $constraint) {
- $definition = $this->getTableConstraintDefinition($result, $constraint);
- if (PEAR::isError($definition)) {
- $db->setOption('idxname_format', $idxname_format);
- return $definition;
- }
- $flag = !empty($definition['primary'])
- ? 'primary_key' : (!empty($definition['unique'])
- ? 'unique_key' : false);
- if ($flag) {
- foreach ($definition['fields'] as $field => $sort) {
- if (empty($flags[$field]) || $flags[$field] != 'primary_key') {
- $flags[$field] = $flag;
- }
- }
- }
- }
-
- $res = array();
-
- if ($mode) {
- $res['num_fields'] = count($fields);
- }
-
- foreach ($fields as $i => $field) {
- $definition = $this->getTableFieldDefinition($result, $field);
- if (PEAR::isError($definition)) {
- $db->setOption('idxname_format', $idxname_format);
- return $definition;
- }
- $res[$i] = $definition[0];
- $res[$i]['name'] = $field;
- $res[$i]['table'] = $result;
- $res[$i]['type'] = preg_replace('/^([a-z]+).*$/i', '\\1', trim($definition[0]['nativetype']));
- // 'primary_key', 'unique_key', 'multiple_key'
- $res[$i]['flags'] = empty($flags[$field]) ? '' : $flags[$field];
- // not_null', 'unsigned', 'auto_increment', 'default_[rawencodedvalue]'
- if (!empty($res[$i]['notnull'])) {
- $res[$i]['flags'].= ' not_null';
- }
- if (!empty($res[$i]['unsigned'])) {
- $res[$i]['flags'].= ' unsigned';
- }
- if (!empty($res[$i]['auto_increment'])) {
- $res[$i]['flags'].= ' autoincrement';
- }
- if (!empty($res[$i]['default'])) {
- $res[$i]['flags'].= ' default_'.rawurlencode($res[$i]['default']);
- }
-
- if ($mode & MDB2_TABLEINFO_ORDER) {
- $res['order'][$res[$i]['name']] = $i;
- }
- if ($mode & MDB2_TABLEINFO_ORDERTABLE) {
- $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
- }
- }
-
- $db->setOption('idxname_format', $idxname_format);
- return $res;
- }
-}
+ |
+// +----------------------------------------------------------------------+
+//
+// $Id: Common.php 295587 2010-02-28 17:16:38Z quipo $
+//
+
+/**
+ * @package MDB2
+ * @category Database
+ */
+
+/**
+ * These are constants for the tableInfo-function
+ * they are bitwised or'ed. so if there are more constants to be defined
+ * in the future, adjust MDB2_TABLEINFO_FULL accordingly
+ */
+
+define('MDB2_TABLEINFO_ORDER', 1);
+define('MDB2_TABLEINFO_ORDERTABLE', 2);
+define('MDB2_TABLEINFO_FULL', 3);
+
+/**
+ * Base class for the schema reverse engineering module that is extended by each MDB2 driver
+ *
+ * To load this module in the MDB2 object:
+ * $mdb->loadModule('Reverse');
+ *
+ * @package MDB2
+ * @category Database
+ * @author Lukas Smith
+ */
+class MDB2_Driver_Reverse_Common extends MDB2_Module_Common
+{
+ // {{{ splitTableSchema()
+
+ /**
+ * Split the "[owner|schema].table" notation into an array
+ *
+ * @param string $table [schema and] table name
+ *
+ * @return array array(schema, table)
+ * @access private
+ */
+ function splitTableSchema($table)
+ {
+ $ret = array();
+ if (strpos($table, '.') !== false) {
+ return explode('.', $table);
+ }
+ return array(null, $table);
+ }
+
+ // }}}
+ // {{{ getTableFieldDefinition()
+
+ /**
+ * Get the structure of a field into an array
+ *
+ * @param string $table name of table that should be used in method
+ * @param string $field name of field that should be used in method
+ * @return mixed data array on success, a MDB2 error on failure.
+ * The returned array contains an array for each field definition,
+ * with all or some of these indices, depending on the field data type:
+ * [notnull] [nativetype] [length] [fixed] [default] [type] [mdb2type]
+ * @access public
+ */
+ function getTableFieldDefinition($table, $field)
+ {
+ $db = $this->getDBInstance();
+ if (PEAR::isError($db)) {
+ return $db;
+ }
+
+ return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
+ 'method not implemented', __FUNCTION__);
+ }
+
+ // }}}
+ // {{{ getTableIndexDefinition()
+
+ /**
+ * Get the structure of an index into an array
+ *
+ * @param string $table name of table that should be used in method
+ * @param string $index name of index that should be used in method
+ * @return mixed data array on success, a MDB2 error on failure
+ * The returned array has this structure:
+ *
+ * array (
+ * [fields] => array (
+ * [field1name] => array() // one entry per each field covered
+ * [field2name] => array() // by the index
+ * [field3name] => array(
+ * [sorting] => ascending
+ * )
+ * )
+ * );
+ *
+ * @access public
+ */
+ function getTableIndexDefinition($table, $index)
+ {
+ $db = $this->getDBInstance();
+ if (PEAR::isError($db)) {
+ return $db;
+ }
+
+ return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
+ 'method not implemented', __FUNCTION__);
+ }
+
+ // }}}
+ // {{{ getTableConstraintDefinition()
+
+ /**
+ * Get the structure of an constraints into an array
+ *
+ * @param string $table name of table that should be used in method
+ * @param string $index name of index that should be used in method
+ * @return mixed data array on success, a MDB2 error on failure
+ * The returned array has this structure:
+ *
+ * array (
+ * [primary] => 0
+ * [unique] => 0
+ * [foreign] => 1
+ * [check] => 0
+ * [fields] => array (
+ * [field1name] => array() // one entry per each field covered
+ * [field2name] => array() // by the index
+ * [field3name] => array(
+ * [sorting] => ascending
+ * [position] => 3
+ * )
+ * )
+ * [references] => array(
+ * [table] => name
+ * [fields] => array(
+ * [field1name] => array( //one entry per each referenced field
+ * [position] => 1
+ * )
+ * )
+ * )
+ * [deferrable] => 0
+ * [initiallydeferred] => 0
+ * [onupdate] => CASCADE|RESTRICT|SET NULL|SET DEFAULT|NO ACTION
+ * [ondelete] => CASCADE|RESTRICT|SET NULL|SET DEFAULT|NO ACTION
+ * [match] => SIMPLE|PARTIAL|FULL
+ * );
+ *
+ * @access public
+ */
+ function getTableConstraintDefinition($table, $index)
+ {
+ $db = $this->getDBInstance();
+ if (PEAR::isError($db)) {
+ return $db;
+ }
+
+ return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
+ 'method not implemented', __FUNCTION__);
+ }
+
+ // }}}
+ // {{{ getSequenceDefinition()
+
+ /**
+ * Get the structure of a sequence into an array
+ *
+ * @param string $sequence name of sequence that should be used in method
+ * @return mixed data array on success, a MDB2 error on failure
+ * The returned array has this structure:
+ *
+ * array (
+ * [start] => n
+ * );
+ *
+ * @access public
+ */
+ function getSequenceDefinition($sequence)
+ {
+ $db = $this->getDBInstance();
+ if (PEAR::isError($db)) {
+ return $db;
+ }
+
+ $start = $db->currId($sequence);
+ if (PEAR::isError($start)) {
+ return $start;
+ }
+ if ($db->supports('current_id')) {
+ $start++;
+ } else {
+ $db->warnings[] = 'database does not support getting current
+ sequence value, the sequence value was incremented';
+ }
+ $definition = array();
+ if ($start != 1) {
+ $definition = array('start' => $start);
+ }
+ return $definition;
+ }
+
+ // }}}
+ // {{{ getTriggerDefinition()
+
+ /**
+ * Get the structure of a trigger into an array
+ *
+ * EXPERIMENTAL
+ *
+ * WARNING: this function is experimental and may change the returned value
+ * at any time until labelled as non-experimental
+ *
+ * @param string $trigger name of trigger that should be used in method
+ * @return mixed data array on success, a MDB2 error on failure
+ * The returned array has this structure:
+ *
+ * array (
+ * [trigger_name] => 'trigger name',
+ * [table_name] => 'table name',
+ * [trigger_body] => 'trigger body definition',
+ * [trigger_type] => 'BEFORE' | 'AFTER',
+ * [trigger_event] => 'INSERT' | 'UPDATE' | 'DELETE'
+ * //or comma separated list of multiple events, when supported
+ * [trigger_enabled] => true|false
+ * [trigger_comment] => 'trigger comment',
+ * );
+ *
+ * The oci8 driver also returns a [when_clause] index.
+ * @access public
+ */
+ function getTriggerDefinition($trigger)
+ {
+ $db = $this->getDBInstance();
+ if (PEAR::isError($db)) {
+ return $db;
+ }
+
+ return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
+ 'method not implemented', __FUNCTION__);
+ }
+
+ // }}}
+ // {{{ tableInfo()
+
+ /**
+ * Returns information about a table or a result set
+ *
+ * The format of the resulting array depends on which $mode
+ * you select. The sample output below is based on this query:
+ *
+ * SELECT tblFoo.fldID, tblFoo.fldPhone, tblBar.fldId
+ * FROM tblFoo
+ * JOIN tblBar ON tblFoo.fldId = tblBar.fldId
+ *
+ *
+ *
+ * -
+ *
+ * null (default)
+ *
+ * [0] => Array (
+ * [table] => tblFoo
+ * [name] => fldId
+ * [type] => int
+ * [len] => 11
+ * [flags] => primary_key not_null
+ * )
+ * [1] => Array (
+ * [table] => tblFoo
+ * [name] => fldPhone
+ * [type] => string
+ * [len] => 20
+ * [flags] =>
+ * )
+ * [2] => Array (
+ * [table] => tblBar
+ * [name] => fldId
+ * [type] => int
+ * [len] => 11
+ * [flags] => primary_key not_null
+ * )
+ *
+ *
+ * -
+ *
+ * MDB2_TABLEINFO_ORDER
+ *
+ *
In addition to the information found in the default output,
+ * a notation of the number of columns is provided by the
+ * num_fields element while the order
+ * element provides an array with the column names as the keys and
+ * their location index number (corresponding to the keys in the
+ * the default output) as the values.
+ *
+ * If a result set has identical field names, the last one is
+ * used.
+ *
+ *
+ * [num_fields] => 3
+ * [order] => Array (
+ * [fldId] => 2
+ * [fldTrans] => 1
+ * )
+ *
+ *
+ * -
+ *
+ * MDB2_TABLEINFO_ORDERTABLE
+ *
+ *
Similar to MDB2_TABLEINFO_ORDER but adds more
+ * dimensions to the array in which the table names are keys and
+ * the field names are sub-keys. This is helpful for queries that
+ * join tables which have identical field names.
+ *
+ *
+ * [num_fields] => 3
+ * [ordertable] => Array (
+ * [tblFoo] => Array (
+ * [fldId] => 0
+ * [fldPhone] => 1
+ * )
+ * [tblBar] => Array (
+ * [fldId] => 2
+ * )
+ * )
+ *
+ *
+ *
+ *
+ *
+ * The flags element contains a space separated list
+ * of extra information about the field. This data is inconsistent
+ * between DBMS's due to the way each DBMS works.
+ * + primary_key
+ * + unique_key
+ * + multiple_key
+ * + not_null
+ *
+ * Most DBMS's only provide the table and flags
+ * elements if $result is a table name. The following DBMS's
+ * provide full information from queries:
+ * + fbsql
+ * + mysql
+ *
+ * If the 'portability' option has MDB2_PORTABILITY_FIX_CASE
+ * turned on, the names of tables and fields will be lower or upper cased.
+ *
+ * @param object|string $result MDB2_result object from a query or a
+ * string containing the name of a table.
+ * While this also accepts a query result
+ * resource identifier, this behavior is
+ * deprecated.
+ * @param int $mode either unused or one of the tableInfo modes:
+ * MDB2_TABLEINFO_ORDERTABLE,
+ * MDB2_TABLEINFO_ORDER or
+ * MDB2_TABLEINFO_FULL (which does both).
+ * These are bitwise, so the first two can be
+ * combined using |.
+ *
+ * @return array an associative array with the information requested.
+ * A MDB2_Error object on failure.
+ *
+ * @see MDB2_Driver_Common::setOption()
+ */
+ function tableInfo($result, $mode = null)
+ {
+ $db = $this->getDBInstance();
+ if (PEAR::isError($db)) {
+ return $db;
+ }
+
+ if (!is_string($result)) {
+ return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
+ 'method not implemented', __FUNCTION__);
+ }
+
+ $db->loadModule('Manager', null, true);
+ $fields = $db->manager->listTableFields($result);
+ if (PEAR::isError($fields)) {
+ return $fields;
+ }
+
+ $flags = array();
+
+ $idxname_format = $db->getOption('idxname_format');
+ $db->setOption('idxname_format', '%s');
+
+ $indexes = $db->manager->listTableIndexes($result);
+ if (PEAR::isError($indexes)) {
+ $db->setOption('idxname_format', $idxname_format);
+ return $indexes;
+ }
+
+ foreach ($indexes as $index) {
+ $definition = $this->getTableIndexDefinition($result, $index);
+ if (PEAR::isError($definition)) {
+ $db->setOption('idxname_format', $idxname_format);
+ return $definition;
+ }
+ if (count($definition['fields']) > 1) {
+ foreach ($definition['fields'] as $field => $sort) {
+ $flags[$field] = 'multiple_key';
+ }
+ }
+ }
+
+ $constraints = $db->manager->listTableConstraints($result);
+ if (PEAR::isError($constraints)) {
+ return $constraints;
+ }
+
+ foreach ($constraints as $constraint) {
+ $definition = $this->getTableConstraintDefinition($result, $constraint);
+ if (PEAR::isError($definition)) {
+ $db->setOption('idxname_format', $idxname_format);
+ return $definition;
+ }
+ $flag = !empty($definition['primary'])
+ ? 'primary_key' : (!empty($definition['unique'])
+ ? 'unique_key' : false);
+ if ($flag) {
+ foreach ($definition['fields'] as $field => $sort) {
+ if (empty($flags[$field]) || $flags[$field] != 'primary_key') {
+ $flags[$field] = $flag;
+ }
+ }
+ }
+ }
+
+ $res = array();
+
+ if ($mode) {
+ $res['num_fields'] = count($fields);
+ }
+
+ foreach ($fields as $i => $field) {
+ $definition = $this->getTableFieldDefinition($result, $field);
+ if (PEAR::isError($definition)) {
+ $db->setOption('idxname_format', $idxname_format);
+ return $definition;
+ }
+ $res[$i] = $definition[0];
+ $res[$i]['name'] = $field;
+ $res[$i]['table'] = $result;
+ $res[$i]['type'] = preg_replace('/^([a-z]+).*$/i', '\\1', trim($definition[0]['nativetype']));
+ // 'primary_key', 'unique_key', 'multiple_key'
+ $res[$i]['flags'] = empty($flags[$field]) ? '' : $flags[$field];
+ // not_null', 'unsigned', 'auto_increment', 'default_[rawencodedvalue]'
+ if (!empty($res[$i]['notnull'])) {
+ $res[$i]['flags'].= ' not_null';
+ }
+ if (!empty($res[$i]['unsigned'])) {
+ $res[$i]['flags'].= ' unsigned';
+ }
+ if (!empty($res[$i]['auto_increment'])) {
+ $res[$i]['flags'].= ' autoincrement';
+ }
+ if (!empty($res[$i]['default'])) {
+ $res[$i]['flags'].= ' default_'.rawurlencode($res[$i]['default']);
+ }
+
+ if ($mode & MDB2_TABLEINFO_ORDER) {
+ $res['order'][$res[$i]['name']] = $i;
+ }
+ if ($mode & MDB2_TABLEINFO_ORDERTABLE) {
+ $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
+ }
+ }
+
+ $db->setOption('idxname_format', $idxname_format);
+ return $res;
+ }
+}
?>
\ No newline at end of file
diff --git a/3rdparty/MDB2/Driver/Reverse/mysql.php b/3rdparty/MDB2/Driver/Reverse/mysql.php
index 6e366c22a5..7b9b4e0019 100644
--- a/3rdparty/MDB2/Driver/Reverse/mysql.php
+++ b/3rdparty/MDB2/Driver/Reverse/mysql.php
@@ -1,536 +1,546 @@
- |
-// +----------------------------------------------------------------------+
-//
-// $Id: mysql.php,v 1.80 2008/03/26 21:15:37 quipo Exp $
-//
-
-require_once('MDB2/Driver/Reverse/Common.php');
-
-/**
- * MDB2 MySQL driver for the schema reverse engineering module
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- * @author Lorenzo Alberton
- */
-class MDB2_Driver_Reverse_mysql extends MDB2_Driver_Reverse_Common
-{
- // {{{ getTableFieldDefinition()
-
- /**
- * Get the structure of a field into an array
- *
- * @param string $table_name name of table that should be used in method
- * @param string $field_name name of field that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- */
- function getTableFieldDefinition($table_name, $field_name)
- {
- $db =$this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $result = $db->loadModule('Datatype', null, true);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- list($schema, $table) = $this->splitTableSchema($table_name);
-
- $table = $db->quoteIdentifier($table, true);
- $query = "SHOW FULL COLUMNS FROM $table LIKE ".$db->quote($field_name);
- $columns = $db->queryAll($query, null, MDB2_FETCHMODE_ASSOC);
- if (PEAR::isError($columns)) {
- return $columns;
- }
- foreach ($columns as $column) {
- $column = array_change_key_case($column, CASE_LOWER);
- $column['name'] = $column['field'];
- unset($column['field']);
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($db->options['field_case'] == CASE_LOWER) {
- $column['name'] = strtolower($column['name']);
- } else {
- $column['name'] = strtoupper($column['name']);
- }
- } else {
- $column = array_change_key_case($column, $db->options['field_case']);
- }
- if ($field_name == $column['name']) {
- $mapped_datatype = $db->datatype->mapNativeDatatype($column);
- if (PEAR::isError($mapped_datatype)) {
- return $mapped_datatype;
- }
- list($types, $length, $unsigned, $fixed) = $mapped_datatype;
- $notnull = false;
- if (empty($column['null']) || $column['null'] !== 'YES') {
- $notnull = true;
- }
- $default = false;
- if (array_key_exists('default', $column)) {
- $default = $column['default'];
- if (is_null($default) && $notnull) {
- $default = '';
- }
- }
- $autoincrement = false;
- if (!empty($column['extra']) && $column['extra'] == 'auto_increment') {
- $autoincrement = true;
- }
- $collate = null;
- if (!empty($column['collation'])) {
- $collate = $column['collation'];
- $charset = preg_replace('/(.+?)(_.+)?/', '$1', $collate);
- }
-
- $definition[0] = array(
- 'notnull' => $notnull,
- 'nativetype' => preg_replace('/^([a-z]+)[^a-z].*/i', '\\1', $column['type'])
- );
- if (!is_null($length)) {
- $definition[0]['length'] = $length;
- }
- if (!is_null($unsigned)) {
- $definition[0]['unsigned'] = $unsigned;
- }
- if (!is_null($fixed)) {
- $definition[0]['fixed'] = $fixed;
- }
- if ($default !== false) {
- $definition[0]['default'] = $default;
- }
- if ($autoincrement !== false) {
- $definition[0]['autoincrement'] = $autoincrement;
- }
- if (!is_null($collate)) {
- $definition[0]['collate'] = $collate;
- $definition[0]['charset'] = $charset;
- }
- foreach ($types as $key => $type) {
- $definition[$key] = $definition[0];
- if ($type == 'clob' || $type == 'blob') {
- unset($definition[$key]['default']);
- } elseif ($type == 'timestamp' && $notnull && empty($definition[$key]['default'])) {
- $definition[$key]['default'] = '0000-00-00 00:00:00';
- }
- $definition[$key]['type'] = $type;
- $definition[$key]['mdb2type'] = $type;
- }
- return $definition;
- }
- }
-
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'it was not specified an existing table column', __FUNCTION__);
- }
-
- // }}}
- // {{{ getTableIndexDefinition()
-
- /**
- * Get the structure of an index into an array
- *
- * @param string $table_name name of table that should be used in method
- * @param string $index_name name of index that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- */
- function getTableIndexDefinition($table_name, $index_name)
- {
- $db =$this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- list($schema, $table) = $this->splitTableSchema($table_name);
-
- $table = $db->quoteIdentifier($table, true);
- $query = "SHOW INDEX FROM $table /*!50002 WHERE Key_name = %s */";
- $index_name_mdb2 = $db->getIndexName($index_name);
- $result = $db->queryRow(sprintf($query, $db->quote($index_name_mdb2)));
- if (!PEAR::isError($result) && !is_null($result)) {
- // apply 'idxname_format' only if the query succeeded, otherwise
- // fallback to the given $index_name, without transformation
- $index_name = $index_name_mdb2;
- }
- $result = $db->query(sprintf($query, $db->quote($index_name)));
- if (PEAR::isError($result)) {
- return $result;
- }
- $colpos = 1;
- $definition = array();
- while (is_array($row = $result->fetchRow(MDB2_FETCHMODE_ASSOC))) {
- $row = array_change_key_case($row, CASE_LOWER);
- $key_name = $row['key_name'];
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($db->options['field_case'] == CASE_LOWER) {
- $key_name = strtolower($key_name);
- } else {
- $key_name = strtoupper($key_name);
- }
- }
- if ($index_name == $key_name) {
- if (!$row['non_unique']) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- $index_name . ' is not an existing table index', __FUNCTION__);
- }
- $column_name = $row['column_name'];
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($db->options['field_case'] == CASE_LOWER) {
- $column_name = strtolower($column_name);
- } else {
- $column_name = strtoupper($column_name);
- }
- }
- $definition['fields'][$column_name] = array(
- 'position' => $colpos++
- );
- if (!empty($row['collation'])) {
- $definition['fields'][$column_name]['sorting'] = ($row['collation'] == 'A'
- ? 'ascending' : 'descending');
- }
- }
- }
- $result->free();
- if (empty($definition['fields'])) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- $index_name . ' is not an existing table index', __FUNCTION__);
- }
- return $definition;
- }
-
- // }}}
- // {{{ getTableConstraintDefinition()
-
- /**
- * Get the structure of a constraint into an array
- *
- * @param string $table_name name of table that should be used in method
- * @param string $constraint_name name of constraint that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- */
- function getTableConstraintDefinition($table_name, $constraint_name)
- {
- $db =$this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- list($schema, $table) = $this->splitTableSchema($table_name);
- $constraint_name_original = $constraint_name;
-
- $table = $db->quoteIdentifier($table, true);
- $query = "SHOW INDEX FROM $table /*!50002 WHERE Key_name = %s */";
- if (strtolower($constraint_name) != 'primary') {
- $constraint_name_mdb2 = $db->getIndexName($constraint_name);
- $result = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2)));
- if (!PEAR::isError($result) && !is_null($result)) {
- // apply 'idxname_format' only if the query succeeded, otherwise
- // fallback to the given $index_name, without transformation
- $constraint_name = $constraint_name_mdb2;
- }
- }
- $result = $db->query(sprintf($query, $db->quote($constraint_name)));
- if (PEAR::isError($result)) {
- return $result;
- }
- $colpos = 1;
- //default values, eventually overridden
- $definition = array(
- 'primary' => false,
- 'unique' => false,
- 'foreign' => false,
- 'check' => false,
- 'fields' => array(),
- 'references' => array(
- 'table' => '',
- 'fields' => array(),
- ),
- 'onupdate' => '',
- 'ondelete' => '',
- 'match' => '',
- 'deferrable' => false,
- 'initiallydeferred' => false,
- );
- while (is_array($row = $result->fetchRow(MDB2_FETCHMODE_ASSOC))) {
- $row = array_change_key_case($row, CASE_LOWER);
- $key_name = $row['key_name'];
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($db->options['field_case'] == CASE_LOWER) {
- $key_name = strtolower($key_name);
- } else {
- $key_name = strtoupper($key_name);
- }
- }
- if ($constraint_name == $key_name) {
- if ($row['non_unique']) {
- //FOREIGN KEY?
- return $this->_getTableFKConstraintDefinition($table, $constraint_name_original, $definition);
- }
- if ($row['key_name'] == 'PRIMARY') {
- $definition['primary'] = true;
- } elseif (!$row['non_unique']) {
- $definition['unique'] = true;
- }
- $column_name = $row['column_name'];
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($db->options['field_case'] == CASE_LOWER) {
- $column_name = strtolower($column_name);
- } else {
- $column_name = strtoupper($column_name);
- }
- }
- $definition['fields'][$column_name] = array(
- 'position' => $colpos++
- );
- if (!empty($row['collation'])) {
- $definition['fields'][$column_name]['sorting'] = ($row['collation'] == 'A'
- ? 'ascending' : 'descending');
- }
- }
- }
- $result->free();
- if (empty($definition['fields'])) {
- return $this->_getTableFKConstraintDefinition($table, $constraint_name_original, $definition);
- }
- return $definition;
- }
-
- // }}}
- // {{{ _getTableFKConstraintDefinition()
-
- /**
- * Get the FK definition from the CREATE TABLE statement
- *
- * @param string $table table name
- * @param string $constraint_name constraint name
- * @param array $definition default values for constraint definition
- *
- * @return array|PEAR_Error
- * @access private
- */
- function _getTableFKConstraintDefinition($table, $constraint_name, $definition)
- {
- $db =$this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- $query = 'SHOW CREATE TABLE '. $db->escape($table);
- $constraint = $db->queryOne($query, 'text', 1);
- if (!PEAR::isError($constraint) && !empty($constraint)) {
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($db->options['field_case'] == CASE_LOWER) {
- $constraint = strtolower($constraint);
- } else {
- $constraint = strtoupper($constraint);
- }
- }
- $constraint_name_original = $constraint_name;
- $constraint_name = $db->getIndexName($constraint_name);
- $pattern = '/\bCONSTRAINT\s+'.$constraint_name.'\s+FOREIGN KEY\s+\(([^\)]+)\) \bREFERENCES\b ([^ ]+) \(([^\)]+)\)/i';
- if (!preg_match($pattern, str_replace('`', '', $constraint), $matches)) {
- //fallback to original constraint name
- $pattern = '/\bCONSTRAINT\s+'.$constraint_name_original.'\s+FOREIGN KEY\s+\(([^\)]+)\) \bREFERENCES\b ([^ ]+) \(([^\)]+)\)/i';
- }
- if (preg_match($pattern, str_replace('`', '', $constraint), $matches)) {
- $definition['foreign'] = true;
- $column_names = explode(',', $matches[1]);
- $referenced_cols = explode(',', $matches[3]);
- $definition['references'] = array(
- 'table' => $matches[2],
- 'fields' => array(),
- );
- $colpos = 1;
- foreach ($column_names as $column_name) {
- $definition['fields'][trim($column_name)] = array(
- 'position' => $colpos++
- );
- }
- $colpos = 1;
- foreach ($referenced_cols as $column_name) {
- $definition['references']['fields'][trim($column_name)] = array(
- 'position' => $colpos++
- );
- }
- $definition['onupdate'] = 'NO ACTION';
- $definition['ondelete'] = 'NO ACTION';
- $definition['match'] = 'SIMPLE';
- return $definition;
- }
- }
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- $constraint_name . ' is not an existing table constraint', __FUNCTION__);
- }
-
- // }}}
- // {{{ getTriggerDefinition()
-
- /**
- * Get the structure of a trigger into an array
- *
- * EXPERIMENTAL
- *
- * WARNING: this function is experimental and may change the returned value
- * at any time until labelled as non-experimental
- *
- * @param string $trigger name of trigger that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- */
- function getTriggerDefinition($trigger)
- {
- $db =$this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = 'SELECT trigger_name,
- event_object_table AS table_name,
- action_statement AS trigger_body,
- action_timing AS trigger_type,
- event_manipulation AS trigger_event
- FROM information_schema.triggers
- WHERE trigger_name = '. $db->quote($trigger, 'text');
- $types = array(
- 'trigger_name' => 'text',
- 'table_name' => 'text',
- 'trigger_body' => 'text',
- 'trigger_type' => 'text',
- 'trigger_event' => 'text',
- );
- $def = $db->queryRow($query, $types, MDB2_FETCHMODE_ASSOC);
- if (PEAR::isError($def)) {
- return $def;
- }
- $def['trigger_comment'] = '';
- $def['trigger_enabled'] = true;
- return $def;
- }
-
- // }}}
- // {{{ tableInfo()
-
- /**
- * Returns information about a table or a result set
- *
- * @param object|string $result MDB2_result object from a query or a
- * string containing the name of a table.
- * While this also accepts a query result
- * resource identifier, this behavior is
- * deprecated.
- * @param int $mode a valid tableInfo mode
- *
- * @return array an associative array with the information requested.
- * A MDB2_Error object on failure.
- *
- * @see MDB2_Driver_Common::setOption()
- */
- function tableInfo($result, $mode = null)
- {
- if (is_string($result)) {
- return parent::tableInfo($result, $mode);
- }
-
- $db =$this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $resource = MDB2::isResultCommon($result) ? $result->getResource() : $result;
- if (!is_resource($resource)) {
- return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'Could not generate result resource', __FUNCTION__);
- }
-
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($db->options['field_case'] == CASE_LOWER) {
- $case_func = 'strtolower';
- } else {
- $case_func = 'strtoupper';
- }
- } else {
- $case_func = 'strval';
- }
-
- $count = @mysql_num_fields($resource);
- $res = array();
- if ($mode) {
- $res['num_fields'] = $count;
- }
-
- $db->loadModule('Datatype', null, true);
- for ($i = 0; $i < $count; $i++) {
- $res[$i] = array(
- 'table' => $case_func(@mysql_field_table($resource, $i)),
- 'name' => $case_func(@mysql_field_name($resource, $i)),
- 'type' => @mysql_field_type($resource, $i),
- 'length' => @mysql_field_len($resource, $i),
- 'flags' => @mysql_field_flags($resource, $i),
- );
- if ($res[$i]['type'] == 'string') {
- $res[$i]['type'] = 'char';
- } elseif ($res[$i]['type'] == 'unknown') {
- $res[$i]['type'] = 'decimal';
- }
- $mdb2type_info = $db->datatype->mapNativeDatatype($res[$i]);
- if (PEAR::isError($mdb2type_info)) {
- return $mdb2type_info;
- }
- $res[$i]['mdb2type'] = $mdb2type_info[0][0];
- if ($mode & MDB2_TABLEINFO_ORDER) {
- $res['order'][$res[$i]['name']] = $i;
- }
- if ($mode & MDB2_TABLEINFO_ORDERTABLE) {
- $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
- }
- }
-
- return $res;
- }
-}
+ |
+// +----------------------------------------------------------------------+
+//
+// $Id: mysql.php 295587 2010-02-28 17:16:38Z quipo $
+//
+
+require_once 'MDB2/Driver/Reverse/Common.php';
+
+/**
+ * MDB2 MySQL driver for the schema reverse engineering module
+ *
+ * @package MDB2
+ * @category Database
+ * @author Lukas Smith
+ * @author Lorenzo Alberton
+ */
+class MDB2_Driver_Reverse_mysql extends MDB2_Driver_Reverse_Common
+{
+ // {{{ getTableFieldDefinition()
+
+ /**
+ * Get the structure of a field into an array
+ *
+ * @param string $table_name name of table that should be used in method
+ * @param string $field_name name of field that should be used in method
+ * @return mixed data array on success, a MDB2 error on failure
+ * @access public
+ */
+ function getTableFieldDefinition($table_name, $field_name)
+ {
+ $db = $this->getDBInstance();
+ if (PEAR::isError($db)) {
+ return $db;
+ }
+
+ $result = $db->loadModule('Datatype', null, true);
+ if (PEAR::isError($result)) {
+ return $result;
+ }
+
+ list($schema, $table) = $this->splitTableSchema($table_name);
+
+ $table = $db->quoteIdentifier($table, true);
+ $query = "SHOW FULL COLUMNS FROM $table LIKE ".$db->quote($field_name);
+ $columns = $db->queryAll($query, null, MDB2_FETCHMODE_ASSOC);
+ if (PEAR::isError($columns)) {
+ return $columns;
+ }
+ foreach ($columns as $column) {
+ $column = array_change_key_case($column, CASE_LOWER);
+ $column['name'] = $column['field'];
+ unset($column['field']);
+ if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
+ if ($db->options['field_case'] == CASE_LOWER) {
+ $column['name'] = strtolower($column['name']);
+ } else {
+ $column['name'] = strtoupper($column['name']);
+ }
+ } else {
+ $column = array_change_key_case($column, $db->options['field_case']);
+ }
+ if ($field_name == $column['name']) {
+ $mapped_datatype = $db->datatype->mapNativeDatatype($column);
+ if (PEAR::isError($mapped_datatype)) {
+ return $mapped_datatype;
+ }
+ list($types, $length, $unsigned, $fixed) = $mapped_datatype;
+ $notnull = false;
+ if (empty($column['null']) || $column['null'] !== 'YES') {
+ $notnull = true;
+ }
+ $default = false;
+ if (array_key_exists('default', $column)) {
+ $default = $column['default'];
+ if ((null === $default) && $notnull) {
+ $default = '';
+ }
+ }
+ $definition[0] = array(
+ 'notnull' => $notnull,
+ 'nativetype' => preg_replace('/^([a-z]+)[^a-z].*/i', '\\1', $column['type'])
+ );
+ $autoincrement = false;
+ if (!empty($column['extra'])) {
+ if ($column['extra'] == 'auto_increment') {
+ $autoincrement = true;
+ } else {
+ $definition[0]['extra'] = $column['extra'];
+ }
+ }
+ $collate = null;
+ if (!empty($column['collation'])) {
+ $collate = $column['collation'];
+ $charset = preg_replace('/(.+?)(_.+)?/', '$1', $collate);
+ }
+
+ if (null !== $length) {
+ $definition[0]['length'] = $length;
+ }
+ if (null !== $unsigned) {
+ $definition[0]['unsigned'] = $unsigned;
+ }
+ if (null !== $fixed) {
+ $definition[0]['fixed'] = $fixed;
+ }
+ if ($default !== false) {
+ $definition[0]['default'] = $default;
+ }
+ if ($autoincrement !== false) {
+ $definition[0]['autoincrement'] = $autoincrement;
+ }
+ if (null !== $collate) {
+ $definition[0]['collate'] = $collate;
+ $definition[0]['charset'] = $charset;
+ }
+ foreach ($types as $key => $type) {
+ $definition[$key] = $definition[0];
+ if ($type == 'clob' || $type == 'blob') {
+ unset($definition[$key]['default']);
+ } elseif ($type == 'timestamp' && $notnull && empty($definition[$key]['default'])) {
+ $definition[$key]['default'] = '0000-00-00 00:00:00';
+ }
+ $definition[$key]['type'] = $type;
+ $definition[$key]['mdb2type'] = $type;
+ }
+ return $definition;
+ }
+ }
+
+ return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
+ 'it was not specified an existing table column', __FUNCTION__);
+ }
+
+ // }}}
+ // {{{ getTableIndexDefinition()
+
+ /**
+ * Get the structure of an index into an array
+ *
+ * @param string $table_name name of table that should be used in method
+ * @param string $index_name name of index that should be used in method
+ * @return mixed data array on success, a MDB2 error on failure
+ * @access public
+ */
+ function getTableIndexDefinition($table_name, $index_name)
+ {
+ $db = $this->getDBInstance();
+ if (PEAR::isError($db)) {
+ return $db;
+ }
+
+ list($schema, $table) = $this->splitTableSchema($table_name);
+
+ $table = $db->quoteIdentifier($table, true);
+ $query = "SHOW INDEX FROM $table /*!50002 WHERE Key_name = %s */";
+ $index_name_mdb2 = $db->getIndexName($index_name);
+ $result = $db->queryRow(sprintf($query, $db->quote($index_name_mdb2)));
+ if (!PEAR::isError($result) && (null !== $result)) {
+ // apply 'idxname_format' only if the query succeeded, otherwise
+ // fallback to the given $index_name, without transformation
+ $index_name = $index_name_mdb2;
+ }
+ $result = $db->query(sprintf($query, $db->quote($index_name)));
+ if (PEAR::isError($result)) {
+ return $result;
+ }
+ $colpos = 1;
+ $definition = array();
+ while (is_array($row = $result->fetchRow(MDB2_FETCHMODE_ASSOC))) {
+ $row = array_change_key_case($row, CASE_LOWER);
+ $key_name = $row['key_name'];
+ if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
+ if ($db->options['field_case'] == CASE_LOWER) {
+ $key_name = strtolower($key_name);
+ } else {
+ $key_name = strtoupper($key_name);
+ }
+ }
+ if ($index_name == $key_name) {
+ if (!$row['non_unique']) {
+ return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
+ $index_name . ' is not an existing table index', __FUNCTION__);
+ }
+ $column_name = $row['column_name'];
+ if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
+ if ($db->options['field_case'] == CASE_LOWER) {
+ $column_name = strtolower($column_name);
+ } else {
+ $column_name = strtoupper($column_name);
+ }
+ }
+ $definition['fields'][$column_name] = array(
+ 'position' => $colpos++
+ );
+ if (!empty($row['collation'])) {
+ $definition['fields'][$column_name]['sorting'] = ($row['collation'] == 'A'
+ ? 'ascending' : 'descending');
+ }
+ }
+ }
+ $result->free();
+ if (empty($definition['fields'])) {
+ return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
+ $index_name . ' is not an existing table index', __FUNCTION__);
+ }
+ return $definition;
+ }
+
+ // }}}
+ // {{{ getTableConstraintDefinition()
+
+ /**
+ * Get the structure of a constraint into an array
+ *
+ * @param string $table_name name of table that should be used in method
+ * @param string $constraint_name name of constraint that should be used in method
+ * @return mixed data array on success, a MDB2 error on failure
+ * @access public
+ */
+ function getTableConstraintDefinition($table_name, $constraint_name)
+ {
+ $db = $this->getDBInstance();
+ if (PEAR::isError($db)) {
+ return $db;
+ }
+
+ list($schema, $table) = $this->splitTableSchema($table_name);
+ $constraint_name_original = $constraint_name;
+
+ $table = $db->quoteIdentifier($table, true);
+ $query = "SHOW INDEX FROM $table /*!50002 WHERE Key_name = %s */";
+ if (strtolower($constraint_name) != 'primary') {
+ $constraint_name_mdb2 = $db->getIndexName($constraint_name);
+ $result = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2)));
+ if (!PEAR::isError($result) && (null !== $result)) {
+ // apply 'idxname_format' only if the query succeeded, otherwise
+ // fallback to the given $index_name, without transformation
+ $constraint_name = $constraint_name_mdb2;
+ }
+ }
+ $result = $db->query(sprintf($query, $db->quote($constraint_name)));
+ if (PEAR::isError($result)) {
+ return $result;
+ }
+ $colpos = 1;
+ //default values, eventually overridden
+ $definition = array(
+ 'primary' => false,
+ 'unique' => false,
+ 'foreign' => false,
+ 'check' => false,
+ 'fields' => array(),
+ 'references' => array(
+ 'table' => '',
+ 'fields' => array(),
+ ),
+ 'onupdate' => '',
+ 'ondelete' => '',
+ 'match' => '',
+ 'deferrable' => false,
+ 'initiallydeferred' => false,
+ );
+ while (is_array($row = $result->fetchRow(MDB2_FETCHMODE_ASSOC))) {
+ $row = array_change_key_case($row, CASE_LOWER);
+ $key_name = $row['key_name'];
+ if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
+ if ($db->options['field_case'] == CASE_LOWER) {
+ $key_name = strtolower($key_name);
+ } else {
+ $key_name = strtoupper($key_name);
+ }
+ }
+ if ($constraint_name == $key_name) {
+ if ($row['non_unique']) {
+ //FOREIGN KEY?
+ return $this->_getTableFKConstraintDefinition($table, $constraint_name_original, $definition);
+ }
+ if ($row['key_name'] == 'PRIMARY') {
+ $definition['primary'] = true;
+ } elseif (!$row['non_unique']) {
+ $definition['unique'] = true;
+ }
+ $column_name = $row['column_name'];
+ if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
+ if ($db->options['field_case'] == CASE_LOWER) {
+ $column_name = strtolower($column_name);
+ } else {
+ $column_name = strtoupper($column_name);
+ }
+ }
+ $definition['fields'][$column_name] = array(
+ 'position' => $colpos++
+ );
+ if (!empty($row['collation'])) {
+ $definition['fields'][$column_name]['sorting'] = ($row['collation'] == 'A'
+ ? 'ascending' : 'descending');
+ }
+ }
+ }
+ $result->free();
+ if (empty($definition['fields'])) {
+ return $this->_getTableFKConstraintDefinition($table, $constraint_name_original, $definition);
+ }
+ return $definition;
+ }
+
+ // }}}
+ // {{{ _getTableFKConstraintDefinition()
+
+ /**
+ * Get the FK definition from the CREATE TABLE statement
+ *
+ * @param string $table table name
+ * @param string $constraint_name constraint name
+ * @param array $definition default values for constraint definition
+ *
+ * @return array|PEAR_Error
+ * @access private
+ */
+ function _getTableFKConstraintDefinition($table, $constraint_name, $definition)
+ {
+ $db = $this->getDBInstance();
+ if (PEAR::isError($db)) {
+ return $db;
+ }
+ //Use INFORMATION_SCHEMA instead?
+ //SELECT *
+ // FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS
+ // WHERE CONSTRAINT_SCHEMA = '$dbname'
+ // AND TABLE_NAME = '$table'
+ // AND CONSTRAINT_NAME = '$constraint_name';
+ $query = 'SHOW CREATE TABLE '. $db->escape($table);
+ $constraint = $db->queryOne($query, 'text', 1);
+ if (!PEAR::isError($constraint) && !empty($constraint)) {
+ if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
+ if ($db->options['field_case'] == CASE_LOWER) {
+ $constraint = strtolower($constraint);
+ } else {
+ $constraint = strtoupper($constraint);
+ }
+ }
+ $constraint_name_original = $constraint_name;
+ $constraint_name = $db->getIndexName($constraint_name);
+ $pattern = '/\bCONSTRAINT\s+'.$constraint_name.'\s+FOREIGN KEY\s+\(([^\)]+)\) \bREFERENCES\b ([^\s]+) \(([^\)]+)\)(?: ON DELETE ([^\s]+))?(?: ON UPDATE ([^\s]+))?/i';
+ if (!preg_match($pattern, str_replace('`', '', $constraint), $matches)) {
+ //fallback to original constraint name
+ $pattern = '/\bCONSTRAINT\s+'.$constraint_name_original.'\s+FOREIGN KEY\s+\(([^\)]+)\) \bREFERENCES\b ([^\s]+) \(([^\)]+)\)(?: ON DELETE ([^\s]+))?(?: ON UPDATE ([^\s]+))?/i';
+ }
+ if (preg_match($pattern, str_replace('`', '', $constraint), $matches)) {
+ $definition['foreign'] = true;
+ $column_names = explode(',', $matches[1]);
+ $referenced_cols = explode(',', $matches[3]);
+ $definition['references'] = array(
+ 'table' => $matches[2],
+ 'fields' => array(),
+ );
+ $colpos = 1;
+ foreach ($column_names as $column_name) {
+ $definition['fields'][trim($column_name)] = array(
+ 'position' => $colpos++
+ );
+ }
+ $colpos = 1;
+ foreach ($referenced_cols as $column_name) {
+ $definition['references']['fields'][trim($column_name)] = array(
+ 'position' => $colpos++
+ );
+ }
+ $definition['ondelete'] = empty($matches[4]) ? 'RESTRICT' : strtoupper($matches[4]);
+ $definition['onupdate'] = empty($matches[5]) ? 'RESTRICT' : strtoupper($matches[5]);
+ $definition['match'] = 'SIMPLE';
+ return $definition;
+ }
+ }
+ return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
+ $constraint_name . ' is not an existing table constraint', __FUNCTION__);
+ }
+
+ // }}}
+ // {{{ getTriggerDefinition()
+
+ /**
+ * Get the structure of a trigger into an array
+ *
+ * EXPERIMENTAL
+ *
+ * WARNING: this function is experimental and may change the returned value
+ * at any time until labelled as non-experimental
+ *
+ * @param string $trigger name of trigger that should be used in method
+ * @return mixed data array on success, a MDB2 error on failure
+ * @access public
+ */
+ function getTriggerDefinition($trigger)
+ {
+ $db = $this->getDBInstance();
+ if (PEAR::isError($db)) {
+ return $db;
+ }
+
+ $query = 'SELECT trigger_name,
+ event_object_table AS table_name,
+ action_statement AS trigger_body,
+ action_timing AS trigger_type,
+ event_manipulation AS trigger_event
+ FROM information_schema.triggers
+ WHERE trigger_name = '. $db->quote($trigger, 'text');
+ $types = array(
+ 'trigger_name' => 'text',
+ 'table_name' => 'text',
+ 'trigger_body' => 'text',
+ 'trigger_type' => 'text',
+ 'trigger_event' => 'text',
+ );
+ $def = $db->queryRow($query, $types, MDB2_FETCHMODE_ASSOC);
+ if (PEAR::isError($def)) {
+ return $def;
+ }
+ $def['trigger_comment'] = '';
+ $def['trigger_enabled'] = true;
+ return $def;
+ }
+
+ // }}}
+ // {{{ tableInfo()
+
+ /**
+ * Returns information about a table or a result set
+ *
+ * @param object|string $result MDB2_result object from a query or a
+ * string containing the name of a table.
+ * While this also accepts a query result
+ * resource identifier, this behavior is
+ * deprecated.
+ * @param int $mode a valid tableInfo mode
+ *
+ * @return array an associative array with the information requested.
+ * A MDB2_Error object on failure.
+ *
+ * @see MDB2_Driver_Common::setOption()
+ */
+ function tableInfo($result, $mode = null)
+ {
+ if (is_string($result)) {
+ return parent::tableInfo($result, $mode);
+ }
+
+ $db = $this->getDBInstance();
+ if (PEAR::isError($db)) {
+ return $db;
+ }
+
+ $resource = MDB2::isResultCommon($result) ? $result->getResource() : $result;
+ if (!is_resource($resource)) {
+ return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
+ 'Could not generate result resource', __FUNCTION__);
+ }
+
+ if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
+ if ($db->options['field_case'] == CASE_LOWER) {
+ $case_func = 'strtolower';
+ } else {
+ $case_func = 'strtoupper';
+ }
+ } else {
+ $case_func = 'strval';
+ }
+
+ $count = @mysql_num_fields($resource);
+ $res = array();
+ if ($mode) {
+ $res['num_fields'] = $count;
+ }
+
+ $db->loadModule('Datatype', null, true);
+ for ($i = 0; $i < $count; $i++) {
+ $res[$i] = array(
+ 'table' => $case_func(@mysql_field_table($resource, $i)),
+ 'name' => $case_func(@mysql_field_name($resource, $i)),
+ 'type' => @mysql_field_type($resource, $i),
+ 'length' => @mysql_field_len($resource, $i),
+ 'flags' => @mysql_field_flags($resource, $i),
+ );
+ if ($res[$i]['type'] == 'string') {
+ $res[$i]['type'] = 'char';
+ } elseif ($res[$i]['type'] == 'unknown') {
+ $res[$i]['type'] = 'decimal';
+ }
+ $mdb2type_info = $db->datatype->mapNativeDatatype($res[$i]);
+ if (PEAR::isError($mdb2type_info)) {
+ return $mdb2type_info;
+ }
+ $res[$i]['mdb2type'] = $mdb2type_info[0][0];
+ if ($mode & MDB2_TABLEINFO_ORDER) {
+ $res['order'][$res[$i]['name']] = $i;
+ }
+ if ($mode & MDB2_TABLEINFO_ORDERTABLE) {
+ $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
+ }
+ }
+
+ return $res;
+ }
+}
?>
\ No newline at end of file
diff --git a/3rdparty/MDB2/Driver/Reverse/pgsql.php b/3rdparty/MDB2/Driver/Reverse/pgsql.php
index 8669c2b919..45aa5a1503 100644
--- a/3rdparty/MDB2/Driver/Reverse/pgsql.php
+++ b/3rdparty/MDB2/Driver/Reverse/pgsql.php
@@ -1,573 +1,574 @@
- |
-// | Lorenzo Alberton |
-// +----------------------------------------------------------------------+
-//
-// $Id: pgsql.php,v 1.75 2008/08/22 16:36:20 quipo Exp $
-
-require_once('MDB2/Driver/Reverse/Common.php');
-
-/**
- * MDB2 PostGreSQL driver for the schema reverse engineering module
- *
- * @package MDB2
- * @category Database
- * @author Paul Cooper
- * @author Lorenzo Alberton
- */
-class MDB2_Driver_Reverse_pgsql extends MDB2_Driver_Reverse_Common
-{
- // {{{ getTableFieldDefinition()
-
- /**
- * Get the structure of a field into an array
- *
- * @param string $table_name name of table that should be used in method
- * @param string $field_name name of field that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- */
- function getTableFieldDefinition($table_name, $field_name)
- {
- $db =$this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $result = $db->loadModule('Datatype', null, true);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- list($schema, $table) = $this->splitTableSchema($table_name);
-
- $query = "SELECT a.attname AS name,
- t.typname AS type,
- CASE a.attlen
- WHEN -1 THEN
- CASE t.typname
- WHEN 'numeric' THEN (a.atttypmod / 65536)
- WHEN 'decimal' THEN (a.atttypmod / 65536)
- WHEN 'money' THEN (a.atttypmod / 65536)
- ELSE CASE a.atttypmod
- WHEN -1 THEN NULL
- ELSE a.atttypmod - 4
- END
- END
- ELSE a.attlen
- END AS length,
- CASE t.typname
- WHEN 'numeric' THEN (a.atttypmod % 65536) - 4
- WHEN 'decimal' THEN (a.atttypmod % 65536) - 4
- WHEN 'money' THEN (a.atttypmod % 65536) - 4
- ELSE 0
- END AS scale,
- a.attnotnull,
- a.atttypmod,
- a.atthasdef,
- (SELECT substring(pg_get_expr(d.adbin, d.adrelid) for 128)
- FROM pg_attrdef d
- WHERE d.adrelid = a.attrelid
- AND d.adnum = a.attnum
- AND a.atthasdef
- ) as default
- FROM pg_attribute a,
- pg_class c,
- pg_type t
- WHERE c.relname = ".$db->quote($table, 'text')."
- AND a.atttypid = t.oid
- AND c.oid = a.attrelid
- AND NOT a.attisdropped
- AND a.attnum > 0
- AND a.attname = ".$db->quote($field_name, 'text')."
- ORDER BY a.attnum";
- $column = $db->queryRow($query, null, MDB2_FETCHMODE_ASSOC);
- if (PEAR::isError($column)) {
- return $column;
- }
-
- if (empty($column)) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'it was not specified an existing table column', __FUNCTION__);
- }
-
- $column = array_change_key_case($column, CASE_LOWER);
- $mapped_datatype = $db->datatype->mapNativeDatatype($column);
- if (PEAR::isError($mapped_datatype)) {
- return $mapped_datatype;
- }
- list($types, $length, $unsigned, $fixed) = $mapped_datatype;
- $notnull = false;
- if (!empty($column['attnotnull']) && $column['attnotnull'] == 't') {
- $notnull = true;
- }
- $default = null;
- if ($column['atthasdef'] === 't'
- && !preg_match("/nextval\('([^']+)'/", $column['default'])
- ) {
- $pattern = '/^\'(.*)\'::[\w ]+$/i';
- $default = $column['default'];#substr($column['adsrc'], 1, -1);
- if (is_null($default) && $notnull) {
- $default = '';
- } elseif (!empty($default) && preg_match($pattern, $default)) {
- //remove data type cast
- $default = preg_replace ($pattern, '\\1', $default);
- }
- }
- $autoincrement = false;
- if (preg_match("/nextval\('([^']+)'/", $column['default'], $nextvals)) {
- $autoincrement = true;
- }
- $definition[0] = array('notnull' => $notnull, 'nativetype' => $column['type']);
- if (!is_null($length)) {
- $definition[0]['length'] = $length;
- }
- if (!is_null($unsigned)) {
- $definition[0]['unsigned'] = $unsigned;
- }
- if (!is_null($fixed)) {
- $definition[0]['fixed'] = $fixed;
- }
- if ($default !== false) {
- $definition[0]['default'] = $default;
- }
- if ($autoincrement !== false) {
- $definition[0]['autoincrement'] = $autoincrement;
- }
- foreach ($types as $key => $type) {
- $definition[$key] = $definition[0];
- if ($type == 'clob' || $type == 'blob') {
- unset($definition[$key]['default']);
- }
- $definition[$key]['type'] = $type;
- $definition[$key]['mdb2type'] = $type;
- }
- return $definition;
- }
-
- // }}}
- // {{{ getTableIndexDefinition()
-
- /**
- * Get the structure of an index into an array
- *
- * @param string $table_name name of table that should be used in method
- * @param string $index_name name of index that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- */
- function getTableIndexDefinition($table_name, $index_name)
- {
- $db =$this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- list($schema, $table) = $this->splitTableSchema($table_name);
-
- $query = 'SELECT relname, indkey FROM pg_index, pg_class';
- $query.= ' WHERE pg_class.oid = pg_index.indexrelid';
- $query.= " AND indisunique != 't' AND indisprimary != 't'";
- $query.= ' AND pg_class.relname = %s';
- $index_name_mdb2 = $db->getIndexName($index_name);
- $row = $db->queryRow(sprintf($query, $db->quote($index_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC);
- if (PEAR::isError($row) || empty($row)) {
- // fallback to the given $index_name, without transformation
- $row = $db->queryRow(sprintf($query, $db->quote($index_name, 'text')), null, MDB2_FETCHMODE_ASSOC);
- }
- if (PEAR::isError($row)) {
- return $row;
- }
-
- if (empty($row)) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'it was not specified an existing table index', __FUNCTION__);
- }
-
- $row = array_change_key_case($row, CASE_LOWER);
-
- $db->loadModule('Manager', null, true);
- $columns = $db->manager->listTableFields($table_name);
-
- $definition = array();
-
- $index_column_numbers = explode(' ', $row['indkey']);
-
- $colpos = 1;
- foreach ($index_column_numbers as $number) {
- $definition['fields'][$columns[($number - 1)]] = array(
- 'position' => $colpos++,
- 'sorting' => 'ascending',
- );
- }
- return $definition;
- }
-
- // }}}
- // {{{ getTableConstraintDefinition()
-
- /**
- * Get the structure of a constraint into an array
- *
- * @param string $table_name name of table that should be used in method
- * @param string $constraint_name name of constraint that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- */
- function getTableConstraintDefinition($table_name, $constraint_name)
- {
- $db =$this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- list($schema, $table) = $this->splitTableSchema($table_name);
-
- $query = "SELECT c.oid,
- c.conname AS constraint_name,
- CASE WHEN c.contype = 'c' THEN 1 ELSE 0 END AS \"check\",
- CASE WHEN c.contype = 'f' THEN 1 ELSE 0 END AS \"foreign\",
- CASE WHEN c.contype = 'p' THEN 1 ELSE 0 END AS \"primary\",
- CASE WHEN c.contype = 'u' THEN 1 ELSE 0 END AS \"unique\",
- CASE WHEN c.condeferrable = 'f' THEN 0 ELSE 1 END AS deferrable,
- CASE WHEN c.condeferred = 'f' THEN 0 ELSE 1 END AS initiallydeferred,
- --array_to_string(c.conkey, ' ') AS constraint_key,
- t.relname AS table_name,
- t2.relname AS references_table,
- CASE confupdtype
- WHEN 'a' THEN 'NO ACTION'
- WHEN 'r' THEN 'RESTRICT'
- WHEN 'c' THEN 'CASCADE'
- WHEN 'n' THEN 'SET NULL'
- WHEN 'd' THEN 'SET DEFAULT'
- END AS onupdate,
- CASE confdeltype
- WHEN 'a' THEN 'NO ACTION'
- WHEN 'r' THEN 'RESTRICT'
- WHEN 'c' THEN 'CASCADE'
- WHEN 'n' THEN 'SET NULL'
- WHEN 'd' THEN 'SET DEFAULT'
- END AS ondelete,
- CASE confmatchtype
- WHEN 'u' THEN 'UNSPECIFIED'
- WHEN 'f' THEN 'FULL'
- WHEN 'p' THEN 'PARTIAL'
- END AS match,
- --array_to_string(c.confkey, ' ') AS fk_constraint_key,
- consrc
- FROM pg_constraint c
- LEFT JOIN pg_class t ON c.conrelid = t.oid
- LEFT JOIN pg_class t2 ON c.confrelid = t2.oid
- WHERE c.conname = %s
- AND t.relname = " . $db->quote($table, 'text');
- $constraint_name_mdb2 = $db->getIndexName($constraint_name);
- $row = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC);
- if (PEAR::isError($row) || empty($row)) {
- // fallback to the given $index_name, without transformation
- $constraint_name_mdb2 = $constraint_name;
- $row = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC);
- }
- if (PEAR::isError($row)) {
- return $row;
- }
- $uniqueIndex = false;
- if (empty($row)) {
- // We might be looking for a UNIQUE index that was not created
- // as a constraint but should be treated as such.
- $query = 'SELECT relname AS constraint_name,
- indkey,
- 0 AS "check",
- 0 AS "foreign",
- 0 AS "primary",
- 1 AS "unique",
- 0 AS deferrable,
- 0 AS initiallydeferred,
- NULL AS references_table,
- NULL AS onupdate,
- NULL AS ondelete,
- NULL AS match
- FROM pg_index, pg_class
- WHERE pg_class.oid = pg_index.indexrelid
- AND indisunique = \'t\'
- AND pg_class.relname = %s';
- $constraint_name_mdb2 = $db->getIndexName($constraint_name);
- $row = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC);
- if (PEAR::isError($row) || empty($row)) {
- // fallback to the given $index_name, without transformation
- $constraint_name_mdb2 = $constraint_name;
- $row = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC);
- }
- if (PEAR::isError($row)) {
- return $row;
- }
- if (empty($row)) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- $constraint_name . ' is not an existing table constraint', __FUNCTION__);
- }
- $uniqueIndex = true;
- }
-
- $row = array_change_key_case($row, CASE_LOWER);
-
- $definition = array(
- 'primary' => (boolean)$row['primary'],
- 'unique' => (boolean)$row['unique'],
- 'foreign' => (boolean)$row['foreign'],
- 'check' => (boolean)$row['check'],
- 'fields' => array(),
- 'references' => array(
- 'table' => $row['references_table'],
- 'fields' => array(),
- ),
- 'deferrable' => (boolean)$row['deferrable'],
- 'initiallydeferred' => (boolean)$row['initiallydeferred'],
- 'onupdate' => $row['onupdate'],
- 'ondelete' => $row['ondelete'],
- 'match' => $row['match'],
- );
-
- if ($uniqueIndex) {
- $db->loadModule('Manager', null, true);
- $columns = $db->manager->listTableFields($table_name);
- $index_column_numbers = explode(' ', $row['indkey']);
- $colpos = 1;
- foreach ($index_column_numbers as $number) {
- $definition['fields'][$columns[($number - 1)]] = array(
- 'position' => $colpos++,
- 'sorting' => 'ascending',
- );
- }
- return $definition;
- }
-
- $query = 'SELECT a.attname
- FROM pg_constraint c
- LEFT JOIN pg_class t ON c.conrelid = t.oid
- LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(c.conkey)
- WHERE c.conname = %s
- AND t.relname = ' . $db->quote($table, 'text');
- $fields = $db->queryCol(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null);
- if (PEAR::isError($fields)) {
- return $fields;
- }
- $colpos = 1;
- foreach ($fields as $field) {
- $definition['fields'][$field] = array(
- 'position' => $colpos++,
- 'sorting' => 'ascending',
- );
- }
-
- if ($definition['foreign']) {
- $query = 'SELECT a.attname
- FROM pg_constraint c
- LEFT JOIN pg_class t ON c.confrelid = t.oid
- LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(c.confkey)
- WHERE c.conname = %s
- AND t.relname = ' . $db->quote($definition['references']['table'], 'text');
- $foreign_fields = $db->queryCol(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null);
- if (PEAR::isError($foreign_fields)) {
- return $foreign_fields;
- }
- $colpos = 1;
- foreach ($foreign_fields as $foreign_field) {
- $definition['references']['fields'][$foreign_field] = array(
- 'position' => $colpos++,
- );
- }
- }
-
- if ($definition['check']) {
- $check_def = $db->queryOne("SELECT pg_get_constraintdef(" . $row['oid'] . ", 't')");
- // ...
- }
- return $definition;
- }
-
- // }}}
- // {{{ getTriggerDefinition()
-
- /**
- * Get the structure of a trigger into an array
- *
- * EXPERIMENTAL
- *
- * WARNING: this function is experimental and may change the returned value
- * at any time until labelled as non-experimental
- *
- * @param string $trigger name of trigger that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- *
- * @TODO: add support for plsql functions and functions with args
- */
- function getTriggerDefinition($trigger)
- {
- $db =$this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = "SELECT trg.tgname AS trigger_name,
- tbl.relname AS table_name,
- CASE
- WHEN p.proname IS NOT NULL THEN 'EXECUTE PROCEDURE ' || p.proname || '();'
- ELSE ''
- END AS trigger_body,
- CASE trg.tgtype & cast(2 as int2)
- WHEN 0 THEN 'AFTER'
- ELSE 'BEFORE'
- END AS trigger_type,
- CASE trg.tgtype & cast(28 as int2)
- WHEN 16 THEN 'UPDATE'
- WHEN 8 THEN 'DELETE'
- WHEN 4 THEN 'INSERT'
- WHEN 20 THEN 'INSERT, UPDATE'
- WHEN 28 THEN 'INSERT, UPDATE, DELETE'
- WHEN 24 THEN 'UPDATE, DELETE'
- WHEN 12 THEN 'INSERT, DELETE'
- END AS trigger_event,
- CASE trg.tgenabled
- WHEN 'O' THEN 't'
- ELSE trg.tgenabled
- END AS trigger_enabled,
- obj_description(trg.oid, 'pg_trigger') AS trigger_comment
- FROM pg_trigger trg,
- pg_class tbl,
- pg_proc p
- WHERE trg.tgrelid = tbl.oid
- AND trg.tgfoid = p.oid
- AND trg.tgname = ". $db->quote($trigger, 'text');
- $types = array(
- 'trigger_name' => 'text',
- 'table_name' => 'text',
- 'trigger_body' => 'text',
- 'trigger_type' => 'text',
- 'trigger_event' => 'text',
- 'trigger_comment' => 'text',
- 'trigger_enabled' => 'boolean',
- );
- return $db->queryRow($query, $types, MDB2_FETCHMODE_ASSOC);
- }
-
- // }}}
- // {{{ tableInfo()
-
- /**
- * Returns information about a table or a result set
- *
- * NOTE: only supports 'table' and 'flags' if $result
- * is a table name.
- *
- * @param object|string $result MDB2_result object from a query or a
- * string containing the name of a table.
- * While this also accepts a query result
- * resource identifier, this behavior is
- * deprecated.
- * @param int $mode a valid tableInfo mode
- *
- * @return array an associative array with the information requested.
- * A MDB2_Error object on failure.
- *
- * @see MDB2_Driver_Common::tableInfo()
- */
- function tableInfo($result, $mode = null)
- {
- if (is_string($result)) {
- return parent::tableInfo($result, $mode);
- }
-
- $db =$this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $resource = MDB2::isResultCommon($result) ? $result->getResource() : $result;
- if (!is_resource($resource)) {
- return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'Could not generate result resource', __FUNCTION__);
- }
-
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($db->options['field_case'] == CASE_LOWER) {
- $case_func = 'strtolower';
- } else {
- $case_func = 'strtoupper';
- }
- } else {
- $case_func = 'strval';
- }
-
- $count = @pg_num_fields($resource);
- $res = array();
-
- if ($mode) {
- $res['num_fields'] = $count;
- }
-
- $db->loadModule('Datatype', null, true);
- for ($i = 0; $i < $count; $i++) {
- $res[$i] = array(
- 'table' => function_exists('pg_field_table') ? @pg_field_table($resource, $i) : '',
- 'name' => $case_func(@pg_field_name($resource, $i)),
- 'type' => @pg_field_type($resource, $i),
- 'length' => @pg_field_size($resource, $i),
- 'flags' => '',
- );
- $mdb2type_info = $db->datatype->mapNativeDatatype($res[$i]);
- if (PEAR::isError($mdb2type_info)) {
- return $mdb2type_info;
- }
- $res[$i]['mdb2type'] = $mdb2type_info[0][0];
- if ($mode & MDB2_TABLEINFO_ORDER) {
- $res['order'][$res[$i]['name']] = $i;
- }
- if ($mode & MDB2_TABLEINFO_ORDERTABLE) {
- $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
- }
- }
-
- return $res;
- }
-}
+ |
+// | Lorenzo Alberton |
+// +----------------------------------------------------------------------+
+//
+// $Id: pgsql.php 295587 2010-02-28 17:16:38Z quipo $
+
+require_once 'MDB2/Driver/Reverse/Common.php';
+
+/**
+ * MDB2 PostGreSQL driver for the schema reverse engineering module
+ *
+ * @package MDB2
+ * @category Database
+ * @author Paul Cooper
+ * @author Lorenzo Alberton
+ */
+class MDB2_Driver_Reverse_pgsql extends MDB2_Driver_Reverse_Common
+{
+ // {{{ getTableFieldDefinition()
+
+ /**
+ * Get the structure of a field into an array
+ *
+ * @param string $table_name name of table that should be used in method
+ * @param string $field_name name of field that should be used in method
+ * @return mixed data array on success, a MDB2 error on failure
+ * @access public
+ */
+ function getTableFieldDefinition($table_name, $field_name)
+ {
+ $db = $this->getDBInstance();
+ if (PEAR::isError($db)) {
+ return $db;
+ }
+
+ $result = $db->loadModule('Datatype', null, true);
+ if (PEAR::isError($result)) {
+ return $result;
+ }
+
+ list($schema, $table) = $this->splitTableSchema($table_name);
+
+ $query = "SELECT a.attname AS name,
+ t.typname AS type,
+ CASE a.attlen
+ WHEN -1 THEN
+ CASE t.typname
+ WHEN 'numeric' THEN (a.atttypmod / 65536)
+ WHEN 'decimal' THEN (a.atttypmod / 65536)
+ WHEN 'money' THEN (a.atttypmod / 65536)
+ ELSE CASE a.atttypmod
+ WHEN -1 THEN NULL
+ ELSE a.atttypmod - 4
+ END
+ END
+ ELSE a.attlen
+ END AS length,
+ CASE t.typname
+ WHEN 'numeric' THEN (a.atttypmod % 65536) - 4
+ WHEN 'decimal' THEN (a.atttypmod % 65536) - 4
+ WHEN 'money' THEN (a.atttypmod % 65536) - 4
+ ELSE 0
+ END AS scale,
+ a.attnotnull,
+ a.atttypmod,
+ a.atthasdef,
+ (SELECT substring(pg_get_expr(d.adbin, d.adrelid) for 128)
+ FROM pg_attrdef d
+ WHERE d.adrelid = a.attrelid
+ AND d.adnum = a.attnum
+ AND a.atthasdef
+ ) as default
+ FROM pg_attribute a,
+ pg_class c,
+ pg_type t
+ WHERE c.relname = ".$db->quote($table, 'text')."
+ AND a.atttypid = t.oid
+ AND c.oid = a.attrelid
+ AND NOT a.attisdropped
+ AND a.attnum > 0
+ AND a.attname = ".$db->quote($field_name, 'text')."
+ ORDER BY a.attnum";
+ $column = $db->queryRow($query, null, MDB2_FETCHMODE_ASSOC);
+ if (PEAR::isError($column)) {
+ return $column;
+ }
+
+ if (empty($column)) {
+ return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
+ 'it was not specified an existing table column', __FUNCTION__);
+ }
+
+ $column = array_change_key_case($column, CASE_LOWER);
+ $mapped_datatype = $db->datatype->mapNativeDatatype($column);
+ if (PEAR::isError($mapped_datatype)) {
+ return $mapped_datatype;
+ }
+ list($types, $length, $unsigned, $fixed) = $mapped_datatype;
+ $notnull = false;
+ if (!empty($column['attnotnull']) && $column['attnotnull'] == 't') {
+ $notnull = true;
+ }
+ $default = null;
+ if ($column['atthasdef'] === 't'
+ && strpos($column['default'], 'NULL') !== 0
+ && !preg_match("/nextval\('([^']+)'/", $column['default'])
+ ) {
+ $pattern = '/^\'(.*)\'::[\w ]+$/i';
+ $default = $column['default'];#substr($column['adsrc'], 1, -1);
+ if ((null === $default) && $notnull) {
+ $default = '';
+ } elseif (!empty($default) && preg_match($pattern, $default)) {
+ //remove data type cast
+ $default = preg_replace ($pattern, '\\1', $default);
+ }
+ }
+ $autoincrement = false;
+ if (preg_match("/nextval\('([^']+)'/", $column['default'], $nextvals)) {
+ $autoincrement = true;
+ }
+ $definition[0] = array('notnull' => $notnull, 'nativetype' => $column['type']);
+ if (null !== $length) {
+ $definition[0]['length'] = $length;
+ }
+ if (null !== $unsigned) {
+ $definition[0]['unsigned'] = $unsigned;
+ }
+ if (null !== $fixed) {
+ $definition[0]['fixed'] = $fixed;
+ }
+ if ($default !== false) {
+ $definition[0]['default'] = $default;
+ }
+ if ($autoincrement !== false) {
+ $definition[0]['autoincrement'] = $autoincrement;
+ }
+ foreach ($types as $key => $type) {
+ $definition[$key] = $definition[0];
+ if ($type == 'clob' || $type == 'blob') {
+ unset($definition[$key]['default']);
+ }
+ $definition[$key]['type'] = $type;
+ $definition[$key]['mdb2type'] = $type;
+ }
+ return $definition;
+ }
+
+ // }}}
+ // {{{ getTableIndexDefinition()
+
+ /**
+ * Get the structure of an index into an array
+ *
+ * @param string $table_name name of table that should be used in method
+ * @param string $index_name name of index that should be used in method
+ * @return mixed data array on success, a MDB2 error on failure
+ * @access public
+ */
+ function getTableIndexDefinition($table_name, $index_name)
+ {
+ $db = $this->getDBInstance();
+ if (PEAR::isError($db)) {
+ return $db;
+ }
+
+ list($schema, $table) = $this->splitTableSchema($table_name);
+
+ $query = 'SELECT relname, indkey FROM pg_index, pg_class';
+ $query.= ' WHERE pg_class.oid = pg_index.indexrelid';
+ $query.= " AND indisunique != 't' AND indisprimary != 't'";
+ $query.= ' AND pg_class.relname = %s';
+ $index_name_mdb2 = $db->getIndexName($index_name);
+ $row = $db->queryRow(sprintf($query, $db->quote($index_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC);
+ if (PEAR::isError($row) || empty($row)) {
+ // fallback to the given $index_name, without transformation
+ $row = $db->queryRow(sprintf($query, $db->quote($index_name, 'text')), null, MDB2_FETCHMODE_ASSOC);
+ }
+ if (PEAR::isError($row)) {
+ return $row;
+ }
+
+ if (empty($row)) {
+ return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
+ 'it was not specified an existing table index', __FUNCTION__);
+ }
+
+ $row = array_change_key_case($row, CASE_LOWER);
+
+ $db->loadModule('Manager', null, true);
+ $columns = $db->manager->listTableFields($table_name);
+
+ $definition = array();
+
+ $index_column_numbers = explode(' ', $row['indkey']);
+
+ $colpos = 1;
+ foreach ($index_column_numbers as $number) {
+ $definition['fields'][$columns[($number - 1)]] = array(
+ 'position' => $colpos++,
+ 'sorting' => 'ascending',
+ );
+ }
+ return $definition;
+ }
+
+ // }}}
+ // {{{ getTableConstraintDefinition()
+
+ /**
+ * Get the structure of a constraint into an array
+ *
+ * @param string $table_name name of table that should be used in method
+ * @param string $constraint_name name of constraint that should be used in method
+ * @return mixed data array on success, a MDB2 error on failure
+ * @access public
+ */
+ function getTableConstraintDefinition($table_name, $constraint_name)
+ {
+ $db = $this->getDBInstance();
+ if (PEAR::isError($db)) {
+ return $db;
+ }
+
+ list($schema, $table) = $this->splitTableSchema($table_name);
+
+ $query = "SELECT c.oid,
+ c.conname AS constraint_name,
+ CASE WHEN c.contype = 'c' THEN 1 ELSE 0 END AS \"check\",
+ CASE WHEN c.contype = 'f' THEN 1 ELSE 0 END AS \"foreign\",
+ CASE WHEN c.contype = 'p' THEN 1 ELSE 0 END AS \"primary\",
+ CASE WHEN c.contype = 'u' THEN 1 ELSE 0 END AS \"unique\",
+ CASE WHEN c.condeferrable = 'f' THEN 0 ELSE 1 END AS deferrable,
+ CASE WHEN c.condeferred = 'f' THEN 0 ELSE 1 END AS initiallydeferred,
+ --array_to_string(c.conkey, ' ') AS constraint_key,
+ t.relname AS table_name,
+ t2.relname AS references_table,
+ CASE confupdtype
+ WHEN 'a' THEN 'NO ACTION'
+ WHEN 'r' THEN 'RESTRICT'
+ WHEN 'c' THEN 'CASCADE'
+ WHEN 'n' THEN 'SET NULL'
+ WHEN 'd' THEN 'SET DEFAULT'
+ END AS onupdate,
+ CASE confdeltype
+ WHEN 'a' THEN 'NO ACTION'
+ WHEN 'r' THEN 'RESTRICT'
+ WHEN 'c' THEN 'CASCADE'
+ WHEN 'n' THEN 'SET NULL'
+ WHEN 'd' THEN 'SET DEFAULT'
+ END AS ondelete,
+ CASE confmatchtype
+ WHEN 'u' THEN 'UNSPECIFIED'
+ WHEN 'f' THEN 'FULL'
+ WHEN 'p' THEN 'PARTIAL'
+ END AS match,
+ --array_to_string(c.confkey, ' ') AS fk_constraint_key,
+ consrc
+ FROM pg_constraint c
+ LEFT JOIN pg_class t ON c.conrelid = t.oid
+ LEFT JOIN pg_class t2 ON c.confrelid = t2.oid
+ WHERE c.conname = %s
+ AND t.relname = " . $db->quote($table, 'text');
+ $constraint_name_mdb2 = $db->getIndexName($constraint_name);
+ $row = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC);
+ if (PEAR::isError($row) || empty($row)) {
+ // fallback to the given $index_name, without transformation
+ $constraint_name_mdb2 = $constraint_name;
+ $row = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC);
+ }
+ if (PEAR::isError($row)) {
+ return $row;
+ }
+ $uniqueIndex = false;
+ if (empty($row)) {
+ // We might be looking for a UNIQUE index that was not created
+ // as a constraint but should be treated as such.
+ $query = 'SELECT relname AS constraint_name,
+ indkey,
+ 0 AS "check",
+ 0 AS "foreign",
+ 0 AS "primary",
+ 1 AS "unique",
+ 0 AS deferrable,
+ 0 AS initiallydeferred,
+ NULL AS references_table,
+ NULL AS onupdate,
+ NULL AS ondelete,
+ NULL AS match
+ FROM pg_index, pg_class
+ WHERE pg_class.oid = pg_index.indexrelid
+ AND indisunique = \'t\'
+ AND pg_class.relname = %s';
+ $constraint_name_mdb2 = $db->getIndexName($constraint_name);
+ $row = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC);
+ if (PEAR::isError($row) || empty($row)) {
+ // fallback to the given $index_name, without transformation
+ $constraint_name_mdb2 = $constraint_name;
+ $row = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC);
+ }
+ if (PEAR::isError($row)) {
+ return $row;
+ }
+ if (empty($row)) {
+ return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
+ $constraint_name . ' is not an existing table constraint', __FUNCTION__);
+ }
+ $uniqueIndex = true;
+ }
+
+ $row = array_change_key_case($row, CASE_LOWER);
+
+ $definition = array(
+ 'primary' => (boolean)$row['primary'],
+ 'unique' => (boolean)$row['unique'],
+ 'foreign' => (boolean)$row['foreign'],
+ 'check' => (boolean)$row['check'],
+ 'fields' => array(),
+ 'references' => array(
+ 'table' => $row['references_table'],
+ 'fields' => array(),
+ ),
+ 'deferrable' => (boolean)$row['deferrable'],
+ 'initiallydeferred' => (boolean)$row['initiallydeferred'],
+ 'onupdate' => $row['onupdate'],
+ 'ondelete' => $row['ondelete'],
+ 'match' => $row['match'],
+ );
+
+ if ($uniqueIndex) {
+ $db->loadModule('Manager', null, true);
+ $columns = $db->manager->listTableFields($table_name);
+ $index_column_numbers = explode(' ', $row['indkey']);
+ $colpos = 1;
+ foreach ($index_column_numbers as $number) {
+ $definition['fields'][$columns[($number - 1)]] = array(
+ 'position' => $colpos++,
+ 'sorting' => 'ascending',
+ );
+ }
+ return $definition;
+ }
+
+ $query = 'SELECT a.attname
+ FROM pg_constraint c
+ LEFT JOIN pg_class t ON c.conrelid = t.oid
+ LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(c.conkey)
+ WHERE c.conname = %s
+ AND t.relname = ' . $db->quote($table, 'text');
+ $fields = $db->queryCol(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null);
+ if (PEAR::isError($fields)) {
+ return $fields;
+ }
+ $colpos = 1;
+ foreach ($fields as $field) {
+ $definition['fields'][$field] = array(
+ 'position' => $colpos++,
+ 'sorting' => 'ascending',
+ );
+ }
+
+ if ($definition['foreign']) {
+ $query = 'SELECT a.attname
+ FROM pg_constraint c
+ LEFT JOIN pg_class t ON c.confrelid = t.oid
+ LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(c.confkey)
+ WHERE c.conname = %s
+ AND t.relname = ' . $db->quote($definition['references']['table'], 'text');
+ $foreign_fields = $db->queryCol(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null);
+ if (PEAR::isError($foreign_fields)) {
+ return $foreign_fields;
+ }
+ $colpos = 1;
+ foreach ($foreign_fields as $foreign_field) {
+ $definition['references']['fields'][$foreign_field] = array(
+ 'position' => $colpos++,
+ );
+ }
+ }
+
+ if ($definition['check']) {
+ $check_def = $db->queryOne("SELECT pg_get_constraintdef(" . $row['oid'] . ", 't')");
+ // ...
+ }
+ return $definition;
+ }
+
+ // }}}
+ // {{{ getTriggerDefinition()
+
+ /**
+ * Get the structure of a trigger into an array
+ *
+ * EXPERIMENTAL
+ *
+ * WARNING: this function is experimental and may change the returned value
+ * at any time until labelled as non-experimental
+ *
+ * @param string $trigger name of trigger that should be used in method
+ * @return mixed data array on success, a MDB2 error on failure
+ * @access public
+ *
+ * @TODO: add support for plsql functions and functions with args
+ */
+ function getTriggerDefinition($trigger)
+ {
+ $db = $this->getDBInstance();
+ if (PEAR::isError($db)) {
+ return $db;
+ }
+
+ $query = "SELECT trg.tgname AS trigger_name,
+ tbl.relname AS table_name,
+ CASE
+ WHEN p.proname IS NOT NULL THEN 'EXECUTE PROCEDURE ' || p.proname || '();'
+ ELSE ''
+ END AS trigger_body,
+ CASE trg.tgtype & cast(2 as int2)
+ WHEN 0 THEN 'AFTER'
+ ELSE 'BEFORE'
+ END AS trigger_type,
+ CASE trg.tgtype & cast(28 as int2)
+ WHEN 16 THEN 'UPDATE'
+ WHEN 8 THEN 'DELETE'
+ WHEN 4 THEN 'INSERT'
+ WHEN 20 THEN 'INSERT, UPDATE'
+ WHEN 28 THEN 'INSERT, UPDATE, DELETE'
+ WHEN 24 THEN 'UPDATE, DELETE'
+ WHEN 12 THEN 'INSERT, DELETE'
+ END AS trigger_event,
+ CASE trg.tgenabled
+ WHEN 'O' THEN 't'
+ ELSE trg.tgenabled
+ END AS trigger_enabled,
+ obj_description(trg.oid, 'pg_trigger') AS trigger_comment
+ FROM pg_trigger trg,
+ pg_class tbl,
+ pg_proc p
+ WHERE trg.tgrelid = tbl.oid
+ AND trg.tgfoid = p.oid
+ AND trg.tgname = ". $db->quote($trigger, 'text');
+ $types = array(
+ 'trigger_name' => 'text',
+ 'table_name' => 'text',
+ 'trigger_body' => 'text',
+ 'trigger_type' => 'text',
+ 'trigger_event' => 'text',
+ 'trigger_comment' => 'text',
+ 'trigger_enabled' => 'boolean',
+ );
+ return $db->queryRow($query, $types, MDB2_FETCHMODE_ASSOC);
+ }
+
+ // }}}
+ // {{{ tableInfo()
+
+ /**
+ * Returns information about a table or a result set
+ *
+ * NOTE: only supports 'table' and 'flags' if $result
+ * is a table name.
+ *
+ * @param object|string $result MDB2_result object from a query or a
+ * string containing the name of a table.
+ * While this also accepts a query result
+ * resource identifier, this behavior is
+ * deprecated.
+ * @param int $mode a valid tableInfo mode
+ *
+ * @return array an associative array with the information requested.
+ * A MDB2_Error object on failure.
+ *
+ * @see MDB2_Driver_Common::tableInfo()
+ */
+ function tableInfo($result, $mode = null)
+ {
+ if (is_string($result)) {
+ return parent::tableInfo($result, $mode);
+ }
+
+ $db = $this->getDBInstance();
+ if (PEAR::isError($db)) {
+ return $db;
+ }
+
+ $resource = MDB2::isResultCommon($result) ? $result->getResource() : $result;
+ if (!is_resource($resource)) {
+ return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
+ 'Could not generate result resource', __FUNCTION__);
+ }
+
+ if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
+ if ($db->options['field_case'] == CASE_LOWER) {
+ $case_func = 'strtolower';
+ } else {
+ $case_func = 'strtoupper';
+ }
+ } else {
+ $case_func = 'strval';
+ }
+
+ $count = @pg_num_fields($resource);
+ $res = array();
+
+ if ($mode) {
+ $res['num_fields'] = $count;
+ }
+
+ $db->loadModule('Datatype', null, true);
+ for ($i = 0; $i < $count; $i++) {
+ $res[$i] = array(
+ 'table' => function_exists('pg_field_table') ? @pg_field_table($resource, $i) : '',
+ 'name' => $case_func(@pg_field_name($resource, $i)),
+ 'type' => @pg_field_type($resource, $i),
+ 'length' => @pg_field_size($resource, $i),
+ 'flags' => '',
+ );
+ $mdb2type_info = $db->datatype->mapNativeDatatype($res[$i]);
+ if (PEAR::isError($mdb2type_info)) {
+ return $mdb2type_info;
+ }
+ $res[$i]['mdb2type'] = $mdb2type_info[0][0];
+ if ($mode & MDB2_TABLEINFO_ORDER) {
+ $res['order'][$res[$i]['name']] = $i;
+ }
+ if ($mode & MDB2_TABLEINFO_ORDERTABLE) {
+ $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
+ }
+ }
+
+ return $res;
+ }
+}
?>
\ No newline at end of file
diff --git a/3rdparty/MDB2/Driver/Reverse/sqlite.php b/3rdparty/MDB2/Driver/Reverse/sqlite.php
index 60c686c418..b98ccdb62c 100644
--- a/3rdparty/MDB2/Driver/Reverse/sqlite.php
+++ b/3rdparty/MDB2/Driver/Reverse/sqlite.php
@@ -1,609 +1,609 @@
- |
-// | Lorenzo Alberton |
-// +----------------------------------------------------------------------+
-//
-// $Id: sqlite.php,v 1.80 2008/05/03 10:30:14 quipo Exp $
-//
-
-require_once('MDB2/Driver/Reverse/Common.php');
-
-/**
- * MDB2 SQlite driver for the schema reverse engineering module
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Driver_Reverse_sqlite extends MDB2_Driver_Reverse_Common
-{
- /**
- * Remove SQL comments from the field definition
- *
- * @access private
- */
- function _removeComments($sql) {
- $lines = explode("\n", $sql);
- foreach ($lines as $k => $line) {
- $pieces = explode('--', $line);
- if (count($pieces) > 1 && (substr_count($pieces[0], '\'') % 2) == 0) {
- $lines[$k] = substr($line, 0, strpos($line, '--'));
- }
- }
- return implode("\n", $lines);
- }
-
- /**
- *
- */
- function _getTableColumns($sql)
- {
- $db =$this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- $start_pos = strpos($sql, '(');
- $end_pos = strrpos($sql, ')');
- $column_def = substr($sql, $start_pos+1, $end_pos-$start_pos-1);
- // replace the decimal length-places-separator with a colon
- $column_def = preg_replace('/(\d),(\d)/', '\1:\2', $column_def);
- $column_def = $this->_removeComments($column_def);
- $column_sql = explode(',', $column_def);
- $columns = array();
- $count = count($column_sql);
- if ($count == 0) {
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'unexpected empty table column definition list', __FUNCTION__);
- }
- $regexp = '/^\s*([^\s]+) +(CHAR|VARCHAR|VARCHAR2|TEXT|BOOLEAN|SMALLINT|INT|INTEGER|DECIMAL|BIGINT|DOUBLE|FLOAT|DATETIME|DATE|TIME|LONGTEXT|LONGBLOB)( ?\(([1-9][0-9]*)(:([1-9][0-9]*))?\))?( NULL| NOT NULL)?( UNSIGNED)?( NULL| NOT NULL)?( PRIMARY KEY)?( DEFAULT (\'[^\']*\'|[^ ]+))?( NULL| NOT NULL)?( PRIMARY KEY)?(\s*\-\-.*)?$/i';
- $regexp2 = '/^\s*([^ ]+) +(PRIMARY|UNIQUE|CHECK)$/i';
- for ($i=0, $j=0; $i<$count; ++$i) {
- if (!preg_match($regexp, trim($column_sql[$i]), $matches)) {
- if (!preg_match($regexp2, trim($column_sql[$i]))) {
- continue;
- }
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'unexpected table column SQL definition: "'.$column_sql[$i].'"', __FUNCTION__);
- }
- $columns[$j]['name'] = trim($matches[1], implode('', $db->identifier_quoting));
- $columns[$j]['type'] = strtolower($matches[2]);
- if (isset($matches[4]) && strlen($matches[4])) {
- $columns[$j]['length'] = $matches[4];
- }
- if (isset($matches[6]) && strlen($matches[6])) {
- $columns[$j]['decimal'] = $matches[6];
- }
- if (isset($matches[8]) && strlen($matches[8])) {
- $columns[$j]['unsigned'] = true;
- }
- if (isset($matches[9]) && strlen($matches[9])) {
- $columns[$j]['autoincrement'] = true;
- }
- if (isset($matches[12]) && strlen($matches[12])) {
- $default = $matches[12];
- if (strlen($default) && $default[0]=="'") {
- $default = str_replace("''", "'", substr($default, 1, strlen($default)-2));
- }
- if ($default === 'NULL') {
- $default = null;
- }
- $columns[$j]['default'] = $default;
- }
- if (isset($matches[7]) && strlen($matches[7])) {
- $columns[$j]['notnull'] = ($matches[7] === ' NOT NULL');
- } else if (isset($matches[9]) && strlen($matches[9])) {
- $columns[$j]['notnull'] = ($matches[9] === ' NOT NULL');
- } else if (isset($matches[13]) && strlen($matches[13])) {
- $columns[$j]['notnull'] = ($matches[13] === ' NOT NULL');
- }
- ++$j;
- }
- return $columns;
- }
-
- // {{{ getTableFieldDefinition()
-
- /**
- * Get the stucture of a field into an array
- *
- * @param string $table_name name of table that should be used in method
- * @param string $field_name name of field that should be used in method
- * @return mixed data array on success, a MDB2 error on failure.
- * The returned array contains an array for each field definition,
- * with (some of) these indices:
- * [notnull] [nativetype] [length] [fixed] [default] [type] [mdb2type]
- * @access public
- */
- function getTableFieldDefinition($table_name, $field_name)
- {
- $db =$this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- list($schema, $table) = $this->splitTableSchema($table_name);
-
- $result = $db->loadModule('Datatype', null, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- $query = "SELECT sql FROM sqlite_master WHERE type='table' AND ";
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $query.= 'LOWER(name)='.$db->quote(strtolower($table), 'text');
- } else {
- $query.= 'name='.$db->quote($table, 'text');
- }
- $sql = $db->queryOne($query);
- if (PEAR::isError($sql)) {
- return $sql;
- }
- $columns = $this->_getTableColumns($sql);
- foreach ($columns as $column) {
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($db->options['field_case'] == CASE_LOWER) {
- $column['name'] = strtolower($column['name']);
- } else {
- $column['name'] = strtoupper($column['name']);
- }
- } else {
- $column = array_change_key_case($column, $db->options['field_case']);
- }
- if ($field_name == $column['name']) {
- $mapped_datatype = $db->datatype->mapNativeDatatype($column);
- if (PEAR::isError($mapped_datatype)) {
- return $mapped_datatype;
- }
- list($types, $length, $unsigned, $fixed) = $mapped_datatype;
- $notnull = false;
- if (!empty($column['notnull'])) {
- $notnull = $column['notnull'];
- }
- $default = false;
- if (array_key_exists('default', $column)) {
- $default = $column['default'];
- if (is_null($default) && $notnull) {
- $default = '';
- }
- }
- $autoincrement = false;
- if (!empty($column['autoincrement'])) {
- $autoincrement = true;
- }
-
- $definition[0] = array(
- 'notnull' => $notnull,
- 'nativetype' => preg_replace('/^([a-z]+)[^a-z].*/i', '\\1', $column['type'])
- );
- if (!is_null($length)) {
- $definition[0]['length'] = $length;
- }
- if (!is_null($unsigned)) {
- $definition[0]['unsigned'] = $unsigned;
- }
- if (!is_null($fixed)) {
- $definition[0]['fixed'] = $fixed;
- }
- if ($default !== false) {
- $definition[0]['default'] = $default;
- }
- if ($autoincrement !== false) {
- $definition[0]['autoincrement'] = $autoincrement;
- }
- foreach ($types as $key => $type) {
- $definition[$key] = $definition[0];
- if ($type == 'clob' || $type == 'blob') {
- unset($definition[$key]['default']);
- }
- $definition[$key]['type'] = $type;
- $definition[$key]['mdb2type'] = $type;
- }
- return $definition;
- }
- }
-
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'it was not specified an existing table column', __FUNCTION__);
- }
-
- // }}}
- // {{{ getTableIndexDefinition()
-
- /**
- * Get the stucture of an index into an array
- *
- * @param string $table_name name of table that should be used in method
- * @param string $index_name name of index that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- */
- function getTableIndexDefinition($table_name, $index_name)
- {
- $db =$this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- list($schema, $table) = $this->splitTableSchema($table_name);
-
- $query = "SELECT sql FROM sqlite_master WHERE type='index' AND ";
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $query.= 'LOWER(name)=%s AND LOWER(tbl_name)=' . $db->quote(strtolower($table), 'text');
- } else {
- $query.= 'name=%s AND tbl_name=' . $db->quote($table, 'text');
- }
- $query.= ' AND sql NOT NULL ORDER BY name';
- $index_name_mdb2 = $db->getIndexName($index_name);
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $qry = sprintf($query, $db->quote(strtolower($index_name_mdb2), 'text'));
- } else {
- $qry = sprintf($query, $db->quote($index_name_mdb2, 'text'));
- }
- $sql = $db->queryOne($qry, 'text');
- if (PEAR::isError($sql) || empty($sql)) {
- // fallback to the given $index_name, without transformation
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $qry = sprintf($query, $db->quote(strtolower($index_name), 'text'));
- } else {
- $qry = sprintf($query, $db->quote($index_name, 'text'));
- }
- $sql = $db->queryOne($qry, 'text');
- }
- if (PEAR::isError($sql)) {
- return $sql;
- }
- if (!$sql) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'it was not specified an existing table index', __FUNCTION__);
- }
-
- $sql = strtolower($sql);
- $start_pos = strpos($sql, '(');
- $end_pos = strrpos($sql, ')');
- $column_names = substr($sql, $start_pos+1, $end_pos-$start_pos-1);
- $column_names = explode(',', $column_names);
-
- if (preg_match("/^create unique/", $sql)) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'it was not specified an existing table index', __FUNCTION__);
- }
-
- $definition = array();
- $count = count($column_names);
- for ($i=0; $i<$count; ++$i) {
- $column_name = strtok($column_names[$i], ' ');
- $collation = strtok(' ');
- $definition['fields'][$column_name] = array(
- 'position' => $i+1
- );
- if (!empty($collation)) {
- $definition['fields'][$column_name]['sorting'] =
- ($collation=='ASC' ? 'ascending' : 'descending');
- }
- }
-
- if (empty($definition['fields'])) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'it was not specified an existing table index', __FUNCTION__);
- }
- return $definition;
- }
-
- // }}}
- // {{{ getTableConstraintDefinition()
-
- /**
- * Get the stucture of a constraint into an array
- *
- * @param string $table_name name of table that should be used in method
- * @param string $constraint_name name of constraint that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- */
- function getTableConstraintDefinition($table_name, $constraint_name)
- {
- $db =$this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- list($schema, $table) = $this->splitTableSchema($table_name);
-
- $query = "SELECT sql FROM sqlite_master WHERE type='index' AND ";
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $query.= 'LOWER(name)=%s AND LOWER(tbl_name)=' . $db->quote(strtolower($table), 'text');
- } else {
- $query.= 'name=%s AND tbl_name=' . $db->quote($table, 'text');
- }
- $query.= ' AND sql NOT NULL ORDER BY name';
- $constraint_name_mdb2 = $db->getIndexName($constraint_name);
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $qry = sprintf($query, $db->quote(strtolower($constraint_name_mdb2), 'text'));
- } else {
- $qry = sprintf($query, $db->quote($constraint_name_mdb2, 'text'));
- }
- $sql = $db->queryOne($qry, 'text');
- if (PEAR::isError($sql) || empty($sql)) {
- // fallback to the given $index_name, without transformation
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $qry = sprintf($query, $db->quote(strtolower($constraint_name), 'text'));
- } else {
- $qry = sprintf($query, $db->quote($constraint_name, 'text'));
- }
- $sql = $db->queryOne($qry, 'text');
- }
- if (PEAR::isError($sql)) {
- return $sql;
- }
- //default values, eventually overridden
- $definition = array(
- 'primary' => false,
- 'unique' => false,
- 'foreign' => false,
- 'check' => false,
- 'fields' => array(),
- 'references' => array(
- 'table' => '',
- 'fields' => array(),
- ),
- 'onupdate' => '',
- 'ondelete' => '',
- 'match' => '',
- 'deferrable' => false,
- 'initiallydeferred' => false,
- );
- if (!$sql) {
- $query = "SELECT sql FROM sqlite_master WHERE type='table' AND ";
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $query.= 'LOWER(name)='.$db->quote(strtolower($table), 'text');
- } else {
- $query.= 'name='.$db->quote($table, 'text');
- }
- $query.= " AND sql NOT NULL ORDER BY name";
- $sql = $db->queryOne($query, 'text');
- if (PEAR::isError($sql)) {
- return $sql;
- }
- if ($constraint_name == 'primary') {
- // search in table definition for PRIMARY KEYs
- if (preg_match("/\bPRIMARY\s+KEY\b\s*\(([^)]+)/i", $sql, $tmp)) {
- $definition['primary'] = true;
- $definition['fields'] = array();
- $column_names = explode(',', $tmp[1]);
- $colpos = 1;
- foreach ($column_names as $column_name) {
- $definition['fields'][trim($column_name)] = array(
- 'position' => $colpos++
- );
- }
- return $definition;
- }
- if (preg_match("/\"([^\"]+)\"[^\,\"]+\bPRIMARY\s+KEY\b[^\,\)]*/i", $sql, $tmp)) {
- $definition['primary'] = true;
- $definition['fields'] = array();
- $column_names = explode(',', $tmp[1]);
- $colpos = 1;
- foreach ($column_names as $column_name) {
- $definition['fields'][trim($column_name)] = array(
- 'position' => $colpos++
- );
- }
- return $definition;
- }
- } else {
- // search in table definition for FOREIGN KEYs
- $pattern = "/\bCONSTRAINT\b\s+%s\s+
- \bFOREIGN\s+KEY\b\s*\(([^\)]+)\)\s*
- \bREFERENCES\b\s+([^\s]+)\s*\(([^\)]+)\)\s*
- (?:\bMATCH\s*([^\s]+))?\s*
- (?:\bON\s+UPDATE\s+([^\s,\)]+))?\s*
- (?:\bON\s+DELETE\s+([^\s,\)]+))?\s*
- /imsx";
- $found_fk = false;
- if (preg_match(sprintf($pattern, $constraint_name_mdb2), $sql, $tmp)) {
- $found_fk = true;
- } elseif (preg_match(sprintf($pattern, $constraint_name), $sql, $tmp)) {
- $found_fk = true;
- }
- if ($found_fk) {
- $definition['foreign'] = true;
- $definition['match'] = 'SIMPLE';
- $definition['onupdate'] = 'NO ACTION';
- $definition['ondelete'] = 'NO ACTION';
- $definition['references']['table'] = $tmp[2];
- $column_names = explode(',', $tmp[1]);
- $colpos = 1;
- foreach ($column_names as $column_name) {
- $definition['fields'][trim($column_name)] = array(
- 'position' => $colpos++
- );
- }
- $referenced_cols = explode(',', $tmp[3]);
- $colpos = 1;
- foreach ($referenced_cols as $column_name) {
- $definition['references']['fields'][trim($column_name)] = array(
- 'position' => $colpos++
- );
- }
- if (isset($tmp[4])) {
- $definition['match'] = $tmp[4];
- }
- if (isset($tmp[5])) {
- $definition['onupdate'] = $tmp[5];
- }
- if (isset($tmp[6])) {
- $definition['ondelete'] = $tmp[6];
- }
- return $definition;
- }
- }
- $sql = false;
- }
- if (!$sql) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- $constraint_name . ' is not an existing table constraint', __FUNCTION__);
- }
-
- $sql = strtolower($sql);
- $start_pos = strpos($sql, '(');
- $end_pos = strrpos($sql, ')');
- $column_names = substr($sql, $start_pos+1, $end_pos-$start_pos-1);
- $column_names = explode(',', $column_names);
-
- if (!preg_match("/^create unique/", $sql)) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- $constraint_name . ' is not an existing table constraint', __FUNCTION__);
- }
-
- $definition['unique'] = true;
- $count = count($column_names);
- for ($i=0; $i<$count; ++$i) {
- $column_name = strtok($column_names[$i]," ");
- $collation = strtok(" ");
- $definition['fields'][$column_name] = array(
- 'position' => $i+1
- );
- if (!empty($collation)) {
- $definition['fields'][$column_name]['sorting'] =
- ($collation=='ASC' ? 'ascending' : 'descending');
- }
- }
-
- if (empty($definition['fields'])) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- $constraint_name . ' is not an existing table constraint', __FUNCTION__);
- }
- return $definition;
- }
-
- // }}}
- // {{{ getTriggerDefinition()
-
- /**
- * Get the structure of a trigger into an array
- *
- * EXPERIMENTAL
- *
- * WARNING: this function is experimental and may change the returned value
- * at any time until labelled as non-experimental
- *
- * @param string $trigger name of trigger that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- */
- function getTriggerDefinition($trigger)
- {
- $db =$this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = "SELECT name as trigger_name,
- tbl_name AS table_name,
- sql AS trigger_body,
- NULL AS trigger_type,
- NULL AS trigger_event,
- NULL AS trigger_comment,
- 1 AS trigger_enabled
- FROM sqlite_master
- WHERE type='trigger'";
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $query.= ' AND LOWER(name)='.$db->quote(strtolower($trigger), 'text');
- } else {
- $query.= ' AND name='.$db->quote($trigger, 'text');
- }
- $types = array(
- 'trigger_name' => 'text',
- 'table_name' => 'text',
- 'trigger_body' => 'text',
- 'trigger_type' => 'text',
- 'trigger_event' => 'text',
- 'trigger_comment' => 'text',
- 'trigger_enabled' => 'boolean',
- );
- $def = $db->queryRow($query, $types, MDB2_FETCHMODE_ASSOC);
- if (PEAR::isError($def)) {
- return $def;
- }
- if (empty($def)) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'it was not specified an existing trigger', __FUNCTION__);
- }
- if (preg_match("/^create\s+(?:temp|temporary)?trigger\s+(?:if\s+not\s+exists\s+)?.*(before|after)?\s+(insert|update|delete)/Uims", $def['trigger_body'], $tmp)) {
- $def['trigger_type'] = strtoupper($tmp[1]);
- $def['trigger_event'] = strtoupper($tmp[2]);
- }
- return $def;
- }
-
- // }}}
- // {{{ tableInfo()
-
- /**
- * Returns information about a table
- *
- * @param string $result a string containing the name of a table
- * @param int $mode a valid tableInfo mode
- *
- * @return array an associative array with the information requested.
- * A MDB2_Error object on failure.
- *
- * @see MDB2_Driver_Common::tableInfo()
- * @since Method available since Release 1.7.0
- */
- function tableInfo($result, $mode = null)
- {
- if (is_string($result)) {
- return parent::tableInfo($result, $mode);
- }
-
- $db =$this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_NOT_CAPABLE, null, null,
- 'This DBMS can not obtain tableInfo from result sets', __FUNCTION__);
- }
-}
-
+ |
+// | Lorenzo Alberton |
+// +----------------------------------------------------------------------+
+//
+// $Id: sqlite.php 295587 2010-02-28 17:16:38Z quipo $
+//
+
+require_once 'MDB2/Driver/Reverse/Common.php';
+
+/**
+ * MDB2 SQlite driver for the schema reverse engineering module
+ *
+ * @package MDB2
+ * @category Database
+ * @author Lukas Smith
+ */
+class MDB2_Driver_Reverse_sqlite extends MDB2_Driver_Reverse_Common
+{
+ /**
+ * Remove SQL comments from the field definition
+ *
+ * @access private
+ */
+ function _removeComments($sql) {
+ $lines = explode("\n", $sql);
+ foreach ($lines as $k => $line) {
+ $pieces = explode('--', $line);
+ if (count($pieces) > 1 && (substr_count($pieces[0], '\'') % 2) == 0) {
+ $lines[$k] = substr($line, 0, strpos($line, '--'));
+ }
+ }
+ return implode("\n", $lines);
+ }
+
+ /**
+ *
+ */
+ function _getTableColumns($sql)
+ {
+ $db = $this->getDBInstance();
+ if (PEAR::isError($db)) {
+ return $db;
+ }
+ $start_pos = strpos($sql, '(');
+ $end_pos = strrpos($sql, ')');
+ $column_def = substr($sql, $start_pos+1, $end_pos-$start_pos-1);
+ // replace the decimal length-places-separator with a colon
+ $column_def = preg_replace('/(\d),(\d)/', '\1:\2', $column_def);
+ $column_def = $this->_removeComments($column_def);
+ $column_sql = explode(',', $column_def);
+ $columns = array();
+ $count = count($column_sql);
+ if ($count == 0) {
+ return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
+ 'unexpected empty table column definition list', __FUNCTION__);
+ }
+ $regexp = '/^\s*([^\s]+) +(CHAR|VARCHAR|VARCHAR2|TEXT|BOOLEAN|SMALLINT|INT|INTEGER|DECIMAL|BIGINT|DOUBLE|FLOAT|DATETIME|DATE|TIME|LONGTEXT|LONGBLOB)( ?\(([1-9][0-9]*)(:([1-9][0-9]*))?\))?( NULL| NOT NULL)?( UNSIGNED)?( NULL| NOT NULL)?( PRIMARY KEY)?( DEFAULT (\'[^\']*\'|[^ ]+))?( NULL| NOT NULL)?( PRIMARY KEY)?(\s*\-\-.*)?$/i';
+ $regexp2 = '/^\s*([^ ]+) +(PRIMARY|UNIQUE|CHECK)$/i';
+ for ($i=0, $j=0; $i<$count; ++$i) {
+ if (!preg_match($regexp, trim($column_sql[$i]), $matches)) {
+ if (!preg_match($regexp2, trim($column_sql[$i]))) {
+ continue;
+ }
+ return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
+ 'unexpected table column SQL definition: "'.$column_sql[$i].'"', __FUNCTION__);
+ }
+ $columns[$j]['name'] = trim($matches[1], implode('', $db->identifier_quoting));
+ $columns[$j]['type'] = strtolower($matches[2]);
+ if (isset($matches[4]) && strlen($matches[4])) {
+ $columns[$j]['length'] = $matches[4];
+ }
+ if (isset($matches[6]) && strlen($matches[6])) {
+ $columns[$j]['decimal'] = $matches[6];
+ }
+ if (isset($matches[8]) && strlen($matches[8])) {
+ $columns[$j]['unsigned'] = true;
+ }
+ if (isset($matches[9]) && strlen($matches[9])) {
+ $columns[$j]['autoincrement'] = true;
+ }
+ if (isset($matches[12]) && strlen($matches[12])) {
+ $default = $matches[12];
+ if (strlen($default) && $default[0]=="'") {
+ $default = str_replace("''", "'", substr($default, 1, strlen($default)-2));
+ }
+ if ($default === 'NULL') {
+ $default = null;
+ }
+ $columns[$j]['default'] = $default;
+ }
+ if (isset($matches[7]) && strlen($matches[7])) {
+ $columns[$j]['notnull'] = ($matches[7] === ' NOT NULL');
+ } else if (isset($matches[9]) && strlen($matches[9])) {
+ $columns[$j]['notnull'] = ($matches[9] === ' NOT NULL');
+ } else if (isset($matches[13]) && strlen($matches[13])) {
+ $columns[$j]['notnull'] = ($matches[13] === ' NOT NULL');
+ }
+ ++$j;
+ }
+ return $columns;
+ }
+
+ // {{{ getTableFieldDefinition()
+
+ /**
+ * Get the stucture of a field into an array
+ *
+ * @param string $table_name name of table that should be used in method
+ * @param string $field_name name of field that should be used in method
+ * @return mixed data array on success, a MDB2 error on failure.
+ * The returned array contains an array for each field definition,
+ * with (some of) these indices:
+ * [notnull] [nativetype] [length] [fixed] [default] [type] [mdb2type]
+ * @access public
+ */
+ function getTableFieldDefinition($table_name, $field_name)
+ {
+ $db = $this->getDBInstance();
+ if (PEAR::isError($db)) {
+ return $db;
+ }
+
+ list($schema, $table) = $this->splitTableSchema($table_name);
+
+ $result = $db->loadModule('Datatype', null, true);
+ if (PEAR::isError($result)) {
+ return $result;
+ }
+ $query = "SELECT sql FROM sqlite_master WHERE type='table' AND ";
+ if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
+ $query.= 'LOWER(name)='.$db->quote(strtolower($table), 'text');
+ } else {
+ $query.= 'name='.$db->quote($table, 'text');
+ }
+ $sql = $db->queryOne($query);
+ if (PEAR::isError($sql)) {
+ return $sql;
+ }
+ $columns = $this->_getTableColumns($sql);
+ foreach ($columns as $column) {
+ if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
+ if ($db->options['field_case'] == CASE_LOWER) {
+ $column['name'] = strtolower($column['name']);
+ } else {
+ $column['name'] = strtoupper($column['name']);
+ }
+ } else {
+ $column = array_change_key_case($column, $db->options['field_case']);
+ }
+ if ($field_name == $column['name']) {
+ $mapped_datatype = $db->datatype->mapNativeDatatype($column);
+ if (PEAR::isError($mapped_datatype)) {
+ return $mapped_datatype;
+ }
+ list($types, $length, $unsigned, $fixed) = $mapped_datatype;
+ $notnull = false;
+ if (!empty($column['notnull'])) {
+ $notnull = $column['notnull'];
+ }
+ $default = false;
+ if (array_key_exists('default', $column)) {
+ $default = $column['default'];
+ if ((null === $default) && $notnull) {
+ $default = '';
+ }
+ }
+ $autoincrement = false;
+ if (!empty($column['autoincrement'])) {
+ $autoincrement = true;
+ }
+
+ $definition[0] = array(
+ 'notnull' => $notnull,
+ 'nativetype' => preg_replace('/^([a-z]+)[^a-z].*/i', '\\1', $column['type'])
+ );
+ if (null !== $length) {
+ $definition[0]['length'] = $length;
+ }
+ if (null !== $unsigned) {
+ $definition[0]['unsigned'] = $unsigned;
+ }
+ if (null !== $fixed) {
+ $definition[0]['fixed'] = $fixed;
+ }
+ if ($default !== false) {
+ $definition[0]['default'] = $default;
+ }
+ if ($autoincrement !== false) {
+ $definition[0]['autoincrement'] = $autoincrement;
+ }
+ foreach ($types as $key => $type) {
+ $definition[$key] = $definition[0];
+ if ($type == 'clob' || $type == 'blob') {
+ unset($definition[$key]['default']);
+ }
+ $definition[$key]['type'] = $type;
+ $definition[$key]['mdb2type'] = $type;
+ }
+ return $definition;
+ }
+ }
+
+ return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
+ 'it was not specified an existing table column', __FUNCTION__);
+ }
+
+ // }}}
+ // {{{ getTableIndexDefinition()
+
+ /**
+ * Get the stucture of an index into an array
+ *
+ * @param string $table_name name of table that should be used in method
+ * @param string $index_name name of index that should be used in method
+ * @return mixed data array on success, a MDB2 error on failure
+ * @access public
+ */
+ function getTableIndexDefinition($table_name, $index_name)
+ {
+ $db = $this->getDBInstance();
+ if (PEAR::isError($db)) {
+ return $db;
+ }
+
+ list($schema, $table) = $this->splitTableSchema($table_name);
+
+ $query = "SELECT sql FROM sqlite_master WHERE type='index' AND ";
+ if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
+ $query.= 'LOWER(name)=%s AND LOWER(tbl_name)=' . $db->quote(strtolower($table), 'text');
+ } else {
+ $query.= 'name=%s AND tbl_name=' . $db->quote($table, 'text');
+ }
+ $query.= ' AND sql NOT NULL ORDER BY name';
+ $index_name_mdb2 = $db->getIndexName($index_name);
+ if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
+ $qry = sprintf($query, $db->quote(strtolower($index_name_mdb2), 'text'));
+ } else {
+ $qry = sprintf($query, $db->quote($index_name_mdb2, 'text'));
+ }
+ $sql = $db->queryOne($qry, 'text');
+ if (PEAR::isError($sql) || empty($sql)) {
+ // fallback to the given $index_name, without transformation
+ if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
+ $qry = sprintf($query, $db->quote(strtolower($index_name), 'text'));
+ } else {
+ $qry = sprintf($query, $db->quote($index_name, 'text'));
+ }
+ $sql = $db->queryOne($qry, 'text');
+ }
+ if (PEAR::isError($sql)) {
+ return $sql;
+ }
+ if (!$sql) {
+ return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
+ 'it was not specified an existing table index', __FUNCTION__);
+ }
+
+ $sql = strtolower($sql);
+ $start_pos = strpos($sql, '(');
+ $end_pos = strrpos($sql, ')');
+ $column_names = substr($sql, $start_pos+1, $end_pos-$start_pos-1);
+ $column_names = explode(',', $column_names);
+
+ if (preg_match("/^create unique/", $sql)) {
+ return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
+ 'it was not specified an existing table index', __FUNCTION__);
+ }
+
+ $definition = array();
+ $count = count($column_names);
+ for ($i=0; $i<$count; ++$i) {
+ $column_name = strtok($column_names[$i], ' ');
+ $collation = strtok(' ');
+ $definition['fields'][$column_name] = array(
+ 'position' => $i+1
+ );
+ if (!empty($collation)) {
+ $definition['fields'][$column_name]['sorting'] =
+ ($collation=='ASC' ? 'ascending' : 'descending');
+ }
+ }
+
+ if (empty($definition['fields'])) {
+ return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
+ 'it was not specified an existing table index', __FUNCTION__);
+ }
+ return $definition;
+ }
+
+ // }}}
+ // {{{ getTableConstraintDefinition()
+
+ /**
+ * Get the stucture of a constraint into an array
+ *
+ * @param string $table_name name of table that should be used in method
+ * @param string $constraint_name name of constraint that should be used in method
+ * @return mixed data array on success, a MDB2 error on failure
+ * @access public
+ */
+ function getTableConstraintDefinition($table_name, $constraint_name)
+ {
+ $db = $this->getDBInstance();
+ if (PEAR::isError($db)) {
+ return $db;
+ }
+
+ list($schema, $table) = $this->splitTableSchema($table_name);
+
+ $query = "SELECT sql FROM sqlite_master WHERE type='index' AND ";
+ if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
+ $query.= 'LOWER(name)=%s AND LOWER(tbl_name)=' . $db->quote(strtolower($table), 'text');
+ } else {
+ $query.= 'name=%s AND tbl_name=' . $db->quote($table, 'text');
+ }
+ $query.= ' AND sql NOT NULL ORDER BY name';
+ $constraint_name_mdb2 = $db->getIndexName($constraint_name);
+ if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
+ $qry = sprintf($query, $db->quote(strtolower($constraint_name_mdb2), 'text'));
+ } else {
+ $qry = sprintf($query, $db->quote($constraint_name_mdb2, 'text'));
+ }
+ $sql = $db->queryOne($qry, 'text');
+ if (PEAR::isError($sql) || empty($sql)) {
+ // fallback to the given $index_name, without transformation
+ if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
+ $qry = sprintf($query, $db->quote(strtolower($constraint_name), 'text'));
+ } else {
+ $qry = sprintf($query, $db->quote($constraint_name, 'text'));
+ }
+ $sql = $db->queryOne($qry, 'text');
+ }
+ if (PEAR::isError($sql)) {
+ return $sql;
+ }
+ //default values, eventually overridden
+ $definition = array(
+ 'primary' => false,
+ 'unique' => false,
+ 'foreign' => false,
+ 'check' => false,
+ 'fields' => array(),
+ 'references' => array(
+ 'table' => '',
+ 'fields' => array(),
+ ),
+ 'onupdate' => '',
+ 'ondelete' => '',
+ 'match' => '',
+ 'deferrable' => false,
+ 'initiallydeferred' => false,
+ );
+ if (!$sql) {
+ $query = "SELECT sql FROM sqlite_master WHERE type='table' AND ";
+ if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
+ $query.= 'LOWER(name)='.$db->quote(strtolower($table), 'text');
+ } else {
+ $query.= 'name='.$db->quote($table, 'text');
+ }
+ $query.= " AND sql NOT NULL ORDER BY name";
+ $sql = $db->queryOne($query, 'text');
+ if (PEAR::isError($sql)) {
+ return $sql;
+ }
+ if ($constraint_name == 'primary') {
+ // search in table definition for PRIMARY KEYs
+ if (preg_match("/\bPRIMARY\s+KEY\b\s*\(([^)]+)/i", $sql, $tmp)) {
+ $definition['primary'] = true;
+ $definition['fields'] = array();
+ $column_names = explode(',', $tmp[1]);
+ $colpos = 1;
+ foreach ($column_names as $column_name) {
+ $definition['fields'][trim($column_name)] = array(
+ 'position' => $colpos++
+ );
+ }
+ return $definition;
+ }
+ if (preg_match("/\"([^\"]+)\"[^\,\"]+\bPRIMARY\s+KEY\b[^\,\)]*/i", $sql, $tmp)) {
+ $definition['primary'] = true;
+ $definition['fields'] = array();
+ $column_names = explode(',', $tmp[1]);
+ $colpos = 1;
+ foreach ($column_names as $column_name) {
+ $definition['fields'][trim($column_name)] = array(
+ 'position' => $colpos++
+ );
+ }
+ return $definition;
+ }
+ } else {
+ // search in table definition for FOREIGN KEYs
+ $pattern = "/\bCONSTRAINT\b\s+%s\s+
+ \bFOREIGN\s+KEY\b\s*\(([^\)]+)\)\s*
+ \bREFERENCES\b\s+([^\s]+)\s*\(([^\)]+)\)\s*
+ (?:\bMATCH\s*([^\s]+))?\s*
+ (?:\bON\s+UPDATE\s+([^\s,\)]+))?\s*
+ (?:\bON\s+DELETE\s+([^\s,\)]+))?\s*
+ /imsx";
+ $found_fk = false;
+ if (preg_match(sprintf($pattern, $constraint_name_mdb2), $sql, $tmp)) {
+ $found_fk = true;
+ } elseif (preg_match(sprintf($pattern, $constraint_name), $sql, $tmp)) {
+ $found_fk = true;
+ }
+ if ($found_fk) {
+ $definition['foreign'] = true;
+ $definition['match'] = 'SIMPLE';
+ $definition['onupdate'] = 'NO ACTION';
+ $definition['ondelete'] = 'NO ACTION';
+ $definition['references']['table'] = $tmp[2];
+ $column_names = explode(',', $tmp[1]);
+ $colpos = 1;
+ foreach ($column_names as $column_name) {
+ $definition['fields'][trim($column_name)] = array(
+ 'position' => $colpos++
+ );
+ }
+ $referenced_cols = explode(',', $tmp[3]);
+ $colpos = 1;
+ foreach ($referenced_cols as $column_name) {
+ $definition['references']['fields'][trim($column_name)] = array(
+ 'position' => $colpos++
+ );
+ }
+ if (isset($tmp[4])) {
+ $definition['match'] = $tmp[4];
+ }
+ if (isset($tmp[5])) {
+ $definition['onupdate'] = $tmp[5];
+ }
+ if (isset($tmp[6])) {
+ $definition['ondelete'] = $tmp[6];
+ }
+ return $definition;
+ }
+ }
+ $sql = false;
+ }
+ if (!$sql) {
+ return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
+ $constraint_name . ' is not an existing table constraint', __FUNCTION__);
+ }
+
+ $sql = strtolower($sql);
+ $start_pos = strpos($sql, '(');
+ $end_pos = strrpos($sql, ')');
+ $column_names = substr($sql, $start_pos+1, $end_pos-$start_pos-1);
+ $column_names = explode(',', $column_names);
+
+ if (!preg_match("/^create unique/", $sql)) {
+ return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
+ $constraint_name . ' is not an existing table constraint', __FUNCTION__);
+ }
+
+ $definition['unique'] = true;
+ $count = count($column_names);
+ for ($i=0; $i<$count; ++$i) {
+ $column_name = strtok($column_names[$i]," ");
+ $collation = strtok(" ");
+ $definition['fields'][$column_name] = array(
+ 'position' => $i+1
+ );
+ if (!empty($collation)) {
+ $definition['fields'][$column_name]['sorting'] =
+ ($collation=='ASC' ? 'ascending' : 'descending');
+ }
+ }
+
+ if (empty($definition['fields'])) {
+ return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
+ $constraint_name . ' is not an existing table constraint', __FUNCTION__);
+ }
+ return $definition;
+ }
+
+ // }}}
+ // {{{ getTriggerDefinition()
+
+ /**
+ * Get the structure of a trigger into an array
+ *
+ * EXPERIMENTAL
+ *
+ * WARNING: this function is experimental and may change the returned value
+ * at any time until labelled as non-experimental
+ *
+ * @param string $trigger name of trigger that should be used in method
+ * @return mixed data array on success, a MDB2 error on failure
+ * @access public
+ */
+ function getTriggerDefinition($trigger)
+ {
+ $db = $this->getDBInstance();
+ if (PEAR::isError($db)) {
+ return $db;
+ }
+
+ $query = "SELECT name as trigger_name,
+ tbl_name AS table_name,
+ sql AS trigger_body,
+ NULL AS trigger_type,
+ NULL AS trigger_event,
+ NULL AS trigger_comment,
+ 1 AS trigger_enabled
+ FROM sqlite_master
+ WHERE type='trigger'";
+ if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
+ $query.= ' AND LOWER(name)='.$db->quote(strtolower($trigger), 'text');
+ } else {
+ $query.= ' AND name='.$db->quote($trigger, 'text');
+ }
+ $types = array(
+ 'trigger_name' => 'text',
+ 'table_name' => 'text',
+ 'trigger_body' => 'text',
+ 'trigger_type' => 'text',
+ 'trigger_event' => 'text',
+ 'trigger_comment' => 'text',
+ 'trigger_enabled' => 'boolean',
+ );
+ $def = $db->queryRow($query, $types, MDB2_FETCHMODE_ASSOC);
+ if (PEAR::isError($def)) {
+ return $def;
+ }
+ if (empty($def)) {
+ return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
+ 'it was not specified an existing trigger', __FUNCTION__);
+ }
+ if (preg_match("/^create\s+(?:temp|temporary)?trigger\s+(?:if\s+not\s+exists\s+)?.*(before|after)?\s+(insert|update|delete)/Uims", $def['trigger_body'], $tmp)) {
+ $def['trigger_type'] = strtoupper($tmp[1]);
+ $def['trigger_event'] = strtoupper($tmp[2]);
+ }
+ return $def;
+ }
+
+ // }}}
+ // {{{ tableInfo()
+
+ /**
+ * Returns information about a table
+ *
+ * @param string $result a string containing the name of a table
+ * @param int $mode a valid tableInfo mode
+ *
+ * @return array an associative array with the information requested.
+ * A MDB2_Error object on failure.
+ *
+ * @see MDB2_Driver_Common::tableInfo()
+ * @since Method available since Release 1.7.0
+ */
+ function tableInfo($result, $mode = null)
+ {
+ if (is_string($result)) {
+ return parent::tableInfo($result, $mode);
+ }
+
+ $db = $this->getDBInstance();
+ if (PEAR::isError($db)) {
+ return $db;
+ }
+
+ return $db->raiseError(MDB2_ERROR_NOT_CAPABLE, null, null,
+ 'This DBMS can not obtain tableInfo from result sets', __FUNCTION__);
+ }
+}
+
?>
\ No newline at end of file
diff --git a/3rdparty/MDB2/Driver/mysql.php b/3rdparty/MDB2/Driver/mysql.php
index 2cec1e9c03..eda3310dee 100644
--- a/3rdparty/MDB2/Driver/mysql.php
+++ b/3rdparty/MDB2/Driver/mysql.php
@@ -1,1700 +1,1710 @@
- |
-// +----------------------------------------------------------------------+
-//
-// $Id: mysql.php,v 1.214 2008/11/16 21:45:08 quipo Exp $
-//
-
-/**
- * MDB2 MySQL driver
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Driver_mysql extends MDB2_Driver_Common
-{
- // {{{ properties
-
- var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => '\\', 'escape_pattern' => '\\');
-
- var $identifier_quoting = array('start' => '`', 'end' => '`', 'escape' => '`');
-
- var $sql_comments = array(
- array('start' => '-- ', 'end' => "\n", 'escape' => false),
- array('start' => '#', 'end' => "\n", 'escape' => false),
- array('start' => '/*', 'end' => '*/', 'escape' => false),
- );
-
- var $server_capabilities_checked = false;
-
- var $start_transaction = false;
-
- var $varchar_max_length = 255;
-
- // }}}
- // {{{ constructor
-
- /**
- * Constructor
- */
- function __construct()
- {
- parent::__construct();
-
- $this->phptype = 'mysql';
- $this->dbsyntax = 'mysql';
-
- $this->supported['sequences'] = 'emulated';
- $this->supported['indexes'] = true;
- $this->supported['affected_rows'] = true;
- $this->supported['transactions'] = false;
- $this->supported['savepoints'] = false;
- $this->supported['summary_functions'] = true;
- $this->supported['order_by_text'] = true;
- $this->supported['current_id'] = 'emulated';
- $this->supported['limit_queries'] = true;
- $this->supported['LOBs'] = true;
- $this->supported['replace'] = true;
- $this->supported['sub_selects'] = 'emulated';
- $this->supported['triggers'] = false;
- $this->supported['auto_increment'] = true;
- $this->supported['primary_key'] = true;
- $this->supported['result_introspection'] = true;
- $this->supported['prepared_statements'] = 'emulated';
- $this->supported['identifier_quoting'] = true;
- $this->supported['pattern_escaping'] = true;
- $this->supported['new_link'] = true;
-
- $this->options['DBA_username'] = false;
- $this->options['DBA_password'] = false;
- $this->options['default_table_type'] = '';
- $this->options['max_identifiers_length'] = 64;
-
- $this->_reCheckSupportedOptions();
- }
-
- // }}}
- // {{{ _reCheckSupportedOptions()
-
- /**
- * If the user changes certain options, other capabilities may depend
- * on the new settings, so we need to check them (again).
- *
- * @access private
- */
- function _reCheckSupportedOptions()
- {
- $this->supported['transactions'] = $this->options['use_transactions'];
- $this->supported['savepoints'] = $this->options['use_transactions'];
- if ($this->options['default_table_type']) {
- switch (strtoupper($this->options['default_table_type'])) {
- case 'BLACKHOLE':
- case 'MEMORY':
- case 'ARCHIVE':
- case 'CSV':
- case 'HEAP':
- case 'ISAM':
- case 'MERGE':
- case 'MRG_ISAM':
- case 'ISAM':
- case 'MRG_MYISAM':
- case 'MYISAM':
- $this->supported['savepoints'] = false;
- $this->supported['transactions'] = false;
- $this->warnings[] = $this->options['default_table_type'] .
- ' is not a supported default table type';
- break;
- }
- }
- }
-
- // }}}
- // {{{ function setOption($option, $value)
-
- /**
- * set the option for the db class
- *
- * @param string option name
- * @param mixed value for the option
- *
- * @return mixed MDB2_OK or MDB2 Error Object
- *
- * @access public
- */
- function setOption($option, $value)
- {
- $res = parent::setOption($option, $value);
- $this->_reCheckSupportedOptions();
- }
-
- // }}}
- // {{{ errorInfo()
-
- /**
- * This method is used to collect information about an error
- *
- * @param integer $error
- * @return array
- * @access public
- */
- function errorInfo($error = null)
- {
- if ($this->connection) {
- $native_code = @mysql_errno($this->connection);
- $native_msg = @mysql_error($this->connection);
- } else {
- $native_code = @mysql_errno();
- $native_msg = @mysql_error();
- }
- if (is_null($error)) {
- static $ecode_map;
- if (empty($ecode_map)) {
- $ecode_map = array(
- 1000 => MDB2_ERROR_INVALID, //hashchk
- 1001 => MDB2_ERROR_INVALID, //isamchk
- 1004 => MDB2_ERROR_CANNOT_CREATE,
- 1005 => MDB2_ERROR_CANNOT_CREATE,
- 1006 => MDB2_ERROR_CANNOT_CREATE,
- 1007 => MDB2_ERROR_ALREADY_EXISTS,
- 1008 => MDB2_ERROR_CANNOT_DROP,
- 1009 => MDB2_ERROR_CANNOT_DROP,
- 1010 => MDB2_ERROR_CANNOT_DROP,
- 1011 => MDB2_ERROR_CANNOT_DELETE,
- 1022 => MDB2_ERROR_ALREADY_EXISTS,
- 1029 => MDB2_ERROR_NOT_FOUND,
- 1032 => MDB2_ERROR_NOT_FOUND,
- 1044 => MDB2_ERROR_ACCESS_VIOLATION,
- 1045 => MDB2_ERROR_ACCESS_VIOLATION,
- 1046 => MDB2_ERROR_NODBSELECTED,
- 1048 => MDB2_ERROR_CONSTRAINT,
- 1049 => MDB2_ERROR_NOSUCHDB,
- 1050 => MDB2_ERROR_ALREADY_EXISTS,
- 1051 => MDB2_ERROR_NOSUCHTABLE,
- 1054 => MDB2_ERROR_NOSUCHFIELD,
- 1060 => MDB2_ERROR_ALREADY_EXISTS,
- 1061 => MDB2_ERROR_ALREADY_EXISTS,
- 1062 => MDB2_ERROR_ALREADY_EXISTS,
- 1064 => MDB2_ERROR_SYNTAX,
- 1067 => MDB2_ERROR_INVALID,
- 1072 => MDB2_ERROR_NOT_FOUND,
- 1086 => MDB2_ERROR_ALREADY_EXISTS,
- 1091 => MDB2_ERROR_NOT_FOUND,
- 1100 => MDB2_ERROR_NOT_LOCKED,
- 1109 => MDB2_ERROR_NOT_FOUND,
- 1125 => MDB2_ERROR_ALREADY_EXISTS,
- 1136 => MDB2_ERROR_VALUE_COUNT_ON_ROW,
- 1138 => MDB2_ERROR_INVALID,
- 1142 => MDB2_ERROR_ACCESS_VIOLATION,
- 1143 => MDB2_ERROR_ACCESS_VIOLATION,
- 1146 => MDB2_ERROR_NOSUCHTABLE,
- 1149 => MDB2_ERROR_SYNTAX,
- 1169 => MDB2_ERROR_CONSTRAINT,
- 1176 => MDB2_ERROR_NOT_FOUND,
- 1177 => MDB2_ERROR_NOSUCHTABLE,
- 1213 => MDB2_ERROR_DEADLOCK,
- 1216 => MDB2_ERROR_CONSTRAINT,
- 1217 => MDB2_ERROR_CONSTRAINT,
- 1227 => MDB2_ERROR_ACCESS_VIOLATION,
- 1235 => MDB2_ERROR_CANNOT_CREATE,
- 1299 => MDB2_ERROR_INVALID_DATE,
- 1300 => MDB2_ERROR_INVALID,
- 1304 => MDB2_ERROR_ALREADY_EXISTS,
- 1305 => MDB2_ERROR_NOT_FOUND,
- 1306 => MDB2_ERROR_CANNOT_DROP,
- 1307 => MDB2_ERROR_CANNOT_CREATE,
- 1334 => MDB2_ERROR_CANNOT_ALTER,
- 1339 => MDB2_ERROR_NOT_FOUND,
- 1356 => MDB2_ERROR_INVALID,
- 1359 => MDB2_ERROR_ALREADY_EXISTS,
- 1360 => MDB2_ERROR_NOT_FOUND,
- 1363 => MDB2_ERROR_NOT_FOUND,
- 1365 => MDB2_ERROR_DIVZERO,
- 1451 => MDB2_ERROR_CONSTRAINT,
- 1452 => MDB2_ERROR_CONSTRAINT,
- 1542 => MDB2_ERROR_CANNOT_DROP,
- 1546 => MDB2_ERROR_CONSTRAINT,
- 1582 => MDB2_ERROR_CONSTRAINT,
- 2003 => MDB2_ERROR_CONNECT_FAILED,
- 2019 => MDB2_ERROR_INVALID,
- );
- }
- if ($this->options['portability'] & MDB2_PORTABILITY_ERRORS) {
- $ecode_map[1022] = MDB2_ERROR_CONSTRAINT;
- $ecode_map[1048] = MDB2_ERROR_CONSTRAINT_NOT_NULL;
- $ecode_map[1062] = MDB2_ERROR_CONSTRAINT;
- } else {
- // Doing this in case mode changes during runtime.
- $ecode_map[1022] = MDB2_ERROR_ALREADY_EXISTS;
- $ecode_map[1048] = MDB2_ERROR_CONSTRAINT;
- $ecode_map[1062] = MDB2_ERROR_ALREADY_EXISTS;
- }
- if (isset($ecode_map[$native_code])) {
- $error = $ecode_map[$native_code];
- }
- }
- return array($error, $native_code, $native_msg);
- }
-
- // }}}
- // {{{ escape()
-
- /**
- * Quotes a string so it can be safely used in a query. It will quote
- * the text so it can safely be used within a query.
- *
- * @param string the input string to quote
- * @param bool escape wildcards
- *
- * @return string quoted string
- *
- * @access public
- */
- function escape($text, $escape_wildcards = false)
- {
- if ($escape_wildcards) {
- $text = $this->escapePattern($text);
- }
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- $text = @mysql_real_escape_string($text, $connection);
- return $text;
- }
-
- // }}}
- // {{{ beginTransaction()
-
- /**
- * Start a transaction or set a savepoint.
- *
- * @param string name of a savepoint to set
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function beginTransaction($savepoint = null)
- {
- $this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- $this->_getServerCapabilities();
- if (!is_null($savepoint)) {
- if (!$this->supports('savepoints')) {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'savepoints are not supported', __FUNCTION__);
- }
- if (!$this->in_transaction) {
- return $this->raiseError(MDB2_ERROR_INVALID, null, null,
- 'savepoint cannot be released when changes are auto committed', __FUNCTION__);
- }
- $query = 'SAVEPOINT '.$savepoint;
- return $this->_doQuery($query, true);
- } elseif ($this->in_transaction) {
- return MDB2_OK; //nothing to do
- }
- if (!$this->destructor_registered && $this->opened_persistent) {
- $this->destructor_registered = true;
- register_shutdown_function('MDB2_closeOpenTransactions');
- }
- $query = $this->start_transaction ? 'START TRANSACTION' : 'SET AUTOCOMMIT = 0';
- $result =& $this->_doQuery($query, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- $this->in_transaction = true;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ commit()
-
- /**
- * Commit the database changes done during a transaction that is in
- * progress or release a savepoint. This function may only be called when
- * auto-committing is disabled, otherwise it will fail. Therefore, a new
- * transaction is implicitly started after committing the pending changes.
- *
- * @param string name of a savepoint to release
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function commit($savepoint = null)
- {
- $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- if (!$this->in_transaction) {
- return $this->raiseError(MDB2_ERROR_INVALID, null, null,
- 'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__);
- }
- if (!is_null($savepoint)) {
- if (!$this->supports('savepoints')) {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'savepoints are not supported', __FUNCTION__);
- }
- $server_info = $this->getServerVersion();
- if (version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch'], '5.0.3', '<')) {
- return MDB2_OK;
- }
- $query = 'RELEASE SAVEPOINT '.$savepoint;
- return $this->_doQuery($query, true);
- }
-
- if (!$this->supports('transactions')) {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'transactions are not supported', __FUNCTION__);
- }
-
- $result =& $this->_doQuery('COMMIT', true);
- if (PEAR::isError($result)) {
- return $result;
- }
- if (!$this->start_transaction) {
- $query = 'SET AUTOCOMMIT = 1';
- $result =& $this->_doQuery($query, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- $this->in_transaction = false;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ rollback()
-
- /**
- * Cancel any database changes done during a transaction or since a specific
- * savepoint that is in progress. This function may only be called when
- * auto-committing is disabled, otherwise it will fail. Therefore, a new
- * transaction is implicitly started after canceling the pending changes.
- *
- * @param string name of a savepoint to rollback to
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function rollback($savepoint = null)
- {
- $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- if (!$this->in_transaction) {
- return $this->raiseError(MDB2_ERROR_INVALID, null, null,
- 'rollback cannot be done changes are auto committed', __FUNCTION__);
- }
- if (!is_null($savepoint)) {
- if (!$this->supports('savepoints')) {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'savepoints are not supported', __FUNCTION__);
- }
- $query = 'ROLLBACK TO SAVEPOINT '.$savepoint;
- return $this->_doQuery($query, true);
- }
-
- $query = 'ROLLBACK';
- $result =& $this->_doQuery($query, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- if (!$this->start_transaction) {
- $query = 'SET AUTOCOMMIT = 1';
- $result =& $this->_doQuery($query, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- $this->in_transaction = false;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function setTransactionIsolation()
-
- /**
- * Set the transacton isolation level.
- *
- * @param string standard isolation level
- * READ UNCOMMITTED (allows dirty reads)
- * READ COMMITTED (prevents dirty reads)
- * REPEATABLE READ (prevents nonrepeatable reads)
- * SERIALIZABLE (prevents phantom reads)
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- * @since 2.1.1
- */
- static function setTransactionIsolation($isolation, $options = array())
- {
- $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
- if (!$this->supports('transactions')) {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'transactions are not supported', __FUNCTION__);
- }
- switch ($isolation) {
- case 'READ UNCOMMITTED':
- case 'READ COMMITTED':
- case 'REPEATABLE READ':
- case 'SERIALIZABLE':
- break;
- default:
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'isolation level is not supported: '.$isolation, __FUNCTION__);
- }
-
- $query = "SET SESSION TRANSACTION ISOLATION LEVEL $isolation";
- return $this->_doQuery($query, true);
- }
-
- // }}}
- // {{{ _doConnect()
-
- /**
- * do the grunt work of the connect
- *
- * @return connection on success or MDB2 Error Object on failure
- * @access protected
- */
- function _doConnect($username, $password, $persistent = false)
- {
- if (!PEAR::loadExtension($this->phptype)) {
- return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__);
- }
-
- $params = array();
- if ($this->dsn['protocol'] && $this->dsn['protocol'] == 'unix') {
- $params[0] = ':' . $this->dsn['socket'];
- } else {
- $params[0] = $this->dsn['hostspec'] ? $this->dsn['hostspec']
- : 'localhost';
- if ($this->dsn['port']) {
- $params[0].= ':' . $this->dsn['port'];
- }
- }
- $params[] = $username ? $username : null;
- $params[] = $password ? $password : null;
- if (!$persistent) {
- if ($this->_isNewLinkSet()) {
- $params[] = true;
- } else {
- $params[] = false;
- }
- }
- if (version_compare(phpversion(), '4.3.0', '>=')) {
- $params[] = isset($this->dsn['client_flags'])
- ? $this->dsn['client_flags'] : null;
- }
- $connect_function = $persistent ? 'mysql_pconnect' : 'mysql_connect';
-
- $connection = @call_user_func_array($connect_function, $params);
- if (!$connection) {
- if (($err = @mysql_error()) != '') {
- return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
- $err, __FUNCTION__);
- } else {
- return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
- 'unable to establish a connection', __FUNCTION__);
- }
- }
-
- if (!empty($this->dsn['charset'])) {
- $result = $this->setCharset($this->dsn['charset'], $connection);
- if (PEAR::isError($result)) {
- $this->disconnect(false);
- return $result;
- }
- }
-
- return $connection;
- }
-
- // }}}
- // {{{ connect()
-
- /**
- * Connect to the database
- *
- * @return MDB2_OK on success, MDB2 Error Object on failure
- * @access public
- */
- function connect()
- {
- if (is_resource($this->connection)) {
- //if (count(array_diff($this->connected_dsn, $this->dsn)) == 0
- if (MDB2::areEquals($this->connected_dsn, $this->dsn)
- && $this->opened_persistent == $this->options['persistent']
- ) {
- return MDB2_OK;
- }
- $this->disconnect(false);
- }
-
- $connection = $this->_doConnect(
- $this->dsn['username'],
- $this->dsn['password'],
- $this->options['persistent']
- );
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- $this->connection = $connection;
- $this->connected_dsn = $this->dsn;
- $this->connected_database_name = '';
- $this->opened_persistent = $this->options['persistent'];
- $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
-
- if ($this->database_name) {
- if ($this->database_name != $this->connected_database_name) {
- if (!@mysql_select_db($this->database_name, $connection)) {
- $err = $this->raiseError(null, null, null,
- 'Could not select the database: '.$this->database_name, __FUNCTION__);
- return $err;
- }
- $this->connected_database_name = $this->database_name;
- }
- }
-
- $this->_getServerCapabilities();
-
- return MDB2_OK;
- }
-
- // }}}
- // {{{ setCharset()
-
- /**
- * Set the charset on the current connection
- *
- * @param string charset (or array(charset, collation))
- * @param resource connection handle
- *
- * @return true on success, MDB2 Error Object on failure
- */
- function setCharset($charset, $connection = null)
- {
- if (is_null($connection)) {
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- }
- $collation = null;
- if (is_array($charset) && 2 == count($charset)) {
- $collation = array_pop($charset);
- $charset = array_pop($charset);
- }
- $client_info = mysql_get_client_info();
- if (function_exists('mysql_set_charset') && version_compare($client_info, '5.0.6')) {
- if (!$result = mysql_set_charset($charset, $connection)) {
- $err =& $this->raiseError(null, null, null,
- 'Could not set client character set', __FUNCTION__);
- return $err;
- }
- return $result;
- }
- $query = "SET NAMES '".mysql_real_escape_string($charset, $connection)."'";
- if (!is_null($collation)) {
- $query .= " COLLATE '".mysqli_real_escape_string($connection, $collation)."'";
- }
- return $this->_doQuery($query, true, $connection);
- }
-
- // }}}
- // {{{ databaseExists()
-
- /**
- * check if given database name is exists?
- *
- * @param string $name name of the database that should be checked
- *
- * @return mixed true/false on success, a MDB2 error on failure
- * @access public
- */
- function databaseExists($name)
- {
- $connection = $this->_doConnect($this->dsn['username'],
- $this->dsn['password'],
- $this->options['persistent']);
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- $result = @mysql_select_db($name, $connection);
- @mysql_close($connection);
-
- return $result;
- }
-
- // }}}
- // {{{ disconnect()
-
- /**
- * Log out and disconnect from the database.
- *
- * @param boolean $force if the disconnect should be forced even if the
- * connection is opened persistently
- * @return mixed true on success, false if not connected and error
- * object on error
- * @access public
- */
- function disconnect($force = true)
- {
- if (is_resource($this->connection)) {
- if ($this->in_transaction) {
- $dsn = $this->dsn;
- $database_name = $this->database_name;
- $persistent = $this->options['persistent'];
- $this->dsn = $this->connected_dsn;
- $this->database_name = $this->connected_database_name;
- $this->options['persistent'] = $this->opened_persistent;
- $this->rollback();
- $this->dsn = $dsn;
- $this->database_name = $database_name;
- $this->options['persistent'] = $persistent;
- }
-
- if (!$this->opened_persistent || $force) {
- $ok = @mysql_close($this->connection);
- if (!$ok) {
- return $this->raiseError(MDB2_ERROR_DISCONNECT_FAILED,
- null, null, null, __FUNCTION__);
- }
- }
- } else {
- return false;
- }
- return parent::disconnect($force);
- }
-
- // }}}
- // {{{ standaloneQuery()
-
- /**
- * execute a query as DBA
- *
- * @param string $query the SQL query
- * @param mixed $types array that contains the types of the columns in
- * the result set
- * @param boolean $is_manip if the query is a manipulation query
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function &standaloneQuery($query, $types = null, $is_manip = false)
- {
- $user = $this->options['DBA_username']? $this->options['DBA_username'] : $this->dsn['username'];
- $pass = $this->options['DBA_password']? $this->options['DBA_password'] : $this->dsn['password'];
- $connection = $this->_doConnect($user, $pass, $this->options['persistent']);
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- $offset = $this->offset;
- $limit = $this->limit;
- $this->offset = $this->limit = 0;
- $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
-
- $result =& $this->_doQuery($query, $is_manip, $connection, $this->database_name);
- if (!PEAR::isError($result)) {
- $result = $this->_affectedRows($connection, $result);
- }
-
- @mysql_close($connection);
- return $result;
- }
-
- // }}}
- // {{{ _doQuery()
-
- /**
- * Execute a query
- * @param string $query query
- * @param boolean $is_manip if the query is a manipulation query
- * @param resource $connection
- * @param string $database_name
- * @return result or error object
- * @access protected
- */
- function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null)
- {
- $this->last_query = $query;
- $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
- if ($result) {
- if (PEAR::isError($result)) {
- return $result;
- }
- $query = $result;
- }
- if ($this->options['disable_query']) {
- $result = $is_manip ? 0 : null;
- return $result;
- }
-
- if (is_null($connection)) {
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- }
- if (is_null($database_name)) {
- $database_name = $this->database_name;
- }
-
- if ($database_name) {
- if ($database_name != $this->connected_database_name) {
- if (!@mysql_select_db($database_name, $connection)) {
- $err = $this->raiseError(null, null, null,
- 'Could not select the database: '.$database_name, __FUNCTION__);
- return $err;
- }
- $this->connected_database_name = $database_name;
- }
- }
-
- $function = $this->options['result_buffering']
- ? 'mysql_query' : 'mysql_unbuffered_query';
- $result = @$function($query, $connection);
- if (!$result) {
- $err =$this->raiseError(null, null, null,
- 'Could not execute statement', __FUNCTION__);
- return $err;
- }
-
- $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result));
- return $result;
- }
-
- // }}}
- // {{{ _affectedRows()
-
- /**
- * Returns the number of rows affected
- *
- * @param resource $result
- * @param resource $connection
- * @return mixed MDB2 Error Object or the number of rows affected
- * @access private
- */
- function _affectedRows($connection, $result = null)
- {
- if (is_null($connection)) {
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- }
- return @mysql_affected_rows($connection);
- }
-
- // }}}
- // {{{ _modifyQuery()
-
- /**
- * Changes a query string for various DBMS specific reasons
- *
- * @param string $query query to modify
- * @param boolean $is_manip if it is a DML query
- * @param integer $limit limit the number of rows
- * @param integer $offset start reading from given offset
- * @return string modified query
- * @access protected
- */
- function _modifyQuery($query, $is_manip, $limit, $offset)
- {
- if ($this->options['portability'] & MDB2_PORTABILITY_DELETE_COUNT) {
- // "DELETE FROM table" gives 0 affected rows in MySQL.
- // This little hack lets you know how many rows were deleted.
- if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) {
- $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
- 'DELETE FROM \1 WHERE 1=1', $query);
- }
- }
- if ($limit > 0
- && !preg_match('/LIMIT\s*\d(?:\s*(?:,|OFFSET)\s*\d+)?(?:[^\)]*)?$/i', $query)
- ) {
- $query = rtrim($query);
- if (substr($query, -1) == ';') {
- $query = substr($query, 0, -1);
- }
-
- // LIMIT doesn't always come last in the query
- // @see http://dev.mysql.com/doc/refman/5.0/en/select.html
- $after = '';
- if (preg_match('/(\s+INTO\s+(?:OUT|DUMP)FILE\s.*)$/ims', $query, $matches)) {
- $after = $matches[0];
- $query = preg_replace('/(\s+INTO\s+(?:OUT|DUMP)FILE\s.*)$/ims', '', $query);
- } elseif (preg_match('/(\s+FOR\s+UPDATE\s*)$/i', $query, $matches)) {
- $after = $matches[0];
- $query = preg_replace('/(\s+FOR\s+UPDATE\s*)$/im', '', $query);
- } elseif (preg_match('/(\s+LOCK\s+IN\s+SHARE\s+MODE\s*)$/im', $query, $matches)) {
- $after = $matches[0];
- $query = preg_replace('/(\s+LOCK\s+IN\s+SHARE\s+MODE\s*)$/im', '', $query);
- }
-
- if ($is_manip) {
- return $query . " LIMIT $limit" . $after;
- } else {
- return $query . " LIMIT $offset, $limit" . $after;
- }
- }
- return $query;
- }
-
- // }}}
- // {{{ getServerVersion()
-
- /**
- * return version information about the server
- *
- * @param bool $native determines if the raw version string should be returned
- * @return mixed array/string with version information or MDB2 error object
- * @access public
- */
- function getServerVersion($native = false)
- {
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- if ($this->connected_server_info) {
- $server_info = $this->connected_server_info;
- } else {
- $server_info = @mysql_get_server_info($connection);
- }
- if (!$server_info) {
- return $this->raiseError(null, null, null,
- 'Could not get server information', __FUNCTION__);
- }
- // cache server_info
- $this->connected_server_info = $server_info;
- if (!$native) {
- $tmp = explode('.', $server_info, 3);
- if (isset($tmp[2]) && strpos($tmp[2], '-')) {
- $tmp2 = explode('-', @$tmp[2], 2);
- } else {
- $tmp2[0] = isset($tmp[2]) ? $tmp[2] : null;
- $tmp2[1] = null;
- }
- $server_info = array(
- 'major' => isset($tmp[0]) ? $tmp[0] : null,
- 'minor' => isset($tmp[1]) ? $tmp[1] : null,
- 'patch' => $tmp2[0],
- 'extra' => $tmp2[1],
- 'native' => $server_info,
- );
- }
- return $server_info;
- }
-
- // }}}
- // {{{ _getServerCapabilities()
-
- /**
- * Fetch some information about the server capabilities
- * (transactions, subselects, prepared statements, etc).
- *
- * @access private
- */
- function _getServerCapabilities()
- {
- if (!$this->server_capabilities_checked) {
- $this->server_capabilities_checked = true;
-
- //set defaults
- $this->supported['sub_selects'] = 'emulated';
- $this->supported['prepared_statements'] = 'emulated';
- $this->supported['triggers'] = false;
- $this->start_transaction = false;
- $this->varchar_max_length = 255;
-
- $server_info = $this->getServerVersion();
- if (is_array($server_info)) {
- $server_version = $server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch'];
-
- if (!version_compare($server_version, '4.1.0', '<')) {
- $this->supported['sub_selects'] = true;
- $this->supported['prepared_statements'] = true;
- }
-
- // SAVEPOINTs were introduced in MySQL 4.0.14 and 4.1.1 (InnoDB)
- if (version_compare($server_version, '4.1.0', '>=')) {
- if (version_compare($server_version, '4.1.1', '<')) {
- $this->supported['savepoints'] = false;
- }
- } elseif (version_compare($server_version, '4.0.14', '<')) {
- $this->supported['savepoints'] = false;
- }
-
- if (!version_compare($server_version, '4.0.11', '<')) {
- $this->start_transaction = true;
- }
-
- if (!version_compare($server_version, '5.0.3', '<')) {
- $this->varchar_max_length = 65532;
- }
-
- if (!version_compare($server_version, '5.0.2', '<')) {
- $this->supported['triggers'] = true;
- }
- }
- }
- }
-
- // }}}
- // {{{ function _skipUserDefinedVariable($query, $position)
-
- /**
- * Utility method, used by prepare() to avoid misinterpreting MySQL user
- * defined variables (SELECT @x:=5) for placeholders.
- * Check if the placeholder is a false positive, i.e. if it is an user defined
- * variable instead. If so, skip it and advance the position, otherwise
- * return the current position, which is valid
- *
- * @param string $query
- * @param integer $position current string cursor position
- * @return integer $new_position
- * @access protected
- */
- function _skipUserDefinedVariable($query, $position)
- {
- $found = strpos(strrev(substr($query, 0, $position)), '@');
- if ($found === false) {
- return $position;
- }
- $pos = strlen($query) - strlen(substr($query, $position)) - $found - 1;
- $substring = substr($query, $pos, $position - $pos + 2);
- if (preg_match('/^@\w+\s*:=$/', $substring)) {
- return $position + 1; //found an user defined variable: skip it
- }
- return $position;
- }
-
- // }}}
- // {{{ prepare()
-
- /**
- * Prepares a query for multiple execution with execute().
- * With some database backends, this is emulated.
- * prepare() requires a generic query as string like
- * 'INSERT INTO numbers VALUES(?,?)' or
- * 'INSERT INTO numbers VALUES(:foo,:bar)'.
- * The ? and :name and are placeholders which can be set using
- * bindParam() and the query can be sent off using the execute() method.
- * The allowed format for :name can be set with the 'bindname_format' option.
- *
- * @param string $query the query to prepare
- * @param mixed $types array that contains the types of the placeholders
- * @param mixed $result_types array that contains the types of the columns in
- * the result set or MDB2_PREPARE_RESULT, if set to
- * MDB2_PREPARE_MANIP the query is handled as a manipulation query
- * @param mixed $lobs key (field) value (parameter) pair for all lob placeholders
- * @return mixed resource handle for the prepared query on success, a MDB2
- * error on failure
- * @access public
- * @see bindParam, execute
- */
- function &prepare($query, $types = null, $result_types = null, $lobs = array())
- {
- if ($this->options['emulate_prepared']
- || $this->supported['prepared_statements'] !== true
- ) {
- $obj =& parent::prepare($query, $types, $result_types, $lobs);
- return $obj;
- }
- $is_manip = ($result_types === MDB2_PREPARE_MANIP);
- $offset = $this->offset;
- $limit = $this->limit;
- $this->offset = $this->limit = 0;
- $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
- $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre'));
- if ($result) {
- if (PEAR::isError($result)) {
- return $result;
- }
- $query = $result;
- }
- $placeholder_type_guess = $placeholder_type = null;
- $question = '?';
- $colon = ':';
- $positions = array();
- $position = 0;
- while ($position < strlen($query)) {
- $q_position = strpos($query, $question, $position);
- $c_position = strpos($query, $colon, $position);
- if ($q_position && $c_position) {
- $p_position = min($q_position, $c_position);
- } elseif ($q_position) {
- $p_position = $q_position;
- } elseif ($c_position) {
- $p_position = $c_position;
- } else {
- break;
- }
- if (is_null($placeholder_type)) {
- $placeholder_type_guess = $query[$p_position];
- }
-
- $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position);
- if (PEAR::isError($new_pos)) {
- return $new_pos;
- }
- if ($new_pos != $position) {
- $position = $new_pos;
- continue; //evaluate again starting from the new position
- }
-
- //make sure this is not part of an user defined variable
- $new_pos = $this->_skipUserDefinedVariable($query, $position);
- if ($new_pos != $position) {
- $position = $new_pos;
- continue; //evaluate again starting from the new position
- }
-
- if ($query[$position] == $placeholder_type_guess) {
- if (is_null($placeholder_type)) {
- $placeholder_type = $query[$p_position];
- $question = $colon = $placeholder_type;
- }
- if ($placeholder_type == ':') {
- $regexp = '/^.{'.($position+1).'}('.$this->options['bindname_format'].').*$/s';
- $parameter = preg_replace($regexp, '\\1', $query);
- if ($parameter === '') {
- $err =& $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
- 'named parameter name must match "bindname_format" option', __FUNCTION__);
- return $err;
- }
- $positions[$p_position] = $parameter;
- $query = substr_replace($query, '?', $position, strlen($parameter)+1);
- } else {
- $positions[$p_position] = count($positions);
- }
- $position = $p_position + 1;
- } else {
- $position = $p_position;
- }
- }
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- static $prep_statement_counter = 1;
- $statement_name = sprintf($this->options['statement_format'], $this->phptype, $prep_statement_counter++ . sha1(microtime() + mt_rand()));
- $statement_name = substr(strtolower($statement_name), 0, $this->options['max_identifiers_length']);
- $query = "PREPARE $statement_name FROM ".$this->quote($query, 'text');
- $statement =& $this->_doQuery($query, true, $connection);
- if (PEAR::isError($statement)) {
- return $statement;
- }
-
- $class_name = 'MDB2_Statement_'.$this->phptype;
- $obj = new $class_name($this, $statement_name, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);
- $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));
- return $obj;
- }
-
- // }}}
- // {{{ replace()
-
- /**
- * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
- * query, except that if there is already a row in the table with the same
- * key field values, the old row is deleted before the new row is inserted.
- *
- * The REPLACE type of query does not make part of the SQL standards. Since
- * practically only MySQL implements it natively, this type of query is
- * emulated through this method for other DBMS using standard types of
- * queries inside a transaction to assure the atomicity of the operation.
- *
- * @access public
- *
- * @param string $table name of the table on which the REPLACE query will
- * be executed.
- * @param array $fields associative array that describes the fields and the
- * values that will be inserted or updated in the specified table. The
- * indexes of the array are the names of all the fields of the table. The
- * values of the array are also associative arrays that describe the
- * values and other properties of the table fields.
- *
- * Here follows a list of field properties that need to be specified:
- *
- * value:
- * Value to be assigned to the specified field. This value may be
- * of specified in database independent type format as this
- * function can perform the necessary datatype conversions.
- *
- * Default:
- * this property is required unless the Null property
- * is set to 1.
- *
- * type
- * Name of the type of the field. Currently, all types Metabase
- * are supported except for clob and blob.
- *
- * Default: no type conversion
- *
- * null
- * Boolean property that indicates that the value for this field
- * should be set to null.
- *
- * The default value for fields missing in INSERT queries may be
- * specified the definition of a table. Often, the default value
- * is already null, but since the REPLACE may be emulated using
- * an UPDATE query, make sure that all fields of the table are
- * listed in this function argument array.
- *
- * Default: 0
- *
- * key
- * Boolean property that indicates that this field should be
- * handled as a primary key or at least as part of the compound
- * unique index of the table that will determine the row that will
- * updated if it exists or inserted a new row otherwise.
- *
- * This function will fail if no key field is specified or if the
- * value of a key field is set to null because fields that are
- * part of unique index they may not be null.
- *
- * Default: 0
- *
- * @see http://dev.mysql.com/doc/refman/5.0/en/replace.html
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- */
- function replace($table, $fields)
- {
- $count = count($fields);
- $query = $values = '';
- $keys = $colnum = 0;
- for (reset($fields); $colnum < $count; next($fields), $colnum++) {
- $name = key($fields);
- if ($colnum > 0) {
- $query .= ',';
- $values.= ',';
- }
- $query.= $this->quoteIdentifier($name, true);
- if (isset($fields[$name]['null']) && $fields[$name]['null']) {
- $value = 'NULL';
- } else {
- $type = isset($fields[$name]['type']) ? $fields[$name]['type'] : null;
- $value = $this->quote($fields[$name]['value'], $type);
- if (PEAR::isError($value)) {
- return $value;
- }
- }
- $values.= $value;
- if (isset($fields[$name]['key']) && $fields[$name]['key']) {
- if ($value === 'NULL') {
- return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
- 'key value '.$name.' may not be NULL', __FUNCTION__);
- }
- $keys++;
- }
- }
- if ($keys == 0) {
- return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
- 'not specified which fields are keys', __FUNCTION__);
- }
-
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- $table = $this->quoteIdentifier($table, true);
- $query = "REPLACE INTO $table ($query) VALUES ($values)";
- $result =& $this->_doQuery($query, true, $connection);
- if (PEAR::isError($result)) {
- return $result;
- }
- return $this->_affectedRows($connection, $result);
- }
-
- // }}}
- // {{{ nextID()
-
- /**
- * Returns the next free id of a sequence
- *
- * @param string $seq_name name of the sequence
- * @param boolean $ondemand when true the sequence is
- * automatic created, if it
- * not exists
- *
- * @return mixed MDB2 Error Object or id
- * @access public
- */
- function nextID($seq_name, $ondemand = true)
- {
- $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
- $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true);
- $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (NULL)";
- $this->pushErrorHandling(PEAR_ERROR_RETURN);
- $this->expectError(MDB2_ERROR_NOSUCHTABLE);
- $result =& $this->_doQuery($query, true);
- $this->popExpect();
- $this->popErrorHandling();
- if (PEAR::isError($result)) {
- if ($ondemand && $result->getCode() == MDB2_ERROR_NOSUCHTABLE) {
- $this->loadModule('Manager', null, true);
- $result = $this->manager->createSequence($seq_name);
- if (PEAR::isError($result)) {
- return $this->raiseError($result, null, null,
- 'on demand sequence '.$seq_name.' could not be created', __FUNCTION__);
- } else {
- return $this->nextID($seq_name, false);
- }
- }
- return $result;
- }
- $value = $this->lastInsertID();
- if (is_numeric($value)) {
- $query = "DELETE FROM $sequence_name WHERE $seqcol_name < $value";
- $result =& $this->_doQuery($query, true);
- if (PEAR::isError($result)) {
- $this->warnings[] = 'nextID: could not delete previous sequence table values from '.$seq_name;
- }
- }
- return $value;
- }
-
- // }}}
- // {{{ lastInsertID()
-
- /**
- * Returns the autoincrement ID if supported or $id or fetches the current
- * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
- *
- * @param string $table name of the table into which a new row was inserted
- * @param string $field name of the field into which a new row was inserted
- * @return mixed MDB2 Error Object or id
- * @access public
- */
- function lastInsertID($table = null, $field = null)
- {
- // not using mysql_insert_id() due to http://pear.php.net/bugs/bug.php?id=8051
- return $this->queryOne('SELECT LAST_INSERT_ID()', 'integer');
- }
-
- // }}}
- // {{{ currID()
-
- /**
- * Returns the current id of a sequence
- *
- * @param string $seq_name name of the sequence
- * @return mixed MDB2 Error Object or id
- * @access public
- */
- function currID($seq_name)
- {
- $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
- $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true);
- $query = "SELECT MAX($seqcol_name) FROM $sequence_name";
- return $this->queryOne($query, 'integer');
- }
-}
-
-/**
- * MDB2 MySQL result driver
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Result_mysql extends MDB2_Result_Common
-{
- // }}}
- // {{{ fetchRow()
-
- /**
- * Fetch a row and insert the data into an existing array.
- *
- * @param int $fetchmode how the array data should be indexed
- * @param int $rownum number of the row where the data can be found
- * @return int data array on success, a MDB2 error on failure
- * @access public
- */
- function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
- {
- if (!is_null($rownum)) {
- $seek = $this->seek($rownum);
- if (PEAR::isError($seek)) {
- return $seek;
- }
- }
- if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
- $fetchmode = $this->db->fetchmode;
- }
- if ($fetchmode & MDB2_FETCHMODE_ASSOC) {
- $row = @mysql_fetch_assoc($this->result);
- if (is_array($row)
- && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
- ) {
- $row = array_change_key_case($row, $this->db->options['field_case']);
- }
- } else {
- $row = @mysql_fetch_row($this->result);
- }
-
- if (!$row) {
- if ($this->result === false) {
- $err =& $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- return $err;
- }
- $null = null;
- return $null;
- }
- $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL;
- $rtrim = false;
- if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) {
- if (empty($this->types)) {
- $mode += MDB2_PORTABILITY_RTRIM;
- } else {
- $rtrim = true;
- }
- }
- if ($mode) {
- $this->db->_fixResultArrayValues($row, $mode);
- }
- if (!empty($this->types)) {
- $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim);
- }
- if (!empty($this->values)) {
- $this->_assignBindColumns($row);
- }
- if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
- $object_class = $this->db->options['fetch_class'];
- if ($object_class == 'stdClass') {
- $row = (object) $row;
- } else {
- $row = new $object_class($row);
- }
- }
- ++$this->rownum;
- return $row;
- }
-
- // }}}
- // {{{ _getColumnNames()
-
- /**
- * Retrieve the names of columns returned by the DBMS in a query result.
- *
- * @return mixed Array variable that holds the names of columns as keys
- * or an MDB2 error on failure.
- * Some DBMS may not return any columns when the result set
- * does not contain any rows.
- * @access private
- */
- function _getColumnNames()
- {
- $columns = array();
- $numcols = $this->numCols();
- if (PEAR::isError($numcols)) {
- return $numcols;
- }
- for ($column = 0; $column < $numcols; $column++) {
- $column_name = @mysql_field_name($this->result, $column);
- $columns[$column_name] = $column;
- }
- if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $columns = array_change_key_case($columns, $this->db->options['field_case']);
- }
- return $columns;
- }
-
- // }}}
- // {{{ numCols()
-
- /**
- * Count the number of columns returned by the DBMS in a query result.
- *
- * @return mixed integer value with the number of columns, a MDB2 error
- * on failure
- * @access public
- */
- function numCols()
- {
- $cols = @mysql_num_fields($this->result);
- if (is_null($cols)) {
- if ($this->result === false) {
- return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- } elseif (is_null($this->result)) {
- return count($this->types);
- }
- return $this->db->raiseError(null, null, null,
- 'Could not get column count', __FUNCTION__);
- }
- return $cols;
- }
-
- // }}}
- // {{{ free()
-
- /**
- * Free the internal resources associated with result.
- *
- * @return boolean true on success, false if result is invalid
- * @access public
- */
- function free()
- {
- if (is_resource($this->result) && $this->db->connection) {
- $free = @mysql_free_result($this->result);
- if ($free === false) {
- return $this->db->raiseError(null, null, null,
- 'Could not free result', __FUNCTION__);
- }
- }
- $this->result = false;
- return MDB2_OK;
- }
-}
-
-/**
- * MDB2 MySQL buffered result driver
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_BufferedResult_mysql extends MDB2_Result_mysql
-{
- // }}}
- // {{{ seek()
-
- /**
- * Seek to a specific row in a result set
- *
- * @param int $rownum number of the row where the data can be found
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function seek($rownum = 0)
- {
- if ($this->rownum != ($rownum - 1) && !@mysql_data_seek($this->result, $rownum)) {
- if ($this->result === false) {
- return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- } elseif (is_null($this->result)) {
- return MDB2_OK;
- }
- return $this->db->raiseError(MDB2_ERROR_INVALID, null, null,
- 'tried to seek to an invalid row number ('.$rownum.')', __FUNCTION__);
- }
- $this->rownum = $rownum - 1;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ valid()
-
- /**
- * Check if the end of the result set has been reached
- *
- * @return mixed true or false on sucess, a MDB2 error on failure
- * @access public
- */
- function valid()
- {
- $numrows = $this->numRows();
- if (PEAR::isError($numrows)) {
- return $numrows;
- }
- return $this->rownum < ($numrows - 1);
- }
-
- // }}}
- // {{{ numRows()
-
- /**
- * Returns the number of rows in a result object
- *
- * @return mixed MDB2 Error Object or the number of rows
- * @access public
- */
- function numRows()
- {
- $rows = @mysql_num_rows($this->result);
- if (false === $rows) {
- if (false === $this->result) {
- return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- } elseif (is_null($this->result)) {
- return 0;
- }
- return $this->db->raiseError(null, null, null,
- 'Could not get row count', __FUNCTION__);
- }
- return $rows;
- }
-}
-
-/**
- * MDB2 MySQL statement driver
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Statement_mysql extends MDB2_Statement_Common
-{
- // {{{ _execute()
-
- /**
- * Execute a prepared query statement helper method.
- *
- * @param mixed $result_class string which specifies which result class to use
- * @param mixed $result_wrap_class string which specifies which class to wrap results in
- *
- * @return mixed MDB2_Result or integer (affected rows) on success,
- * a MDB2 error on failure
- * @access private
- */
- function &_execute($result_class = true, $result_wrap_class = false)
- {
- if (is_null($this->statement)) {
- $result =& parent::_execute($result_class, $result_wrap_class);
- return $result;
- }
- $this->db->last_query = $this->query;
- $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'pre', 'parameters' => $this->values));
- if ($this->db->getOption('disable_query')) {
- $result = $this->is_manip ? 0 : null;
- return $result;
- }
-
- $connection = $this->db->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- $query = 'EXECUTE '.$this->statement;
- if (!empty($this->positions)) {
- $parameters = array();
- foreach ($this->positions as $parameter) {
- if (!array_key_exists($parameter, $this->values)) {
- return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
- }
- $value = $this->values[$parameter];
- $type = array_key_exists($parameter, $this->types) ? $this->types[$parameter] : null;
- if (is_resource($value) || $type == 'clob' || $type == 'blob' && $this->db->options['lob_allow_url_include']) {
- if (!is_resource($value) && preg_match('/^(\w+:\/\/)(.*)$/', $value, $match)) {
- if ($match[1] == 'file://') {
- $value = $match[2];
- }
- $value = @fopen($value, 'r');
- $close = true;
- }
- if (is_resource($value)) {
- $data = '';
- while (!@feof($value)) {
- $data.= @fread($value, $this->db->options['lob_buffer_length']);
- }
- if ($close) {
- @fclose($value);
- }
- $value = $data;
- }
- }
- $quoted = $this->db->quote($value, $type);
- if (PEAR::isError($quoted)) {
- return $quoted;
- }
- $param_query = 'SET @'.$parameter.' = '.$quoted;
- $result = $this->db->_doQuery($param_query, true, $connection);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- $query.= ' USING @'.implode(', @', array_values($this->positions));
- }
-
- $result = $this->db->_doQuery($query, $this->is_manip, $connection);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- if ($this->is_manip) {
- $affected_rows = $this->db->_affectedRows($connection, $result);
- return $affected_rows;
- }
-
- $result =& $this->db->_wrapResult($result, $this->result_types,
- $result_class, $result_wrap_class, $this->limit, $this->offset);
- $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'post', 'result' => $result));
- return $result;
- }
-
- // }}}
- // {{{ free()
-
- /**
- * Release resources allocated for the specified prepared query.
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function free()
- {
- if (is_null($this->positions)) {
- return $this->db->raiseError(MDB2_ERROR, null, null,
- 'Prepared statement has already been freed', __FUNCTION__);
- }
- $result = MDB2_OK;
-
- if (!is_null($this->statement)) {
- $connection = $this->db->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- $query = 'DEALLOCATE PREPARE '.$this->statement;
- $result = $this->db->_doQuery($query, true, $connection);
- }
-
- parent::free();
- return $result;
- }
-}
-?>
\ No newline at end of file
+ |
+// +----------------------------------------------------------------------+
+//
+// $Id: mysql.php 302867 2010-08-29 11:22:07Z quipo $
+//
+
+/**
+ * MDB2 MySQL driver
+ *
+ * @package MDB2
+ * @category Database
+ * @author Lukas Smith
+ */
+class MDB2_Driver_mysql extends MDB2_Driver_Common
+{
+ // {{{ properties
+
+ var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => '\\', 'escape_pattern' => '\\');
+
+ var $identifier_quoting = array('start' => '`', 'end' => '`', 'escape' => '`');
+
+ var $sql_comments = array(
+ array('start' => '-- ', 'end' => "\n", 'escape' => false),
+ array('start' => '#', 'end' => "\n", 'escape' => false),
+ array('start' => '/*', 'end' => '*/', 'escape' => false),
+ );
+
+ var $server_capabilities_checked = false;
+
+ var $start_transaction = false;
+
+ var $varchar_max_length = 255;
+
+ // }}}
+ // {{{ constructor
+
+ /**
+ * Constructor
+ */
+ function __construct()
+ {
+ parent::__construct();
+
+ $this->phptype = 'mysql';
+ $this->dbsyntax = 'mysql';
+
+ $this->supported['sequences'] = 'emulated';
+ $this->supported['indexes'] = true;
+ $this->supported['affected_rows'] = true;
+ $this->supported['transactions'] = false;
+ $this->supported['savepoints'] = false;
+ $this->supported['summary_functions'] = true;
+ $this->supported['order_by_text'] = true;
+ $this->supported['current_id'] = 'emulated';
+ $this->supported['limit_queries'] = true;
+ $this->supported['LOBs'] = true;
+ $this->supported['replace'] = true;
+ $this->supported['sub_selects'] = 'emulated';
+ $this->supported['triggers'] = false;
+ $this->supported['auto_increment'] = true;
+ $this->supported['primary_key'] = true;
+ $this->supported['result_introspection'] = true;
+ $this->supported['prepared_statements'] = 'emulated';
+ $this->supported['identifier_quoting'] = true;
+ $this->supported['pattern_escaping'] = true;
+ $this->supported['new_link'] = true;
+
+ $this->options['DBA_username'] = false;
+ $this->options['DBA_password'] = false;
+ $this->options['default_table_type'] = '';
+ $this->options['max_identifiers_length'] = 64;
+
+ $this->_reCheckSupportedOptions();
+ }
+
+ // }}}
+ // {{{ _reCheckSupportedOptions()
+
+ /**
+ * If the user changes certain options, other capabilities may depend
+ * on the new settings, so we need to check them (again).
+ *
+ * @access private
+ */
+ function _reCheckSupportedOptions()
+ {
+ $this->supported['transactions'] = $this->options['use_transactions'];
+ $this->supported['savepoints'] = $this->options['use_transactions'];
+ if ($this->options['default_table_type']) {
+ switch (strtoupper($this->options['default_table_type'])) {
+ case 'BLACKHOLE':
+ case 'MEMORY':
+ case 'ARCHIVE':
+ case 'CSV':
+ case 'HEAP':
+ case 'ISAM':
+ case 'MERGE':
+ case 'MRG_ISAM':
+ case 'ISAM':
+ case 'MRG_MYISAM':
+ case 'MYISAM':
+ $this->supported['savepoints'] = false;
+ $this->supported['transactions'] = false;
+ $this->warnings[] = $this->options['default_table_type'] .
+ ' is not a supported default table type';
+ break;
+ }
+ }
+ }
+
+ // }}}
+ // {{{ function setOption($option, $value)
+
+ /**
+ * set the option for the db class
+ *
+ * @param string option name
+ * @param mixed value for the option
+ *
+ * @return mixed MDB2_OK or MDB2 Error Object
+ *
+ * @access public
+ */
+ function setOption($option, $value)
+ {
+ $res = parent::setOption($option, $value);
+ $this->_reCheckSupportedOptions();
+ }
+
+ // }}}
+ // {{{ errorInfo()
+
+ /**
+ * This method is used to collect information about an error
+ *
+ * @param integer $error
+ * @return array
+ * @access public
+ */
+ function errorInfo($error = null)
+ {
+ if ($this->connection) {
+ $native_code = @mysql_errno($this->connection);
+ $native_msg = @mysql_error($this->connection);
+ } else {
+ $native_code = @mysql_errno();
+ $native_msg = @mysql_error();
+ }
+ if (is_null($error)) {
+ static $ecode_map;
+ if (empty($ecode_map)) {
+ $ecode_map = array(
+ 1000 => MDB2_ERROR_INVALID, //hashchk
+ 1001 => MDB2_ERROR_INVALID, //isamchk
+ 1004 => MDB2_ERROR_CANNOT_CREATE,
+ 1005 => MDB2_ERROR_CANNOT_CREATE,
+ 1006 => MDB2_ERROR_CANNOT_CREATE,
+ 1007 => MDB2_ERROR_ALREADY_EXISTS,
+ 1008 => MDB2_ERROR_CANNOT_DROP,
+ 1009 => MDB2_ERROR_CANNOT_DROP,
+ 1010 => MDB2_ERROR_CANNOT_DROP,
+ 1011 => MDB2_ERROR_CANNOT_DELETE,
+ 1022 => MDB2_ERROR_ALREADY_EXISTS,
+ 1029 => MDB2_ERROR_NOT_FOUND,
+ 1032 => MDB2_ERROR_NOT_FOUND,
+ 1044 => MDB2_ERROR_ACCESS_VIOLATION,
+ 1045 => MDB2_ERROR_ACCESS_VIOLATION,
+ 1046 => MDB2_ERROR_NODBSELECTED,
+ 1048 => MDB2_ERROR_CONSTRAINT,
+ 1049 => MDB2_ERROR_NOSUCHDB,
+ 1050 => MDB2_ERROR_ALREADY_EXISTS,
+ 1051 => MDB2_ERROR_NOSUCHTABLE,
+ 1054 => MDB2_ERROR_NOSUCHFIELD,
+ 1060 => MDB2_ERROR_ALREADY_EXISTS,
+ 1061 => MDB2_ERROR_ALREADY_EXISTS,
+ 1062 => MDB2_ERROR_ALREADY_EXISTS,
+ 1064 => MDB2_ERROR_SYNTAX,
+ 1067 => MDB2_ERROR_INVALID,
+ 1072 => MDB2_ERROR_NOT_FOUND,
+ 1086 => MDB2_ERROR_ALREADY_EXISTS,
+ 1091 => MDB2_ERROR_NOT_FOUND,
+ 1100 => MDB2_ERROR_NOT_LOCKED,
+ 1109 => MDB2_ERROR_NOT_FOUND,
+ 1125 => MDB2_ERROR_ALREADY_EXISTS,
+ 1136 => MDB2_ERROR_VALUE_COUNT_ON_ROW,
+ 1138 => MDB2_ERROR_INVALID,
+ 1142 => MDB2_ERROR_ACCESS_VIOLATION,
+ 1143 => MDB2_ERROR_ACCESS_VIOLATION,
+ 1146 => MDB2_ERROR_NOSUCHTABLE,
+ 1149 => MDB2_ERROR_SYNTAX,
+ 1169 => MDB2_ERROR_CONSTRAINT,
+ 1176 => MDB2_ERROR_NOT_FOUND,
+ 1177 => MDB2_ERROR_NOSUCHTABLE,
+ 1213 => MDB2_ERROR_DEADLOCK,
+ 1216 => MDB2_ERROR_CONSTRAINT,
+ 1217 => MDB2_ERROR_CONSTRAINT,
+ 1227 => MDB2_ERROR_ACCESS_VIOLATION,
+ 1235 => MDB2_ERROR_CANNOT_CREATE,
+ 1299 => MDB2_ERROR_INVALID_DATE,
+ 1300 => MDB2_ERROR_INVALID,
+ 1304 => MDB2_ERROR_ALREADY_EXISTS,
+ 1305 => MDB2_ERROR_NOT_FOUND,
+ 1306 => MDB2_ERROR_CANNOT_DROP,
+ 1307 => MDB2_ERROR_CANNOT_CREATE,
+ 1334 => MDB2_ERROR_CANNOT_ALTER,
+ 1339 => MDB2_ERROR_NOT_FOUND,
+ 1356 => MDB2_ERROR_INVALID,
+ 1359 => MDB2_ERROR_ALREADY_EXISTS,
+ 1360 => MDB2_ERROR_NOT_FOUND,
+ 1363 => MDB2_ERROR_NOT_FOUND,
+ 1365 => MDB2_ERROR_DIVZERO,
+ 1451 => MDB2_ERROR_CONSTRAINT,
+ 1452 => MDB2_ERROR_CONSTRAINT,
+ 1542 => MDB2_ERROR_CANNOT_DROP,
+ 1546 => MDB2_ERROR_CONSTRAINT,
+ 1582 => MDB2_ERROR_CONSTRAINT,
+ 2003 => MDB2_ERROR_CONNECT_FAILED,
+ 2019 => MDB2_ERROR_INVALID,
+ );
+ }
+ if ($this->options['portability'] & MDB2_PORTABILITY_ERRORS) {
+ $ecode_map[1022] = MDB2_ERROR_CONSTRAINT;
+ $ecode_map[1048] = MDB2_ERROR_CONSTRAINT_NOT_NULL;
+ $ecode_map[1062] = MDB2_ERROR_CONSTRAINT;
+ } else {
+ // Doing this in case mode changes during runtime.
+ $ecode_map[1022] = MDB2_ERROR_ALREADY_EXISTS;
+ $ecode_map[1048] = MDB2_ERROR_CONSTRAINT;
+ $ecode_map[1062] = MDB2_ERROR_ALREADY_EXISTS;
+ }
+ if (isset($ecode_map[$native_code])) {
+ $error = $ecode_map[$native_code];
+ }
+ }
+ return array($error, $native_code, $native_msg);
+ }
+
+ // }}}
+ // {{{ escape()
+
+ /**
+ * Quotes a string so it can be safely used in a query. It will quote
+ * the text so it can safely be used within a query.
+ *
+ * @param string the input string to quote
+ * @param bool escape wildcards
+ *
+ * @return string quoted string
+ *
+ * @access public
+ */
+ function escape($text, $escape_wildcards = false)
+ {
+ if ($escape_wildcards) {
+ $text = $this->escapePattern($text);
+ }
+ $connection = $this->getConnection();
+ if (PEAR::isError($connection)) {
+ return $connection;
+ }
+ $text = @mysql_real_escape_string($text, $connection);
+ return $text;
+ }
+
+ // }}}
+ // {{{ beginTransaction()
+
+ /**
+ * Start a transaction or set a savepoint.
+ *
+ * @param string name of a savepoint to set
+ * @return mixed MDB2_OK on success, a MDB2 error on failure
+ *
+ * @access public
+ */
+ function beginTransaction($savepoint = null)
+ {
+ $this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
+ $this->_getServerCapabilities();
+ if (!is_null($savepoint)) {
+ if (!$this->supports('savepoints')) {
+ return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
+ 'savepoints are not supported', __FUNCTION__);
+ }
+ if (!$this->in_transaction) {
+ return $this->raiseError(MDB2_ERROR_INVALID, null, null,
+ 'savepoint cannot be released when changes are auto committed', __FUNCTION__);
+ }
+ $query = 'SAVEPOINT '.$savepoint;
+ return $this->_doQuery($query, true);
+ } elseif ($this->in_transaction) {
+ return MDB2_OK; //nothing to do
+ }
+ if (!$this->destructor_registered && $this->opened_persistent) {
+ $this->destructor_registered = true;
+ register_shutdown_function('MDB2_closeOpenTransactions');
+ }
+ $query = $this->start_transaction ? 'START TRANSACTION' : 'SET AUTOCOMMIT = 0';
+ $result = $this->_doQuery($query, true);
+ if (PEAR::isError($result)) {
+ return $result;
+ }
+ $this->in_transaction = true;
+ return MDB2_OK;
+ }
+
+ // }}}
+ // {{{ commit()
+
+ /**
+ * Commit the database changes done during a transaction that is in
+ * progress or release a savepoint. This function may only be called when
+ * auto-committing is disabled, otherwise it will fail. Therefore, a new
+ * transaction is implicitly started after committing the pending changes.
+ *
+ * @param string name of a savepoint to release
+ * @return mixed MDB2_OK on success, a MDB2 error on failure
+ *
+ * @access public
+ */
+ function commit($savepoint = null)
+ {
+ $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
+ if (!$this->in_transaction) {
+ return $this->raiseError(MDB2_ERROR_INVALID, null, null,
+ 'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__);
+ }
+ if (!is_null($savepoint)) {
+ if (!$this->supports('savepoints')) {
+ return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
+ 'savepoints are not supported', __FUNCTION__);
+ }
+ $server_info = $this->getServerVersion();
+ if (version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch'], '5.0.3', '<')) {
+ return MDB2_OK;
+ }
+ $query = 'RELEASE SAVEPOINT '.$savepoint;
+ return $this->_doQuery($query, true);
+ }
+
+ if (!$this->supports('transactions')) {
+ return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
+ 'transactions are not supported', __FUNCTION__);
+ }
+
+ $result = $this->_doQuery('COMMIT', true);
+ if (PEAR::isError($result)) {
+ return $result;
+ }
+ if (!$this->start_transaction) {
+ $query = 'SET AUTOCOMMIT = 1';
+ $result = $this->_doQuery($query, true);
+ if (PEAR::isError($result)) {
+ return $result;
+ }
+ }
+ $this->in_transaction = false;
+ return MDB2_OK;
+ }
+
+ // }}}
+ // {{{ rollback()
+
+ /**
+ * Cancel any database changes done during a transaction or since a specific
+ * savepoint that is in progress. This function may only be called when
+ * auto-committing is disabled, otherwise it will fail. Therefore, a new
+ * transaction is implicitly started after canceling the pending changes.
+ *
+ * @param string name of a savepoint to rollback to
+ * @return mixed MDB2_OK on success, a MDB2 error on failure
+ *
+ * @access public
+ */
+ function rollback($savepoint = null)
+ {
+ $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
+ if (!$this->in_transaction) {
+ return $this->raiseError(MDB2_ERROR_INVALID, null, null,
+ 'rollback cannot be done changes are auto committed', __FUNCTION__);
+ }
+ if (!is_null($savepoint)) {
+ if (!$this->supports('savepoints')) {
+ return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
+ 'savepoints are not supported', __FUNCTION__);
+ }
+ $query = 'ROLLBACK TO SAVEPOINT '.$savepoint;
+ return $this->_doQuery($query, true);
+ }
+
+ $query = 'ROLLBACK';
+ $result = $this->_doQuery($query, true);
+ if (PEAR::isError($result)) {
+ return $result;
+ }
+ if (!$this->start_transaction) {
+ $query = 'SET AUTOCOMMIT = 1';
+ $result = $this->_doQuery($query, true);
+ if (PEAR::isError($result)) {
+ return $result;
+ }
+ }
+ $this->in_transaction = false;
+ return MDB2_OK;
+ }
+
+ // }}}
+ // {{{ function setTransactionIsolation()
+
+ /**
+ * Set the transacton isolation level.
+ *
+ * @param string standard isolation level
+ * READ UNCOMMITTED (allows dirty reads)
+ * READ COMMITTED (prevents dirty reads)
+ * REPEATABLE READ (prevents nonrepeatable reads)
+ * SERIALIZABLE (prevents phantom reads)
+ * @param array some transaction options:
+ * 'wait' => 'WAIT' | 'NO WAIT'
+ * 'rw' => 'READ WRITE' | 'READ ONLY'
+ *
+ * @return mixed MDB2_OK on success, a MDB2 error on failure
+ *
+ * @access public
+ * @since 2.1.1
+ */
+ function setTransactionIsolation($isolation, $options = array())
+ {
+ $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
+ if (!$this->supports('transactions')) {
+ return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
+ 'transactions are not supported', __FUNCTION__);
+ }
+ switch ($isolation) {
+ case 'READ UNCOMMITTED':
+ case 'READ COMMITTED':
+ case 'REPEATABLE READ':
+ case 'SERIALIZABLE':
+ break;
+ default:
+ return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
+ 'isolation level is not supported: '.$isolation, __FUNCTION__);
+ }
+
+ $query = "SET SESSION TRANSACTION ISOLATION LEVEL $isolation";
+ return $this->_doQuery($query, true);
+ }
+
+ // }}}
+ // {{{ _doConnect()
+
+ /**
+ * do the grunt work of the connect
+ *
+ * @return connection on success or MDB2 Error Object on failure
+ * @access protected
+ */
+ function _doConnect($username, $password, $persistent = false)
+ {
+ if (!PEAR::loadExtension($this->phptype)) {
+ return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
+ 'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__);
+ }
+
+ $params = array();
+ $unix = ($this->dsn['protocol'] && $this->dsn['protocol'] == 'unix');
+ if (empty($this->dsn['hostspec'])) {
+ $this->dsn['hostspec'] = $unix ? '' : 'localhost';
+ }
+ if ($this->dsn['hostspec']) {
+ $params[0] = $this->dsn['hostspec'] . ($this->dsn['port'] ? ':' . $this->dsn['port'] : '');
+ } else {
+ $params[0] = ':' . $this->dsn['socket'];
+ }
+ $params[] = $username ? $username : null;
+ $params[] = $password ? $password : null;
+ if (!$persistent) {
+ if ($this->_isNewLinkSet()) {
+ $params[] = true;
+ } else {
+ $params[] = false;
+ }
+ }
+ if (version_compare(phpversion(), '4.3.0', '>=')) {
+ $params[] = isset($this->dsn['client_flags'])
+ ? $this->dsn['client_flags'] : null;
+ }
+ $connect_function = $persistent ? 'mysql_pconnect' : 'mysql_connect';
+
+ $connection = @call_user_func_array($connect_function, $params);
+ if (!$connection) {
+ if (($err = @mysql_error()) != '') {
+ return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
+ $err, __FUNCTION__);
+ } else {
+ return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
+ 'unable to establish a connection', __FUNCTION__);
+ }
+ }
+
+ if (!empty($this->dsn['charset'])) {
+ $result = $this->setCharset($this->dsn['charset'], $connection);
+ if (PEAR::isError($result)) {
+ $this->disconnect(false);
+ return $result;
+ }
+ }
+
+ return $connection;
+ }
+
+ // }}}
+ // {{{ connect()
+
+ /**
+ * Connect to the database
+ *
+ * @return MDB2_OK on success, MDB2 Error Object on failure
+ * @access public
+ */
+ function connect()
+ {
+ if (is_resource($this->connection)) {
+ //if (count(array_diff($this->connected_dsn, $this->dsn)) == 0
+ if (MDB2::areEquals($this->connected_dsn, $this->dsn)
+ && $this->opened_persistent == $this->options['persistent']
+ ) {
+ return MDB2_OK;
+ }
+ $this->disconnect(false);
+ }
+
+ $connection = $this->_doConnect(
+ $this->dsn['username'],
+ $this->dsn['password'],
+ $this->options['persistent']
+ );
+ if (PEAR::isError($connection)) {
+ return $connection;
+ }
+
+ $this->connection = $connection;
+ $this->connected_dsn = $this->dsn;
+ $this->connected_database_name = '';
+ $this->opened_persistent = $this->options['persistent'];
+ $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
+
+ if ($this->database_name) {
+ if ($this->database_name != $this->connected_database_name) {
+ if (!@mysql_select_db($this->database_name, $connection)) {
+ $err = $this->raiseError(null, null, null,
+ 'Could not select the database: '.$this->database_name, __FUNCTION__);
+ return $err;
+ }
+ $this->connected_database_name = $this->database_name;
+ }
+ }
+
+ $this->_getServerCapabilities();
+
+ return MDB2_OK;
+ }
+
+ // }}}
+ // {{{ setCharset()
+
+ /**
+ * Set the charset on the current connection
+ *
+ * @param string charset (or array(charset, collation))
+ * @param resource connection handle
+ *
+ * @return true on success, MDB2 Error Object on failure
+ */
+ function setCharset($charset, $connection = null)
+ {
+ if (is_null($connection)) {
+ $connection = $this->getConnection();
+ if (PEAR::isError($connection)) {
+ return $connection;
+ }
+ }
+ $collation = null;
+ if (is_array($charset) && 2 == count($charset)) {
+ $collation = array_pop($charset);
+ $charset = array_pop($charset);
+ }
+ $client_info = mysql_get_client_info();
+ if (function_exists('mysql_set_charset') && version_compare($client_info, '5.0.6')) {
+ if (!$result = mysql_set_charset($charset, $connection)) {
+ $err = $this->raiseError(null, null, null,
+ 'Could not set client character set', __FUNCTION__);
+ return $err;
+ }
+ return $result;
+ }
+ $query = "SET NAMES '".mysql_real_escape_string($charset, $connection)."'";
+ if (!is_null($collation)) {
+ $query .= " COLLATE '".mysql_real_escape_string($collation, $connection)."'";
+ }
+ return $this->_doQuery($query, true, $connection);
+ }
+
+ // }}}
+ // {{{ databaseExists()
+
+ /**
+ * check if given database name is exists?
+ *
+ * @param string $name name of the database that should be checked
+ *
+ * @return mixed true/false on success, a MDB2 error on failure
+ * @access public
+ */
+ function databaseExists($name)
+ {
+ $connection = $this->_doConnect($this->dsn['username'],
+ $this->dsn['password'],
+ $this->options['persistent']);
+ if (PEAR::isError($connection)) {
+ return $connection;
+ }
+
+ $result = @mysql_select_db($name, $connection);
+ @mysql_close($connection);
+
+ return $result;
+ }
+
+ // }}}
+ // {{{ disconnect()
+
+ /**
+ * Log out and disconnect from the database.
+ *
+ * @param boolean $force if the disconnect should be forced even if the
+ * connection is opened persistently
+ * @return mixed true on success, false if not connected and error
+ * object on error
+ * @access public
+ */
+ function disconnect($force = true)
+ {
+ if (is_resource($this->connection)) {
+ if ($this->in_transaction) {
+ $dsn = $this->dsn;
+ $database_name = $this->database_name;
+ $persistent = $this->options['persistent'];
+ $this->dsn = $this->connected_dsn;
+ $this->database_name = $this->connected_database_name;
+ $this->options['persistent'] = $this->opened_persistent;
+ $this->rollback();
+ $this->dsn = $dsn;
+ $this->database_name = $database_name;
+ $this->options['persistent'] = $persistent;
+ }
+
+ if (!$this->opened_persistent || $force) {
+ $ok = @mysql_close($this->connection);
+ if (!$ok) {
+ return $this->raiseError(MDB2_ERROR_DISCONNECT_FAILED,
+ null, null, null, __FUNCTION__);
+ }
+ }
+ } else {
+ return false;
+ }
+ return parent::disconnect($force);
+ }
+
+ // }}}
+ // {{{ standaloneQuery()
+
+ /**
+ * execute a query as DBA
+ *
+ * @param string $query the SQL query
+ * @param mixed $types array that contains the types of the columns in
+ * the result set
+ * @param boolean $is_manip if the query is a manipulation query
+ * @return mixed MDB2_OK on success, a MDB2 error on failure
+ * @access public
+ */
+ function standaloneQuery($query, $types = null, $is_manip = false)
+ {
+ $user = $this->options['DBA_username']? $this->options['DBA_username'] : $this->dsn['username'];
+ $pass = $this->options['DBA_password']? $this->options['DBA_password'] : $this->dsn['password'];
+ $connection = $this->_doConnect($user, $pass, $this->options['persistent']);
+ if (PEAR::isError($connection)) {
+ return $connection;
+ }
+
+ $offset = $this->offset;
+ $limit = $this->limit;
+ $this->offset = $this->limit = 0;
+ $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
+
+ $result = $this->_doQuery($query, $is_manip, $connection, $this->database_name);
+ if (!PEAR::isError($result)) {
+ $result = $this->_affectedRows($connection, $result);
+ }
+
+ @mysql_close($connection);
+ return $result;
+ }
+
+ // }}}
+ // {{{ _doQuery()
+
+ /**
+ * Execute a query
+ * @param string $query query
+ * @param boolean $is_manip if the query is a manipulation query
+ * @param resource $connection
+ * @param string $database_name
+ * @return result or error object
+ * @access protected
+ */
+ function _doQuery($query, $is_manip = false, $connection = null, $database_name = null)
+ {
+ $this->last_query = $query;
+ $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
+ if ($result) {
+ if (PEAR::isError($result)) {
+ return $result;
+ }
+ $query = $result;
+ }
+ if ($this->options['disable_query']) {
+ $result = $is_manip ? 0 : null;
+ return $result;
+ }
+
+ if (is_null($connection)) {
+ $connection = $this->getConnection();
+ if (PEAR::isError($connection)) {
+ return $connection;
+ }
+ }
+ if (is_null($database_name)) {
+ $database_name = $this->database_name;
+ }
+
+ if ($database_name) {
+ if ($database_name != $this->connected_database_name) {
+ if (!@mysql_select_db($database_name, $connection)) {
+ $err = $this->raiseError(null, null, null,
+ 'Could not select the database: '.$database_name, __FUNCTION__);
+ return $err;
+ }
+ $this->connected_database_name = $database_name;
+ }
+ }
+
+ $function = $this->options['result_buffering']
+ ? 'mysql_query' : 'mysql_unbuffered_query';
+ $result = @$function($query, $connection);
+ if (!$result && 0 !== mysql_errno($connection)) {
+ $err = $this->raiseError(null, null, null,
+ 'Could not execute statement', __FUNCTION__);
+ return $err;
+ }
+
+ $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result));
+ return $result;
+ }
+
+ // }}}
+ // {{{ _affectedRows()
+
+ /**
+ * Returns the number of rows affected
+ *
+ * @param resource $result
+ * @param resource $connection
+ * @return mixed MDB2 Error Object or the number of rows affected
+ * @access private
+ */
+ function _affectedRows($connection, $result = null)
+ {
+ if (is_null($connection)) {
+ $connection = $this->getConnection();
+ if (PEAR::isError($connection)) {
+ return $connection;
+ }
+ }
+ return @mysql_affected_rows($connection);
+ }
+
+ // }}}
+ // {{{ _modifyQuery()
+
+ /**
+ * Changes a query string for various DBMS specific reasons
+ *
+ * @param string $query query to modify
+ * @param boolean $is_manip if it is a DML query
+ * @param integer $limit limit the number of rows
+ * @param integer $offset start reading from given offset
+ * @return string modified query
+ * @access protected
+ */
+ function _modifyQuery($query, $is_manip, $limit, $offset)
+ {
+ if ($this->options['portability'] & MDB2_PORTABILITY_DELETE_COUNT) {
+ // "DELETE FROM table" gives 0 affected rows in MySQL.
+ // This little hack lets you know how many rows were deleted.
+ if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) {
+ $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
+ 'DELETE FROM \1 WHERE 1=1', $query);
+ }
+ }
+ if ($limit > 0
+ && !preg_match('/LIMIT\s*\d(?:\s*(?:,|OFFSET)\s*\d+)?(?:[^\)]*)?$/i', $query)
+ ) {
+ $query = rtrim($query);
+ if (substr($query, -1) == ';') {
+ $query = substr($query, 0, -1);
+ }
+
+ // LIMIT doesn't always come last in the query
+ // @see http://dev.mysql.com/doc/refman/5.0/en/select.html
+ $after = '';
+ if (preg_match('/(\s+INTO\s+(?:OUT|DUMP)FILE\s.*)$/ims', $query, $matches)) {
+ $after = $matches[0];
+ $query = preg_replace('/(\s+INTO\s+(?:OUT|DUMP)FILE\s.*)$/ims', '', $query);
+ } elseif (preg_match('/(\s+FOR\s+UPDATE\s*)$/i', $query, $matches)) {
+ $after = $matches[0];
+ $query = preg_replace('/(\s+FOR\s+UPDATE\s*)$/im', '', $query);
+ } elseif (preg_match('/(\s+LOCK\s+IN\s+SHARE\s+MODE\s*)$/im', $query, $matches)) {
+ $after = $matches[0];
+ $query = preg_replace('/(\s+LOCK\s+IN\s+SHARE\s+MODE\s*)$/im', '', $query);
+ }
+
+ if ($is_manip) {
+ return $query . " LIMIT $limit" . $after;
+ } else {
+ return $query . " LIMIT $offset, $limit" . $after;
+ }
+ }
+ return $query;
+ }
+
+ // }}}
+ // {{{ getServerVersion()
+
+ /**
+ * return version information about the server
+ *
+ * @param bool $native determines if the raw version string should be returned
+ * @return mixed array/string with version information or MDB2 error object
+ * @access public
+ */
+ function getServerVersion($native = false)
+ {
+ $connection = $this->getConnection();
+ if (PEAR::isError($connection)) {
+ return $connection;
+ }
+ if ($this->connected_server_info) {
+ $server_info = $this->connected_server_info;
+ } else {
+ $server_info = @mysql_get_server_info($connection);
+ }
+ if (!$server_info) {
+ return $this->raiseError(null, null, null,
+ 'Could not get server information', __FUNCTION__);
+ }
+ // cache server_info
+ $this->connected_server_info = $server_info;
+ if (!$native) {
+ $tmp = explode('.', $server_info, 3);
+ if (isset($tmp[2]) && strpos($tmp[2], '-')) {
+ $tmp2 = explode('-', @$tmp[2], 2);
+ } else {
+ $tmp2[0] = isset($tmp[2]) ? $tmp[2] : null;
+ $tmp2[1] = null;
+ }
+ $server_info = array(
+ 'major' => isset($tmp[0]) ? $tmp[0] : null,
+ 'minor' => isset($tmp[1]) ? $tmp[1] : null,
+ 'patch' => $tmp2[0],
+ 'extra' => $tmp2[1],
+ 'native' => $server_info,
+ );
+ }
+ return $server_info;
+ }
+
+ // }}}
+ // {{{ _getServerCapabilities()
+
+ /**
+ * Fetch some information about the server capabilities
+ * (transactions, subselects, prepared statements, etc).
+ *
+ * @access private
+ */
+ function _getServerCapabilities()
+ {
+ if (!$this->server_capabilities_checked) {
+ $this->server_capabilities_checked = true;
+
+ //set defaults
+ $this->supported['sub_selects'] = 'emulated';
+ $this->supported['prepared_statements'] = 'emulated';
+ $this->supported['triggers'] = false;
+ $this->start_transaction = false;
+ $this->varchar_max_length = 255;
+
+ $server_info = $this->getServerVersion();
+ if (is_array($server_info)) {
+ $server_version = $server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch'];
+
+ if (!version_compare($server_version, '4.1.0', '<')) {
+ $this->supported['sub_selects'] = true;
+ $this->supported['prepared_statements'] = true;
+ }
+
+ // SAVEPOINTs were introduced in MySQL 4.0.14 and 4.1.1 (InnoDB)
+ if (version_compare($server_version, '4.1.0', '>=')) {
+ if (version_compare($server_version, '4.1.1', '<')) {
+ $this->supported['savepoints'] = false;
+ }
+ } elseif (version_compare($server_version, '4.0.14', '<')) {
+ $this->supported['savepoints'] = false;
+ }
+
+ if (!version_compare($server_version, '4.0.11', '<')) {
+ $this->start_transaction = true;
+ }
+
+ if (!version_compare($server_version, '5.0.3', '<')) {
+ $this->varchar_max_length = 65532;
+ }
+
+ if (!version_compare($server_version, '5.0.2', '<')) {
+ $this->supported['triggers'] = true;
+ }
+ }
+ }
+ }
+
+ // }}}
+ // {{{ function _skipUserDefinedVariable($query, $position)
+
+ /**
+ * Utility method, used by prepare() to avoid misinterpreting MySQL user
+ * defined variables (SELECT @x:=5) for placeholders.
+ * Check if the placeholder is a false positive, i.e. if it is an user defined
+ * variable instead. If so, skip it and advance the position, otherwise
+ * return the current position, which is valid
+ *
+ * @param string $query
+ * @param integer $position current string cursor position
+ * @return integer $new_position
+ * @access protected
+ */
+ function _skipUserDefinedVariable($query, $position)
+ {
+ $found = strpos(strrev(substr($query, 0, $position)), '@');
+ if ($found === false) {
+ return $position;
+ }
+ $pos = strlen($query) - strlen(substr($query, $position)) - $found - 1;
+ $substring = substr($query, $pos, $position - $pos + 2);
+ if (preg_match('/^@\w+\s*:=$/', $substring)) {
+ return $position + 1; //found an user defined variable: skip it
+ }
+ return $position;
+ }
+
+ // }}}
+ // {{{ prepare()
+
+ /**
+ * Prepares a query for multiple execution with execute().
+ * With some database backends, this is emulated.
+ * prepare() requires a generic query as string like
+ * 'INSERT INTO numbers VALUES(?,?)' or
+ * 'INSERT INTO numbers VALUES(:foo,:bar)'.
+ * The ? and :name and are placeholders which can be set using
+ * bindParam() and the query can be sent off using the execute() method.
+ * The allowed format for :name can be set with the 'bindname_format' option.
+ *
+ * @param string $query the query to prepare
+ * @param mixed $types array that contains the types of the placeholders
+ * @param mixed $result_types array that contains the types of the columns in
+ * the result set or MDB2_PREPARE_RESULT, if set to
+ * MDB2_PREPARE_MANIP the query is handled as a manipulation query
+ * @param mixed $lobs key (field) value (parameter) pair for all lob placeholders
+ * @return mixed resource handle for the prepared query on success, a MDB2
+ * error on failure
+ * @access public
+ * @see bindParam, execute
+ */
+ function prepare($query, $types = null, $result_types = null, $lobs = array())
+ {
+ // connect to get server capabilities (http://pear.php.net/bugs/16147)
+ $connection = $this->getConnection();
+ if (PEAR::isError($connection)) {
+ return $connection;
+ }
+
+ if ($this->options['emulate_prepared']
+ || $this->supported['prepared_statements'] !== true
+ ) {
+ return parent::prepare($query, $types, $result_types, $lobs);
+ }
+ $is_manip = ($result_types === MDB2_PREPARE_MANIP);
+ $offset = $this->offset;
+ $limit = $this->limit;
+ $this->offset = $this->limit = 0;
+ $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
+ $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre'));
+ if ($result) {
+ if (PEAR::isError($result)) {
+ return $result;
+ }
+ $query = $result;
+ }
+ $placeholder_type_guess = $placeholder_type = null;
+ $question = '?';
+ $colon = ':';
+ $positions = array();
+ $position = 0;
+ while ($position < strlen($query)) {
+ $q_position = strpos($query, $question, $position);
+ $c_position = strpos($query, $colon, $position);
+ if ($q_position && $c_position) {
+ $p_position = min($q_position, $c_position);
+ } elseif ($q_position) {
+ $p_position = $q_position;
+ } elseif ($c_position) {
+ $p_position = $c_position;
+ } else {
+ break;
+ }
+ if (is_null($placeholder_type)) {
+ $placeholder_type_guess = $query[$p_position];
+ }
+
+ $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position);
+ if (PEAR::isError($new_pos)) {
+ return $new_pos;
+ }
+ if ($new_pos != $position) {
+ $position = $new_pos;
+ continue; //evaluate again starting from the new position
+ }
+
+ //make sure this is not part of an user defined variable
+ $new_pos = $this->_skipUserDefinedVariable($query, $position);
+ if ($new_pos != $position) {
+ $position = $new_pos;
+ continue; //evaluate again starting from the new position
+ }
+
+ if ($query[$position] == $placeholder_type_guess) {
+ if (is_null($placeholder_type)) {
+ $placeholder_type = $query[$p_position];
+ $question = $colon = $placeholder_type;
+ }
+ if ($placeholder_type == ':') {
+ $regexp = '/^.{'.($position+1).'}('.$this->options['bindname_format'].').*$/s';
+ $parameter = preg_replace($regexp, '\\1', $query);
+ if ($parameter === '') {
+ $err = $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
+ 'named parameter name must match "bindname_format" option', __FUNCTION__);
+ return $err;
+ }
+ $positions[$p_position] = $parameter;
+ $query = substr_replace($query, '?', $position, strlen($parameter)+1);
+ } else {
+ $positions[$p_position] = count($positions);
+ }
+ $position = $p_position + 1;
+ } else {
+ $position = $p_position;
+ }
+ }
+
+ static $prep_statement_counter = 1;
+ $statement_name = sprintf($this->options['statement_format'], $this->phptype, $prep_statement_counter++ . sha1(microtime() + mt_rand()));
+ $statement_name = substr(strtolower($statement_name), 0, $this->options['max_identifiers_length']);
+ $query = "PREPARE $statement_name FROM ".$this->quote($query, 'text');
+ $statement = $this->_doQuery($query, true, $connection);
+ if (PEAR::isError($statement)) {
+ return $statement;
+ }
+
+ $class_name = 'MDB2_Statement_'.$this->phptype;
+ $obj = new $class_name($this, $statement_name, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);
+ $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));
+ return $obj;
+ }
+
+ // }}}
+ // {{{ replace()
+
+ /**
+ * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
+ * query, except that if there is already a row in the table with the same
+ * key field values, the old row is deleted before the new row is inserted.
+ *
+ * The REPLACE type of query does not make part of the SQL standards. Since
+ * practically only MySQL implements it natively, this type of query is
+ * emulated through this method for other DBMS using standard types of
+ * queries inside a transaction to assure the atomicity of the operation.
+ *
+ * @access public
+ *
+ * @param string $table name of the table on which the REPLACE query will
+ * be executed.
+ * @param array $fields associative array that describes the fields and the
+ * values that will be inserted or updated in the specified table. The
+ * indexes of the array are the names of all the fields of the table. The
+ * values of the array are also associative arrays that describe the
+ * values and other properties of the table fields.
+ *
+ * Here follows a list of field properties that need to be specified:
+ *
+ * value:
+ * Value to be assigned to the specified field. This value may be
+ * of specified in database independent type format as this
+ * function can perform the necessary datatype conversions.
+ *
+ * Default:
+ * this property is required unless the Null property
+ * is set to 1.
+ *
+ * type
+ * Name of the type of the field. Currently, all types Metabase
+ * are supported except for clob and blob.
+ *
+ * Default: no type conversion
+ *
+ * null
+ * Boolean property that indicates that the value for this field
+ * should be set to null.
+ *
+ * The default value for fields missing in INSERT queries may be
+ * specified the definition of a table. Often, the default value
+ * is already null, but since the REPLACE may be emulated using
+ * an UPDATE query, make sure that all fields of the table are
+ * listed in this function argument array.
+ *
+ * Default: 0
+ *
+ * key
+ * Boolean property that indicates that this field should be
+ * handled as a primary key or at least as part of the compound
+ * unique index of the table that will determine the row that will
+ * updated if it exists or inserted a new row otherwise.
+ *
+ * This function will fail if no key field is specified or if the
+ * value of a key field is set to null because fields that are
+ * part of unique index they may not be null.
+ *
+ * Default: 0
+ *
+ * @see http://dev.mysql.com/doc/refman/5.0/en/replace.html
+ * @return mixed MDB2_OK on success, a MDB2 error on failure
+ */
+ function replace($table, $fields)
+ {
+ $count = count($fields);
+ $query = $values = '';
+ $keys = $colnum = 0;
+ for (reset($fields); $colnum < $count; next($fields), $colnum++) {
+ $name = key($fields);
+ if ($colnum > 0) {
+ $query .= ',';
+ $values.= ',';
+ }
+ $query.= $this->quoteIdentifier($name, true);
+ if (isset($fields[$name]['null']) && $fields[$name]['null']) {
+ $value = 'NULL';
+ } else {
+ $type = isset($fields[$name]['type']) ? $fields[$name]['type'] : null;
+ $value = $this->quote($fields[$name]['value'], $type);
+ if (PEAR::isError($value)) {
+ return $value;
+ }
+ }
+ $values.= $value;
+ if (isset($fields[$name]['key']) && $fields[$name]['key']) {
+ if ($value === 'NULL') {
+ return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
+ 'key value '.$name.' may not be NULL', __FUNCTION__);
+ }
+ $keys++;
+ }
+ }
+ if ($keys == 0) {
+ return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
+ 'not specified which fields are keys', __FUNCTION__);
+ }
+
+ $connection = $this->getConnection();
+ if (PEAR::isError($connection)) {
+ return $connection;
+ }
+
+ $table = $this->quoteIdentifier($table, true);
+ $query = "REPLACE INTO $table ($query) VALUES ($values)";
+ $result = $this->_doQuery($query, true, $connection);
+ if (PEAR::isError($result)) {
+ return $result;
+ }
+ return $this->_affectedRows($connection, $result);
+ }
+
+ // }}}
+ // {{{ nextID()
+
+ /**
+ * Returns the next free id of a sequence
+ *
+ * @param string $seq_name name of the sequence
+ * @param boolean $ondemand when true the sequence is
+ * automatic created, if it
+ * not exists
+ *
+ * @return mixed MDB2 Error Object or id
+ * @access public
+ */
+ function nextID($seq_name, $ondemand = true)
+ {
+ $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
+ $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true);
+ $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (NULL)";
+ $this->pushErrorHandling(PEAR_ERROR_RETURN);
+ $this->expectError(MDB2_ERROR_NOSUCHTABLE);
+ $result = $this->_doQuery($query, true);
+ $this->popExpect();
+ $this->popErrorHandling();
+ if (PEAR::isError($result)) {
+ if ($ondemand && $result->getCode() == MDB2_ERROR_NOSUCHTABLE) {
+ $this->loadModule('Manager', null, true);
+ $result = $this->manager->createSequence($seq_name);
+ if (PEAR::isError($result)) {
+ return $this->raiseError($result, null, null,
+ 'on demand sequence '.$seq_name.' could not be created', __FUNCTION__);
+ } else {
+ return $this->nextID($seq_name, false);
+ }
+ }
+ return $result;
+ }
+ $value = $this->lastInsertID();
+ if (is_numeric($value)) {
+ $query = "DELETE FROM $sequence_name WHERE $seqcol_name < $value";
+ $result = $this->_doQuery($query, true);
+ if (PEAR::isError($result)) {
+ $this->warnings[] = 'nextID: could not delete previous sequence table values from '.$seq_name;
+ }
+ }
+ return $value;
+ }
+
+ // }}}
+ // {{{ lastInsertID()
+
+ /**
+ * Returns the autoincrement ID if supported or $id or fetches the current
+ * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
+ *
+ * @param string $table name of the table into which a new row was inserted
+ * @param string $field name of the field into which a new row was inserted
+ * @return mixed MDB2 Error Object or id
+ * @access public
+ */
+ function lastInsertID($table = null, $field = null)
+ {
+ // not using mysql_insert_id() due to http://pear.php.net/bugs/bug.php?id=8051
+ // not casting to integer to handle BIGINT http://pear.php.net/bugs/bug.php?id=17650
+ return $this->queryOne('SELECT LAST_INSERT_ID()');
+ }
+
+ // }}}
+ // {{{ currID()
+
+ /**
+ * Returns the current id of a sequence
+ *
+ * @param string $seq_name name of the sequence
+ * @return mixed MDB2 Error Object or id
+ * @access public
+ */
+ function currID($seq_name)
+ {
+ $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
+ $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true);
+ $query = "SELECT MAX($seqcol_name) FROM $sequence_name";
+ return $this->queryOne($query, 'integer');
+ }
+}
+
+/**
+ * MDB2 MySQL result driver
+ *
+ * @package MDB2
+ * @category Database
+ * @author Lukas Smith
+ */
+class MDB2_Result_mysql extends MDB2_Result_Common
+{
+ // }}}
+ // {{{ fetchRow()
+
+ /**
+ * Fetch a row and insert the data into an existing array.
+ *
+ * @param int $fetchmode how the array data should be indexed
+ * @param int $rownum number of the row where the data can be found
+ * @return int data array on success, a MDB2 error on failure
+ * @access public
+ */
+ function fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
+ {
+ if (!is_null($rownum)) {
+ $seek = $this->seek($rownum);
+ if (PEAR::isError($seek)) {
+ return $seek;
+ }
+ }
+ if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
+ $fetchmode = $this->db->fetchmode;
+ }
+ if ($fetchmode & MDB2_FETCHMODE_ASSOC) {
+ $row = @mysql_fetch_assoc($this->result);
+ if (is_array($row)
+ && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
+ ) {
+ $row = array_change_key_case($row, $this->db->options['field_case']);
+ }
+ } else {
+ $row = @mysql_fetch_row($this->result);
+ }
+
+ if (!$row) {
+ if ($this->result === false) {
+ $err = $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
+ 'resultset has already been freed', __FUNCTION__);
+ return $err;
+ }
+ return null;
+ }
+ $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL;
+ $rtrim = false;
+ if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) {
+ if (empty($this->types)) {
+ $mode += MDB2_PORTABILITY_RTRIM;
+ } else {
+ $rtrim = true;
+ }
+ }
+ if ($mode) {
+ $this->db->_fixResultArrayValues($row, $mode);
+ }
+ if (!empty($this->types)) {
+ $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim);
+ }
+ if (!empty($this->values)) {
+ $this->_assignBindColumns($row);
+ }
+ if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
+ $object_class = $this->db->options['fetch_class'];
+ if ($object_class == 'stdClass') {
+ $row = (object) $row;
+ } else {
+ $rowObj = new $object_class($row);
+ $row = $rowObj;
+ }
+ }
+ ++$this->rownum;
+ return $row;
+ }
+
+ // }}}
+ // {{{ _getColumnNames()
+
+ /**
+ * Retrieve the names of columns returned by the DBMS in a query result.
+ *
+ * @return mixed Array variable that holds the names of columns as keys
+ * or an MDB2 error on failure.
+ * Some DBMS may not return any columns when the result set
+ * does not contain any rows.
+ * @access private
+ */
+ function _getColumnNames()
+ {
+ $columns = array();
+ $numcols = $this->numCols();
+ if (PEAR::isError($numcols)) {
+ return $numcols;
+ }
+ for ($column = 0; $column < $numcols; $column++) {
+ $column_name = @mysql_field_name($this->result, $column);
+ $columns[$column_name] = $column;
+ }
+ if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
+ $columns = array_change_key_case($columns, $this->db->options['field_case']);
+ }
+ return $columns;
+ }
+
+ // }}}
+ // {{{ numCols()
+
+ /**
+ * Count the number of columns returned by the DBMS in a query result.
+ *
+ * @return mixed integer value with the number of columns, a MDB2 error
+ * on failure
+ * @access public
+ */
+ function numCols()
+ {
+ $cols = @mysql_num_fields($this->result);
+ if (is_null($cols)) {
+ if ($this->result === false) {
+ return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
+ 'resultset has already been freed', __FUNCTION__);
+ } elseif (is_null($this->result)) {
+ return count($this->types);
+ }
+ return $this->db->raiseError(null, null, null,
+ 'Could not get column count', __FUNCTION__);
+ }
+ return $cols;
+ }
+
+ // }}}
+ // {{{ free()
+
+ /**
+ * Free the internal resources associated with result.
+ *
+ * @return boolean true on success, false if result is invalid
+ * @access public
+ */
+ function free()
+ {
+ if (is_resource($this->result) && $this->db->connection) {
+ $free = @mysql_free_result($this->result);
+ if ($free === false) {
+ return $this->db->raiseError(null, null, null,
+ 'Could not free result', __FUNCTION__);
+ }
+ }
+ $this->result = false;
+ return MDB2_OK;
+ }
+}
+
+/**
+ * MDB2 MySQL buffered result driver
+ *
+ * @package MDB2
+ * @category Database
+ * @author Lukas Smith
+ */
+class MDB2_BufferedResult_mysql extends MDB2_Result_mysql
+{
+ // }}}
+ // {{{ seek()
+
+ /**
+ * Seek to a specific row in a result set
+ *
+ * @param int $rownum number of the row where the data can be found
+ * @return mixed MDB2_OK on success, a MDB2 error on failure
+ * @access public
+ */
+ function seek($rownum = 0)
+ {
+ if ($this->rownum != ($rownum - 1) && !@mysql_data_seek($this->result, $rownum)) {
+ if ($this->result === false) {
+ return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
+ 'resultset has already been freed', __FUNCTION__);
+ } elseif (is_null($this->result)) {
+ return MDB2_OK;
+ }
+ return $this->db->raiseError(MDB2_ERROR_INVALID, null, null,
+ 'tried to seek to an invalid row number ('.$rownum.')', __FUNCTION__);
+ }
+ $this->rownum = $rownum - 1;
+ return MDB2_OK;
+ }
+
+ // }}}
+ // {{{ valid()
+
+ /**
+ * Check if the end of the result set has been reached
+ *
+ * @return mixed true or false on sucess, a MDB2 error on failure
+ * @access public
+ */
+ function valid()
+ {
+ $numrows = $this->numRows();
+ if (PEAR::isError($numrows)) {
+ return $numrows;
+ }
+ return $this->rownum < ($numrows - 1);
+ }
+
+ // }}}
+ // {{{ numRows()
+
+ /**
+ * Returns the number of rows in a result object
+ *
+ * @return mixed MDB2 Error Object or the number of rows
+ * @access public
+ */
+ function numRows()
+ {
+ $rows = @mysql_num_rows($this->result);
+ if (false === $rows) {
+ if (false === $this->result) {
+ return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
+ 'resultset has already been freed', __FUNCTION__);
+ } elseif (is_null($this->result)) {
+ return 0;
+ }
+ return $this->db->raiseError(null, null, null,
+ 'Could not get row count', __FUNCTION__);
+ }
+ return $rows;
+ }
+
+ // }}}
+}
+
+/**
+ * MDB2 MySQL statement driver
+ *
+ * @package MDB2
+ * @category Database
+ * @author Lukas Smith
+ */
+class MDB2_Statement_mysql extends MDB2_Statement_Common
+{
+ // {{{ _execute()
+
+ /**
+ * Execute a prepared query statement helper method.
+ *
+ * @param mixed $result_class string which specifies which result class to use
+ * @param mixed $result_wrap_class string which specifies which class to wrap results in
+ *
+ * @return mixed MDB2_Result or integer (affected rows) on success,
+ * a MDB2 error on failure
+ * @access private
+ */
+ function _execute($result_class = true, $result_wrap_class = false)
+ {
+ if (is_null($this->statement)) {
+ $result = parent::_execute($result_class, $result_wrap_class);
+ return $result;
+ }
+ $this->db->last_query = $this->query;
+ $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'pre', 'parameters' => $this->values));
+ if ($this->db->getOption('disable_query')) {
+ $result = $this->is_manip ? 0 : null;
+ return $result;
+ }
+
+ $connection = $this->db->getConnection();
+ if (PEAR::isError($connection)) {
+ return $connection;
+ }
+
+ $query = 'EXECUTE '.$this->statement;
+ if (!empty($this->positions)) {
+ $parameters = array();
+ foreach ($this->positions as $parameter) {
+ if (!array_key_exists($parameter, $this->values)) {
+ return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
+ 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
+ }
+ $close = false;
+ $value = $this->values[$parameter];
+ $type = array_key_exists($parameter, $this->types) ? $this->types[$parameter] : null;
+ if (is_resource($value) || $type == 'clob' || $type == 'blob' && $this->db->options['lob_allow_url_include']) {
+ if (!is_resource($value) && preg_match('/^(\w+:\/\/)(.*)$/', $value, $match)) {
+ if ($match[1] == 'file://') {
+ $value = $match[2];
+ }
+ $value = @fopen($value, 'r');
+ $close = true;
+ }
+ if (is_resource($value)) {
+ $data = '';
+ while (!@feof($value)) {
+ $data.= @fread($value, $this->db->options['lob_buffer_length']);
+ }
+ if ($close) {
+ @fclose($value);
+ }
+ $value = $data;
+ }
+ }
+ $quoted = $this->db->quote($value, $type);
+ if (PEAR::isError($quoted)) {
+ return $quoted;
+ }
+ $param_query = 'SET @'.$parameter.' = '.$quoted;
+ $result = $this->db->_doQuery($param_query, true, $connection);
+ if (PEAR::isError($result)) {
+ return $result;
+ }
+ }
+ $query.= ' USING @'.implode(', @', array_values($this->positions));
+ }
+
+ $result = $this->db->_doQuery($query, $this->is_manip, $connection);
+ if (PEAR::isError($result)) {
+ return $result;
+ }
+
+ if ($this->is_manip) {
+ $affected_rows = $this->db->_affectedRows($connection, $result);
+ return $affected_rows;
+ }
+
+ $result = $this->db->_wrapResult($result, $this->result_types,
+ $result_class, $result_wrap_class, $this->limit, $this->offset);
+ $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'post', 'result' => $result));
+ return $result;
+ }
+
+ // }}}
+ // {{{ free()
+
+ /**
+ * Release resources allocated for the specified prepared query.
+ *
+ * @return mixed MDB2_OK on success, a MDB2 error on failure
+ * @access public
+ */
+ function free()
+ {
+ if (is_null($this->positions)) {
+ return $this->db->raiseError(MDB2_ERROR, null, null,
+ 'Prepared statement has already been freed', __FUNCTION__);
+ }
+ $result = MDB2_OK;
+
+ if (!is_null($this->statement)) {
+ $connection = $this->db->getConnection();
+ if (PEAR::isError($connection)) {
+ return $connection;
+ }
+ $query = 'DEALLOCATE PREPARE '.$this->statement;
+ $result = $this->db->_doQuery($query, true, $connection);
+ }
+
+ parent::free();
+ return $result;
+ }
+}
+?>
diff --git a/3rdparty/MDB2/Driver/pgsql.php b/3rdparty/MDB2/Driver/pgsql.php
index 13fea69068..15bd280f40 100644
--- a/3rdparty/MDB2/Driver/pgsql.php
+++ b/3rdparty/MDB2/Driver/pgsql.php
@@ -1,1519 +1,1548 @@
- |
-// +----------------------------------------------------------------------+
-//
-// $Id: pgsql.php,v 1.203 2008/11/29 14:04:46 afz Exp $
-
-/**
- * MDB2 PostGreSQL driver
- *
- * @package MDB2
- * @category Database
- * @author Paul Cooper
- */
-class MDB2_Driver_pgsql extends MDB2_Driver_Common
-{
- // {{{ properties
- var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => "'", 'escape_pattern' => '\\');
-
- var $identifier_quoting = array('start' => '"', 'end' => '"', 'escape' => '"');
- // }}}
- // {{{ constructor
-
- /**
- * Constructor
- */
- function __construct()
- {
- parent::__construct();
-
- $this->phptype = 'pgsql';
- $this->dbsyntax = 'pgsql';
-
- $this->supported['sequences'] = true;
- $this->supported['indexes'] = true;
- $this->supported['affected_rows'] = true;
- $this->supported['summary_functions'] = true;
- $this->supported['order_by_text'] = true;
- $this->supported['transactions'] = true;
- $this->supported['savepoints'] = true;
- $this->supported['current_id'] = true;
- $this->supported['limit_queries'] = true;
- $this->supported['LOBs'] = true;
- $this->supported['replace'] = 'emulated';
- $this->supported['sub_selects'] = true;
- $this->supported['triggers'] = true;
- $this->supported['auto_increment'] = 'emulated';
- $this->supported['primary_key'] = true;
- $this->supported['result_introspection'] = true;
- $this->supported['prepared_statements'] = true;
- $this->supported['identifier_quoting'] = true;
- $this->supported['pattern_escaping'] = true;
- $this->supported['new_link'] = true;
-
- $this->options['DBA_username'] = false;
- $this->options['DBA_password'] = false;
- $this->options['multi_query'] = false;
- $this->options['disable_smart_seqname'] = true;
- $this->options['max_identifiers_length'] = 63;
- }
-
- // }}}
- // {{{ errorInfo()
-
- /**
- * This method is used to collect information about an error
- *
- * @param integer $error
- * @return array
- * @access public
- */
- function errorInfo($error = null)
- {
- // Fall back to MDB2_ERROR if there was no mapping.
- $error_code = MDB2_ERROR;
-
- $native_msg = '';
- if (is_resource($error)) {
- $native_msg = @pg_result_error($error);
- } elseif ($this->connection) {
- $native_msg = @pg_last_error($this->connection);
- if (!$native_msg && @pg_connection_status($this->connection) === PGSQL_CONNECTION_BAD) {
- $native_msg = 'Database connection has been lost.';
- $error_code = MDB2_ERROR_CONNECT_FAILED;
- }
- } else {
- $native_msg = @pg_last_error();
- }
-
- static $error_regexps;
- if (empty($error_regexps)) {
- $error_regexps = array(
- '/column .* (of relation .*)?does not exist/i'
- => MDB2_ERROR_NOSUCHFIELD,
- '/(relation|sequence|table).*does not exist|class .* not found/i'
- => MDB2_ERROR_NOSUCHTABLE,
- '/database .* does not exist/'
- => MDB2_ERROR_NOT_FOUND,
- '/constraint .* does not exist/'
- => MDB2_ERROR_NOT_FOUND,
- '/index .* does not exist/'
- => MDB2_ERROR_NOT_FOUND,
- '/database .* already exists/i'
- => MDB2_ERROR_ALREADY_EXISTS,
- '/relation .* already exists/i'
- => MDB2_ERROR_ALREADY_EXISTS,
- '/(divide|division) by zero$/i'
- => MDB2_ERROR_DIVZERO,
- '/pg_atoi: error in .*: can\'t parse /i'
- => MDB2_ERROR_INVALID_NUMBER,
- '/invalid input syntax for( type)? (integer|numeric)/i'
- => MDB2_ERROR_INVALID_NUMBER,
- '/value .* is out of range for type \w*int/i'
- => MDB2_ERROR_INVALID_NUMBER,
- '/integer out of range/i'
- => MDB2_ERROR_INVALID_NUMBER,
- '/value too long for type character/i'
- => MDB2_ERROR_INVALID,
- '/attribute .* not found|relation .* does not have attribute/i'
- => MDB2_ERROR_NOSUCHFIELD,
- '/column .* specified in USING clause does not exist in (left|right) table/i'
- => MDB2_ERROR_NOSUCHFIELD,
- '/parser: parse error at or near/i'
- => MDB2_ERROR_SYNTAX,
- '/syntax error at/'
- => MDB2_ERROR_SYNTAX,
- '/column reference .* is ambiguous/i'
- => MDB2_ERROR_SYNTAX,
- '/permission denied/'
- => MDB2_ERROR_ACCESS_VIOLATION,
- '/violates not-null constraint/'
- => MDB2_ERROR_CONSTRAINT_NOT_NULL,
- '/violates [\w ]+ constraint/'
- => MDB2_ERROR_CONSTRAINT,
- '/referential integrity violation/'
- => MDB2_ERROR_CONSTRAINT,
- '/more expressions than target columns/i'
- => MDB2_ERROR_VALUE_COUNT_ON_ROW,
- );
- }
- if (is_numeric($error) && $error < 0) {
- $error_code = $error;
- } else {
- foreach ($error_regexps as $regexp => $code) {
- if (preg_match($regexp, $native_msg)) {
- $error_code = $code;
- break;
- }
- }
- }
- return array($error_code, null, $native_msg);
- }
-
- // }}}
- // {{{ escape()
-
- /**
- * Quotes a string so it can be safely used in a query. It will quote
- * the text so it can safely be used within a query.
- *
- * @param string the input string to quote
- * @param bool escape wildcards
- *
- * @return string quoted string
- *
- * @access public
- */
- function escape($text, $escape_wildcards = false)
- {
- if ($escape_wildcards) {
- $text = $this->escapePattern($text);
- }
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- if (is_resource($connection) && version_compare(PHP_VERSION, '5.2.0RC5', '>=')) {
- $text = @pg_escape_string($connection, $text);
- } else {
- $text = @pg_escape_string($text);
- }
- return $text;
- }
-
- // }}}
- // {{{ beginTransaction()
-
- /**
- * Start a transaction or set a savepoint.
- *
- * @param string name of a savepoint to set
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function beginTransaction($savepoint = null)
- {
- $this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- if (!is_null($savepoint)) {
- if (!$this->in_transaction) {
- return $this->raiseError(MDB2_ERROR_INVALID, null, null,
- 'savepoint cannot be released when changes are auto committed', __FUNCTION__);
- }
- $query = 'SAVEPOINT '.$savepoint;
- return $this->_doQuery($query, true);
- } elseif ($this->in_transaction) {
- return MDB2_OK; //nothing to do
- }
- if (!$this->destructor_registered && $this->opened_persistent) {
- $this->destructor_registered = true;
- register_shutdown_function('MDB2_closeOpenTransactions');
- }
- $result =& $this->_doQuery('BEGIN', true);
- if (PEAR::isError($result)) {
- return $result;
- }
- $this->in_transaction = true;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ commit()
-
- /**
- * Commit the database changes done during a transaction that is in
- * progress or release a savepoint. This function may only be called when
- * auto-committing is disabled, otherwise it will fail. Therefore, a new
- * transaction is implicitly started after committing the pending changes.
- *
- * @param string name of a savepoint to release
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function commit($savepoint = null)
- {
- $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- if (!$this->in_transaction) {
- return $this->raiseError(MDB2_ERROR_INVALID, null, null,
- 'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__);
- }
- if (!is_null($savepoint)) {
- $query = 'RELEASE SAVEPOINT '.$savepoint;
- return $this->_doQuery($query, true);
- }
-
- $result =& $this->_doQuery('COMMIT', true);
- if (PEAR::isError($result)) {
- return $result;
- }
- $this->in_transaction = false;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ rollback()
-
- /**
- * Cancel any database changes done during a transaction or since a specific
- * savepoint that is in progress. This function may only be called when
- * auto-committing is disabled, otherwise it will fail. Therefore, a new
- * transaction is implicitly started after canceling the pending changes.
- *
- * @param string name of a savepoint to rollback to
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function rollback($savepoint = null)
- {
- $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- if (!$this->in_transaction) {
- return $this->raiseError(MDB2_ERROR_INVALID, null, null,
- 'rollback cannot be done changes are auto committed', __FUNCTION__);
- }
- if (!is_null($savepoint)) {
- $query = 'ROLLBACK TO SAVEPOINT '.$savepoint;
- return $this->_doQuery($query, true);
- }
-
- $query = 'ROLLBACK';
- $result =& $this->_doQuery($query, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- $this->in_transaction = false;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function setTransactionIsolation()
-
- /**
- * Set the transacton isolation level.
- *
- * @param string standard isolation level
- * READ UNCOMMITTED (allows dirty reads)
- * READ COMMITTED (prevents dirty reads)
- * REPEATABLE READ (prevents nonrepeatable reads)
- * SERIALIZABLE (prevents phantom reads)
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- * @since 2.1.1
- */
- static function setTransactionIsolation($isolation, $options = array())
- {
- $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
- switch ($isolation) {
- case 'READ UNCOMMITTED':
- case 'READ COMMITTED':
- case 'REPEATABLE READ':
- case 'SERIALIZABLE':
- break;
- default:
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'isolation level is not supported: '.$isolation, __FUNCTION__);
- }
-
- $query = "SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL $isolation";
- return $this->_doQuery($query, true);
- }
-
- // }}}
- // {{{ _doConnect()
-
- /**
- * Do the grunt work of connecting to the database
- *
- * @return mixed connection resource on success, MDB2 Error Object on failure
- * @access protected
- */
- function _doConnect($username, $password, $database_name, $persistent = false)
- {
- if (!PEAR::loadExtension($this->phptype)) {
- return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__);
- }
-
- if ($database_name == '') {
- $database_name = 'template1';
- }
-
- $protocol = $this->dsn['protocol'] ? $this->dsn['protocol'] : 'tcp';
-
- $params = array('');
- if ($protocol == 'tcp') {
- if ($this->dsn['hostspec']) {
- $params[0].= 'host=' . $this->dsn['hostspec'];
- }
- if ($this->dsn['port']) {
- $params[0].= ' port=' . $this->dsn['port'];
- }
- } elseif ($protocol == 'unix') {
- // Allow for pg socket in non-standard locations.
- if ($this->dsn['socket']) {
- $params[0].= 'host=' . $this->dsn['socket'];
- }
- if ($this->dsn['port']) {
- $params[0].= ' port=' . $this->dsn['port'];
- }
- }
- if ($database_name) {
- $params[0].= ' dbname=\'' . addslashes($database_name) . '\'';
- }
- if ($username) {
- $params[0].= ' user=\'' . addslashes($username) . '\'';
- }
- if ($password) {
- $params[0].= ' password=\'' . addslashes($password) . '\'';
- }
- if (!empty($this->dsn['options'])) {
- $params[0].= ' options=' . $this->dsn['options'];
- }
- if (!empty($this->dsn['tty'])) {
- $params[0].= ' tty=' . $this->dsn['tty'];
- }
- if (!empty($this->dsn['connect_timeout'])) {
- $params[0].= ' connect_timeout=' . $this->dsn['connect_timeout'];
- }
- if (!empty($this->dsn['sslmode'])) {
- $params[0].= ' sslmode=' . $this->dsn['sslmode'];
- }
- if (!empty($this->dsn['service'])) {
- $params[0].= ' service=' . $this->dsn['service'];
- }
-
- if ($this->_isNewLinkSet()) {
- if (version_compare(phpversion(), '4.3.0', '>=')) {
- $params[] = PGSQL_CONNECT_FORCE_NEW;
- }
- }
-
- $connect_function = $persistent ? 'pg_pconnect' : 'pg_connect';
- $connection = @call_user_func_array($connect_function, $params);
- if (!$connection) {
- return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
- 'unable to establish a connection', __FUNCTION__);
- }
-
- if (empty($this->dsn['disable_iso_date'])) {
- if (!@pg_query($connection, "SET SESSION DATESTYLE = 'ISO'")) {
- return $this->raiseError(null, null, null,
- 'Unable to set date style to iso', __FUNCTION__);
- }
- }
-
- if (!empty($this->dsn['charset'])) {
- $result = $this->setCharset($this->dsn['charset'], $connection);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- return $connection;
- }
-
- // }}}
- // {{{ connect()
-
- /**
- * Connect to the database
- *
- * @return true on success, MDB2 Error Object on failure
- * @access public
- */
- function connect()
- {
- if (is_resource($this->connection)) {
- //if (count(array_diff($this->connected_dsn, $this->dsn)) == 0
- if (MDB2::areEquals($this->connected_dsn, $this->dsn)
- && $this->connected_database_name == $this->database_name
- && ($this->opened_persistent == $this->options['persistent'])
- ) {
- return MDB2_OK;
- }
- $this->disconnect(false);
- }
-
- if ($this->database_name) {
- $connection = $this->_doConnect($this->dsn['username'],
- $this->dsn['password'],
- $this->database_name,
- $this->options['persistent']);
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- $this->connection = $connection;
- $this->connected_dsn = $this->dsn;
- $this->connected_database_name = $this->database_name;
- $this->opened_persistent = $this->options['persistent'];
- $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
- }
-
- return MDB2_OK;
- }
-
- // }}}
- // {{{ setCharset()
-
- /**
- * Set the charset on the current connection
- *
- * @param string charset
- * @param resource connection handle
- *
- * @return true on success, MDB2 Error Object on failure
- */
- function setCharset($charset, $connection = null)
- {
- if (is_null($connection)) {
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- }
- if (is_array($charset)) {
- $charset = array_shift($charset);
- $this->warnings[] = 'postgresql does not support setting client collation';
- }
- $result = @pg_set_client_encoding($connection, $charset);
- if ($result == -1) {
- return $this->raiseError(null, null, null,
- 'Unable to set client charset: '.$charset, __FUNCTION__);
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ databaseExists()
-
- /**
- * check if given database name is exists?
- *
- * @param string $name name of the database that should be checked
- *
- * @return mixed true/false on success, a MDB2 error on failure
- * @access public
- */
- function databaseExists($name)
- {
- $res = $this->_doConnect($this->dsn['username'],
- $this->dsn['password'],
- $this->escape($name),
- $this->options['persistent']);
- if (!PEAR::isError($res)) {
- return true;
- }
-
- return false;
- }
-
- // }}}
- // {{{ disconnect()
-
- /**
- * Log out and disconnect from the database.
- *
- * @param boolean $force if the disconnect should be forced even if the
- * connection is opened persistently
- * @return mixed true on success, false if not connected and error
- * object on error
- * @access public
- */
- function disconnect($force = true)
- {
- if (is_resource($this->connection)) {
- if ($this->in_transaction) {
- $dsn = $this->dsn;
- $database_name = $this->database_name;
- $persistent = $this->options['persistent'];
- $this->dsn = $this->connected_dsn;
- $this->database_name = $this->connected_database_name;
- $this->options['persistent'] = $this->opened_persistent;
- $this->rollback();
- $this->dsn = $dsn;
- $this->database_name = $database_name;
- $this->options['persistent'] = $persistent;
- }
-
- if (!$this->opened_persistent || $force) {
- $ok = @pg_close($this->connection);
- if (!$ok) {
- return $this->raiseError(MDB2_ERROR_DISCONNECT_FAILED,
- null, null, null, __FUNCTION__);
- }
- }
- } else {
- return false;
- }
- return parent::disconnect($force);
- }
-
- // }}}
- // {{{ standaloneQuery()
-
- /**
- * execute a query as DBA
- *
- * @param string $query the SQL query
- * @param mixed $types array that contains the types of the columns in
- * the result set
- * @param boolean $is_manip if the query is a manipulation query
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function &standaloneQuery($query, $types = null, $is_manip = false)
- {
- $user = $this->options['DBA_username']? $this->options['DBA_username'] : $this->dsn['username'];
- $pass = $this->options['DBA_password']? $this->options['DBA_password'] : $this->dsn['password'];
- $connection = $this->_doConnect($user, $pass, $this->database_name, $this->options['persistent']);
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- $offset = $this->offset;
- $limit = $this->limit;
- $this->offset = $this->limit = 0;
- $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
-
- $result =& $this->_doQuery($query, $is_manip, $connection, $this->database_name);
- if (!PEAR::isError($result)) {
- if ($is_manip) {
- $result = $this->_affectedRows($connection, $result);
- } else {
- $result =& $this->_wrapResult($result, $types, true, false, $limit, $offset);
- }
- }
-
- @pg_close($connection);
- return $result;
- }
-
- // }}}
- // {{{ _doQuery()
-
- /**
- * Execute a query
- * @param string $query query
- * @param boolean $is_manip if the query is a manipulation query
- * @param resource $connection
- * @param string $database_name
- * @return result or error object
- * @access protected
- */
- function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null)
- {
- $this->last_query = $query;
- $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
- if ($result) {
- if (PEAR::isError($result)) {
- return $result;
- }
- $query = $result;
- }
- if ($this->options['disable_query']) {
- $result = $is_manip ? 0 : null;
- return $result;
- }
-
- if (is_null($connection)) {
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- }
-
- $function = $this->options['multi_query'] ? 'pg_send_query' : 'pg_query';
- $result = @$function($connection, $query);
- if (!$result) {
- $err =& $this->raiseError(null, null, null,
- 'Could not execute statement', __FUNCTION__);
- return $err;
- } elseif ($this->options['multi_query']) {
- if (!($result = @pg_get_result($connection))) {
- $err =& $this->raiseError(null, null, null,
- 'Could not get the first result from a multi query', __FUNCTION__);
- return $err;
- }
- }
-
- $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result));
- return $result;
- }
-
- // }}}
- // {{{ _affectedRows()
-
- /**
- * Returns the number of rows affected
- *
- * @param resource $result
- * @param resource $connection
- * @return mixed MDB2 Error Object or the number of rows affected
- * @access private
- */
- function _affectedRows($connection, $result = null)
- {
- if (is_null($connection)) {
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- }
- return @pg_affected_rows($result);
- }
-
- // }}}
- // {{{ _modifyQuery()
-
- /**
- * Changes a query string for various DBMS specific reasons
- *
- * @param string $query query to modify
- * @param boolean $is_manip if it is a DML query
- * @param integer $limit limit the number of rows
- * @param integer $offset start reading from given offset
- * @return string modified query
- * @access protected
- */
- function _modifyQuery($query, $is_manip, $limit, $offset)
- {
- if ($limit > 0
- && !preg_match('/LIMIT\s*\d(?:\s*(?:,|OFFSET)\s*\d+)?(?:[^\)]*)?$/i', $query)
- ) {
- $query = rtrim($query);
- if (substr($query, -1) == ';') {
- $query = substr($query, 0, -1);
- }
- if ($is_manip) {
- $query = $this->_modifyManipQuery($query, $limit);
- } else {
- $query.= " LIMIT $limit OFFSET $offset";
- }
- }
- return $query;
- }
-
- // }}}
- // {{{ _modifyManipQuery()
-
- /**
- * Changes a manip query string for various DBMS specific reasons
- *
- * @param string $query query to modify
- * @param integer $limit limit the number of rows
- * @return string modified query
- * @access protected
- */
- function _modifyManipQuery($query, $limit)
- {
- $pos = strpos(strtolower($query), 'where');
- $where = $pos ? substr($query, $pos) : '';
-
- $manip_clause = '(\bDELETE\b\s+(?:\*\s+)?\bFROM\b|\bUPDATE\b)';
- $from_clause = '([\w\.]+)';
- $where_clause = '(?:(.*)\bWHERE\b\s+(.*))|(.*)';
- $pattern = '/^'. $manip_clause . '\s+' . $from_clause .'(?:\s)*(?:'. $where_clause .')?$/i';
- $matches = preg_match($pattern, $query, $match);
- if ($matches) {
- $manip = $match[1];
- $from = $match[2];
- $what = (count($matches) == 6) ? $match[5] : $match[3];
- return $manip.' '.$from.' '.$what.' WHERE ctid=(SELECT ctid FROM '.$from.' '.$where.' LIMIT '.$limit.')';
- }
- //return error?
- return $query;
- }
-
- // }}}
- // {{{ getServerVersion()
-
- /**
- * return version information about the server
- *
- * @param bool $native determines if the raw version string should be returned
- * @return mixed array/string with version information or MDB2 error object
- * @access public
- */
- function getServerVersion($native = false)
- {
- $query = 'SHOW SERVER_VERSION';
- if ($this->connected_server_info) {
- $server_info = $this->connected_server_info;
- } else {
- $server_info = $this->queryOne($query, 'text');
- if (PEAR::isError($server_info)) {
- return $server_info;
- }
- }
- // cache server_info
- $this->connected_server_info = $server_info;
- if (!$native && !PEAR::isError($server_info)) {
- $tmp = explode('.', $server_info, 3);
- if (empty($tmp[2])
- && isset($tmp[1])
- && preg_match('/(\d+)(.*)/', $tmp[1], $tmp2)
- ) {
- $server_info = array(
- 'major' => $tmp[0],
- 'minor' => $tmp2[1],
- 'patch' => null,
- 'extra' => $tmp2[2],
- 'native' => $server_info,
- );
- } else {
- $server_info = array(
- 'major' => isset($tmp[0]) ? $tmp[0] : null,
- 'minor' => isset($tmp[1]) ? $tmp[1] : null,
- 'patch' => isset($tmp[2]) ? $tmp[2] : null,
- 'extra' => null,
- 'native' => $server_info,
- );
- }
- }
- return $server_info;
- }
-
- // }}}
- // {{{ prepare()
-
- /**
- * Prepares a query for multiple execution with execute().
- * With some database backends, this is emulated.
- * prepare() requires a generic query as string like
- * 'INSERT INTO numbers VALUES(?,?)' or
- * 'INSERT INTO numbers VALUES(:foo,:bar)'.
- * The ? and :name and are placeholders which can be set using
- * bindParam() and the query can be sent off using the execute() method.
- * The allowed format for :name can be set with the 'bindname_format' option.
- *
- * @param string $query the query to prepare
- * @param mixed $types array that contains the types of the placeholders
- * @param mixed $result_types array that contains the types of the columns in
- * the result set or MDB2_PREPARE_RESULT, if set to
- * MDB2_PREPARE_MANIP the query is handled as a manipulation query
- * @param mixed $lobs key (field) value (parameter) pair for all lob placeholders
- * @return mixed resource handle for the prepared query on success, a MDB2
- * error on failure
- * @access public
- * @see bindParam, execute
- */
- function &prepare($query, $types = null, $result_types = null, $lobs = array())
- {
- if ($this->options['emulate_prepared']) {
- $obj =& parent::prepare($query, $types, $result_types, $lobs);
- return $obj;
- }
- $is_manip = ($result_types === MDB2_PREPARE_MANIP);
- $offset = $this->offset;
- $limit = $this->limit;
- $this->offset = $this->limit = 0;
- $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre'));
- if ($result) {
- if (PEAR::isError($result)) {
- return $result;
- }
- $query = $result;
- }
- $pgtypes = function_exists('pg_prepare') ? false : array();
- if ($pgtypes !== false && !empty($types)) {
- $this->loadModule('Datatype', null, true);
- }
- $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
- $placeholder_type_guess = $placeholder_type = null;
- $question = '?';
- $colon = ':';
- $positions = array();
- $position = $parameter = 0;
- while ($position < strlen($query)) {
- $q_position = strpos($query, $question, $position);
- $c_position = strpos($query, $colon, $position);
- //skip "::type" cast ("select id::varchar(20) from sometable where name=?")
- $doublecolon_position = strpos($query, '::', $position);
- if ($doublecolon_position !== false && $doublecolon_position == $c_position) {
- $c_position = strpos($query, $colon, $position+2);
- }
- if ($q_position && $c_position) {
- $p_position = min($q_position, $c_position);
- } elseif ($q_position) {
- $p_position = $q_position;
- } elseif ($c_position) {
- $p_position = $c_position;
- } else {
- break;
- }
- if (is_null($placeholder_type)) {
- $placeholder_type_guess = $query[$p_position];
- }
-
- $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position);
- if (PEAR::isError($new_pos)) {
- return $new_pos;
- }
- if ($new_pos != $position) {
- $position = $new_pos;
- continue; //evaluate again starting from the new position
- }
-
- if ($query[$position] == $placeholder_type_guess) {
- if (is_null($placeholder_type)) {
- $placeholder_type = $query[$p_position];
- $question = $colon = $placeholder_type;
- if (!empty($types) && is_array($types)) {
- if ($placeholder_type == ':') {
- } else {
- $types = array_values($types);
- }
- }
- }
- if ($placeholder_type_guess == '?') {
- $length = 1;
- $name = $parameter;
- } else {
- $regexp = '/^.{'.($position+1).'}('.$this->options['bindname_format'].').*$/s';
- $param = preg_replace($regexp, '\\1', $query);
- if ($param === '') {
- $err =& $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
- 'named parameter name must match "bindname_format" option', __FUNCTION__);
- return $err;
- }
- $length = strlen($param) + 1;
- $name = $param;
- }
- if ($pgtypes !== false) {
- if (is_array($types) && array_key_exists($name, $types)) {
- $pgtypes[] = $this->datatype->mapPrepareDatatype($types[$name]);
- } elseif (is_array($types) && array_key_exists($parameter, $types)) {
- $pgtypes[] = $this->datatype->mapPrepareDatatype($types[$parameter]);
- } else {
- $pgtypes[] = 'text';
- }
- }
- if (($key_parameter = array_search($name, $positions))) {
- $next_parameter = 1;
- foreach ($positions as $key => $value) {
- if ($key_parameter == $key) {
- break;
- }
- ++$next_parameter;
- }
- } else {
- ++$parameter;
- $next_parameter = $parameter;
- $positions[] = $name;
- }
- $query = substr_replace($query, '$'.$parameter, $position, $length);
- $position = $p_position + strlen($parameter);
- } else {
- $position = $p_position;
- }
- }
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- static $prep_statement_counter = 1;
- $statement_name = sprintf($this->options['statement_format'], $this->phptype, $prep_statement_counter++ . sha1(microtime() + mt_rand()));
- $statement_name = substr(strtolower($statement_name), 0, $this->options['max_identifiers_length']);
- if ($pgtypes === false) {
- $result = @pg_prepare($connection, $statement_name, $query);
- if (!$result) {
- $err =& $this->raiseError(null, null, null,
- 'Unable to create prepared statement handle', __FUNCTION__);
- return $err;
- }
- } else {
- $types_string = '';
- if ($pgtypes) {
- $types_string = ' ('.implode(', ', $pgtypes).') ';
- }
- $query = 'PREPARE '.$statement_name.$types_string.' AS '.$query;
- $statement =& $this->_doQuery($query, true, $connection);
- if (PEAR::isError($statement)) {
- return $statement;
- }
- }
-
- $class_name = 'MDB2_Statement_'.$this->phptype;
- $obj = new $class_name($this, $statement_name, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);
- $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));
- return $obj;
- }
-
- // }}}
- // {{{ function getSequenceName($sqn)
-
- /**
- * adds sequence name formatting to a sequence name
- *
- * @param string name of the sequence
- *
- * @return string formatted sequence name
- *
- * @access public
- */
- function getSequenceName($sqn)
- {
- if (false === $this->options['disable_smart_seqname']) {
- if (strpos($sqn, '_') !== false) {
- list($table, $field) = explode('_', $sqn, 2);
- }
- $schema_list = $this->queryOne("SELECT array_to_string(current_schemas(false), ',')");
- if (PEAR::isError($schema_list) || empty($schema_list) || count($schema_list) < 2) {
- $order_by = ' a.attnum';
- $schema_clause = ' AND n.nspname=current_schema()';
- } else {
- $schemas = explode(',', $schema_list);
- $schema_clause = ' AND n.nspname IN ('.$schema_list.')';
- $counter = 1;
- $order_by = ' CASE ';
- foreach ($schemas as $schema) {
- $order_by .= ' WHEN n.nspname='.$schema.' THEN '.$counter++;
- }
- $order_by .= ' ELSE '.$counter.' END, a.attnum';
- }
-
- $query = "SELECT substring((SELECT substring(pg_get_expr(d.adbin, d.adrelid) for 128)
- FROM pg_attrdef d
- WHERE d.adrelid = a.attrelid
- AND d.adnum = a.attnum
- AND a.atthasdef
- ) FROM 'nextval[^'']*''([^'']*)')
- FROM pg_attribute a
- LEFT JOIN pg_class c ON c.oid = a.attrelid
- LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef
- LEFT JOIN pg_namespace n ON c.relnamespace = n.oid
- WHERE (c.relname = ".$this->quote($sqn, 'text');
- if (!empty($field)) {
- $query .= " OR (c.relname = ".$this->quote($table, 'text')." AND a.attname = ".$this->quote($field, 'text').")";
- }
- $query .= " )"
- .$schema_clause."
- AND NOT a.attisdropped
- AND a.attnum > 0
- AND pg_get_expr(d.adbin, d.adrelid) LIKE 'nextval%'
- ORDER BY ".$order_by;
- $seqname = $this->queryOne($query);
- if (!PEAR::isError($seqname) && !empty($seqname) && is_string($seqname)) {
- return $seqname;
- }
- }
-
- return parent::getSequenceName($sqn);
- }
-
- // }}}
- // {{{ nextID()
-
- /**
- * Returns the next free id of a sequence
- *
- * @param string $seq_name name of the sequence
- * @param boolean $ondemand when true the sequence is
- * automatic created, if it
- * not exists
- * @return mixed MDB2 Error Object or id
- * @access public
- */
- function nextID($seq_name, $ondemand = true)
- {
- $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
- $query = "SELECT NEXTVAL('$sequence_name')";
- $this->pushErrorHandling(PEAR_ERROR_RETURN);
- $this->expectError(MDB2_ERROR_NOSUCHTABLE);
- $result = $this->queryOne($query, 'integer');
- $this->popExpect();
- $this->popErrorHandling();
- if (PEAR::isError($result)) {
- if ($ondemand && $result->getCode() == MDB2_ERROR_NOSUCHTABLE) {
- $this->loadModule('Manager', null, true);
- $result = $this->manager->createSequence($seq_name);
- if (PEAR::isError($result)) {
- return $this->raiseError($result, null, null,
- 'on demand sequence could not be created', __FUNCTION__);
- }
- return $this->nextId($seq_name, false);
- }
- }
- return $result;
- }
-
- // }}}
- // {{{ lastInsertID()
-
- /**
- * Returns the autoincrement ID if supported or $id or fetches the current
- * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
- *
- * @param string $table name of the table into which a new row was inserted
- * @param string $field name of the field into which a new row was inserted
- * @return mixed MDB2 Error Object or id
- * @access public
- */
- function lastInsertID($table = null, $field = null)
- {
- if (empty($table) && empty($field)) {
- return $this->queryOne('SELECT lastval()', 'integer');
- }
- $seq = $table.(empty($field) ? '' : '_'.$field);
- $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq), true);
- return $this->queryOne("SELECT currval('$sequence_name')", 'integer');
- }
-
- // }}}
- // {{{ currID()
-
- /**
- * Returns the current id of a sequence
- *
- * @param string $seq_name name of the sequence
- * @return mixed MDB2 Error Object or id
- * @access public
- */
- function currID($seq_name)
- {
- $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
- return $this->queryOne("SELECT last_value FROM $sequence_name", 'integer');
- }
-}
-
-/**
- * MDB2 PostGreSQL result driver
- *
- * @package MDB2
- * @category Database
- * @author Paul Cooper
- */
-class MDB2_Result_pgsql extends MDB2_Result_Common
-{
- // }}}
- // {{{ fetchRow()
-
- /**
- * Fetch a row and insert the data into an existing array.
- *
- * @param int $fetchmode how the array data should be indexed
- * @param int $rownum number of the row where the data can be found
- * @return int data array on success, a MDB2 error on failure
- * @access public
- */
- function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
- {
- if (!is_null($rownum)) {
- $seek = $this->seek($rownum);
- if (PEAR::isError($seek)) {
- return $seek;
- }
- }
- if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
- $fetchmode = $this->db->fetchmode;
- }
- if ($fetchmode & MDB2_FETCHMODE_ASSOC) {
- $row = @pg_fetch_array($this->result, null, PGSQL_ASSOC);
- if (is_array($row)
- && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
- ) {
- $row = array_change_key_case($row, $this->db->options['field_case']);
- }
- } else {
- $row = @pg_fetch_row($this->result);
- }
- if (!$row) {
- if ($this->result === false) {
- $err =& $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- return $err;
- }
- $null = null;
- return $null;
- }
- $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL;
- $rtrim = false;
- if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) {
- if (empty($this->types)) {
- $mode += MDB2_PORTABILITY_RTRIM;
- } else {
- $rtrim = true;
- }
- }
- if ($mode) {
- $this->db->_fixResultArrayValues($row, $mode);
- }
- if (!empty($this->types)) {
- $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim);
- }
- if (!empty($this->values)) {
- $this->_assignBindColumns($row);
- }
- if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
- $object_class = $this->db->options['fetch_class'];
- if ($object_class == 'stdClass') {
- $row = (object) $row;
- } else {
- $row = new $object_class($row);
- }
- }
- ++$this->rownum;
- return $row;
- }
-
- // }}}
- // {{{ _getColumnNames()
-
- /**
- * Retrieve the names of columns returned by the DBMS in a query result.
- *
- * @return mixed Array variable that holds the names of columns as keys
- * or an MDB2 error on failure.
- * Some DBMS may not return any columns when the result set
- * does not contain any rows.
- * @access private
- */
- function _getColumnNames()
- {
- $columns = array();
- $numcols = $this->numCols();
- if (PEAR::isError($numcols)) {
- return $numcols;
- }
- for ($column = 0; $column < $numcols; $column++) {
- $column_name = @pg_field_name($this->result, $column);
- $columns[$column_name] = $column;
- }
- if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $columns = array_change_key_case($columns, $this->db->options['field_case']);
- }
- return $columns;
- }
-
- // }}}
- // {{{ numCols()
-
- /**
- * Count the number of columns returned by the DBMS in a query result.
- *
- * @access public
- * @return mixed integer value with the number of columns, a MDB2 error
- * on failure
- */
- function numCols()
- {
- $cols = @pg_num_fields($this->result);
- if (is_null($cols)) {
- if ($this->result === false) {
- return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- } elseif (is_null($this->result)) {
- return count($this->types);
- }
- return $this->db->raiseError(null, null, null,
- 'Could not get column count', __FUNCTION__);
- }
- return $cols;
- }
-
- // }}}
- // {{{ nextResult()
-
- /**
- * Move the internal result pointer to the next available result
- *
- * @return true on success, false if there is no more result set or an error object on failure
- * @access public
- */
- function nextResult()
- {
- $connection = $this->db->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- if (!($this->result = @pg_get_result($connection))) {
- return false;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ free()
-
- /**
- * Free the internal resources associated with result.
- *
- * @return boolean true on success, false if result is invalid
- * @access public
- */
- function free()
- {
- if (is_resource($this->result) && $this->db->connection) {
- $free = @pg_free_result($this->result);
- if ($free === false) {
- return $this->db->raiseError(null, null, null,
- 'Could not free result', __FUNCTION__);
- }
- }
- $this->result = false;
- return MDB2_OK;
- }
-}
-
-/**
- * MDB2 PostGreSQL buffered result driver
- *
- * @package MDB2
- * @category Database
- * @author Paul Cooper
- */
-class MDB2_BufferedResult_pgsql extends MDB2_Result_pgsql
-{
- // {{{ seek()
-
- /**
- * Seek to a specific row in a result set
- *
- * @param int $rownum number of the row where the data can be found
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function seek($rownum = 0)
- {
- if ($this->rownum != ($rownum - 1) && !@pg_result_seek($this->result, $rownum)) {
- if ($this->result === false) {
- return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- } elseif (is_null($this->result)) {
- return MDB2_OK;
- }
- return $this->db->raiseError(MDB2_ERROR_INVALID, null, null,
- 'tried to seek to an invalid row number ('.$rownum.')', __FUNCTION__);
- }
- $this->rownum = $rownum - 1;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ valid()
-
- /**
- * Check if the end of the result set has been reached
- *
- * @return mixed true or false on sucess, a MDB2 error on failure
- * @access public
- */
- function valid()
- {
- $numrows = $this->numRows();
- if (PEAR::isError($numrows)) {
- return $numrows;
- }
- return $this->rownum < ($numrows - 1);
- }
-
- // }}}
- // {{{ numRows()
-
- /**
- * Returns the number of rows in a result object
- *
- * @return mixed MDB2 Error Object or the number of rows
- * @access public
- */
- function numRows()
- {
- $rows = @pg_num_rows($this->result);
- if (is_null($rows)) {
- if ($this->result === false) {
- return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- } elseif (is_null($this->result)) {
- return 0;
- }
- return $this->db->raiseError(null, null, null,
- 'Could not get row count', __FUNCTION__);
- }
- return $rows;
- }
-}
-
-/**
- * MDB2 PostGreSQL statement driver
- *
- * @package MDB2
- * @category Database
- * @author Paul Cooper
- */
-class MDB2_Statement_pgsql extends MDB2_Statement_Common
-{
- // {{{ _execute()
-
- /**
- * Execute a prepared query statement helper method.
- *
- * @param mixed $result_class string which specifies which result class to use
- * @param mixed $result_wrap_class string which specifies which class to wrap results in
- *
- * @return mixed MDB2_Result or integer (affected rows) on success,
- * a MDB2 error on failure
- * @access private
- */
- function &_execute($result_class = true, $result_wrap_class = false)
- {
- if (is_null($this->statement)) {
- $result =& parent::_execute($result_class, $result_wrap_class);
- return $result;
- }
- $this->db->last_query = $this->query;
- $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'pre', 'parameters' => $this->values));
- if ($this->db->getOption('disable_query')) {
- $result = $this->is_manip ? 0 : null;
- return $result;
- }
-
- $connection = $this->db->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- $query = false;
- $parameters = array();
- // todo: disabled until pg_execute() bytea issues are cleared up
- if (true || !function_exists('pg_execute')) {
- $query = 'EXECUTE '.$this->statement;
- }
- if (!empty($this->positions)) {
- foreach ($this->positions as $parameter) {
- if (!array_key_exists($parameter, $this->values)) {
- return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
- }
- $value = $this->values[$parameter];
- $type = array_key_exists($parameter, $this->types) ? $this->types[$parameter] : null;
- if (is_resource($value) || $type == 'clob' || $type == 'blob' || $this->db->options['lob_allow_url_include']) {
- if (!is_resource($value) && preg_match('/^(\w+:\/\/)(.*)$/', $value, $match)) {
- if ($match[1] == 'file://') {
- $value = $match[2];
- }
- $value = @fopen($value, 'r');
- $close = true;
- }
- if (is_resource($value)) {
- $data = '';
- while (!@feof($value)) {
- $data.= @fread($value, $this->db->options['lob_buffer_length']);
- }
- if ($close) {
- @fclose($value);
- }
- $value = $data;
- }
- }
- $quoted = $this->db->quote($value, $type, $query);
- if (PEAR::isError($quoted)) {
- return $quoted;
- }
- $parameters[] = $quoted;
- }
- if ($query) {
- $query.= ' ('.implode(', ', $parameters).')';
- }
- }
-
- if (!$query) {
- $result = @pg_execute($connection, $this->statement, $parameters);
- if (!$result) {
- $err =& $this->db->raiseError(null, null, null,
- 'Unable to execute statement', __FUNCTION__);
- return $err;
- }
- } else {
- $result = $this->db->_doQuery($query, $this->is_manip, $connection);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- if ($this->is_manip) {
- $affected_rows = $this->db->_affectedRows($connection, $result);
- return $affected_rows;
- }
-
- $result =& $this->db->_wrapResult($result, $this->result_types,
- $result_class, $result_wrap_class, $this->limit, $this->offset);
- $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'post', 'result' => $result));
- return $result;
- }
-
- // }}}
- // {{{ free()
-
- /**
- * Release resources allocated for the specified prepared query.
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function free()
- {
- if (is_null($this->positions)) {
- return $this->db->raiseError(MDB2_ERROR, null, null,
- 'Prepared statement has already been freed', __FUNCTION__);
- }
- $result = MDB2_OK;
-
- if (!is_null($this->statement)) {
- $connection = $this->db->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- $query = 'DEALLOCATE PREPARE '.$this->statement;
- $result = $this->db->_doQuery($query, true, $connection);
- }
-
- parent::free();
- return $result;
- }
-}
+ |
+// +----------------------------------------------------------------------+
+//
+// $Id: pgsql.php 295587 2010-02-28 17:16:38Z quipo $
+
+/**
+ * MDB2 PostGreSQL driver
+ *
+ * @package MDB2
+ * @category Database
+ * @author Paul Cooper
+ */
+class MDB2_Driver_pgsql extends MDB2_Driver_Common
+{
+ // {{{ properties
+ var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => "'", 'escape_pattern' => '\\');
+
+ var $identifier_quoting = array('start' => '"', 'end' => '"', 'escape' => '"');
+ // }}}
+ // {{{ constructor
+
+ /**
+ * Constructor
+ */
+ function __construct()
+ {
+ parent::__construct();
+
+ $this->phptype = 'pgsql';
+ $this->dbsyntax = 'pgsql';
+
+ $this->supported['sequences'] = true;
+ $this->supported['indexes'] = true;
+ $this->supported['affected_rows'] = true;
+ $this->supported['summary_functions'] = true;
+ $this->supported['order_by_text'] = true;
+ $this->supported['transactions'] = true;
+ $this->supported['savepoints'] = true;
+ $this->supported['current_id'] = true;
+ $this->supported['limit_queries'] = true;
+ $this->supported['LOBs'] = true;
+ $this->supported['replace'] = 'emulated';
+ $this->supported['sub_selects'] = true;
+ $this->supported['triggers'] = true;
+ $this->supported['auto_increment'] = 'emulated';
+ $this->supported['primary_key'] = true;
+ $this->supported['result_introspection'] = true;
+ $this->supported['prepared_statements'] = true;
+ $this->supported['identifier_quoting'] = true;
+ $this->supported['pattern_escaping'] = true;
+ $this->supported['new_link'] = true;
+
+ $this->options['DBA_username'] = false;
+ $this->options['DBA_password'] = false;
+ $this->options['multi_query'] = false;
+ $this->options['disable_smart_seqname'] = true;
+ $this->options['max_identifiers_length'] = 63;
+ }
+
+ // }}}
+ // {{{ errorInfo()
+
+ /**
+ * This method is used to collect information about an error
+ *
+ * @param integer $error
+ * @return array
+ * @access public
+ */
+ function errorInfo($error = null)
+ {
+ // Fall back to MDB2_ERROR if there was no mapping.
+ $error_code = MDB2_ERROR;
+
+ $native_msg = '';
+ if (is_resource($error)) {
+ $native_msg = @pg_result_error($error);
+ } elseif ($this->connection) {
+ $native_msg = @pg_last_error($this->connection);
+ if (!$native_msg && @pg_connection_status($this->connection) === PGSQL_CONNECTION_BAD) {
+ $native_msg = 'Database connection has been lost.';
+ $error_code = MDB2_ERROR_CONNECT_FAILED;
+ }
+ } else {
+ $native_msg = @pg_last_error();
+ }
+
+ static $error_regexps;
+ if (empty($error_regexps)) {
+ $error_regexps = array(
+ '/column .* (of relation .*)?does not exist/i'
+ => MDB2_ERROR_NOSUCHFIELD,
+ '/(relation|sequence|table).*does not exist|class .* not found/i'
+ => MDB2_ERROR_NOSUCHTABLE,
+ '/database .* does not exist/'
+ => MDB2_ERROR_NOT_FOUND,
+ '/constraint .* does not exist/'
+ => MDB2_ERROR_NOT_FOUND,
+ '/index .* does not exist/'
+ => MDB2_ERROR_NOT_FOUND,
+ '/database .* already exists/i'
+ => MDB2_ERROR_ALREADY_EXISTS,
+ '/relation .* already exists/i'
+ => MDB2_ERROR_ALREADY_EXISTS,
+ '/(divide|division) by zero$/i'
+ => MDB2_ERROR_DIVZERO,
+ '/pg_atoi: error in .*: can\'t parse /i'
+ => MDB2_ERROR_INVALID_NUMBER,
+ '/invalid input syntax for( type)? (integer|numeric)/i'
+ => MDB2_ERROR_INVALID_NUMBER,
+ '/value .* is out of range for type \w*int/i'
+ => MDB2_ERROR_INVALID_NUMBER,
+ '/integer out of range/i'
+ => MDB2_ERROR_INVALID_NUMBER,
+ '/value too long for type character/i'
+ => MDB2_ERROR_INVALID,
+ '/attribute .* not found|relation .* does not have attribute/i'
+ => MDB2_ERROR_NOSUCHFIELD,
+ '/column .* specified in USING clause does not exist in (left|right) table/i'
+ => MDB2_ERROR_NOSUCHFIELD,
+ '/parser: parse error at or near/i'
+ => MDB2_ERROR_SYNTAX,
+ '/syntax error at/'
+ => MDB2_ERROR_SYNTAX,
+ '/column reference .* is ambiguous/i'
+ => MDB2_ERROR_SYNTAX,
+ '/permission denied/'
+ => MDB2_ERROR_ACCESS_VIOLATION,
+ '/violates not-null constraint/'
+ => MDB2_ERROR_CONSTRAINT_NOT_NULL,
+ '/violates [\w ]+ constraint/'
+ => MDB2_ERROR_CONSTRAINT,
+ '/referential integrity violation/'
+ => MDB2_ERROR_CONSTRAINT,
+ '/more expressions than target columns/i'
+ => MDB2_ERROR_VALUE_COUNT_ON_ROW,
+ );
+ }
+ if (is_numeric($error) && $error < 0) {
+ $error_code = $error;
+ } else {
+ foreach ($error_regexps as $regexp => $code) {
+ if (preg_match($regexp, $native_msg)) {
+ $error_code = $code;
+ break;
+ }
+ }
+ }
+ return array($error_code, null, $native_msg);
+ }
+
+ // }}}
+ // {{{ escape()
+
+ /**
+ * Quotes a string so it can be safely used in a query. It will quote
+ * the text so it can safely be used within a query.
+ *
+ * @param string the input string to quote
+ * @param bool escape wildcards
+ *
+ * @return string quoted string
+ *
+ * @access public
+ */
+ function escape($text, $escape_wildcards = false)
+ {
+ if ($escape_wildcards) {
+ $text = $this->escapePattern($text);
+ }
+ $connection = $this->getConnection();
+ if (PEAR::isError($connection)) {
+ return $connection;
+ }
+ if (is_resource($connection) && version_compare(PHP_VERSION, '5.2.0RC5', '>=')) {
+ $text = @pg_escape_string($connection, $text);
+ } else {
+ $text = @pg_escape_string($text);
+ }
+ return $text;
+ }
+
+ // }}}
+ // {{{ beginTransaction()
+
+ /**
+ * Start a transaction or set a savepoint.
+ *
+ * @param string name of a savepoint to set
+ * @return mixed MDB2_OK on success, a MDB2 error on failure
+ *
+ * @access public
+ */
+ function beginTransaction($savepoint = null)
+ {
+ $this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
+ if (null !== $savepoint) {
+ if (!$this->in_transaction) {
+ return $this->raiseError(MDB2_ERROR_INVALID, null, null,
+ 'savepoint cannot be released when changes are auto committed', __FUNCTION__);
+ }
+ $query = 'SAVEPOINT '.$savepoint;
+ return $this->_doQuery($query, true);
+ }
+ if ($this->in_transaction) {
+ return MDB2_OK; //nothing to do
+ }
+ if (!$this->destructor_registered && $this->opened_persistent) {
+ $this->destructor_registered = true;
+ register_shutdown_function('MDB2_closeOpenTransactions');
+ }
+ $result = $this->_doQuery('BEGIN', true);
+ if (PEAR::isError($result)) {
+ return $result;
+ }
+ $this->in_transaction = true;
+ return MDB2_OK;
+ }
+
+ // }}}
+ // {{{ commit()
+
+ /**
+ * Commit the database changes done during a transaction that is in
+ * progress or release a savepoint. This function may only be called when
+ * auto-committing is disabled, otherwise it will fail. Therefore, a new
+ * transaction is implicitly started after committing the pending changes.
+ *
+ * @param string name of a savepoint to release
+ * @return mixed MDB2_OK on success, a MDB2 error on failure
+ *
+ * @access public
+ */
+ function commit($savepoint = null)
+ {
+ $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
+ if (!$this->in_transaction) {
+ return $this->raiseError(MDB2_ERROR_INVALID, null, null,
+ 'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__);
+ }
+ if (null !== $savepoint) {
+ $query = 'RELEASE SAVEPOINT '.$savepoint;
+ return $this->_doQuery($query, true);
+ }
+
+ $result = $this->_doQuery('COMMIT', true);
+ if (PEAR::isError($result)) {
+ return $result;
+ }
+ $this->in_transaction = false;
+ return MDB2_OK;
+ }
+
+ // }}}
+ // {{{ rollback()
+
+ /**
+ * Cancel any database changes done during a transaction or since a specific
+ * savepoint that is in progress. This function may only be called when
+ * auto-committing is disabled, otherwise it will fail. Therefore, a new
+ * transaction is implicitly started after canceling the pending changes.
+ *
+ * @param string name of a savepoint to rollback to
+ * @return mixed MDB2_OK on success, a MDB2 error on failure
+ *
+ * @access public
+ */
+ function rollback($savepoint = null)
+ {
+ $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
+ if (!$this->in_transaction) {
+ return $this->raiseError(MDB2_ERROR_INVALID, null, null,
+ 'rollback cannot be done changes are auto committed', __FUNCTION__);
+ }
+ if (null !== $savepoint) {
+ $query = 'ROLLBACK TO SAVEPOINT '.$savepoint;
+ return $this->_doQuery($query, true);
+ }
+
+ $query = 'ROLLBACK';
+ $result = $this->_doQuery($query, true);
+ if (PEAR::isError($result)) {
+ return $result;
+ }
+ $this->in_transaction = false;
+ return MDB2_OK;
+ }
+
+ // }}}
+ // {{{ function setTransactionIsolation()
+
+ /**
+ * Set the transacton isolation level.
+ *
+ * @param string standard isolation level
+ * READ UNCOMMITTED (allows dirty reads)
+ * READ COMMITTED (prevents dirty reads)
+ * REPEATABLE READ (prevents nonrepeatable reads)
+ * SERIALIZABLE (prevents phantom reads)
+ * @param array some transaction options:
+ * 'wait' => 'WAIT' | 'NO WAIT'
+ * 'rw' => 'READ WRITE' | 'READ ONLY'
+ *
+ * @return mixed MDB2_OK on success, a MDB2 error on failure
+ *
+ * @access public
+ * @since 2.1.1
+ */
+ function setTransactionIsolation($isolation, $options = array())
+ {
+ $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
+ switch ($isolation) {
+ case 'READ UNCOMMITTED':
+ case 'READ COMMITTED':
+ case 'REPEATABLE READ':
+ case 'SERIALIZABLE':
+ break;
+ default:
+ return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
+ 'isolation level is not supported: '.$isolation, __FUNCTION__);
+ }
+
+ $query = "SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL $isolation";
+ return $this->_doQuery($query, true);
+ }
+
+ // }}}
+ // {{{ _doConnect()
+
+ /**
+ * Do the grunt work of connecting to the database
+ *
+ * @return mixed connection resource on success, MDB2 Error Object on failure
+ * @access protected
+ */
+ function _doConnect($username, $password, $database_name, $persistent = false)
+ {
+ if (!PEAR::loadExtension($this->phptype)) {
+ return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
+ 'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__);
+ }
+
+ if ($database_name == '') {
+ $database_name = 'template1';
+ }
+
+ $protocol = $this->dsn['protocol'] ? $this->dsn['protocol'] : 'tcp';
+
+ $params = array('');
+ if ($protocol == 'tcp') {
+ if ($this->dsn['hostspec']) {
+ $params[0].= 'host=' . $this->dsn['hostspec'];
+ }
+ if ($this->dsn['port']) {
+ $params[0].= ' port=' . $this->dsn['port'];
+ }
+ } elseif ($protocol == 'unix') {
+ // Allow for pg socket in non-standard locations.
+ if ($this->dsn['socket']) {
+ $params[0].= 'host=' . $this->dsn['socket'];
+ }
+ if ($this->dsn['port']) {
+ $params[0].= ' port=' . $this->dsn['port'];
+ }
+ }
+ if ($database_name) {
+ $params[0].= ' dbname=\'' . addslashes($database_name) . '\'';
+ }
+ if ($username) {
+ $params[0].= ' user=\'' . addslashes($username) . '\'';
+ }
+ if ($password) {
+ $params[0].= ' password=\'' . addslashes($password) . '\'';
+ }
+ if (!empty($this->dsn['options'])) {
+ $params[0].= ' options=' . $this->dsn['options'];
+ }
+ if (!empty($this->dsn['tty'])) {
+ $params[0].= ' tty=' . $this->dsn['tty'];
+ }
+ if (!empty($this->dsn['connect_timeout'])) {
+ $params[0].= ' connect_timeout=' . $this->dsn['connect_timeout'];
+ }
+ if (!empty($this->dsn['sslmode'])) {
+ $params[0].= ' sslmode=' . $this->dsn['sslmode'];
+ }
+ if (!empty($this->dsn['service'])) {
+ $params[0].= ' service=' . $this->dsn['service'];
+ }
+
+ if ($this->_isNewLinkSet()) {
+ if (version_compare(phpversion(), '4.3.0', '>=')) {
+ $params[] = PGSQL_CONNECT_FORCE_NEW;
+ }
+ }
+
+ $connect_function = $persistent ? 'pg_pconnect' : 'pg_connect';
+ $connection = @call_user_func_array($connect_function, $params);
+ if (!$connection) {
+ return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
+ 'unable to establish a connection', __FUNCTION__);
+ }
+
+ if (empty($this->dsn['disable_iso_date'])) {
+ if (!@pg_query($connection, "SET SESSION DATESTYLE = 'ISO'")) {
+ return $this->raiseError(null, null, null,
+ 'Unable to set date style to iso', __FUNCTION__);
+ }
+ }
+
+ if (!empty($this->dsn['charset'])) {
+ $result = $this->setCharset($this->dsn['charset'], $connection);
+ if (PEAR::isError($result)) {
+ return $result;
+ }
+ }
+
+ // Enable extra compatibility settings on 8.2 and later
+ if (function_exists('pg_parameter_status')) {
+ $version = pg_parameter_status($connection, 'server_version');
+ if ($version == false) {
+ return $this->raiseError(null, null, null,
+ 'Unable to retrieve server version', __FUNCTION__);
+ }
+ $version = explode ('.', $version);
+ if ( $version['0'] > 8
+ || ($version['0'] == 8 && $version['1'] >= 2)
+ ) {
+ if (!@pg_query($connection, "SET SESSION STANDARD_CONFORMING_STRINGS = OFF")) {
+ return $this->raiseError(null, null, null,
+ 'Unable to set standard_conforming_strings to off', __FUNCTION__);
+ }
+
+ if (!@pg_query($connection, "SET SESSION ESCAPE_STRING_WARNING = OFF")) {
+ return $this->raiseError(null, null, null,
+ 'Unable to set escape_string_warning to off', __FUNCTION__);
+ }
+ }
+ }
+
+ return $connection;
+ }
+
+ // }}}
+ // {{{ connect()
+
+ /**
+ * Connect to the database
+ *
+ * @return true on success, MDB2 Error Object on failure
+ * @access public
+ */
+ function connect()
+ {
+ if (is_resource($this->connection)) {
+ //if (count(array_diff($this->connected_dsn, $this->dsn)) == 0
+ if (MDB2::areEquals($this->connected_dsn, $this->dsn)
+ && $this->connected_database_name == $this->database_name
+ && ($this->opened_persistent == $this->options['persistent'])
+ ) {
+ return MDB2_OK;
+ }
+ $this->disconnect(false);
+ }
+
+ if ($this->database_name) {
+ $connection = $this->_doConnect($this->dsn['username'],
+ $this->dsn['password'],
+ $this->database_name,
+ $this->options['persistent']);
+ if (PEAR::isError($connection)) {
+ return $connection;
+ }
+
+ $this->connection = $connection;
+ $this->connected_dsn = $this->dsn;
+ $this->connected_database_name = $this->database_name;
+ $this->opened_persistent = $this->options['persistent'];
+ $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
+ }
+
+ return MDB2_OK;
+ }
+
+ // }}}
+ // {{{ setCharset()
+
+ /**
+ * Set the charset on the current connection
+ *
+ * @param string charset
+ * @param resource connection handle
+ *
+ * @return true on success, MDB2 Error Object on failure
+ */
+ function setCharset($charset, $connection = null)
+ {
+ if (null === $connection) {
+ $connection = $this->getConnection();
+ if (PEAR::isError($connection)) {
+ return $connection;
+ }
+ }
+ if (is_array($charset)) {
+ $charset = array_shift($charset);
+ $this->warnings[] = 'postgresql does not support setting client collation';
+ }
+ $result = @pg_set_client_encoding($connection, $charset);
+ if ($result == -1) {
+ return $this->raiseError(null, null, null,
+ 'Unable to set client charset: '.$charset, __FUNCTION__);
+ }
+ return MDB2_OK;
+ }
+
+ // }}}
+ // {{{ databaseExists()
+
+ /**
+ * check if given database name is exists?
+ *
+ * @param string $name name of the database that should be checked
+ *
+ * @return mixed true/false on success, a MDB2 error on failure
+ * @access public
+ */
+ function databaseExists($name)
+ {
+ $res = $this->_doConnect($this->dsn['username'],
+ $this->dsn['password'],
+ $this->escape($name),
+ $this->options['persistent']);
+ if (!PEAR::isError($res)) {
+ return true;
+ }
+
+ return false;
+ }
+
+ // }}}
+ // {{{ disconnect()
+
+ /**
+ * Log out and disconnect from the database.
+ *
+ * @param boolean $force if the disconnect should be forced even if the
+ * connection is opened persistently
+ * @return mixed true on success, false if not connected and error
+ * object on error
+ * @access public
+ */
+ function disconnect($force = true)
+ {
+ if (is_resource($this->connection)) {
+ if ($this->in_transaction) {
+ $dsn = $this->dsn;
+ $database_name = $this->database_name;
+ $persistent = $this->options['persistent'];
+ $this->dsn = $this->connected_dsn;
+ $this->database_name = $this->connected_database_name;
+ $this->options['persistent'] = $this->opened_persistent;
+ $this->rollback();
+ $this->dsn = $dsn;
+ $this->database_name = $database_name;
+ $this->options['persistent'] = $persistent;
+ }
+
+ if (!$this->opened_persistent || $force) {
+ $ok = @pg_close($this->connection);
+ if (!$ok) {
+ return $this->raiseError(MDB2_ERROR_DISCONNECT_FAILED,
+ null, null, null, __FUNCTION__);
+ }
+ }
+ } else {
+ return false;
+ }
+ return parent::disconnect($force);
+ }
+
+ // }}}
+ // {{{ standaloneQuery()
+
+ /**
+ * execute a query as DBA
+ *
+ * @param string $query the SQL query
+ * @param mixed $types array that contains the types of the columns in
+ * the result set
+ * @param boolean $is_manip if the query is a manipulation query
+ * @return mixed MDB2_OK on success, a MDB2 error on failure
+ * @access public
+ */
+ function standaloneQuery($query, $types = null, $is_manip = false)
+ {
+ $user = $this->options['DBA_username']? $this->options['DBA_username'] : $this->dsn['username'];
+ $pass = $this->options['DBA_password']? $this->options['DBA_password'] : $this->dsn['password'];
+ $connection = $this->_doConnect($user, $pass, $this->database_name, $this->options['persistent']);
+ if (PEAR::isError($connection)) {
+ return $connection;
+ }
+
+ $offset = $this->offset;
+ $limit = $this->limit;
+ $this->offset = $this->limit = 0;
+ $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
+
+ $result = $this->_doQuery($query, $is_manip, $connection, $this->database_name);
+ if (!PEAR::isError($result)) {
+ if ($is_manip) {
+ $result = $this->_affectedRows($connection, $result);
+ } else {
+ $result =& $this->_wrapResult($result, $types, true, false, $limit, $offset);
+ }
+ }
+
+ @pg_close($connection);
+ return $result;
+ }
+
+ // }}}
+ // {{{ _doQuery()
+
+ /**
+ * Execute a query
+ * @param string $query query
+ * @param boolean $is_manip if the query is a manipulation query
+ * @param resource $connection
+ * @param string $database_name
+ * @return result or error object
+ * @access protected
+ */
+ function _doQuery($query, $is_manip = false, $connection = null, $database_name = null)
+ {
+ $this->last_query = $query;
+ $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
+ if ($result) {
+ if (PEAR::isError($result)) {
+ return $result;
+ }
+ $query = $result;
+ }
+ if ($this->options['disable_query']) {
+ $result = $is_manip ? 0 : null;
+ return $result;
+ }
+
+ if (null === $connection) {
+ $connection = $this->getConnection();
+ if (PEAR::isError($connection)) {
+ return $connection;
+ }
+ }
+
+ $function = $this->options['multi_query'] ? 'pg_send_query' : 'pg_query';
+ $result = @$function($connection, $query);
+ if (!$result) {
+ $err = $this->raiseError(null, null, null,
+ 'Could not execute statement', __FUNCTION__);
+ return $err;
+ } elseif ($this->options['multi_query']) {
+ if (!($result = @pg_get_result($connection))) {
+ $err = $this->raiseError(null, null, null,
+ 'Could not get the first result from a multi query', __FUNCTION__);
+ return $err;
+ }
+ }
+
+ $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result));
+ return $result;
+ }
+
+ // }}}
+ // {{{ _affectedRows()
+
+ /**
+ * Returns the number of rows affected
+ *
+ * @param resource $result
+ * @param resource $connection
+ * @return mixed MDB2 Error Object or the number of rows affected
+ * @access private
+ */
+ function _affectedRows($connection, $result = null)
+ {
+ if (null === $connection) {
+ $connection = $this->getConnection();
+ if (PEAR::isError($connection)) {
+ return $connection;
+ }
+ }
+ return @pg_affected_rows($result);
+ }
+
+ // }}}
+ // {{{ _modifyQuery()
+
+ /**
+ * Changes a query string for various DBMS specific reasons
+ *
+ * @param string $query query to modify
+ * @param boolean $is_manip if it is a DML query
+ * @param integer $limit limit the number of rows
+ * @param integer $offset start reading from given offset
+ * @return string modified query
+ * @access protected
+ */
+ function _modifyQuery($query, $is_manip, $limit, $offset)
+ {
+ if ($limit > 0
+ && !preg_match('/LIMIT\s*\d(?:\s*(?:,|OFFSET)\s*\d+)?(?:[^\)]*)?$/i', $query)
+ ) {
+ $query = rtrim($query);
+ if (substr($query, -1) == ';') {
+ $query = substr($query, 0, -1);
+ }
+ if ($is_manip) {
+ $query = $this->_modifyManipQuery($query, $limit);
+ } else {
+ $query.= " LIMIT $limit OFFSET $offset";
+ }
+ }
+ return $query;
+ }
+
+ // }}}
+ // {{{ _modifyManipQuery()
+
+ /**
+ * Changes a manip query string for various DBMS specific reasons
+ *
+ * @param string $query query to modify
+ * @param integer $limit limit the number of rows
+ * @return string modified query
+ * @access protected
+ */
+ function _modifyManipQuery($query, $limit)
+ {
+ $pos = strpos(strtolower($query), 'where');
+ $where = $pos ? substr($query, $pos) : '';
+
+ $manip_clause = '(\bDELETE\b\s+(?:\*\s+)?\bFROM\b|\bUPDATE\b)';
+ $from_clause = '([\w\.]+)';
+ $where_clause = '(?:(.*)\bWHERE\b\s+(.*))|(.*)';
+ $pattern = '/^'. $manip_clause . '\s+' . $from_clause .'(?:\s)*(?:'. $where_clause .')?$/i';
+ $matches = preg_match($pattern, $query, $match);
+ if ($matches) {
+ $manip = $match[1];
+ $from = $match[2];
+ $what = (count($matches) == 6) ? $match[5] : $match[3];
+ return $manip.' '.$from.' '.$what.' WHERE ctid=(SELECT ctid FROM '.$from.' '.$where.' LIMIT '.$limit.')';
+ }
+ //return error?
+ return $query;
+ }
+
+ // }}}
+ // {{{ getServerVersion()
+
+ /**
+ * return version information about the server
+ *
+ * @param bool $native determines if the raw version string should be returned
+ * @return mixed array/string with version information or MDB2 error object
+ * @access public
+ */
+ function getServerVersion($native = false)
+ {
+ $query = 'SHOW SERVER_VERSION';
+ if ($this->connected_server_info) {
+ $server_info = $this->connected_server_info;
+ } else {
+ $server_info = $this->queryOne($query, 'text');
+ if (PEAR::isError($server_info)) {
+ return $server_info;
+ }
+ }
+ // cache server_info
+ $this->connected_server_info = $server_info;
+ if (!$native && !PEAR::isError($server_info)) {
+ $tmp = explode('.', $server_info, 3);
+ if (empty($tmp[2])
+ && isset($tmp[1])
+ && preg_match('/(\d+)(.*)/', $tmp[1], $tmp2)
+ ) {
+ $server_info = array(
+ 'major' => $tmp[0],
+ 'minor' => $tmp2[1],
+ 'patch' => null,
+ 'extra' => $tmp2[2],
+ 'native' => $server_info,
+ );
+ } else {
+ $server_info = array(
+ 'major' => isset($tmp[0]) ? $tmp[0] : null,
+ 'minor' => isset($tmp[1]) ? $tmp[1] : null,
+ 'patch' => isset($tmp[2]) ? $tmp[2] : null,
+ 'extra' => null,
+ 'native' => $server_info,
+ );
+ }
+ }
+ return $server_info;
+ }
+
+ // }}}
+ // {{{ prepare()
+
+ /**
+ * Prepares a query for multiple execution with execute().
+ * With some database backends, this is emulated.
+ * prepare() requires a generic query as string like
+ * 'INSERT INTO numbers VALUES(?,?)' or
+ * 'INSERT INTO numbers VALUES(:foo,:bar)'.
+ * The ? and :name and are placeholders which can be set using
+ * bindParam() and the query can be sent off using the execute() method.
+ * The allowed format for :name can be set with the 'bindname_format' option.
+ *
+ * @param string $query the query to prepare
+ * @param mixed $types array that contains the types of the placeholders
+ * @param mixed $result_types array that contains the types of the columns in
+ * the result set or MDB2_PREPARE_RESULT, if set to
+ * MDB2_PREPARE_MANIP the query is handled as a manipulation query
+ * @param mixed $lobs key (field) value (parameter) pair for all lob placeholders
+ * @return mixed resource handle for the prepared query on success, a MDB2
+ * error on failure
+ * @access public
+ * @see bindParam, execute
+ */
+ function prepare($query, $types = null, $result_types = null, $lobs = array())
+ {
+ if ($this->options['emulate_prepared']) {
+ return parent::prepare($query, $types, $result_types, $lobs);
+ }
+ $is_manip = ($result_types === MDB2_PREPARE_MANIP);
+ $offset = $this->offset;
+ $limit = $this->limit;
+ $this->offset = $this->limit = 0;
+ $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre'));
+ if ($result) {
+ if (PEAR::isError($result)) {
+ return $result;
+ }
+ $query = $result;
+ }
+ $pgtypes = function_exists('pg_prepare') ? false : array();
+ if ($pgtypes !== false && !empty($types)) {
+ $this->loadModule('Datatype', null, true);
+ }
+ $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
+ $placeholder_type_guess = $placeholder_type = null;
+ $question = '?';
+ $colon = ':';
+ $positions = array();
+ $position = $parameter = 0;
+ while ($position < strlen($query)) {
+ $q_position = strpos($query, $question, $position);
+ $c_position = strpos($query, $colon, $position);
+ //skip "::type" cast ("select id::varchar(20) from sometable where name=?")
+ $doublecolon_position = strpos($query, '::', $position);
+ if ($doublecolon_position !== false && $doublecolon_position == $c_position) {
+ $c_position = strpos($query, $colon, $position+2);
+ }
+ if ($q_position && $c_position) {
+ $p_position = min($q_position, $c_position);
+ } elseif ($q_position) {
+ $p_position = $q_position;
+ } elseif ($c_position) {
+ $p_position = $c_position;
+ } else {
+ break;
+ }
+ if (null === $placeholder_type) {
+ $placeholder_type_guess = $query[$p_position];
+ }
+
+ $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position);
+ if (PEAR::isError($new_pos)) {
+ return $new_pos;
+ }
+ if ($new_pos != $position) {
+ $position = $new_pos;
+ continue; //evaluate again starting from the new position
+ }
+
+ if ($query[$position] == $placeholder_type_guess) {
+ if (null === $placeholder_type) {
+ $placeholder_type = $query[$p_position];
+ $question = $colon = $placeholder_type;
+ if (!empty($types) && is_array($types)) {
+ if ($placeholder_type == ':') {
+ } else {
+ $types = array_values($types);
+ }
+ }
+ }
+ if ($placeholder_type_guess == '?') {
+ $length = 1;
+ $name = $parameter;
+ } else {
+ $regexp = '/^.{'.($position+1).'}('.$this->options['bindname_format'].').*$/s';
+ $param = preg_replace($regexp, '\\1', $query);
+ if ($param === '') {
+ $err = $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
+ 'named parameter name must match "bindname_format" option', __FUNCTION__);
+ return $err;
+ }
+ $length = strlen($param) + 1;
+ $name = $param;
+ }
+ if ($pgtypes !== false) {
+ if (is_array($types) && array_key_exists($name, $types)) {
+ $pgtypes[] = $this->datatype->mapPrepareDatatype($types[$name]);
+ } elseif (is_array($types) && array_key_exists($parameter, $types)) {
+ $pgtypes[] = $this->datatype->mapPrepareDatatype($types[$parameter]);
+ } else {
+ $pgtypes[] = 'text';
+ }
+ }
+ if (($key_parameter = array_search($name, $positions))) {
+ $next_parameter = 1;
+ foreach ($positions as $key => $value) {
+ if ($key_parameter == $key) {
+ break;
+ }
+ ++$next_parameter;
+ }
+ } else {
+ ++$parameter;
+ $next_parameter = $parameter;
+ $positions[] = $name;
+ }
+ $query = substr_replace($query, '$'.$parameter, $position, $length);
+ $position = $p_position + strlen($parameter);
+ } else {
+ $position = $p_position;
+ }
+ }
+ $connection = $this->getConnection();
+ if (PEAR::isError($connection)) {
+ return $connection;
+ }
+ static $prep_statement_counter = 1;
+ $statement_name = sprintf($this->options['statement_format'], $this->phptype, $prep_statement_counter++ . sha1(microtime() + mt_rand()));
+ $statement_name = substr(strtolower($statement_name), 0, $this->options['max_identifiers_length']);
+ if (false === $pgtypes) {
+ $result = @pg_prepare($connection, $statement_name, $query);
+ if (!$result) {
+ $err = $this->raiseError(null, null, null,
+ 'Unable to create prepared statement handle', __FUNCTION__);
+ return $err;
+ }
+ } else {
+ $types_string = '';
+ if ($pgtypes) {
+ $types_string = ' ('.implode(', ', $pgtypes).') ';
+ }
+ $query = 'PREPARE '.$statement_name.$types_string.' AS '.$query;
+ $statement = $this->_doQuery($query, true, $connection);
+ if (PEAR::isError($statement)) {
+ return $statement;
+ }
+ }
+
+ $class_name = 'MDB2_Statement_'.$this->phptype;
+ $obj = new $class_name($this, $statement_name, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);
+ $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));
+ return $obj;
+ }
+
+ // }}}
+ // {{{ function getSequenceName($sqn)
+
+ /**
+ * adds sequence name formatting to a sequence name
+ *
+ * @param string name of the sequence
+ *
+ * @return string formatted sequence name
+ *
+ * @access public
+ */
+ function getSequenceName($sqn)
+ {
+ if (false === $this->options['disable_smart_seqname']) {
+ if (strpos($sqn, '_') !== false) {
+ list($table, $field) = explode('_', $sqn, 2);
+ }
+ $schema_list = $this->queryOne("SELECT array_to_string(current_schemas(false), ',')");
+ if (PEAR::isError($schema_list) || empty($schema_list) || count($schema_list) < 2) {
+ $order_by = ' a.attnum';
+ $schema_clause = ' AND n.nspname=current_schema()';
+ } else {
+ $schemas = explode(',', $schema_list);
+ $schema_clause = ' AND n.nspname IN ('.$schema_list.')';
+ $counter = 1;
+ $order_by = ' CASE ';
+ foreach ($schemas as $schema) {
+ $order_by .= ' WHEN n.nspname='.$schema.' THEN '.$counter++;
+ }
+ $order_by .= ' ELSE '.$counter.' END, a.attnum';
+ }
+
+ $query = "SELECT substring((SELECT substring(pg_get_expr(d.adbin, d.adrelid) for 128)
+ FROM pg_attrdef d
+ WHERE d.adrelid = a.attrelid
+ AND d.adnum = a.attnum
+ AND a.atthasdef
+ ) FROM 'nextval[^'']*''([^'']*)')
+ FROM pg_attribute a
+ LEFT JOIN pg_class c ON c.oid = a.attrelid
+ LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef
+ LEFT JOIN pg_namespace n ON c.relnamespace = n.oid
+ WHERE (c.relname = ".$this->quote($sqn, 'text');
+ if (!empty($field)) {
+ $query .= " OR (c.relname = ".$this->quote($table, 'text')." AND a.attname = ".$this->quote($field, 'text').")";
+ }
+ $query .= " )"
+ .$schema_clause."
+ AND NOT a.attisdropped
+ AND a.attnum > 0
+ AND pg_get_expr(d.adbin, d.adrelid) LIKE 'nextval%'
+ ORDER BY ".$order_by;
+ $seqname = $this->queryOne($query);
+ if (!PEAR::isError($seqname) && !empty($seqname) && is_string($seqname)) {
+ return $seqname;
+ }
+ }
+
+ return parent::getSequenceName($sqn);
+ }
+
+ // }}}
+ // {{{ nextID()
+
+ /**
+ * Returns the next free id of a sequence
+ *
+ * @param string $seq_name name of the sequence
+ * @param boolean $ondemand when true the sequence is
+ * automatic created, if it
+ * not exists
+ * @return mixed MDB2 Error Object or id
+ * @access public
+ */
+ function nextID($seq_name, $ondemand = true)
+ {
+ $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
+ $query = "SELECT NEXTVAL('$sequence_name')";
+ $this->pushErrorHandling(PEAR_ERROR_RETURN);
+ $this->expectError(MDB2_ERROR_NOSUCHTABLE);
+ $result = $this->queryOne($query, 'integer');
+ $this->popExpect();
+ $this->popErrorHandling();
+ if (PEAR::isError($result)) {
+ if ($ondemand && $result->getCode() == MDB2_ERROR_NOSUCHTABLE) {
+ $this->loadModule('Manager', null, true);
+ $result = $this->manager->createSequence($seq_name);
+ if (PEAR::isError($result)) {
+ return $this->raiseError($result, null, null,
+ 'on demand sequence could not be created', __FUNCTION__);
+ }
+ return $this->nextId($seq_name, false);
+ }
+ }
+ return $result;
+ }
+
+ // }}}
+ // {{{ lastInsertID()
+
+ /**
+ * Returns the autoincrement ID if supported or $id or fetches the current
+ * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
+ *
+ * @param string $table name of the table into which a new row was inserted
+ * @param string $field name of the field into which a new row was inserted
+ * @return mixed MDB2 Error Object or id
+ * @access public
+ */
+ function lastInsertID($table = null, $field = null)
+ {
+ if (empty($table) && empty($field)) {
+ return $this->queryOne('SELECT lastval()', 'integer');
+ }
+ $seq = $table.(empty($field) ? '' : '_'.$field);
+ $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq), true);
+ return $this->queryOne("SELECT currval('$sequence_name')", 'integer');
+ }
+
+ // }}}
+ // {{{ currID()
+
+ /**
+ * Returns the current id of a sequence
+ *
+ * @param string $seq_name name of the sequence
+ * @return mixed MDB2 Error Object or id
+ * @access public
+ */
+ function currID($seq_name)
+ {
+ $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
+ return $this->queryOne("SELECT last_value FROM $sequence_name", 'integer');
+ }
+}
+
+/**
+ * MDB2 PostGreSQL result driver
+ *
+ * @package MDB2
+ * @category Database
+ * @author Paul Cooper
+ */
+class MDB2_Result_pgsql extends MDB2_Result_Common
+{
+ // }}}
+ // {{{ fetchRow()
+
+ /**
+ * Fetch a row and insert the data into an existing array.
+ *
+ * @param int $fetchmode how the array data should be indexed
+ * @param int $rownum number of the row where the data can be found
+ * @return int data array on success, a MDB2 error on failure
+ * @access public
+ */
+ function fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
+ {
+ if (null !== $rownum) {
+ $seek = $this->seek($rownum);
+ if (PEAR::isError($seek)) {
+ return $seek;
+ }
+ }
+ if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
+ $fetchmode = $this->db->fetchmode;
+ }
+ if ($fetchmode & MDB2_FETCHMODE_ASSOC) {
+ $row = @pg_fetch_array($this->result, null, PGSQL_ASSOC);
+ if (is_array($row)
+ && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
+ ) {
+ $row = array_change_key_case($row, $this->db->options['field_case']);
+ }
+ } else {
+ $row = @pg_fetch_row($this->result);
+ }
+ if (!$row) {
+ if (false === $this->result) {
+ $err = $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
+ 'resultset has already been freed', __FUNCTION__);
+ return $err;
+ }
+ return null;
+ }
+ $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL;
+ $rtrim = false;
+ if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) {
+ if (empty($this->types)) {
+ $mode += MDB2_PORTABILITY_RTRIM;
+ } else {
+ $rtrim = true;
+ }
+ }
+ if ($mode) {
+ $this->db->_fixResultArrayValues($row, $mode);
+ }
+ if (!empty($this->types)) {
+ $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim);
+ }
+ if (!empty($this->values)) {
+ $this->_assignBindColumns($row);
+ }
+ if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
+ $object_class = $this->db->options['fetch_class'];
+ if ($object_class == 'stdClass') {
+ $row = (object) $row;
+ } else {
+ $rowObj = new $object_class($row);
+ $row = $rowObj;
+ }
+ }
+ ++$this->rownum;
+ return $row;
+ }
+
+ // }}}
+ // {{{ _getColumnNames()
+
+ /**
+ * Retrieve the names of columns returned by the DBMS in a query result.
+ *
+ * @return mixed Array variable that holds the names of columns as keys
+ * or an MDB2 error on failure.
+ * Some DBMS may not return any columns when the result set
+ * does not contain any rows.
+ * @access private
+ */
+ function _getColumnNames()
+ {
+ $columns = array();
+ $numcols = $this->numCols();
+ if (PEAR::isError($numcols)) {
+ return $numcols;
+ }
+ for ($column = 0; $column < $numcols; $column++) {
+ $column_name = @pg_field_name($this->result, $column);
+ $columns[$column_name] = $column;
+ }
+ if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
+ $columns = array_change_key_case($columns, $this->db->options['field_case']);
+ }
+ return $columns;
+ }
+
+ // }}}
+ // {{{ numCols()
+
+ /**
+ * Count the number of columns returned by the DBMS in a query result.
+ *
+ * @access public
+ * @return mixed integer value with the number of columns, a MDB2 error
+ * on failure
+ */
+ function numCols()
+ {
+ $cols = @pg_num_fields($this->result);
+ if (null === $cols) {
+ if (false === $this->result) {
+ return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
+ 'resultset has already been freed', __FUNCTION__);
+ }
+ if (null === $this->result) {
+ return count($this->types);
+ }
+ return $this->db->raiseError(null, null, null,
+ 'Could not get column count', __FUNCTION__);
+ }
+ return $cols;
+ }
+
+ // }}}
+ // {{{ nextResult()
+
+ /**
+ * Move the internal result pointer to the next available result
+ *
+ * @return true on success, false if there is no more result set or an error object on failure
+ * @access public
+ */
+ function nextResult()
+ {
+ $connection = $this->db->getConnection();
+ if (PEAR::isError($connection)) {
+ return $connection;
+ }
+
+ if (!($this->result = @pg_get_result($connection))) {
+ return false;
+ }
+ return MDB2_OK;
+ }
+
+ // }}}
+ // {{{ free()
+
+ /**
+ * Free the internal resources associated with result.
+ *
+ * @return boolean true on success, false if result is invalid
+ * @access public
+ */
+ function free()
+ {
+ if (is_resource($this->result) && $this->db->connection) {
+ $free = @pg_free_result($this->result);
+ if (false === $free) {
+ return $this->db->raiseError(null, null, null,
+ 'Could not free result', __FUNCTION__);
+ }
+ }
+ $this->result = false;
+ return MDB2_OK;
+ }
+}
+
+/**
+ * MDB2 PostGreSQL buffered result driver
+ *
+ * @package MDB2
+ * @category Database
+ * @author Paul Cooper
+ */
+class MDB2_BufferedResult_pgsql extends MDB2_Result_pgsql
+{
+ // {{{ seek()
+
+ /**
+ * Seek to a specific row in a result set
+ *
+ * @param int $rownum number of the row where the data can be found
+ * @return mixed MDB2_OK on success, a MDB2 error on failure
+ * @access public
+ */
+ function seek($rownum = 0)
+ {
+ if ($this->rownum != ($rownum - 1) && !@pg_result_seek($this->result, $rownum)) {
+ if (false === $this->result) {
+ return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
+ 'resultset has already been freed', __FUNCTION__);
+ }
+ if (null === $this->result) {
+ return MDB2_OK;
+ }
+ return $this->db->raiseError(MDB2_ERROR_INVALID, null, null,
+ 'tried to seek to an invalid row number ('.$rownum.')', __FUNCTION__);
+ }
+ $this->rownum = $rownum - 1;
+ return MDB2_OK;
+ }
+
+ // }}}
+ // {{{ valid()
+
+ /**
+ * Check if the end of the result set has been reached
+ *
+ * @return mixed true or false on sucess, a MDB2 error on failure
+ * @access public
+ */
+ function valid()
+ {
+ $numrows = $this->numRows();
+ if (PEAR::isError($numrows)) {
+ return $numrows;
+ }
+ return $this->rownum < ($numrows - 1);
+ }
+
+ // }}}
+ // {{{ numRows()
+
+ /**
+ * Returns the number of rows in a result object
+ *
+ * @return mixed MDB2 Error Object or the number of rows
+ * @access public
+ */
+ function numRows()
+ {
+ $rows = @pg_num_rows($this->result);
+ if (null === $rows) {
+ if (false === $this->result) {
+ return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
+ 'resultset has already been freed', __FUNCTION__);
+ }
+ if (null === $this->result) {
+ return 0;
+ }
+ return $this->db->raiseError(null, null, null,
+ 'Could not get row count', __FUNCTION__);
+ }
+ return $rows;
+ }
+}
+
+/**
+ * MDB2 PostGreSQL statement driver
+ *
+ * @package MDB2
+ * @category Database
+ * @author Paul Cooper
+ */
+class MDB2_Statement_pgsql extends MDB2_Statement_Common
+{
+ // {{{ _execute()
+
+ /**
+ * Execute a prepared query statement helper method.
+ *
+ * @param mixed $result_class string which specifies which result class to use
+ * @param mixed $result_wrap_class string which specifies which class to wrap results in
+ *
+ * @return mixed MDB2_Result or integer (affected rows) on success,
+ * a MDB2 error on failure
+ * @access private
+ */
+ function _execute($result_class = true, $result_wrap_class = false)
+ {
+ if (null === $this->statement) {
+ return parent::_execute($result_class, $result_wrap_class);
+ }
+ $this->db->last_query = $this->query;
+ $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'pre', 'parameters' => $this->values));
+ if ($this->db->getOption('disable_query')) {
+ $result = $this->is_manip ? 0 : null;
+ return $result;
+ }
+
+ $connection = $this->db->getConnection();
+ if (PEAR::isError($connection)) {
+ return $connection;
+ }
+
+ $query = false;
+ $parameters = array();
+ // todo: disabled until pg_execute() bytea issues are cleared up
+ if (true || !function_exists('pg_execute')) {
+ $query = 'EXECUTE '.$this->statement;
+ }
+ if (!empty($this->positions)) {
+ foreach ($this->positions as $parameter) {
+ if (!array_key_exists($parameter, $this->values)) {
+ return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
+ 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
+ }
+ $value = $this->values[$parameter];
+ $type = array_key_exists($parameter, $this->types) ? $this->types[$parameter] : null;
+ if (is_resource($value) || $type == 'clob' || $type == 'blob' || $this->db->options['lob_allow_url_include']) {
+ if (!is_resource($value) && preg_match('/^(\w+:\/\/)(.*)$/', $value, $match)) {
+ if ($match[1] == 'file://') {
+ $value = $match[2];
+ }
+ $value = @fopen($value, 'r');
+ $close = true;
+ }
+ if (is_resource($value)) {
+ $data = '';
+ while (!@feof($value)) {
+ $data.= @fread($value, $this->db->options['lob_buffer_length']);
+ }
+ if ($close) {
+ @fclose($value);
+ }
+ $value = $data;
+ }
+ }
+ $quoted = $this->db->quote($value, $type, $query);
+ if (PEAR::isError($quoted)) {
+ return $quoted;
+ }
+ $parameters[] = $quoted;
+ }
+ if ($query) {
+ $query.= ' ('.implode(', ', $parameters).')';
+ }
+ }
+
+ if (!$query) {
+ $result = @pg_execute($connection, $this->statement, $parameters);
+ if (!$result) {
+ $err = $this->db->raiseError(null, null, null,
+ 'Unable to execute statement', __FUNCTION__);
+ return $err;
+ }
+ } else {
+ $result = $this->db->_doQuery($query, $this->is_manip, $connection);
+ if (PEAR::isError($result)) {
+ return $result;
+ }
+ }
+
+ if ($this->is_manip) {
+ $affected_rows = $this->db->_affectedRows($connection, $result);
+ return $affected_rows;
+ }
+
+ $result = $this->db->_wrapResult($result, $this->result_types,
+ $result_class, $result_wrap_class, $this->limit, $this->offset);
+ $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'post', 'result' => $result));
+ return $result;
+ }
+
+ // }}}
+ // {{{ free()
+
+ /**
+ * Release resources allocated for the specified prepared query.
+ *
+ * @return mixed MDB2_OK on success, a MDB2 error on failure
+ * @access public
+ */
+ function free()
+ {
+ if (null === $this->positions) {
+ return $this->db->raiseError(MDB2_ERROR, null, null,
+ 'Prepared statement has already been freed', __FUNCTION__);
+ }
+ $result = MDB2_OK;
+
+ if (null !== $this->statement) {
+ $connection = $this->db->getConnection();
+ if (PEAR::isError($connection)) {
+ return $connection;
+ }
+ $query = 'DEALLOCATE PREPARE '.$this->statement;
+ $result = $this->db->_doQuery($query, true, $connection);
+ }
+
+ parent::free();
+ return $result;
+ }
+}
?>
\ No newline at end of file
diff --git a/3rdparty/MDB2/Driver/sqlite.php b/3rdparty/MDB2/Driver/sqlite.php
index 5d2ad27d01..e8f1bba583 100644
--- a/3rdparty/MDB2/Driver/sqlite.php
+++ b/3rdparty/MDB2/Driver/sqlite.php
@@ -1,1088 +1,1093 @@
- |
-// +----------------------------------------------------------------------+
-//
-// $Id: sqlite.php,v 1.165 2008/11/30 14:28:01 afz Exp $
-//
-
-/**
- * MDB2 SQLite driver
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Driver_sqlite extends MDB2_Driver_Common
-{
- // {{{ properties
- var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => "'", 'escape_pattern' => false);
-
- var $identifier_quoting = array('start' => '"', 'end' => '"', 'escape' => '"');
-
- var $_lasterror = '';
-
- var $fix_assoc_fields_names = false;
-
- // }}}
- // {{{ constructor
-
- /**
- * Constructor
- */
- function __construct()
- {
- parent::__construct();
-
- $this->phptype = 'sqlite';
- $this->dbsyntax = 'sqlite';
-
- $this->supported['sequences'] = 'emulated';
- $this->supported['indexes'] = true;
- $this->supported['affected_rows'] = true;
- $this->supported['summary_functions'] = true;
- $this->supported['order_by_text'] = true;
- $this->supported['current_id'] = 'emulated';
- $this->supported['limit_queries'] = true;
- $this->supported['LOBs'] = true;
- $this->supported['replace'] = true;
- $this->supported['transactions'] = true;
- $this->supported['savepoints'] = false;
- $this->supported['sub_selects'] = true;
- $this->supported['triggers'] = true;
- $this->supported['auto_increment'] = true;
- $this->supported['primary_key'] = false; // requires alter table implementation
- $this->supported['result_introspection'] = false; // not implemented
- $this->supported['prepared_statements'] = 'emulated';
- $this->supported['identifier_quoting'] = true;
- $this->supported['pattern_escaping'] = false;
- $this->supported['new_link'] = false;
-
- $this->options['DBA_username'] = false;
- $this->options['DBA_password'] = false;
- $this->options['base_transaction_name'] = '___php_MDB2_sqlite_auto_commit_off';
- $this->options['fixed_float'] = 0;
- $this->options['database_path'] = '';
- $this->options['database_extension'] = '';
- $this->options['server_version'] = '';
- $this->options['max_identifiers_length'] = 128; //no real limit
- }
-
- // }}}
- // {{{ errorInfo()
-
- /**
- * This method is used to collect information about an error
- *
- * @param integer $error
- * @return array
- * @access public
- */
- function errorInfo($error = null)
- {
- $native_code = null;
- if ($this->connection) {
- $native_code = @sqlite_last_error($this->connection);
- }
- $native_msg = $this->_lasterror
- ? html_entity_decode($this->_lasterror) : @sqlite_error_string($native_code);
-
- // PHP 5.2+ prepends the function name to $php_errormsg, so we need
- // this hack to work around it, per bug #9599.
- $native_msg = preg_replace('/^sqlite[a-z_]+\(\)[^:]*: /', '', $native_msg);
-
- if (is_null($error)) {
- static $error_regexps;
- if (empty($error_regexps)) {
- $error_regexps = array(
- '/^no such table:/' => MDB2_ERROR_NOSUCHTABLE,
- '/^no such index:/' => MDB2_ERROR_NOT_FOUND,
- '/^(table|index) .* already exists$/' => MDB2_ERROR_ALREADY_EXISTS,
- '/PRIMARY KEY must be unique/i' => MDB2_ERROR_CONSTRAINT,
- '/is not unique/' => MDB2_ERROR_CONSTRAINT,
- '/columns .* are not unique/i' => MDB2_ERROR_CONSTRAINT,
- '/uniqueness constraint failed/' => MDB2_ERROR_CONSTRAINT,
- '/may not be NULL/' => MDB2_ERROR_CONSTRAINT_NOT_NULL,
- '/^no such column:/' => MDB2_ERROR_NOSUCHFIELD,
- '/no column named/' => MDB2_ERROR_NOSUCHFIELD,
- '/column not present in both tables/i' => MDB2_ERROR_NOSUCHFIELD,
- '/^near ".*": syntax error$/' => MDB2_ERROR_SYNTAX,
- '/[0-9]+ values for [0-9]+ columns/i' => MDB2_ERROR_VALUE_COUNT_ON_ROW,
- );
- }
- foreach ($error_regexps as $regexp => $code) {
- if (preg_match($regexp, $native_msg)) {
- $error = $code;
- break;
- }
- }
- }
- return array($error, $native_code, $native_msg);
- }
-
- // }}}
- // {{{ escape()
-
- /**
- * Quotes a string so it can be safely used in a query. It will quote
- * the text so it can safely be used within a query.
- *
- * @param string the input string to quote
- * @param bool escape wildcards
- *
- * @return string quoted string
- *
- * @access public
- */
- function escape($text, $escape_wildcards = false)
- {
- $text = @sqlite_escape_string($text);
- return $text;
- }
-
- // }}}
- // {{{ beginTransaction()
-
- /**
- * Start a transaction or set a savepoint.
- *
- * @param string name of a savepoint to set
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function beginTransaction($savepoint = null)
- {
- $this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- if (!is_null($savepoint)) {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'savepoints are not supported', __FUNCTION__);
- } elseif ($this->in_transaction) {
- return MDB2_OK; //nothing to do
- }
- if (!$this->destructor_registered && $this->opened_persistent) {
- $this->destructor_registered = true;
- register_shutdown_function('MDB2_closeOpenTransactions');
- }
- $query = 'BEGIN TRANSACTION '.$this->options['base_transaction_name'];
- $result =$this->_doQuery($query, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- $this->in_transaction = true;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ commit()
-
- /**
- * Commit the database changes done during a transaction that is in
- * progress or release a savepoint. This function may only be called when
- * auto-committing is disabled, otherwise it will fail. Therefore, a new
- * transaction is implicitly started after committing the pending changes.
- *
- * @param string name of a savepoint to release
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function commit($savepoint = null)
- {
- $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- if (!$this->in_transaction) {
- return $this->raiseError(MDB2_ERROR_INVALID, null, null,
- 'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__);
- }
- if (!is_null($savepoint)) {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'savepoints are not supported', __FUNCTION__);
- }
-
- $query = 'COMMIT TRANSACTION '.$this->options['base_transaction_name'];
- $result =$this->_doQuery($query, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- $this->in_transaction = false;
- return MDB2_OK;
- }
-
- // }}}
- // {{{
-
- /**
- * Cancel any database changes done during a transaction or since a specific
- * savepoint that is in progress. This function may only be called when
- * auto-committing is disabled, otherwise it will fail. Therefore, a new
- * transaction is implicitly started after canceling the pending changes.
- *
- * @param string name of a savepoint to rollback to
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function rollback($savepoint = null)
- {
- $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- if (!$this->in_transaction) {
- return $this->raiseError(MDB2_ERROR_INVALID, null, null,
- 'rollback cannot be done changes are auto committed', __FUNCTION__);
- }
- if (!is_null($savepoint)) {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'savepoints are not supported', __FUNCTION__);
- }
-
- $query = 'ROLLBACK TRANSACTION '.$this->options['base_transaction_name'];
- $result =$this->_doQuery($query, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- $this->in_transaction = false;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function setTransactionIsolation()
-
- /**
- * Set the transacton isolation level.
- *
- * @param string standard isolation level
- * READ UNCOMMITTED (allows dirty reads)
- * READ COMMITTED (prevents dirty reads)
- * REPEATABLE READ (prevents nonrepeatable reads)
- * SERIALIZABLE (prevents phantom reads)
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- * @since 2.1.1
- */
- static function setTransactionIsolation($isolation,$options=array())
- {
- $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
- switch ($isolation) {
- case 'READ UNCOMMITTED':
- $isolation = 0;
- break;
- case 'READ COMMITTED':
- case 'REPEATABLE READ':
- case 'SERIALIZABLE':
- $isolation = 1;
- break;
- default:
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'isolation level is not supported: '.$isolation, __FUNCTION__);
- }
-
- $query = "PRAGMA read_uncommitted=$isolation";
- return $this->_doQuery($query, true);
- }
-
- // }}}
- // {{{ getDatabaseFile()
-
- /**
- * Builds the string with path+dbname+extension
- *
- * @return string full database path+file
- * @access protected
- */
- function _getDatabaseFile($database_name)
- {
- if ($database_name === '' || $database_name === ':memory:') {
- return $database_name;
- }
- return $this->options['database_path'].$database_name.$this->options['database_extension'];
- }
-
- // }}}
- // {{{ connect()
-
- /**
- * Connect to the database
- *
- * @return true on success, MDB2 Error Object on failure
- **/
- function connect()
- {
- $datadir=OC_Config::getValue( "datadirectory", OC::$SERVERROOT."/data" );
- $database_file = $this->_getDatabaseFile($this->database_name);
- if (is_resource($this->connection)) {
- //if (count(array_diff($this->connected_dsn, $this->dsn)) == 0
- if (MDB2::areEquals($this->connected_dsn, $this->dsn)
- && $this->connected_database_name == $database_file
- && $this->opened_persistent == $this->options['persistent']
- ) {
- return MDB2_OK;
- }
- $this->disconnect(false);
- }
-
- if (!PEAR::loadExtension($this->phptype)) {
- return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__);
- }
-
- if (empty($this->database_name)) {
- return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
- 'unable to establish a connection', __FUNCTION__);
- }
-
- if ($database_file !== ':memory:') {
- if(!strpos($database_file,'.db')){
- $database_file="$datadir/$database_file.db";
- }
- if (!file_exists($database_file)) {
- if (!touch($database_file)) {
- return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'Could not create database file', __FUNCTION__);
- }
- if (!isset($this->dsn['mode'])
- || !is_numeric($this->dsn['mode'])
- ) {
- $mode = 0644;
- } else {
- $mode = octdec($this->dsn['mode']);
- }
- if (!chmod($database_file, $mode)) {
- return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'Could not be chmodded database file', __FUNCTION__);
- }
- if (!file_exists($database_file)) {
- return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'Could not be found database file', __FUNCTION__);
- }
- }
- if (!is_file($database_file)) {
- return $this->raiseError(MDB2_ERROR_INVALID, null, null,
- 'Database is a directory name', __FUNCTION__);
- }
- if (!is_readable($database_file)) {
- return $this->raiseError(MDB2_ERROR_ACCESS_VIOLATION, null, null,
- 'Could not read database file', __FUNCTION__);
- }
- }
-
- $connect_function = ($this->options['persistent'] ? 'sqlite_popen' : 'sqlite_open');
- $php_errormsg = '';
- if (version_compare('5.1.0', PHP_VERSION, '>')) {
- @ini_set('track_errors', true);
- echo 1;
- $connection = @$connect_function($database_file);
- echo 2;
- @ini_restore('track_errors');
- } else {
- $connection = @$connect_function($database_file, 0666, $php_errormsg);
- }
- $this->_lasterror = $php_errormsg;
- if (!$connection) {
- return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
- 'unable to establish a connection', __FUNCTION__);
- }
-
- if ($this->fix_assoc_fields_names ||
- $this->options['portability'] & MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES)
- {
- @sqlite_query("PRAGMA short_column_names = 1", $connection);
- $this->fix_assoc_fields_names = true;
- }
-
- $this->connection = $connection;
- $this->connected_dsn = $this->dsn;
- $this->connected_database_name = $database_file;
- $this->opened_persistent = $this->getoption('persistent');
- $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
-
- return MDB2_OK;
- }
-
- // }}}
- // {{{ databaseExists()
-
- /**
- * check if given database name is exists?
- *
- * @param string $name name of the database that should be checked
- *
- * @return mixed true/false on success, a MDB2 error on failure
- * @access public
- */
- function databaseExists($name)
- {
- $database_file = $this->_getDatabaseFile($name);
- $result = file_exists($database_file);
- return $result;
- }
-
- // }}}
- // {{{ disconnect()
-
- /**
- * Log out and disconnect from the database.
- *
- * @param boolean $force if the disconnect should be forced even if the
- * connection is opened persistently
- * @return mixed true on success, false if not connected and error
- * object on error
- * @access public
- */
- function disconnect($force = true)
- {
- if (is_resource($this->connection)) {
- if ($this->in_transaction) {
- $dsn = $this->dsn;
- $database_name = $this->database_name;
- $persistent = $this->options['persistent'];
- $this->dsn = $this->connected_dsn;
- $this->database_name = $this->connected_database_name;
- $this->options['persistent'] = $this->opened_persistent;
- $this->rollback();
- $this->dsn = $dsn;
- $this->database_name = $database_name;
- $this->options['persistent'] = $persistent;
- }
-
- if (!$this->opened_persistent || $force) {
- @sqlite_close($this->connection);
- }
- } else {
- return false;
- }
- return parent::disconnect($force);
- }
-
- // }}}
- // {{{ _doQuery()
-
- /**
- * Execute a query
- * @param string $query query
- * @param boolean $is_manip if the query is a manipulation query
- * @param resource $connection
- * @param string $database_name
- * @return result or error object
- * @access protected
- */
- function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null)
- {
- $this->last_query = $query;
- $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
- if ($result) {
- if (PEAR::isError($result)) {
- return $result;
- }
- $query = $result;
- }
- if ($this->options['disable_query']) {
- $result = $is_manip ? 0 : null;
- return $result;
- }
-
- if (is_null($connection)) {
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- }
-
- $function = $this->options['result_buffering']
- ? 'sqlite_query' : 'sqlite_unbuffered_query';
- $php_errormsg = '';
- if (version_compare('5.1.0', PHP_VERSION, '>')) {
- @ini_set('track_errors', true);
- do {
- $result = @$function($query.';', $connection);
- } while (sqlite_last_error($connection) == SQLITE_SCHEMA);
- @ini_restore('track_errors');
- } else {
- do {
- $result = @$function($query.';', $connection, SQLITE_BOTH, $php_errormsg);
- } while (sqlite_last_error($connection) == SQLITE_SCHEMA);
- }
- $this->_lasterror = $php_errormsg;
-
- if (!$result) {
- $err =$this->raiseError(null, null, null,
- 'Could not execute statement', __FUNCTION__);
- return $err;
- }
-
- $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result));
- return $result;
- }
-
- // }}}
- // {{{ _affectedRows()
-
- /**
- * Returns the number of rows affected
- *
- * @param resource $result
- * @param resource $connection
- * @return mixed MDB2 Error Object or the number of rows affected
- * @access private
- */
- function _affectedRows($connection, $result = null)
- {
- if (is_null($connection)) {
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- }
- return @sqlite_changes($connection);
- }
-
- // }}}
- // {{{ _modifyQuery()
-
- /**
- * Changes a query string for various DBMS specific reasons
- *
- * @param string $query query to modify
- * @param boolean $is_manip if it is a DML query
- * @param integer $limit limit the number of rows
- * @param integer $offset start reading from given offset
- * @return string modified query
- * @access protected
- */
- function _modifyQuery($query, $is_manip, $limit, $offset)
- {
- if ($this->options['portability'] & MDB2_PORTABILITY_DELETE_COUNT) {
- if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) {
- $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
- 'DELETE FROM \1 WHERE 1=1', $query);
- }
- }
- if ($limit > 0
- && !preg_match('/LIMIT\s*\d(?:\s*(?:,|OFFSET)\s*\d+)?(?:[^\)]*)?$/i', $query)
- ) {
- $query = rtrim($query);
- if (substr($query, -1) == ';') {
- $query = substr($query, 0, -1);
- }
- if ($is_manip) {
- $query.= " LIMIT $limit";
- } else {
- $query.= " LIMIT $offset,$limit";
- }
- }
- return $query;
- }
-
- // }}}
- // {{{ getServerVersion()
-
- /**
- * return version information about the server
- *
- * @param bool $native determines if the raw version string should be returned
- * @return mixed array/string with version information or MDB2 error object
- * @access public
- */
- function getServerVersion($native = false)
- {
- $server_info = false;
- if ($this->connected_server_info) {
- $server_info = $this->connected_server_info;
- } elseif ($this->options['server_version']) {
- $server_info = $this->options['server_version'];
- } elseif (function_exists('sqlite_libversion')) {
- $server_info = @sqlite_libversion();
- }
- if (!$server_info) {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'Requires either the "server_version" option or the sqlite_libversion() function', __FUNCTION__);
- }
- // cache server_info
- $this->connected_server_info = $server_info;
- if (!$native) {
- $tmp = explode('.', $server_info, 3);
- $server_info = array(
- 'major' => isset($tmp[0]) ? $tmp[0] : null,
- 'minor' => isset($tmp[1]) ? $tmp[1] : null,
- 'patch' => isset($tmp[2]) ? $tmp[2] : null,
- 'extra' => null,
- 'native' => $server_info,
- );
- }
- return $server_info;
- }
-
- // }}}
- // {{{ replace()
-
- /**
- * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
- * query, except that if there is already a row in the table with the same
- * key field values, the old row is deleted before the new row is inserted.
- *
- * The REPLACE type of query does not make part of the SQL standards. Since
- * practically only SQLite implements it natively, this type of query is
- * emulated through this method for other DBMS using standard types of
- * queries inside a transaction to assure the atomicity of the operation.
- *
- * @access public
- *
- * @param string $table name of the table on which the REPLACE query will
- * be executed.
- * @param array $fields associative array that describes the fields and the
- * values that will be inserted or updated in the specified table. The
- * indexes of the array are the names of all the fields of the table. The
- * values of the array are also associative arrays that describe the
- * values and other properties of the table fields.
- *
- * Here follows a list of field properties that need to be specified:
- *
- * value:
- * Value to be assigned to the specified field. This value may be
- * of specified in database independent type format as this
- * function can perform the necessary datatype conversions.
- *
- * Default:
- * this property is required unless the Null property
- * is set to 1.
- *
- * type
- * Name of the type of the field. Currently, all types Metabase
- * are supported except for clob and blob.
- *
- * Default: no type conversion
- *
- * null
- * Boolean property that indicates that the value for this field
- * should be set to null.
- *
- * The default value for fields missing in INSERT queries may be
- * specified the definition of a table. Often, the default value
- * is already null, but since the REPLACE may be emulated using
- * an UPDATE query, make sure that all fields of the table are
- * listed in this function argument array.
- *
- * Default: 0
- *
- * key
- * Boolean property that indicates that this field should be
- * handled as a primary key or at least as part of the compound
- * unique index of the table that will determine the row that will
- * updated if it exists or inserted a new row otherwise.
- *
- * This function will fail if no key field is specified or if the
- * value of a key field is set to null because fields that are
- * part of unique index they may not be null.
- *
- * Default: 0
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- */
- function replace($table, $fields)
- {
- $count = count($fields);
- $query = $values = '';
- $keys = $colnum = 0;
- for (reset($fields); $colnum < $count; next($fields), $colnum++) {
- $name = key($fields);
- if ($colnum > 0) {
- $query .= ',';
- $values.= ',';
- }
- $query.= $this->quoteIdentifier($name, true);
- if (isset($fields[$name]['null']) && $fields[$name]['null']) {
- $value = 'NULL';
- } else {
- $type = isset($fields[$name]['type']) ? $fields[$name]['type'] : null;
- $value = $this->quote($fields[$name]['value'], $type);
- if (PEAR::isError($value)) {
- return $value;
- }
- }
- $values.= $value;
- if (isset($fields[$name]['key']) && $fields[$name]['key']) {
- if ($value === 'NULL') {
- return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
- 'key value '.$name.' may not be NULL', __FUNCTION__);
- }
- $keys++;
- }
- }
- if ($keys == 0) {
- return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
- 'not specified which fields are keys', __FUNCTION__);
- }
-
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- $table = $this->quoteIdentifier($table, true);
- $query = "REPLACE INTO $table ($query) VALUES ($values)";
- $result =$this->_doQuery($query, true, $connection);
- if (PEAR::isError($result)) {
- return $result;
- }
- return $this->_affectedRows($connection, $result);
- }
-
- // }}}
- // {{{ nextID()
-
- /**
- * Returns the next free id of a sequence
- *
- * @param string $seq_name name of the sequence
- * @param boolean $ondemand when true the sequence is
- * automatic created, if it
- * not exists
- *
- * @return mixed MDB2 Error Object or id
- * @access public
- */
- function nextID($seq_name, $ondemand = true)
- {
- $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
- $seqcol_name = $this->options['seqcol_name'];
- $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (NULL)";
- $this->pushErrorHandling(PEAR_ERROR_RETURN);
- $this->expectError(MDB2_ERROR_NOSUCHTABLE);
- $result =$this->_doQuery($query, true);
- $this->popExpect();
- $this->popErrorHandling();
- if (PEAR::isError($result)) {
- if ($ondemand && $result->getCode() == MDB2_ERROR_NOSUCHTABLE) {
- $this->loadModule('Manager', null, true);
- $result = $this->manager->createSequence($seq_name);
- if (PEAR::isError($result)) {
- return $this->raiseError($result, null, null,
- 'on demand sequence '.$seq_name.' could not be created', __FUNCTION__);
- } else {
- return $this->nextID($seq_name, false);
- }
- }
- return $result;
- }
- $value = $this->lastInsertID();
- if (is_numeric($value)) {
- $query = "DELETE FROM $sequence_name WHERE $seqcol_name < $value";
- $result =$this->_doQuery($query, true);
- if (PEAR::isError($result)) {
- $this->warnings[] = 'nextID: could not delete previous sequence table values from '.$seq_name;
- }
- }
- return $value;
- }
-
- // }}}
- // {{{ lastInsertID()
-
- /**
- * Returns the autoincrement ID if supported or $id or fetches the current
- * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
- *
- * @param string $table name of the table into which a new row was inserted
- * @param string $field name of the field into which a new row was inserted
- * @return mixed MDB2 Error Object or id
- * @access public
- */
- function lastInsertID($table = null, $field = null)
- {
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- $value = @sqlite_last_insert_rowid($connection);
- if (!$value) {
- return $this->raiseError(null, null, null,
- 'Could not get last insert ID', __FUNCTION__);
- }
- return $value;
- }
-
- // }}}
- // {{{ currID()
-
- /**
- * Returns the current id of a sequence
- *
- * @param string $seq_name name of the sequence
- * @return mixed MDB2 Error Object or id
- * @access public
- */
- function currID($seq_name)
- {
- $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
- $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true);
- $query = "SELECT MAX($seqcol_name) FROM $sequence_name";
- return $this->queryOne($query, 'integer');
- }
-}
-
-/**
- * MDB2 SQLite result driver
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Result_sqlite extends MDB2_Result_Common
-{
- // }}}
- // {{{ fetchRow()
-
- /**
- * Fetch a row and insert the data into an existing array.
- *
- * @param int $fetchmode how the array data should be indexed
- * @param int $rownum number of the row where the data can be found
- * @return int data array on success, a MDB2 error on failure
- * @access public
- */
- function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
- {
- if (!is_null($rownum)) {
- $seek = $this->seek($rownum);
- if (PEAR::isError($seek)) {
- return $seek;
- }
- }
- if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
- $fetchmode = $this->db->fetchmode;
- }
- if ($fetchmode & MDB2_FETCHMODE_ASSOC) {
- $row = @sqlite_fetch_array($this->result, SQLITE_ASSOC);
- if (is_array($row)
- && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
- ) {
- $row = array_change_key_case($row, $this->db->options['field_case']);
- }
- } else {
- $row = @sqlite_fetch_array($this->result, SQLITE_NUM);
- }
- if (!$row) {
- if ($this->result === false) {
- $err =$this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- return $err;
- }
- $null = null;
- return $null;
- }
- $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL;
- $rtrim = false;
- if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) {
- if (empty($this->types)) {
- $mode += MDB2_PORTABILITY_RTRIM;
- } else {
- $rtrim = true;
- }
- }
- if ($mode) {
- $this->db->_fixResultArrayValues($row, $mode);
- }
- if (!empty($this->types)) {
- $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim);
- }
- if (!empty($this->values)) {
- $this->_assignBindColumns($row);
- }
- if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
- $object_class = $this->db->options['fetch_class'];
- if ($object_class == 'stdClass') {
- $row = (object) $row;
- } else {
- $row = new $object_class($row);
- }
- }
- ++$this->rownum;
- return $row;
- }
-
- // }}}
- // {{{ _getColumnNames()
-
- /**
- * Retrieve the names of columns returned by the DBMS in a query result.
- *
- * @return mixed Array variable that holds the names of columns as keys
- * or an MDB2 error on failure.
- * Some DBMS may not return any columns when the result set
- * does not contain any rows.
- * @access private
- */
- function _getColumnNames()
- {
- $columns = array();
- $numcols = $this->numCols();
- if (PEAR::isError($numcols)) {
- return $numcols;
- }
- for ($column = 0; $column < $numcols; $column++) {
- $column_name = @sqlite_field_name($this->result, $column);
- $columns[$column_name] = $column;
- }
- if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $columns = array_change_key_case($columns, $this->db->options['field_case']);
- }
- return $columns;
- }
-
- // }}}
- // {{{ numCols()
-
- /**
- * Count the number of columns returned by the DBMS in a query result.
- *
- * @access public
- * @return mixed integer value with the number of columns, a MDB2 error
- * on failure
- */
- function numCols()
- {
- $cols = @sqlite_num_fields($this->result);
- if (is_null($cols)) {
- if ($this->result === false) {
- return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- } elseif (is_null($this->result)) {
- return count($this->types);
- }
- return $this->db->raiseError(null, null, null,
- 'Could not get column count', __FUNCTION__);
- }
- return $cols;
- }
-}
-
-/**
- * MDB2 SQLite buffered result driver
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_BufferedResult_sqlite extends MDB2_Result_sqlite
-{
- // {{{ seek()
-
- /**
- * Seek to a specific row in a result set
- *
- * @param int $rownum number of the row where the data can be found
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function seek($rownum = 0)
- {
- if (!@sqlite_seek($this->result, $rownum)) {
- if ($this->result === false) {
- return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- } elseif (is_null($this->result)) {
- return MDB2_OK;
- }
- return $this->db->raiseError(MDB2_ERROR_INVALID, null, null,
- 'tried to seek to an invalid row number ('.$rownum.')', __FUNCTION__);
- }
- $this->rownum = $rownum - 1;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ valid()
-
- /**
- * Check if the end of the result set has been reached
- *
- * @return mixed true or false on sucess, a MDB2 error on failure
- * @access public
- */
- function valid()
- {
- $numrows = $this->numRows();
- if (PEAR::isError($numrows)) {
- return $numrows;
- }
- return $this->rownum < ($numrows - 1);
- }
-
- // }}}
- // {{{ numRows()
-
- /**
- * Returns the number of rows in a result object
- *
- * @return mixed MDB2 Error Object or the number of rows
- * @access public
- */
- function numRows()
- {
- $rows = @sqlite_num_rows($this->result);
- if (is_null($rows)) {
- if ($this->result === false) {
- return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- } elseif (is_null($this->result)) {
- return 0;
- }
- return $this->db->raiseError(null, null, null,
- 'Could not get row count', __FUNCTION__);
- }
- return $rows;
- }
-}
-
-/**
- * MDB2 SQLite statement driver
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Statement_sqlite extends MDB2_Statement_Common
-{
-
-}
-
-?>
+ |
+// +----------------------------------------------------------------------+
+//
+// $Id: sqlite.php 295587 2010-02-28 17:16:38Z quipo $
+//
+
+/**
+ * MDB2 SQLite driver
+ *
+ * @package MDB2
+ * @category Database
+ * @author Lukas Smith
+ */
+class MDB2_Driver_sqlite extends MDB2_Driver_Common
+{
+ // {{{ properties
+ var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => "'", 'escape_pattern' => false);
+
+ var $identifier_quoting = array('start' => '"', 'end' => '"', 'escape' => '"');
+
+ var $_lasterror = '';
+
+ var $fix_assoc_fields_names = false;
+
+ // }}}
+ // {{{ constructor
+
+ /**
+ * Constructor
+ */
+ function __construct()
+ {
+ parent::__construct();
+
+ $this->phptype = 'sqlite';
+ $this->dbsyntax = 'sqlite';
+
+ $this->supported['sequences'] = 'emulated';
+ $this->supported['indexes'] = true;
+ $this->supported['affected_rows'] = true;
+ $this->supported['summary_functions'] = true;
+ $this->supported['order_by_text'] = true;
+ $this->supported['current_id'] = 'emulated';
+ $this->supported['limit_queries'] = true;
+ $this->supported['LOBs'] = true;
+ $this->supported['replace'] = true;
+ $this->supported['transactions'] = true;
+ $this->supported['savepoints'] = false;
+ $this->supported['sub_selects'] = true;
+ $this->supported['triggers'] = true;
+ $this->supported['auto_increment'] = true;
+ $this->supported['primary_key'] = false; // requires alter table implementation
+ $this->supported['result_introspection'] = false; // not implemented
+ $this->supported['prepared_statements'] = 'emulated';
+ $this->supported['identifier_quoting'] = true;
+ $this->supported['pattern_escaping'] = false;
+ $this->supported['new_link'] = false;
+
+ $this->options['DBA_username'] = false;
+ $this->options['DBA_password'] = false;
+ $this->options['base_transaction_name'] = '___php_MDB2_sqlite_auto_commit_off';
+ $this->options['fixed_float'] = 0;
+ $this->options['database_path'] = '';
+ $this->options['database_extension'] = '';
+ $this->options['server_version'] = '';
+ $this->options['max_identifiers_length'] = 128; //no real limit
+ }
+
+ // }}}
+ // {{{ errorInfo()
+
+ /**
+ * This method is used to collect information about an error
+ *
+ * @param integer $error
+ * @return array
+ * @access public
+ */
+ function errorInfo($error = null)
+ {
+ $native_code = null;
+ if ($this->connection) {
+ $native_code = @sqlite_last_error($this->connection);
+ }
+ $native_msg = $this->_lasterror
+ ? html_entity_decode($this->_lasterror) : @sqlite_error_string($native_code);
+
+ // PHP 5.2+ prepends the function name to $php_errormsg, so we need
+ // this hack to work around it, per bug #9599.
+ $native_msg = preg_replace('/^sqlite[a-z_]+\(\)[^:]*: /', '', $native_msg);
+
+ if (null === $error) {
+ static $error_regexps;
+ if (empty($error_regexps)) {
+ $error_regexps = array(
+ '/^no such table:/' => MDB2_ERROR_NOSUCHTABLE,
+ '/^no such index:/' => MDB2_ERROR_NOT_FOUND,
+ '/^(table|index) .* already exists$/' => MDB2_ERROR_ALREADY_EXISTS,
+ '/PRIMARY KEY must be unique/i' => MDB2_ERROR_CONSTRAINT,
+ '/is not unique/' => MDB2_ERROR_CONSTRAINT,
+ '/columns .* are not unique/i' => MDB2_ERROR_CONSTRAINT,
+ '/uniqueness constraint failed/' => MDB2_ERROR_CONSTRAINT,
+ '/may not be NULL/' => MDB2_ERROR_CONSTRAINT_NOT_NULL,
+ '/^no such column:/' => MDB2_ERROR_NOSUCHFIELD,
+ '/no column named/' => MDB2_ERROR_NOSUCHFIELD,
+ '/column not present in both tables/i' => MDB2_ERROR_NOSUCHFIELD,
+ '/^near ".*": syntax error$/' => MDB2_ERROR_SYNTAX,
+ '/[0-9]+ values for [0-9]+ columns/i' => MDB2_ERROR_VALUE_COUNT_ON_ROW,
+ );
+ }
+ foreach ($error_regexps as $regexp => $code) {
+ if (preg_match($regexp, $native_msg)) {
+ $error = $code;
+ break;
+ }
+ }
+ }
+ return array($error, $native_code, $native_msg);
+ }
+
+ // }}}
+ // {{{ escape()
+
+ /**
+ * Quotes a string so it can be safely used in a query. It will quote
+ * the text so it can safely be used within a query.
+ *
+ * @param string the input string to quote
+ * @param bool escape wildcards
+ *
+ * @return string quoted string
+ *
+ * @access public
+ */
+ function escape($text, $escape_wildcards = false)
+ {
+ $text = @sqlite_escape_string($text);
+ return $text;
+ }
+
+ // }}}
+ // {{{ beginTransaction()
+
+ /**
+ * Start a transaction or set a savepoint.
+ *
+ * @param string name of a savepoint to set
+ * @return mixed MDB2_OK on success, a MDB2 error on failure
+ *
+ * @access public
+ */
+ function beginTransaction($savepoint = null)
+ {
+ $this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
+ if (null !== $savepoint) {
+ return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
+ 'savepoints are not supported', __FUNCTION__);
+ }
+ if ($this->in_transaction) {
+ return MDB2_OK; //nothing to do
+ }
+ if (!$this->destructor_registered && $this->opened_persistent) {
+ $this->destructor_registered = true;
+ register_shutdown_function('MDB2_closeOpenTransactions');
+ }
+ $query = 'BEGIN TRANSACTION '.$this->options['base_transaction_name'];
+ $result = $this->_doQuery($query, true);
+ if (PEAR::isError($result)) {
+ return $result;
+ }
+ $this->in_transaction = true;
+ return MDB2_OK;
+ }
+
+ // }}}
+ // {{{ commit()
+
+ /**
+ * Commit the database changes done during a transaction that is in
+ * progress or release a savepoint. This function may only be called when
+ * auto-committing is disabled, otherwise it will fail. Therefore, a new
+ * transaction is implicitly started after committing the pending changes.
+ *
+ * @param string name of a savepoint to release
+ * @return mixed MDB2_OK on success, a MDB2 error on failure
+ *
+ * @access public
+ */
+ function commit($savepoint = null)
+ {
+ $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
+ if (!$this->in_transaction) {
+ return $this->raiseError(MDB2_ERROR_INVALID, null, null,
+ 'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__);
+ }
+ if (null !== $savepoint) {
+ return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
+ 'savepoints are not supported', __FUNCTION__);
+ }
+
+ $query = 'COMMIT TRANSACTION '.$this->options['base_transaction_name'];
+ $result = $this->_doQuery($query, true);
+ if (PEAR::isError($result)) {
+ return $result;
+ }
+ $this->in_transaction = false;
+ return MDB2_OK;
+ }
+
+ // }}}
+ // {{{
+
+ /**
+ * Cancel any database changes done during a transaction or since a specific
+ * savepoint that is in progress. This function may only be called when
+ * auto-committing is disabled, otherwise it will fail. Therefore, a new
+ * transaction is implicitly started after canceling the pending changes.
+ *
+ * @param string name of a savepoint to rollback to
+ * @return mixed MDB2_OK on success, a MDB2 error on failure
+ *
+ * @access public
+ */
+ function rollback($savepoint = null)
+ {
+ $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
+ if (!$this->in_transaction) {
+ return $this->raiseError(MDB2_ERROR_INVALID, null, null,
+ 'rollback cannot be done changes are auto committed', __FUNCTION__);
+ }
+ if (null !== $savepoint) {
+ return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
+ 'savepoints are not supported', __FUNCTION__);
+ }
+
+ $query = 'ROLLBACK TRANSACTION '.$this->options['base_transaction_name'];
+ $result = $this->_doQuery($query, true);
+ if (PEAR::isError($result)) {
+ return $result;
+ }
+ $this->in_transaction = false;
+ return MDB2_OK;
+ }
+
+ // }}}
+ // {{{ function setTransactionIsolation()
+
+ /**
+ * Set the transacton isolation level.
+ *
+ * @param string standard isolation level
+ * READ UNCOMMITTED (allows dirty reads)
+ * READ COMMITTED (prevents dirty reads)
+ * REPEATABLE READ (prevents nonrepeatable reads)
+ * SERIALIZABLE (prevents phantom reads)
+ * @param array some transaction options:
+ * 'wait' => 'WAIT' | 'NO WAIT'
+ * 'rw' => 'READ WRITE' | 'READ ONLY'
+ *
+ * @return mixed MDB2_OK on success, a MDB2 error on failure
+ *
+ * @access public
+ * @since 2.1.1
+ */
+ function setTransactionIsolation($isolation, $options = array())
+ {
+ $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
+ switch ($isolation) {
+ case 'READ UNCOMMITTED':
+ $isolation = 0;
+ break;
+ case 'READ COMMITTED':
+ case 'REPEATABLE READ':
+ case 'SERIALIZABLE':
+ $isolation = 1;
+ break;
+ default:
+ return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
+ 'isolation level is not supported: '.$isolation, __FUNCTION__);
+ }
+
+ $query = "PRAGMA read_uncommitted=$isolation";
+ return $this->_doQuery($query, true);
+ }
+
+ // }}}
+ // {{{ getDatabaseFile()
+
+ /**
+ * Builds the string with path+dbname+extension
+ *
+ * @return string full database path+file
+ * @access protected
+ */
+ function _getDatabaseFile($database_name)
+ {
+ if ($database_name === '' || $database_name === ':memory:') {
+ return $database_name;
+ }
+ return $this->options['database_path'].$database_name.$this->options['database_extension'];
+ }
+
+ // }}}
+ // {{{ connect()
+
+ /**
+ * Connect to the database
+ *
+ * @return true on success, MDB2 Error Object on failure
+ **/
+ function connect()
+ {
+ $database_file = $this->_getDatabaseFile($this->database_name);
+ if (is_resource($this->connection)) {
+ //if (count(array_diff($this->connected_dsn, $this->dsn)) == 0
+ if (MDB2::areEquals($this->connected_dsn, $this->dsn)
+ && $this->connected_database_name == $database_file
+ && $this->opened_persistent == $this->options['persistent']
+ ) {
+ return MDB2_OK;
+ }
+ $this->disconnect(false);
+ }
+
+ if (!PEAR::loadExtension($this->phptype)) {
+ return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
+ 'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__);
+ }
+
+ if (empty($this->database_name)) {
+ return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
+ 'unable to establish a connection', __FUNCTION__);
+ }
+
+ if ($database_file !== ':memory:') {
+ if (!file_exists($database_file)) {
+ if (!touch($database_file)) {
+ return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
+ 'Could not create database file', __FUNCTION__);
+ }
+ if (!isset($this->dsn['mode'])
+ || !is_numeric($this->dsn['mode'])
+ ) {
+ $mode = 0644;
+ } else {
+ $mode = octdec($this->dsn['mode']);
+ }
+ if (!chmod($database_file, $mode)) {
+ return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
+ 'Could not be chmodded database file', __FUNCTION__);
+ }
+ if (!file_exists($database_file)) {
+ return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
+ 'Could not be found database file', __FUNCTION__);
+ }
+ }
+ if (!is_file($database_file)) {
+ return $this->raiseError(MDB2_ERROR_INVALID, null, null,
+ 'Database is a directory name', __FUNCTION__);
+ }
+ if (!is_readable($database_file)) {
+ return $this->raiseError(MDB2_ERROR_ACCESS_VIOLATION, null, null,
+ 'Could not read database file', __FUNCTION__);
+ }
+ }
+
+ $connect_function = ($this->options['persistent'] ? 'sqlite_popen' : 'sqlite_open');
+ $php_errormsg = '';
+ if (version_compare('5.1.0', PHP_VERSION, '>')) {
+ @ini_set('track_errors', true);
+ $connection = @$connect_function($database_file);
+ @ini_restore('track_errors');
+ } else {
+ $connection = @$connect_function($database_file, 0666, $php_errormsg);
+ }
+ $this->_lasterror = $php_errormsg;
+ if (!$connection) {
+ return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
+ 'unable to establish a connection', __FUNCTION__);
+ }
+
+ if ($this->fix_assoc_fields_names ||
+ $this->options['portability'] & MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES)
+ {
+ @sqlite_query("PRAGMA short_column_names = 1", $connection);
+ $this->fix_assoc_fields_names = true;
+ }
+
+ $this->connection = $connection;
+ $this->connected_dsn = $this->dsn;
+ $this->connected_database_name = $database_file;
+ $this->opened_persistent = $this->getoption('persistent');
+ $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
+
+ return MDB2_OK;
+ }
+
+ // }}}
+ // {{{ databaseExists()
+
+ /**
+ * check if given database name is exists?
+ *
+ * @param string $name name of the database that should be checked
+ *
+ * @return mixed true/false on success, a MDB2 error on failure
+ * @access public
+ */
+ function databaseExists($name)
+ {
+ $database_file = $this->_getDatabaseFile($name);
+ $result = file_exists($database_file);
+ return $result;
+ }
+
+ // }}}
+ // {{{ disconnect()
+
+ /**
+ * Log out and disconnect from the database.
+ *
+ * @param boolean $force if the disconnect should be forced even if the
+ * connection is opened persistently
+ * @return mixed true on success, false if not connected and error
+ * object on error
+ * @access public
+ */
+ function disconnect($force = true)
+ {
+ if (is_resource($this->connection)) {
+ if ($this->in_transaction) {
+ $dsn = $this->dsn;
+ $database_name = $this->database_name;
+ $persistent = $this->options['persistent'];
+ $this->dsn = $this->connected_dsn;
+ $this->database_name = $this->connected_database_name;
+ $this->options['persistent'] = $this->opened_persistent;
+ $this->rollback();
+ $this->dsn = $dsn;
+ $this->database_name = $database_name;
+ $this->options['persistent'] = $persistent;
+ }
+
+ if (!$this->opened_persistent || $force) {
+ @sqlite_close($this->connection);
+ }
+ } else {
+ return false;
+ }
+ return parent::disconnect($force);
+ }
+
+ // }}}
+ // {{{ _doQuery()
+
+ /**
+ * Execute a query
+ * @param string $query query
+ * @param boolean $is_manip if the query is a manipulation query
+ * @param resource $connection
+ * @param string $database_name
+ * @return result or error object
+ * @access protected
+ */
+ function _doQuery($query, $is_manip = false, $connection = null, $database_name = null)
+ {
+ $this->last_query = $query;
+ $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
+ if ($result) {
+ if (PEAR::isError($result)) {
+ return $result;
+ }
+ $query = $result;
+ }
+ if ($this->options['disable_query']) {
+ $result = $is_manip ? 0 : null;
+ return $result;
+ }
+
+ if (null === $connection) {
+ $connection = $this->getConnection();
+ if (PEAR::isError($connection)) {
+ return $connection;
+ }
+ }
+
+ $function = $this->options['result_buffering']
+ ? 'sqlite_query' : 'sqlite_unbuffered_query';
+ $php_errormsg = '';
+ if (version_compare('5.1.0', PHP_VERSION, '>')) {
+ @ini_set('track_errors', true);
+ do {
+ $result = @$function($query.';', $connection);
+ } while (sqlite_last_error($connection) == SQLITE_SCHEMA);
+ @ini_restore('track_errors');
+ } else {
+ do {
+ $result = @$function($query.';', $connection, SQLITE_BOTH, $php_errormsg);
+ } while (sqlite_last_error($connection) == SQLITE_SCHEMA);
+ }
+ $this->_lasterror = $php_errormsg;
+
+ if (!$result) {
+ $code = null;
+ if (0 === strpos($this->_lasterror, 'no such table')) {
+ $code = MDB2_ERROR_NOSUCHTABLE;
+ }
+ $err = $this->raiseError($code, null, null,
+ 'Could not execute statement', __FUNCTION__);
+ return $err;
+ }
+
+ $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result));
+ return $result;
+ }
+
+ // }}}
+ // {{{ _affectedRows()
+
+ /**
+ * Returns the number of rows affected
+ *
+ * @param resource $result
+ * @param resource $connection
+ * @return mixed MDB2 Error Object or the number of rows affected
+ * @access private
+ */
+ function _affectedRows($connection, $result = null)
+ {
+ if (null === $connection) {
+ $connection = $this->getConnection();
+ if (PEAR::isError($connection)) {
+ return $connection;
+ }
+ }
+ return @sqlite_changes($connection);
+ }
+
+ // }}}
+ // {{{ _modifyQuery()
+
+ /**
+ * Changes a query string for various DBMS specific reasons
+ *
+ * @param string $query query to modify
+ * @param boolean $is_manip if it is a DML query
+ * @param integer $limit limit the number of rows
+ * @param integer $offset start reading from given offset
+ * @return string modified query
+ * @access protected
+ */
+ function _modifyQuery($query, $is_manip, $limit, $offset)
+ {
+ if ($this->options['portability'] & MDB2_PORTABILITY_DELETE_COUNT) {
+ if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) {
+ $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
+ 'DELETE FROM \1 WHERE 1=1', $query);
+ }
+ }
+ if ($limit > 0
+ && !preg_match('/LIMIT\s*\d(?:\s*(?:,|OFFSET)\s*\d+)?(?:[^\)]*)?$/i', $query)
+ ) {
+ $query = rtrim($query);
+ if (substr($query, -1) == ';') {
+ $query = substr($query, 0, -1);
+ }
+ if ($is_manip) {
+ $query.= " LIMIT $limit";
+ } else {
+ $query.= " LIMIT $offset,$limit";
+ }
+ }
+ return $query;
+ }
+
+ // }}}
+ // {{{ getServerVersion()
+
+ /**
+ * return version information about the server
+ *
+ * @param bool $native determines if the raw version string should be returned
+ * @return mixed array/string with version information or MDB2 error object
+ * @access public
+ */
+ function getServerVersion($native = false)
+ {
+ $server_info = false;
+ if ($this->connected_server_info) {
+ $server_info = $this->connected_server_info;
+ } elseif ($this->options['server_version']) {
+ $server_info = $this->options['server_version'];
+ } elseif (function_exists('sqlite_libversion')) {
+ $server_info = @sqlite_libversion();
+ }
+ if (!$server_info) {
+ return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
+ 'Requires either the "server_version" option or the sqlite_libversion() function', __FUNCTION__);
+ }
+ // cache server_info
+ $this->connected_server_info = $server_info;
+ if (!$native) {
+ $tmp = explode('.', $server_info, 3);
+ $server_info = array(
+ 'major' => isset($tmp[0]) ? $tmp[0] : null,
+ 'minor' => isset($tmp[1]) ? $tmp[1] : null,
+ 'patch' => isset($tmp[2]) ? $tmp[2] : null,
+ 'extra' => null,
+ 'native' => $server_info,
+ );
+ }
+ return $server_info;
+ }
+
+ // }}}
+ // {{{ replace()
+
+ /**
+ * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
+ * query, except that if there is already a row in the table with the same
+ * key field values, the old row is deleted before the new row is inserted.
+ *
+ * The REPLACE type of query does not make part of the SQL standards. Since
+ * practically only SQLite implements it natively, this type of query is
+ * emulated through this method for other DBMS using standard types of
+ * queries inside a transaction to assure the atomicity of the operation.
+ *
+ * @access public
+ *
+ * @param string $table name of the table on which the REPLACE query will
+ * be executed.
+ * @param array $fields associative array that describes the fields and the
+ * values that will be inserted or updated in the specified table. The
+ * indexes of the array are the names of all the fields of the table. The
+ * values of the array are also associative arrays that describe the
+ * values and other properties of the table fields.
+ *
+ * Here follows a list of field properties that need to be specified:
+ *
+ * value:
+ * Value to be assigned to the specified field. This value may be
+ * of specified in database independent type format as this
+ * function can perform the necessary datatype conversions.
+ *
+ * Default:
+ * this property is required unless the Null property
+ * is set to 1.
+ *
+ * type
+ * Name of the type of the field. Currently, all types Metabase
+ * are supported except for clob and blob.
+ *
+ * Default: no type conversion
+ *
+ * null
+ * Boolean property that indicates that the value for this field
+ * should be set to null.
+ *
+ * The default value for fields missing in INSERT queries may be
+ * specified the definition of a table. Often, the default value
+ * is already null, but since the REPLACE may be emulated using
+ * an UPDATE query, make sure that all fields of the table are
+ * listed in this function argument array.
+ *
+ * Default: 0
+ *
+ * key
+ * Boolean property that indicates that this field should be
+ * handled as a primary key or at least as part of the compound
+ * unique index of the table that will determine the row that will
+ * updated if it exists or inserted a new row otherwise.
+ *
+ * This function will fail if no key field is specified or if the
+ * value of a key field is set to null because fields that are
+ * part of unique index they may not be null.
+ *
+ * Default: 0
+ *
+ * @return mixed MDB2_OK on success, a MDB2 error on failure
+ */
+ function replace($table, $fields)
+ {
+ $count = count($fields);
+ $query = $values = '';
+ $keys = $colnum = 0;
+ for (reset($fields); $colnum < $count; next($fields), $colnum++) {
+ $name = key($fields);
+ if ($colnum > 0) {
+ $query .= ',';
+ $values.= ',';
+ }
+ $query.= $this->quoteIdentifier($name, true);
+ if (isset($fields[$name]['null']) && $fields[$name]['null']) {
+ $value = 'NULL';
+ } else {
+ $type = isset($fields[$name]['type']) ? $fields[$name]['type'] : null;
+ $value = $this->quote($fields[$name]['value'], $type);
+ if (PEAR::isError($value)) {
+ return $value;
+ }
+ }
+ $values.= $value;
+ if (isset($fields[$name]['key']) && $fields[$name]['key']) {
+ if ($value === 'NULL') {
+ return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
+ 'key value '.$name.' may not be NULL', __FUNCTION__);
+ }
+ $keys++;
+ }
+ }
+ if ($keys == 0) {
+ return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
+ 'not specified which fields are keys', __FUNCTION__);
+ }
+
+ $connection = $this->getConnection();
+ if (PEAR::isError($connection)) {
+ return $connection;
+ }
+
+ $table = $this->quoteIdentifier($table, true);
+ $query = "REPLACE INTO $table ($query) VALUES ($values)";
+ $result = $this->_doQuery($query, true, $connection);
+ if (PEAR::isError($result)) {
+ return $result;
+ }
+ return $this->_affectedRows($connection, $result);
+ }
+
+ // }}}
+ // {{{ nextID()
+
+ /**
+ * Returns the next free id of a sequence
+ *
+ * @param string $seq_name name of the sequence
+ * @param boolean $ondemand when true the sequence is
+ * automatic created, if it
+ * not exists
+ *
+ * @return mixed MDB2 Error Object or id
+ * @access public
+ */
+ function nextID($seq_name, $ondemand = true)
+ {
+ $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
+ $seqcol_name = $this->options['seqcol_name'];
+ $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (NULL)";
+ $this->pushErrorHandling(PEAR_ERROR_RETURN);
+ $this->expectError(MDB2_ERROR_NOSUCHTABLE);
+ $result = $this->_doQuery($query, true);
+ $this->popExpect();
+ $this->popErrorHandling();
+ if (PEAR::isError($result)) {
+ if ($ondemand && $result->getCode() == MDB2_ERROR_NOSUCHTABLE) {
+ $this->loadModule('Manager', null, true);
+ $result = $this->manager->createSequence($seq_name);
+ if (PEAR::isError($result)) {
+ return $this->raiseError($result, null, null,
+ 'on demand sequence '.$seq_name.' could not be created', __FUNCTION__);
+ } else {
+ return $this->nextID($seq_name, false);
+ }
+ }
+ return $result;
+ }
+ $value = $this->lastInsertID();
+ if (is_numeric($value)) {
+ $query = "DELETE FROM $sequence_name WHERE $seqcol_name < $value";
+ $result = $this->_doQuery($query, true);
+ if (PEAR::isError($result)) {
+ $this->warnings[] = 'nextID: could not delete previous sequence table values from '.$seq_name;
+ }
+ }
+ return $value;
+ }
+
+ // }}}
+ // {{{ lastInsertID()
+
+ /**
+ * Returns the autoincrement ID if supported or $id or fetches the current
+ * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
+ *
+ * @param string $table name of the table into which a new row was inserted
+ * @param string $field name of the field into which a new row was inserted
+ * @return mixed MDB2 Error Object or id
+ * @access public
+ */
+ function lastInsertID($table = null, $field = null)
+ {
+ $connection = $this->getConnection();
+ if (PEAR::isError($connection)) {
+ return $connection;
+ }
+ $value = @sqlite_last_insert_rowid($connection);
+ if (!$value) {
+ return $this->raiseError(null, null, null,
+ 'Could not get last insert ID', __FUNCTION__);
+ }
+ return $value;
+ }
+
+ // }}}
+ // {{{ currID()
+
+ /**
+ * Returns the current id of a sequence
+ *
+ * @param string $seq_name name of the sequence
+ * @return mixed MDB2 Error Object or id
+ * @access public
+ */
+ function currID($seq_name)
+ {
+ $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
+ $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true);
+ $query = "SELECT MAX($seqcol_name) FROM $sequence_name";
+ return $this->queryOne($query, 'integer');
+ }
+}
+
+/**
+ * MDB2 SQLite result driver
+ *
+ * @package MDB2
+ * @category Database
+ * @author Lukas Smith
+ */
+class MDB2_Result_sqlite extends MDB2_Result_Common
+{
+ // }}}
+ // {{{ fetchRow()
+
+ /**
+ * Fetch a row and insert the data into an existing array.
+ *
+ * @param int $fetchmode how the array data should be indexed
+ * @param int $rownum number of the row where the data can be found
+ * @return int data array on success, a MDB2 error on failure
+ * @access public
+ */
+ function fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
+ {
+ if (null !== $rownum) {
+ $seek = $this->seek($rownum);
+ if (PEAR::isError($seek)) {
+ return $seek;
+ }
+ }
+ if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
+ $fetchmode = $this->db->fetchmode;
+ }
+ if ($fetchmode & MDB2_FETCHMODE_ASSOC) {
+ $row = @sqlite_fetch_array($this->result, SQLITE_ASSOC);
+ if (is_array($row)
+ && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
+ ) {
+ $row = array_change_key_case($row, $this->db->options['field_case']);
+ }
+ } else {
+ $row = @sqlite_fetch_array($this->result, SQLITE_NUM);
+ }
+ if (!$row) {
+ if (false === $this->result) {
+ $err = $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
+ 'resultset has already been freed', __FUNCTION__);
+ return $err;
+ }
+ return null;
+ }
+ $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL;
+ $rtrim = false;
+ if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) {
+ if (empty($this->types)) {
+ $mode += MDB2_PORTABILITY_RTRIM;
+ } else {
+ $rtrim = true;
+ }
+ }
+ if ($mode) {
+ $this->db->_fixResultArrayValues($row, $mode);
+ }
+ if (!empty($this->types)) {
+ $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim);
+ }
+ if (!empty($this->values)) {
+ $this->_assignBindColumns($row);
+ }
+ if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
+ $object_class = $this->db->options['fetch_class'];
+ if ($object_class == 'stdClass') {
+ $row = (object) $row;
+ } else {
+ $rowObj = new $object_class($row);
+ $row = $rowObj;
+ }
+ }
+ ++$this->rownum;
+ return $row;
+ }
+
+ // }}}
+ // {{{ _getColumnNames()
+
+ /**
+ * Retrieve the names of columns returned by the DBMS in a query result.
+ *
+ * @return mixed Array variable that holds the names of columns as keys
+ * or an MDB2 error on failure.
+ * Some DBMS may not return any columns when the result set
+ * does not contain any rows.
+ * @access private
+ */
+ function _getColumnNames()
+ {
+ $columns = array();
+ $numcols = $this->numCols();
+ if (PEAR::isError($numcols)) {
+ return $numcols;
+ }
+ for ($column = 0; $column < $numcols; $column++) {
+ $column_name = @sqlite_field_name($this->result, $column);
+ $columns[$column_name] = $column;
+ }
+ if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
+ $columns = array_change_key_case($columns, $this->db->options['field_case']);
+ }
+ return $columns;
+ }
+
+ // }}}
+ // {{{ numCols()
+
+ /**
+ * Count the number of columns returned by the DBMS in a query result.
+ *
+ * @access public
+ * @return mixed integer value with the number of columns, a MDB2 error
+ * on failure
+ */
+ function numCols()
+ {
+ $cols = @sqlite_num_fields($this->result);
+ if (null === $cols) {
+ if (false === $this->result) {
+ return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
+ 'resultset has already been freed', __FUNCTION__);
+ }
+ if (null === $this->result) {
+ return count($this->types);
+ }
+ return $this->db->raiseError(null, null, null,
+ 'Could not get column count', __FUNCTION__);
+ }
+ return $cols;
+ }
+}
+
+/**
+ * MDB2 SQLite buffered result driver
+ *
+ * @package MDB2
+ * @category Database
+ * @author Lukas Smith
+ */
+class MDB2_BufferedResult_sqlite extends MDB2_Result_sqlite
+{
+ // {{{ seek()
+
+ /**
+ * Seek to a specific row in a result set
+ *
+ * @param int $rownum number of the row where the data can be found
+ * @return mixed MDB2_OK on success, a MDB2 error on failure
+ * @access public
+ */
+ function seek($rownum = 0)
+ {
+ if (!@sqlite_seek($this->result, $rownum)) {
+ if (false === $this->result) {
+ return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
+ 'resultset has already been freed', __FUNCTION__);
+ }
+ if (null === $this->result) {
+ return MDB2_OK;
+ }
+ return $this->db->raiseError(MDB2_ERROR_INVALID, null, null,
+ 'tried to seek to an invalid row number ('.$rownum.')', __FUNCTION__);
+ }
+ $this->rownum = $rownum - 1;
+ return MDB2_OK;
+ }
+
+ // }}}
+ // {{{ valid()
+
+ /**
+ * Check if the end of the result set has been reached
+ *
+ * @return mixed true or false on sucess, a MDB2 error on failure
+ * @access public
+ */
+ function valid()
+ {
+ $numrows = $this->numRows();
+ if (PEAR::isError($numrows)) {
+ return $numrows;
+ }
+ return $this->rownum < ($numrows - 1);
+ }
+
+ // }}}
+ // {{{ numRows()
+
+ /**
+ * Returns the number of rows in a result object
+ *
+ * @return mixed MDB2 Error Object or the number of rows
+ * @access public
+ */
+ function numRows()
+ {
+ $rows = @sqlite_num_rows($this->result);
+ if (null === $rows) {
+ if (false === $this->result) {
+ return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
+ 'resultset has already been freed', __FUNCTION__);
+ }
+ if (null === $this->result) {
+ return 0;
+ }
+ return $this->db->raiseError(null, null, null,
+ 'Could not get row count', __FUNCTION__);
+ }
+ return $rows;
+ }
+}
+
+/**
+ * MDB2 SQLite statement driver
+ *
+ * @package MDB2
+ * @category Database
+ * @author Lukas Smith
+ */
+class MDB2_Statement_sqlite extends MDB2_Statement_Common
+{
+
+}
+?>
\ No newline at end of file
diff --git a/3rdparty/MDB2/Extended.php b/3rdparty/MDB2/Extended.php
index 864ab92354..fed82f9659 100644
--- a/3rdparty/MDB2/Extended.php
+++ b/3rdparty/MDB2/Extended.php
@@ -1,721 +1,720 @@
- |
-// +----------------------------------------------------------------------+
-//
-// $Id: Extended.php,v 1.60 2007/11/28 19:49:34 quipo Exp $
-
-/**
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-
-/**
- * Used by autoPrepare()
- */
-define('MDB2_AUTOQUERY_INSERT', 1);
-define('MDB2_AUTOQUERY_UPDATE', 2);
-define('MDB2_AUTOQUERY_DELETE', 3);
-define('MDB2_AUTOQUERY_SELECT', 4);
-
-/**
- * MDB2_Extended: class which adds several high level methods to MDB2
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Extended extends MDB2_Module_Common
-{
- // {{{ autoPrepare()
-
- /**
- * Generate an insert, update or delete query and call prepare() on it
- *
- * @param string table
- * @param array the fields names
- * @param int type of query to build
- * MDB2_AUTOQUERY_INSERT
- * MDB2_AUTOQUERY_UPDATE
- * MDB2_AUTOQUERY_DELETE
- * MDB2_AUTOQUERY_SELECT
- * @param string (in case of update and delete queries, this string will be put after the sql WHERE statement)
- * @param array that contains the types of the placeholders
- * @param mixed array that contains the types of the columns in
- * the result set or MDB2_PREPARE_RESULT, if set to
- * MDB2_PREPARE_MANIP the query is handled as a manipulation query
- *
- * @return resource handle for the query
- * @see buildManipSQL
- * @access public
- */
- function autoPrepare($table, $table_fields, $mode = MDB2_AUTOQUERY_INSERT,
- $where = false, $types = null, $result_types = MDB2_PREPARE_MANIP)
- {
- $query = $this->buildManipSQL($table, $table_fields, $mode, $where);
- if (PEAR::isError($query)) {
- return $query;
- }
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- $lobs = array();
- foreach ((array)$types as $param => $type) {
- if (($type == 'clob') || ($type == 'blob')) {
- $lobs[$param] = $table_fields[$param];
- }
- }
- return $db->prepare($query, $types, $result_types, $lobs);
- }
-
- // }}}
- // {{{ autoExecute()
-
- /**
- * Generate an insert, update or delete query and call prepare() and execute() on it
- *
- * @param string name of the table
- * @param array assoc ($key=>$value) where $key is a field name and $value its value
- * @param int type of query to build
- * MDB2_AUTOQUERY_INSERT
- * MDB2_AUTOQUERY_UPDATE
- * MDB2_AUTOQUERY_DELETE
- * MDB2_AUTOQUERY_SELECT
- * @param string (in case of update and delete queries, this string will be put after the sql WHERE statement)
- * @param array that contains the types of the placeholders
- * @param string which specifies which result class to use
- * @param mixed array that contains the types of the columns in
- * the result set or MDB2_PREPARE_RESULT, if set to
- * MDB2_PREPARE_MANIP the query is handled as a manipulation query
- *
- * @return bool|MDB2_Error true on success, a MDB2 error on failure
- * @see buildManipSQL
- * @see autoPrepare
- * @access public
- */
- function &autoExecute($table, $fields_values, $mode = MDB2_AUTOQUERY_INSERT,
- $where = false, $types = null, $result_class = true, $result_types = MDB2_PREPARE_MANIP)
- {
- $fields_values = (array)$fields_values;
- if ($mode == MDB2_AUTOQUERY_SELECT) {
- if (is_array($result_types)) {
- $keys = array_keys($result_types);
- } elseif (!empty($fields_values)) {
- $keys = $fields_values;
- } else {
- $keys = array();
- }
- } else {
- $keys = array_keys($fields_values);
- }
- $params = array_values($fields_values);
- if (empty($params)) {
- $query = $this->buildManipSQL($table, $keys, $mode, $where);
-
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- if ($mode == MDB2_AUTOQUERY_SELECT) {
- $result =& $db->query($query, $result_types, $result_class);
- } else {
- $result = $db->exec($query);
- }
- } else {
- $stmt = $this->autoPrepare($table, $keys, $mode, $where, $types, $result_types);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
- $result =& $stmt->execute($params, $result_class);
- $stmt->free();
- }
- return $result;
- }
-
- // }}}
- // {{{ buildManipSQL()
-
- /**
- * Make automaticaly an sql query for prepare()
- *
- * Example : buildManipSQL('table_sql', array('field1', 'field2', 'field3'), MDB2_AUTOQUERY_INSERT)
- * will return the string : INSERT INTO table_sql (field1,field2,field3) VALUES (?,?,?)
- * NB : - This belongs more to a SQL Builder class, but this is a simple facility
- * - Be carefull ! If you don't give a $where param with an UPDATE/DELETE query, all
- * the records of the table will be updated/deleted !
- *
- * @param string name of the table
- * @param ordered array containing the fields names
- * @param int type of query to build
- * MDB2_AUTOQUERY_INSERT
- * MDB2_AUTOQUERY_UPDATE
- * MDB2_AUTOQUERY_DELETE
- * MDB2_AUTOQUERY_SELECT
- * @param string (in case of update and delete queries, this string will be put after the sql WHERE statement)
- *
- * @return string sql query for prepare()
- * @access public
- */
- function buildManipSQL($table, $table_fields, $mode, $where = false)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if ($db->options['quote_identifier']) {
- $table = $db->quoteIdentifier($table);
- }
-
- if (!empty($table_fields) && $db->options['quote_identifier']) {
- foreach ($table_fields as $key => $field) {
- $table_fields[$key] = $db->quoteIdentifier($field);
- }
- }
-
- if ($where !== false && !is_null($where)) {
- if (is_array($where)) {
- $where = implode(' AND ', $where);
- }
- $where = ' WHERE '.$where;
- }
-
- switch ($mode) {
- case MDB2_AUTOQUERY_INSERT:
- if (empty($table_fields)) {
- return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'Insert requires table fields', __FUNCTION__);
- }
- $cols = implode(', ', $table_fields);
- $values = '?'.str_repeat(', ?', (count($table_fields) - 1));
- return 'INSERT INTO '.$table.' ('.$cols.') VALUES ('.$values.')';
- break;
- case MDB2_AUTOQUERY_UPDATE:
- if (empty($table_fields)) {
- return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'Update requires table fields', __FUNCTION__);
- }
- $set = implode(' = ?, ', $table_fields).' = ?';
- $sql = 'UPDATE '.$table.' SET '.$set.$where;
- return $sql;
- break;
- case MDB2_AUTOQUERY_DELETE:
- $sql = 'DELETE FROM '.$table.$where;
- return $sql;
- break;
- case MDB2_AUTOQUERY_SELECT:
- $cols = !empty($table_fields) ? implode(', ', $table_fields) : '*';
- $sql = 'SELECT '.$cols.' FROM '.$table.$where;
- return $sql;
- break;
- }
- return $db->raiseError(MDB2_ERROR_SYNTAX, null, null,
- 'Non existant mode', __FUNCTION__);
- }
-
- // }}}
- // {{{ limitQuery()
-
- /**
- * Generates a limited query
- *
- * @param string query
- * @param array that contains the types of the columns in the result set
- * @param integer the numbers of rows to fetch
- * @param integer the row to start to fetching
- * @param string which specifies which result class to use
- * @param mixed string which specifies which class to wrap results in
- *
- * @return MDB2_Result|MDB2_Error result set on success, a MDB2 error on failure
- * @access public
- */
- function &limitQuery($query, $types, $limit, $offset = 0, $result_class = true,
- $result_wrap_class = false)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $result = $db->setLimit($limit, $offset);
- if (PEAR::isError($result)) {
- return $result;
- }
- $result =& $db->query($query, $types, $result_class, $result_wrap_class);
- return $result;
- }
-
- // }}}
- // {{{ execParam()
-
- /**
- * Execute a parameterized DML statement.
- *
- * @param string the SQL query
- * @param array if supplied, prepare/execute will be used
- * with this array as execute parameters
- * @param array that contains the types of the values defined in $params
- *
- * @return int|MDB2_Error affected rows on success, a MDB2 error on failure
- * @access public
- */
- function execParam($query, $params = array(), $param_types = null)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- settype($params, 'array');
- if (empty($params)) {
- return $db->exec($query);
- }
-
- $stmt = $db->prepare($query, $param_types, MDB2_PREPARE_MANIP);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
-
- $result = $stmt->execute($params);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- $stmt->free();
- return $result;
- }
-
- // }}}
- // {{{ getOne()
-
- /**
- * Fetch the first column of the first row of data returned from a query.
- * Takes care of doing the query and freeing the results when finished.
- *
- * @param string the SQL query
- * @param string that contains the type of the column in the result set
- * @param array if supplied, prepare/execute will be used
- * with this array as execute parameters
- * @param array that contains the types of the values defined in $params
- * @param int|string which column to return
- *
- * @return scalar|MDB2_Error data on success, a MDB2 error on failure
- * @access public
- */
- function getOne($query, $type = null, $params = array(),
- $param_types = null, $colnum = 0)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- settype($params, 'array');
- settype($type, 'array');
- if (empty($params)) {
- return $db->queryOne($query, $type, $colnum);
- }
-
- $stmt = $db->prepare($query, $param_types, $type);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
-
- $result = $stmt->execute($params);
- if (!MDB2::isResultCommon($result)) {
- return $result;
- }
-
- $one = $result->fetchOne($colnum);
- $stmt->free();
- $result->free();
- return $one;
- }
-
- // }}}
- // {{{ getRow()
-
- /**
- * Fetch the first row of data returned from a query. Takes care
- * of doing the query and freeing the results when finished.
- *
- * @param string the SQL query
- * @param array that contains the types of the columns in the result set
- * @param array if supplied, prepare/execute will be used
- * with this array as execute parameters
- * @param array that contains the types of the values defined in $params
- * @param int the fetch mode to use
- *
- * @return array|MDB2_Error data on success, a MDB2 error on failure
- * @access public
- */
- function getRow($query, $types = null, $params = array(),
- $param_types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- settype($params, 'array');
- if (empty($params)) {
- return $db->queryRow($query, $types, $fetchmode);
- }
-
- $stmt = $db->prepare($query, $param_types, $types);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
-
- $result = $stmt->execute($params);
- if (!MDB2::isResultCommon($result)) {
- return $result;
- }
-
- $row = $result->fetchRow($fetchmode);
- $stmt->free();
- $result->free();
- return $row;
- }
-
- // }}}
- // {{{ getCol()
-
- /**
- * Fetch a single column from a result set and return it as an
- * indexed array.
- *
- * @param string the SQL query
- * @param string that contains the type of the column in the result set
- * @param array if supplied, prepare/execute will be used
- * with this array as execute parameters
- * @param array that contains the types of the values defined in $params
- * @param int|string which column to return
- *
- * @return array|MDB2_Error data on success, a MDB2 error on failure
- * @access public
- */
- function getCol($query, $type = null, $params = array(),
- $param_types = null, $colnum = 0)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- settype($params, 'array');
- settype($type, 'array');
- if (empty($params)) {
- return $db->queryCol($query, $type, $colnum);
- }
-
- $stmt = $db->prepare($query, $param_types, $type);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
-
- $result = $stmt->execute($params);
- if (!MDB2::isResultCommon($result)) {
- return $result;
- }
-
- $col = $result->fetchCol($colnum);
- $stmt->free();
- $result->free();
- return $col;
- }
-
- // }}}
- // {{{ getAll()
-
- /**
- * Fetch all the rows returned from a query.
- *
- * @param string the SQL query
- * @param array that contains the types of the columns in the result set
- * @param array if supplied, prepare/execute will be used
- * with this array as execute parameters
- * @param array that contains the types of the values defined in $params
- * @param int the fetch mode to use
- * @param bool if set to true, the $all will have the first
- * column as its first dimension
- * @param bool $force_array used only when the query returns exactly
- * two columns. If true, the values of the returned array will be
- * one-element arrays instead of scalars.
- * @param bool $group if true, the values of the returned array is
- * wrapped in another array. If the same key value (in the first
- * column) repeats itself, the values will be appended to this array
- * instead of overwriting the existing values.
- *
- * @return array|MDB2_Error data on success, a MDB2 error on failure
- * @access public
- */
- function getAll($query, $types = null, $params = array(),
- $param_types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT,
- $rekey = false, $force_array = false, $group = false)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- settype($params, 'array');
- if (empty($params)) {
- return $db->queryAll($query, $types, $fetchmode, $rekey, $force_array, $group);
- }
-
- $stmt = $db->prepare($query, $param_types, $types);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
-
- $result = $stmt->execute($params);
- if (!MDB2::isResultCommon($result)) {
- return $result;
- }
-
- $all = $result->fetchAll($fetchmode, $rekey, $force_array, $group);
- $stmt->free();
- $result->free();
- return $all;
- }
-
- // }}}
- // {{{ getAssoc()
-
- /**
- * Fetch the entire result set of a query and return it as an
- * associative array using the first column as the key.
- *
- * If the result set contains more than two columns, the value
- * will be an array of the values from column 2-n. If the result
- * set contains only two columns, the returned value will be a
- * scalar with the value of the second column (unless forced to an
- * array with the $force_array parameter). A MDB2 error code is
- * returned on errors. If the result set contains fewer than two
- * columns, a MDB2_ERROR_TRUNCATED error is returned.
- *
- * For example, if the table 'mytable' contains:
- *
- * ID TEXT DATE
- * --------------------------------
- * 1 'one' 944679408
- * 2 'two' 944679408
- * 3 'three' 944679408
- *
- * Then the call getAssoc('SELECT id,text FROM mytable') returns:
- *
- * array(
- * '1' => 'one',
- * '2' => 'two',
- * '3' => 'three',
- * )
- *
- * ...while the call getAssoc('SELECT id,text,date FROM mytable') returns:
- *
- * array(
- * '1' => array('one', '944679408'),
- * '2' => array('two', '944679408'),
- * '3' => array('three', '944679408')
- * )
- *
- *
- * If the more than one row occurs with the same value in the
- * first column, the last row overwrites all previous ones by
- * default. Use the $group parameter if you don't want to
- * overwrite like this. Example:
- *
- * getAssoc('SELECT category,id,name FROM mytable', null, null
- * MDB2_FETCHMODE_ASSOC, false, true) returns:
- * array(
- * '1' => array(array('id' => '4', 'name' => 'number four'),
- * array('id' => '6', 'name' => 'number six')
- * ),
- * '9' => array(array('id' => '4', 'name' => 'number four'),
- * array('id' => '6', 'name' => 'number six')
- * )
- * )
- *
- *
- * Keep in mind that database functions in PHP usually return string
- * values for results regardless of the database's internal type.
- *
- * @param string the SQL query
- * @param array that contains the types of the columns in the result set
- * @param array if supplied, prepare/execute will be used
- * with this array as execute parameters
- * @param array that contains the types of the values defined in $params
- * @param bool $force_array used only when the query returns
- * exactly two columns. If TRUE, the values of the returned array
- * will be one-element arrays instead of scalars.
- * @param bool $group if TRUE, the values of the returned array
- * is wrapped in another array. If the same key value (in the first
- * column) repeats itself, the values will be appended to this array
- * instead of overwriting the existing values.
- *
- * @return array|MDB2_Error data on success, a MDB2 error on failure
- * @access public
- */
- function getAssoc($query, $types = null, $params = array(), $param_types = null,
- $fetchmode = MDB2_FETCHMODE_DEFAULT, $force_array = false, $group = false)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- settype($params, 'array');
- if (empty($params)) {
- return $db->queryAll($query, $types, $fetchmode, true, $force_array, $group);
- }
-
- $stmt = $db->prepare($query, $param_types, $types);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
-
- $result = $stmt->execute($params);
- if (!MDB2::isResultCommon($result)) {
- return $result;
- }
-
- $all = $result->fetchAll($fetchmode, true, $force_array, $group);
- $stmt->free();
- $result->free();
- return $all;
- }
-
- // }}}
- // {{{ executeMultiple()
-
- /**
- * This function does several execute() calls on the same statement handle.
- * $params must be an array indexed numerically from 0, one execute call is
- * done for every 'row' in the array.
- *
- * If an error occurs during execute(), executeMultiple() does not execute
- * the unfinished rows, but rather returns that error.
- *
- * @param resource query handle from prepare()
- * @param array numeric array containing the data to insert into the query
- *
- * @return bool|MDB2_Error true on success, a MDB2 error on failure
- * @access public
- * @see prepare(), execute()
- */
- function executeMultiple(&$stmt, $params = null)
- {
- for ($i = 0, $j = count($params); $i < $j; $i++) {
- $result = $stmt->execute($params[$i]);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ getBeforeID()
-
- /**
- * Returns the next free id of a sequence if the RDBMS
- * does not support auto increment
- *
- * @param string name of the table into which a new row was inserted
- * @param string name of the field into which a new row was inserted
- * @param bool when true the sequence is automatic created, if it not exists
- * @param bool if the returned value should be quoted
- *
- * @return int|MDB2_Error id on success, a MDB2 error on failure
- * @access public
- */
- function getBeforeID($table, $field = null, $ondemand = true, $quote = true)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if ($db->supports('auto_increment') !== true) {
- $seq = $table.(empty($field) ? '' : '_'.$field);
- $id = $db->nextID($seq, $ondemand);
- if (!$quote || PEAR::isError($id)) {
- return $id;
- }
- return $db->quote($id, 'integer');
- } elseif (!$quote) {
- return null;
- }
- return 'NULL';
- }
-
- // }}}
- // {{{ getAfterID()
-
- /**
- * Returns the autoincrement ID if supported or $id
- *
- * @param mixed value as returned by getBeforeId()
- * @param string name of the table into which a new row was inserted
- * @param string name of the field into which a new row was inserted
- *
- * @return int|MDB2_Error id on success, a MDB2 error on failure
- * @access public
- */
- function getAfterID($id, $table, $field = null)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if ($db->supports('auto_increment') !== true) {
- return $id;
- }
- return $db->lastInsertID($table, $field);
- }
-
- // }}}
-}
+ |
+// +----------------------------------------------------------------------+
+//
+// $Id: Extended.php 302784 2010-08-25 23:29:16Z quipo $
+
+/**
+ * @package MDB2
+ * @category Database
+ * @author Lukas Smith
+ */
+
+/**
+ * Used by autoPrepare()
+ */
+define('MDB2_AUTOQUERY_INSERT', 1);
+define('MDB2_AUTOQUERY_UPDATE', 2);
+define('MDB2_AUTOQUERY_DELETE', 3);
+define('MDB2_AUTOQUERY_SELECT', 4);
+
+/**
+ * MDB2_Extended: class which adds several high level methods to MDB2
+ *
+ * @package MDB2
+ * @category Database
+ * @author Lukas Smith
+ */
+class MDB2_Extended extends MDB2_Module_Common
+{
+ // {{{ autoPrepare()
+
+ /**
+ * Generate an insert, update or delete query and call prepare() on it
+ *
+ * @param string table
+ * @param array the fields names
+ * @param int type of query to build
+ * MDB2_AUTOQUERY_INSERT
+ * MDB2_AUTOQUERY_UPDATE
+ * MDB2_AUTOQUERY_DELETE
+ * MDB2_AUTOQUERY_SELECT
+ * @param string (in case of update and delete queries, this string will be put after the sql WHERE statement)
+ * @param array that contains the types of the placeholders
+ * @param mixed array that contains the types of the columns in
+ * the result set or MDB2_PREPARE_RESULT, if set to
+ * MDB2_PREPARE_MANIP the query is handled as a manipulation query
+ *
+ * @return resource handle for the query
+ * @see buildManipSQL
+ * @access public
+ */
+ function autoPrepare($table, $table_fields, $mode = MDB2_AUTOQUERY_INSERT,
+ $where = false, $types = null, $result_types = MDB2_PREPARE_MANIP)
+ {
+ $query = $this->buildManipSQL($table, $table_fields, $mode, $where);
+ if (PEAR::isError($query)) {
+ return $query;
+ }
+ $db = $this->getDBInstance();
+ if (PEAR::isError($db)) {
+ return $db;
+ }
+ $lobs = array();
+ foreach ((array)$types as $param => $type) {
+ if (($type == 'clob') || ($type == 'blob')) {
+ $lobs[$param] = $table_fields[$param];
+ }
+ }
+ return $db->prepare($query, $types, $result_types, $lobs);
+ }
+
+ // }}}
+ // {{{ autoExecute()
+
+ /**
+ * Generate an insert, update or delete query and call prepare() and execute() on it
+ *
+ * @param string name of the table
+ * @param array assoc ($key=>$value) where $key is a field name and $value its value
+ * @param int type of query to build
+ * MDB2_AUTOQUERY_INSERT
+ * MDB2_AUTOQUERY_UPDATE
+ * MDB2_AUTOQUERY_DELETE
+ * MDB2_AUTOQUERY_SELECT
+ * @param string (in case of update and delete queries, this string will be put after the sql WHERE statement)
+ * @param array that contains the types of the placeholders
+ * @param string which specifies which result class to use
+ * @param mixed array that contains the types of the columns in
+ * the result set or MDB2_PREPARE_RESULT, if set to
+ * MDB2_PREPARE_MANIP the query is handled as a manipulation query
+ *
+ * @return bool|MDB2_Error true on success, a MDB2 error on failure
+ * @see buildManipSQL
+ * @see autoPrepare
+ * @access public
+ */
+ function autoExecute($table, $fields_values, $mode = MDB2_AUTOQUERY_INSERT,
+ $where = false, $types = null, $result_class = true, $result_types = MDB2_PREPARE_MANIP)
+ {
+ $fields_values = (array)$fields_values;
+ if ($mode == MDB2_AUTOQUERY_SELECT) {
+ if (is_array($result_types)) {
+ $keys = array_keys($result_types);
+ } elseif (!empty($fields_values)) {
+ $keys = $fields_values;
+ } else {
+ $keys = array();
+ }
+ } else {
+ $keys = array_keys($fields_values);
+ }
+ $params = array_values($fields_values);
+ if (empty($params)) {
+ $query = $this->buildManipSQL($table, $keys, $mode, $where);
+
+ $db = $this->getDBInstance();
+ if (PEAR::isError($db)) {
+ return $db;
+ }
+ if ($mode == MDB2_AUTOQUERY_SELECT) {
+ $result = $db->query($query, $result_types, $result_class);
+ } else {
+ $result = $db->exec($query);
+ }
+ } else {
+ $stmt = $this->autoPrepare($table, $keys, $mode, $where, $types, $result_types);
+ if (PEAR::isError($stmt)) {
+ return $stmt;
+ }
+ $result = $stmt->execute($params, $result_class);
+ $stmt->free();
+ }
+ return $result;
+ }
+
+ // }}}
+ // {{{ buildManipSQL()
+
+ /**
+ * Make automaticaly an sql query for prepare()
+ *
+ * Example : buildManipSQL('table_sql', array('field1', 'field2', 'field3'), MDB2_AUTOQUERY_INSERT)
+ * will return the string : INSERT INTO table_sql (field1,field2,field3) VALUES (?,?,?)
+ * NB : - This belongs more to a SQL Builder class, but this is a simple facility
+ * - Be carefull ! If you don't give a $where param with an UPDATE/DELETE query, all
+ * the records of the table will be updated/deleted !
+ *
+ * @param string name of the table
+ * @param ordered array containing the fields names
+ * @param int type of query to build
+ * MDB2_AUTOQUERY_INSERT
+ * MDB2_AUTOQUERY_UPDATE
+ * MDB2_AUTOQUERY_DELETE
+ * MDB2_AUTOQUERY_SELECT
+ * @param string (in case of update and delete queries, this string will be put after the sql WHERE statement)
+ *
+ * @return string sql query for prepare()
+ * @access public
+ */
+ function buildManipSQL($table, $table_fields, $mode, $where = false)
+ {
+ $db = $this->getDBInstance();
+ if (PEAR::isError($db)) {
+ return $db;
+ }
+
+ if ($db->options['quote_identifier']) {
+ $table = $db->quoteIdentifier($table);
+ }
+
+ if (!empty($table_fields) && $db->options['quote_identifier']) {
+ foreach ($table_fields as $key => $field) {
+ $table_fields[$key] = $db->quoteIdentifier($field);
+ }
+ }
+
+ if ((false !== $where) && (null !== $where)) {
+ if (is_array($where)) {
+ $where = implode(' AND ', $where);
+ }
+ $where = ' WHERE '.$where;
+ }
+
+ switch ($mode) {
+ case MDB2_AUTOQUERY_INSERT:
+ if (empty($table_fields)) {
+ return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
+ 'Insert requires table fields', __FUNCTION__);
+ }
+ $cols = implode(', ', $table_fields);
+ $values = '?'.str_repeat(', ?', (count($table_fields) - 1));
+ return 'INSERT INTO '.$table.' ('.$cols.') VALUES ('.$values.')';
+ break;
+ case MDB2_AUTOQUERY_UPDATE:
+ if (empty($table_fields)) {
+ return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
+ 'Update requires table fields', __FUNCTION__);
+ }
+ $set = implode(' = ?, ', $table_fields).' = ?';
+ $sql = 'UPDATE '.$table.' SET '.$set.$where;
+ return $sql;
+ break;
+ case MDB2_AUTOQUERY_DELETE:
+ $sql = 'DELETE FROM '.$table.$where;
+ return $sql;
+ break;
+ case MDB2_AUTOQUERY_SELECT:
+ $cols = !empty($table_fields) ? implode(', ', $table_fields) : '*';
+ $sql = 'SELECT '.$cols.' FROM '.$table.$where;
+ return $sql;
+ break;
+ }
+ return $db->raiseError(MDB2_ERROR_SYNTAX, null, null,
+ 'Non existant mode', __FUNCTION__);
+ }
+
+ // }}}
+ // {{{ limitQuery()
+
+ /**
+ * Generates a limited query
+ *
+ * @param string query
+ * @param array that contains the types of the columns in the result set
+ * @param integer the numbers of rows to fetch
+ * @param integer the row to start to fetching
+ * @param string which specifies which result class to use
+ * @param mixed string which specifies which class to wrap results in
+ *
+ * @return MDB2_Result|MDB2_Error result set on success, a MDB2 error on failure
+ * @access public
+ */
+ function limitQuery($query, $types, $limit, $offset = 0, $result_class = true,
+ $result_wrap_class = false)
+ {
+ $db = $this->getDBInstance();
+ if (PEAR::isError($db)) {
+ return $db;
+ }
+
+ $result = $db->setLimit($limit, $offset);
+ if (PEAR::isError($result)) {
+ return $result;
+ }
+ return $db->query($query, $types, $result_class, $result_wrap_class);
+ }
+
+ // }}}
+ // {{{ execParam()
+
+ /**
+ * Execute a parameterized DML statement.
+ *
+ * @param string the SQL query
+ * @param array if supplied, prepare/execute will be used
+ * with this array as execute parameters
+ * @param array that contains the types of the values defined in $params
+ *
+ * @return int|MDB2_Error affected rows on success, a MDB2 error on failure
+ * @access public
+ */
+ function execParam($query, $params = array(), $param_types = null)
+ {
+ $db = $this->getDBInstance();
+ if (PEAR::isError($db)) {
+ return $db;
+ }
+
+ settype($params, 'array');
+ if (empty($params)) {
+ return $db->exec($query);
+ }
+
+ $stmt = $db->prepare($query, $param_types, MDB2_PREPARE_MANIP);
+ if (PEAR::isError($stmt)) {
+ return $stmt;
+ }
+
+ $result = $stmt->execute($params);
+ if (PEAR::isError($result)) {
+ return $result;
+ }
+
+ $stmt->free();
+ return $result;
+ }
+
+ // }}}
+ // {{{ getOne()
+
+ /**
+ * Fetch the first column of the first row of data returned from a query.
+ * Takes care of doing the query and freeing the results when finished.
+ *
+ * @param string the SQL query
+ * @param string that contains the type of the column in the result set
+ * @param array if supplied, prepare/execute will be used
+ * with this array as execute parameters
+ * @param array that contains the types of the values defined in $params
+ * @param int|string which column to return
+ *
+ * @return scalar|MDB2_Error data on success, a MDB2 error on failure
+ * @access public
+ */
+ function getOne($query, $type = null, $params = array(),
+ $param_types = null, $colnum = 0)
+ {
+ $db = $this->getDBInstance();
+ if (PEAR::isError($db)) {
+ return $db;
+ }
+
+ settype($params, 'array');
+ settype($type, 'array');
+ if (empty($params)) {
+ return $db->queryOne($query, $type, $colnum);
+ }
+
+ $stmt = $db->prepare($query, $param_types, $type);
+ if (PEAR::isError($stmt)) {
+ return $stmt;
+ }
+
+ $result = $stmt->execute($params);
+ if (!MDB2::isResultCommon($result)) {
+ return $result;
+ }
+
+ $one = $result->fetchOne($colnum);
+ $stmt->free();
+ $result->free();
+ return $one;
+ }
+
+ // }}}
+ // {{{ getRow()
+
+ /**
+ * Fetch the first row of data returned from a query. Takes care
+ * of doing the query and freeing the results when finished.
+ *
+ * @param string the SQL query
+ * @param array that contains the types of the columns in the result set
+ * @param array if supplied, prepare/execute will be used
+ * with this array as execute parameters
+ * @param array that contains the types of the values defined in $params
+ * @param int the fetch mode to use
+ *
+ * @return array|MDB2_Error data on success, a MDB2 error on failure
+ * @access public
+ */
+ function getRow($query, $types = null, $params = array(),
+ $param_types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT)
+ {
+ $db = $this->getDBInstance();
+ if (PEAR::isError($db)) {
+ return $db;
+ }
+
+ settype($params, 'array');
+ if (empty($params)) {
+ return $db->queryRow($query, $types, $fetchmode);
+ }
+
+ $stmt = $db->prepare($query, $param_types, $types);
+ if (PEAR::isError($stmt)) {
+ return $stmt;
+ }
+
+ $result = $stmt->execute($params);
+ if (!MDB2::isResultCommon($result)) {
+ return $result;
+ }
+
+ $row = $result->fetchRow($fetchmode);
+ $stmt->free();
+ $result->free();
+ return $row;
+ }
+
+ // }}}
+ // {{{ getCol()
+
+ /**
+ * Fetch a single column from a result set and return it as an
+ * indexed array.
+ *
+ * @param string the SQL query
+ * @param string that contains the type of the column in the result set
+ * @param array if supplied, prepare/execute will be used
+ * with this array as execute parameters
+ * @param array that contains the types of the values defined in $params
+ * @param int|string which column to return
+ *
+ * @return array|MDB2_Error data on success, a MDB2 error on failure
+ * @access public
+ */
+ function getCol($query, $type = null, $params = array(),
+ $param_types = null, $colnum = 0)
+ {
+ $db = $this->getDBInstance();
+ if (PEAR::isError($db)) {
+ return $db;
+ }
+
+ settype($params, 'array');
+ settype($type, 'array');
+ if (empty($params)) {
+ return $db->queryCol($query, $type, $colnum);
+ }
+
+ $stmt = $db->prepare($query, $param_types, $type);
+ if (PEAR::isError($stmt)) {
+ return $stmt;
+ }
+
+ $result = $stmt->execute($params);
+ if (!MDB2::isResultCommon($result)) {
+ return $result;
+ }
+
+ $col = $result->fetchCol($colnum);
+ $stmt->free();
+ $result->free();
+ return $col;
+ }
+
+ // }}}
+ // {{{ getAll()
+
+ /**
+ * Fetch all the rows returned from a query.
+ *
+ * @param string the SQL query
+ * @param array that contains the types of the columns in the result set
+ * @param array if supplied, prepare/execute will be used
+ * with this array as execute parameters
+ * @param array that contains the types of the values defined in $params
+ * @param int the fetch mode to use
+ * @param bool if set to true, the $all will have the first
+ * column as its first dimension
+ * @param bool $force_array used only when the query returns exactly
+ * two columns. If true, the values of the returned array will be
+ * one-element arrays instead of scalars.
+ * @param bool $group if true, the values of the returned array is
+ * wrapped in another array. If the same key value (in the first
+ * column) repeats itself, the values will be appended to this array
+ * instead of overwriting the existing values.
+ *
+ * @return array|MDB2_Error data on success, a MDB2 error on failure
+ * @access public
+ */
+ function getAll($query, $types = null, $params = array(),
+ $param_types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT,
+ $rekey = false, $force_array = false, $group = false)
+ {
+ $db = $this->getDBInstance();
+ if (PEAR::isError($db)) {
+ return $db;
+ }
+
+ settype($params, 'array');
+ if (empty($params)) {
+ return $db->queryAll($query, $types, $fetchmode, $rekey, $force_array, $group);
+ }
+
+ $stmt = $db->prepare($query, $param_types, $types);
+ if (PEAR::isError($stmt)) {
+ return $stmt;
+ }
+
+ $result = $stmt->execute($params);
+ if (!MDB2::isResultCommon($result)) {
+ return $result;
+ }
+
+ $all = $result->fetchAll($fetchmode, $rekey, $force_array, $group);
+ $stmt->free();
+ $result->free();
+ return $all;
+ }
+
+ // }}}
+ // {{{ getAssoc()
+
+ /**
+ * Fetch the entire result set of a query and return it as an
+ * associative array using the first column as the key.
+ *
+ * If the result set contains more than two columns, the value
+ * will be an array of the values from column 2-n. If the result
+ * set contains only two columns, the returned value will be a
+ * scalar with the value of the second column (unless forced to an
+ * array with the $force_array parameter). A MDB2 error code is
+ * returned on errors. If the result set contains fewer than two
+ * columns, a MDB2_ERROR_TRUNCATED error is returned.
+ *
+ * For example, if the table 'mytable' contains:
+ *
+ * ID TEXT DATE
+ * --------------------------------
+ * 1 'one' 944679408
+ * 2 'two' 944679408
+ * 3 'three' 944679408
+ *
+ * Then the call getAssoc('SELECT id,text FROM mytable') returns:
+ *
+ * array(
+ * '1' => 'one',
+ * '2' => 'two',
+ * '3' => 'three',
+ * )
+ *
+ * ...while the call getAssoc('SELECT id,text,date FROM mytable') returns:
+ *
+ * array(
+ * '1' => array('one', '944679408'),
+ * '2' => array('two', '944679408'),
+ * '3' => array('three', '944679408')
+ * )
+ *
+ *
+ * If the more than one row occurs with the same value in the
+ * first column, the last row overwrites all previous ones by
+ * default. Use the $group parameter if you don't want to
+ * overwrite like this. Example:
+ *
+ * getAssoc('SELECT category,id,name FROM mytable', null, null
+ * MDB2_FETCHMODE_ASSOC, false, true) returns:
+ * array(
+ * '1' => array(array('id' => '4', 'name' => 'number four'),
+ * array('id' => '6', 'name' => 'number six')
+ * ),
+ * '9' => array(array('id' => '4', 'name' => 'number four'),
+ * array('id' => '6', 'name' => 'number six')
+ * )
+ * )
+ *
+ *
+ * Keep in mind that database functions in PHP usually return string
+ * values for results regardless of the database's internal type.
+ *
+ * @param string the SQL query
+ * @param array that contains the types of the columns in the result set
+ * @param array if supplied, prepare/execute will be used
+ * with this array as execute parameters
+ * @param array that contains the types of the values defined in $params
+ * @param bool $force_array used only when the query returns
+ * exactly two columns. If TRUE, the values of the returned array
+ * will be one-element arrays instead of scalars.
+ * @param bool $group if TRUE, the values of the returned array
+ * is wrapped in another array. If the same key value (in the first
+ * column) repeats itself, the values will be appended to this array
+ * instead of overwriting the existing values.
+ *
+ * @return array|MDB2_Error data on success, a MDB2 error on failure
+ * @access public
+ */
+ function getAssoc($query, $types = null, $params = array(), $param_types = null,
+ $fetchmode = MDB2_FETCHMODE_DEFAULT, $force_array = false, $group = false)
+ {
+ $db = $this->getDBInstance();
+ if (PEAR::isError($db)) {
+ return $db;
+ }
+
+ settype($params, 'array');
+ if (empty($params)) {
+ return $db->queryAll($query, $types, $fetchmode, true, $force_array, $group);
+ }
+
+ $stmt = $db->prepare($query, $param_types, $types);
+ if (PEAR::isError($stmt)) {
+ return $stmt;
+ }
+
+ $result = $stmt->execute($params);
+ if (!MDB2::isResultCommon($result)) {
+ return $result;
+ }
+
+ $all = $result->fetchAll($fetchmode, true, $force_array, $group);
+ $stmt->free();
+ $result->free();
+ return $all;
+ }
+
+ // }}}
+ // {{{ executeMultiple()
+
+ /**
+ * This function does several execute() calls on the same statement handle.
+ * $params must be an array indexed numerically from 0, one execute call is
+ * done for every 'row' in the array.
+ *
+ * If an error occurs during execute(), executeMultiple() does not execute
+ * the unfinished rows, but rather returns that error.
+ *
+ * @param resource query handle from prepare()
+ * @param array numeric array containing the data to insert into the query
+ *
+ * @return bool|MDB2_Error true on success, a MDB2 error on failure
+ * @access public
+ * @see prepare(), execute()
+ */
+ function executeMultiple($stmt, $params = null)
+ {
+ for ($i = 0, $j = count($params); $i < $j; $i++) {
+ $result = $stmt->execute($params[$i]);
+ if (PEAR::isError($result)) {
+ return $result;
+ }
+ }
+ return MDB2_OK;
+ }
+
+ // }}}
+ // {{{ getBeforeID()
+
+ /**
+ * Returns the next free id of a sequence if the RDBMS
+ * does not support auto increment
+ *
+ * @param string name of the table into which a new row was inserted
+ * @param string name of the field into which a new row was inserted
+ * @param bool when true the sequence is automatic created, if it not exists
+ * @param bool if the returned value should be quoted
+ *
+ * @return int|MDB2_Error id on success, a MDB2 error on failure
+ * @access public
+ */
+ function getBeforeID($table, $field = null, $ondemand = true, $quote = true)
+ {
+ $db = $this->getDBInstance();
+ if (PEAR::isError($db)) {
+ return $db;
+ }
+
+ if ($db->supports('auto_increment') !== true) {
+ $seq = $table.(empty($field) ? '' : '_'.$field);
+ $id = $db->nextID($seq, $ondemand);
+ if (!$quote || PEAR::isError($id)) {
+ return $id;
+ }
+ return $db->quote($id, 'integer');
+ } elseif (!$quote) {
+ return null;
+ }
+ return 'NULL';
+ }
+
+ // }}}
+ // {{{ getAfterID()
+
+ /**
+ * Returns the autoincrement ID if supported or $id
+ *
+ * @param mixed value as returned by getBeforeId()
+ * @param string name of the table into which a new row was inserted
+ * @param string name of the field into which a new row was inserted
+ *
+ * @return int|MDB2_Error id on success, a MDB2 error on failure
+ * @access public
+ */
+ function getAfterID($id, $table, $field = null)
+ {
+ $db = $this->getDBInstance();
+ if (PEAR::isError($db)) {
+ return $db;
+ }
+
+ if ($db->supports('auto_increment') !== true) {
+ return $id;
+ }
+ return $db->lastInsertID($table, $field);
+ }
+
+ // }}}
+}
?>
\ No newline at end of file
diff --git a/3rdparty/MDB2/Iterator.php b/3rdparty/MDB2/Iterator.php
index ca5e7b69c2..8d31919b6d 100644
--- a/3rdparty/MDB2/Iterator.php
+++ b/3rdparty/MDB2/Iterator.php
@@ -1,259 +1,259 @@
- |
-// +----------------------------------------------------------------------+
-//
-// $Id: Iterator.php,v 1.22 2006/05/06 14:03:41 lsmith Exp $
-
-/**
- * PHP5 Iterator
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Iterator implements Iterator
-{
- protected $fetchmode;
- protected $result;
- protected $row;
-
- // {{{ constructor
-
- /**
- * Constructor
- */
- public function __construct($result, $fetchmode = MDB2_FETCHMODE_DEFAULT)
- {
- $this->result = $result;
- $this->fetchmode = $fetchmode;
- }
- // }}}
-
- // {{{ seek()
-
- /**
- * Seek forward to a specific row in a result set
- *
- * @param int number of the row where the data can be found
- *
- * @return void
- * @access public
- */
- public function seek($rownum)
- {
- $this->row = null;
- if ($this->result) {
- $this->result->seek($rownum);
- }
- }
- // }}}
-
- // {{{ next()
-
- /**
- * Fetch next row of data
- *
- * @return void
- * @access public
- */
- public function next()
- {
- $this->row = null;
- }
- // }}}
-
- // {{{ current()
-
- /**
- * return a row of data
- *
- * @return void
- * @access public
- */
- public function current()
- {
- if (is_null($this->row)) {
- $row = $this->result->fetchRow($this->fetchmode);
- if (PEAR::isError($row)) {
- $row = false;
- }
- $this->row = $row;
- }
- return $this->row;
- }
- // }}}
-
- // {{{ valid()
-
- /**
- * Check if the end of the result set has been reached
- *
- * @return bool true/false, false is also returned on failure
- * @access public
- */
- public function valid()
- {
- return (bool)$this->current();
- }
- // }}}
-
- // {{{ free()
-
- /**
- * Free the internal resources associated with result.
- *
- * @return bool|MDB2_Error true on success, false|MDB2_Error if result is invalid
- * @access public
- */
- public function free()
- {
- if ($this->result) {
- return $this->result->free();
- }
- $this->result = false;
- $this->row = null;
- return false;
- }
- // }}}
-
- // {{{ key()
-
- /**
- * Returns the row number
- *
- * @return int|bool|MDB2_Error true on success, false|MDB2_Error if result is invalid
- * @access public
- */
- public function key()
- {
- if ($this->result) {
- return $this->result->rowCount();
- }
- return false;
- }
- // }}}
-
- // {{{ rewind()
-
- /**
- * Seek to the first row in a result set
- *
- * @return void
- * @access public
- */
- public function rewind()
- {
- }
- // }}}
-
- // {{{ destructor
-
- /**
- * Destructor
- */
- public function __destruct()
- {
- $this->free();
- }
- // }}}
-}
-
-/**
- * PHP5 buffered Iterator
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_BufferedIterator extends MDB2_Iterator implements SeekableIterator
-{
- // {{{ valid()
-
- /**
- * Check if the end of the result set has been reached
- *
- * @return bool|MDB2_Error true on success, false|MDB2_Error if result is invalid
- * @access public
- */
- public function valid()
- {
- if ($this->result) {
- return $this->result->valid();
- }
- return false;
- }
- // }}}
-
- // {{{count()
-
- /**
- * Returns the number of rows in a result object
- *
- * @return int|MDB2_Error number of rows, false|MDB2_Error if result is invalid
- * @access public
- */
- public function count()
- {
- if ($this->result) {
- return $this->result->numRows();
- }
- return false;
- }
- // }}}
-
- // {{{ rewind()
-
- /**
- * Seek to the first row in a result set
- *
- * @return void
- * @access public
- */
- public function rewind()
- {
- $this->seek(0);
- }
- // }}}
-}
-
+ |
+// +----------------------------------------------------------------------+
+//
+// $Id: Iterator.php 295586 2010-02-28 17:04:17Z quipo $
+
+/**
+ * PHP5 Iterator
+ *
+ * @package MDB2
+ * @category Database
+ * @author Lukas Smith
+ */
+class MDB2_Iterator implements Iterator
+{
+ protected $fetchmode;
+ protected $result;
+ protected $row;
+
+ // {{{ constructor
+
+ /**
+ * Constructor
+ */
+ public function __construct($result, $fetchmode = MDB2_FETCHMODE_DEFAULT)
+ {
+ $this->result = $result;
+ $this->fetchmode = $fetchmode;
+ }
+ // }}}
+
+ // {{{ seek()
+
+ /**
+ * Seek forward to a specific row in a result set
+ *
+ * @param int number of the row where the data can be found
+ *
+ * @return void
+ * @access public
+ */
+ public function seek($rownum)
+ {
+ $this->row = null;
+ if ($this->result) {
+ $this->result->seek($rownum);
+ }
+ }
+ // }}}
+
+ // {{{ next()
+
+ /**
+ * Fetch next row of data
+ *
+ * @return void
+ * @access public
+ */
+ public function next()
+ {
+ $this->row = null;
+ }
+ // }}}
+
+ // {{{ current()
+
+ /**
+ * return a row of data
+ *
+ * @return void
+ * @access public
+ */
+ public function current()
+ {
+ if (null === $this->row) {
+ $row = $this->result->fetchRow($this->fetchmode);
+ if (PEAR::isError($row)) {
+ $row = false;
+ }
+ $this->row = $row;
+ }
+ return $this->row;
+ }
+ // }}}
+
+ // {{{ valid()
+
+ /**
+ * Check if the end of the result set has been reached
+ *
+ * @return bool true/false, false is also returned on failure
+ * @access public
+ */
+ public function valid()
+ {
+ return (bool)$this->current();
+ }
+ // }}}
+
+ // {{{ free()
+
+ /**
+ * Free the internal resources associated with result.
+ *
+ * @return bool|MDB2_Error true on success, false|MDB2_Error if result is invalid
+ * @access public
+ */
+ public function free()
+ {
+ if ($this->result) {
+ return $this->result->free();
+ }
+ $this->result = false;
+ $this->row = null;
+ return false;
+ }
+ // }}}
+
+ // {{{ key()
+
+ /**
+ * Returns the row number
+ *
+ * @return int|bool|MDB2_Error true on success, false|MDB2_Error if result is invalid
+ * @access public
+ */
+ public function key()
+ {
+ if ($this->result) {
+ return $this->result->rowCount();
+ }
+ return false;
+ }
+ // }}}
+
+ // {{{ rewind()
+
+ /**
+ * Seek to the first row in a result set
+ *
+ * @return void
+ * @access public
+ */
+ public function rewind()
+ {
+ }
+ // }}}
+
+ // {{{ destructor
+
+ /**
+ * Destructor
+ */
+ public function __destruct()
+ {
+ $this->free();
+ }
+ // }}}
+}
+
+/**
+ * PHP5 buffered Iterator
+ *
+ * @package MDB2
+ * @category Database
+ * @author Lukas Smith
+ */
+class MDB2_BufferedIterator extends MDB2_Iterator implements SeekableIterator
+{
+ // {{{ valid()
+
+ /**
+ * Check if the end of the result set has been reached
+ *
+ * @return bool|MDB2_Error true on success, false|MDB2_Error if result is invalid
+ * @access public
+ */
+ public function valid()
+ {
+ if ($this->result) {
+ return $this->result->valid();
+ }
+ return false;
+ }
+ // }}}
+
+ // {{{count()
+
+ /**
+ * Returns the number of rows in a result object
+ *
+ * @return int|MDB2_Error number of rows, false|MDB2_Error if result is invalid
+ * @access public
+ */
+ public function count()
+ {
+ if ($this->result) {
+ return $this->result->numRows();
+ }
+ return false;
+ }
+ // }}}
+
+ // {{{ rewind()
+
+ /**
+ * Seek to the first row in a result set
+ *
+ * @return void
+ * @access public
+ */
+ public function rewind()
+ {
+ $this->seek(0);
+ }
+ // }}}
+}
+
?>
\ No newline at end of file
diff --git a/3rdparty/MDB2/LOB.php b/3rdparty/MDB2/LOB.php
index ae67224020..f7df13dc47 100644
--- a/3rdparty/MDB2/LOB.php
+++ b/3rdparty/MDB2/LOB.php
@@ -1,264 +1,264 @@
- |
-// +----------------------------------------------------------------------+
-//
-// $Id: LOB.php,v 1.34 2006/10/25 11:52:21 lsmith Exp $
-
-/**
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-
-require_once('MDB2.php');
-
-/**
- * MDB2_LOB: user land stream wrapper implementation for LOB support
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_LOB
-{
- /**
- * contains the key to the global MDB2 instance array of the associated
- * MDB2 instance
- *
- * @var integer
- * @access protected
- */
- var $db_index;
-
- /**
- * contains the key to the global MDB2_LOB instance array of the associated
- * MDB2_LOB instance
- *
- * @var integer
- * @access protected
- */
- var $lob_index;
-
- // {{{ stream_open()
-
- /**
- * open stream
- *
- * @param string specifies the URL that was passed to fopen()
- * @param string the mode used to open the file
- * @param int holds additional flags set by the streams API
- * @param string not used
- *
- * @return bool
- * @access public
- */
- function stream_open($path, $mode, $options, &$opened_path)
- {
- if (!preg_match('/^rb?\+?$/', $mode)) {
- return false;
- }
- $url = parse_url($path);
- if (empty($url['host'])) {
- return false;
- }
- $this->db_index = (int)$url['host'];
- if (!isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
- return false;
- }
- $db =& $GLOBALS['_MDB2_databases'][$this->db_index];
- $this->lob_index = (int)$url['user'];
- if (!isset($db->datatype->lobs[$this->lob_index])) {
- return false;
- }
- return true;
- }
- // }}}
-
- // {{{ stream_read()
-
- /**
- * read stream
- *
- * @param int number of bytes to read
- *
- * @return string
- * @access public
- */
- function stream_read($count)
- {
- if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
- $db =& $GLOBALS['_MDB2_databases'][$this->db_index];
- $db->datatype->_retrieveLOB($db->datatype->lobs[$this->lob_index]);
-
- $data = $db->datatype->_readLOB($db->datatype->lobs[$this->lob_index], $count);
- $length = strlen($data);
- if ($length == 0) {
- $db->datatype->lobs[$this->lob_index]['endOfLOB'] = true;
- }
- $db->datatype->lobs[$this->lob_index]['position'] += $length;
- return $data;
- }
- }
- // }}}
-
- // {{{ stream_write()
-
- /**
- * write stream, note implemented
- *
- * @param string data
- *
- * @return int
- * @access public
- */
- function stream_write($data)
- {
- return 0;
- }
- // }}}
-
- // {{{ stream_tell()
-
- /**
- * return the current position
- *
- * @return int current position
- * @access public
- */
- function stream_tell()
- {
- if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
- $db =& $GLOBALS['_MDB2_databases'][$this->db_index];
- return $db->datatype->lobs[$this->lob_index]['position'];
- }
- }
- // }}}
-
- // {{{ stream_eof()
-
- /**
- * Check if stream reaches EOF
- *
- * @return bool
- * @access public
- */
- function stream_eof()
- {
- if (!isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
- return true;
- }
-
- $db =& $GLOBALS['_MDB2_databases'][$this->db_index];
- $result = $db->datatype->_endOfLOB($db->datatype->lobs[$this->lob_index]);
- if (version_compare(phpversion(), "5.0", ">=")
- && version_compare(phpversion(), "5.1", "<")
- ) {
- return !$result;
- }
- return $result;
- }
- // }}}
-
- // {{{ stream_seek()
-
- /**
- * Seek stream, not implemented
- *
- * @param int offset
- * @param int whence
- *
- * @return bool
- * @access public
- */
- function stream_seek($offset, $whence)
- {
- return false;
- }
- // }}}
-
- // {{{ stream_stat()
-
- /**
- * return information about stream
- *
- * @access public
- */
- function stream_stat()
- {
- if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
- $db =& $GLOBALS['_MDB2_databases'][$this->db_index];
- return array(
- 'db_index' => $this->db_index,
- 'lob_index' => $this->lob_index,
- );
- }
- }
- // }}}
-
- // {{{ stream_close()
-
- /**
- * close stream
- *
- * @access public
- */
- function stream_close()
- {
- if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
- $db =& $GLOBALS['_MDB2_databases'][$this->db_index];
- if (isset($db->datatype->lobs[$this->lob_index])) {
- $db->datatype->_destroyLOB($db->datatype->lobs[$this->lob_index]);
- unset($db->datatype->lobs[$this->lob_index]);
- }
- }
- }
- // }}}
-}
-
-// register streams wrapper
-if (!stream_wrapper_register("MDB2LOB", "MDB2_LOB")) {
- MDB2::raiseError();
- return false;
-}
-
-?>
+ |
+// +----------------------------------------------------------------------+
+//
+// $Id: LOB.php 222350 2006-10-25 11:52:21Z lsmith $
+
+/**
+ * @package MDB2
+ * @category Database
+ * @author Lukas Smith
+ */
+
+require_once 'MDB2.php';
+
+/**
+ * MDB2_LOB: user land stream wrapper implementation for LOB support
+ *
+ * @package MDB2
+ * @category Database
+ * @author Lukas Smith
+ */
+class MDB2_LOB
+{
+ /**
+ * contains the key to the global MDB2 instance array of the associated
+ * MDB2 instance
+ *
+ * @var integer
+ * @access protected
+ */
+ var $db_index;
+
+ /**
+ * contains the key to the global MDB2_LOB instance array of the associated
+ * MDB2_LOB instance
+ *
+ * @var integer
+ * @access protected
+ */
+ var $lob_index;
+
+ // {{{ stream_open()
+
+ /**
+ * open stream
+ *
+ * @param string specifies the URL that was passed to fopen()
+ * @param string the mode used to open the file
+ * @param int holds additional flags set by the streams API
+ * @param string not used
+ *
+ * @return bool
+ * @access public
+ */
+ function stream_open($path, $mode, $options, &$opened_path)
+ {
+ if (!preg_match('/^rb?\+?$/', $mode)) {
+ return false;
+ }
+ $url = parse_url($path);
+ if (empty($url['host'])) {
+ return false;
+ }
+ $this->db_index = (int)$url['host'];
+ if (!isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
+ return false;
+ }
+ $db =& $GLOBALS['_MDB2_databases'][$this->db_index];
+ $this->lob_index = (int)$url['user'];
+ if (!isset($db->datatype->lobs[$this->lob_index])) {
+ return false;
+ }
+ return true;
+ }
+ // }}}
+
+ // {{{ stream_read()
+
+ /**
+ * read stream
+ *
+ * @param int number of bytes to read
+ *
+ * @return string
+ * @access public
+ */
+ function stream_read($count)
+ {
+ if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
+ $db =& $GLOBALS['_MDB2_databases'][$this->db_index];
+ $db->datatype->_retrieveLOB($db->datatype->lobs[$this->lob_index]);
+
+ $data = $db->datatype->_readLOB($db->datatype->lobs[$this->lob_index], $count);
+ $length = strlen($data);
+ if ($length == 0) {
+ $db->datatype->lobs[$this->lob_index]['endOfLOB'] = true;
+ }
+ $db->datatype->lobs[$this->lob_index]['position'] += $length;
+ return $data;
+ }
+ }
+ // }}}
+
+ // {{{ stream_write()
+
+ /**
+ * write stream, note implemented
+ *
+ * @param string data
+ *
+ * @return int
+ * @access public
+ */
+ function stream_write($data)
+ {
+ return 0;
+ }
+ // }}}
+
+ // {{{ stream_tell()
+
+ /**
+ * return the current position
+ *
+ * @return int current position
+ * @access public
+ */
+ function stream_tell()
+ {
+ if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
+ $db =& $GLOBALS['_MDB2_databases'][$this->db_index];
+ return $db->datatype->lobs[$this->lob_index]['position'];
+ }
+ }
+ // }}}
+
+ // {{{ stream_eof()
+
+ /**
+ * Check if stream reaches EOF
+ *
+ * @return bool
+ * @access public
+ */
+ function stream_eof()
+ {
+ if (!isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
+ return true;
+ }
+
+ $db =& $GLOBALS['_MDB2_databases'][$this->db_index];
+ $result = $db->datatype->_endOfLOB($db->datatype->lobs[$this->lob_index]);
+ if (version_compare(phpversion(), "5.0", ">=")
+ && version_compare(phpversion(), "5.1", "<")
+ ) {
+ return !$result;
+ }
+ return $result;
+ }
+ // }}}
+
+ // {{{ stream_seek()
+
+ /**
+ * Seek stream, not implemented
+ *
+ * @param int offset
+ * @param int whence
+ *
+ * @return bool
+ * @access public
+ */
+ function stream_seek($offset, $whence)
+ {
+ return false;
+ }
+ // }}}
+
+ // {{{ stream_stat()
+
+ /**
+ * return information about stream
+ *
+ * @access public
+ */
+ function stream_stat()
+ {
+ if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
+ $db =& $GLOBALS['_MDB2_databases'][$this->db_index];
+ return array(
+ 'db_index' => $this->db_index,
+ 'lob_index' => $this->lob_index,
+ );
+ }
+ }
+ // }}}
+
+ // {{{ stream_close()
+
+ /**
+ * close stream
+ *
+ * @access public
+ */
+ function stream_close()
+ {
+ if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
+ $db =& $GLOBALS['_MDB2_databases'][$this->db_index];
+ if (isset($db->datatype->lobs[$this->lob_index])) {
+ $db->datatype->_destroyLOB($db->datatype->lobs[$this->lob_index]);
+ unset($db->datatype->lobs[$this->lob_index]);
+ }
+ }
+ }
+ // }}}
+}
+
+// register streams wrapper
+if (!stream_wrapper_register("MDB2LOB", "MDB2_LOB")) {
+ MDB2::raiseError();
+ return false;
+}
+
+?>
diff --git a/3rdparty/MDB2/Schema.php b/3rdparty/MDB2/Schema.php
index 25818460a6..0373970181 100644
--- a/3rdparty/MDB2/Schema.php
+++ b/3rdparty/MDB2/Schema.php
@@ -51,7 +51,7 @@
* @link http://pear.php.net/packages/MDB2_Schema
*/
-// require_once('MDB2.php');
+require_once 'MDB2.php';
define('MDB2_SCHEMA_DUMP_ALL', 0);
define('MDB2_SCHEMA_DUMP_STRUCTURE', 1);
@@ -237,9 +237,10 @@ class MDB2_Schema extends PEAR
* @access public
* @see MDB2::parseDSN
*/
- static function factory(&$db, $options = array())
+ function &factory(&$db, $options = array())
{
- $obj =new MDB2_Schema();
+ $obj =& new MDB2_Schema();
+
$result = $obj->connect($db, $options);
if (PEAR::isError($result)) {
return $result;
@@ -280,14 +281,16 @@ class MDB2_Schema extends PEAR
}
}
}
+
$this->disconnect();
if (!MDB2::isConnection($db)) {
- $db =MDB2::factory($db, $db_options);
+ $db =& MDB2::factory($db, $db_options);
}
if (PEAR::isError($db)) {
return $db;
}
+
$this->db =& $db;
$this->db->loadModule('Datatype');
$this->db->loadModule('Manager');
@@ -377,7 +380,7 @@ class MDB2_Schema extends PEAR
$dtd_file = $this->options['dtd_file'];
if ($dtd_file) {
include_once 'XML/DTD/XmlValidator.php';
- $dtd =new XML_DTD_XmlValidator;
+ $dtd =& new XML_DTD_XmlValidator;
if (!$dtd->isValid($dtd_file, $input_file)) {
return $this->raiseError(MDB2_SCHEMA_ERROR_PARSE, null, null, $dtd->getMessage());
}
@@ -390,7 +393,7 @@ class MDB2_Schema extends PEAR
return $result;
}
- $parser =new $class_name($variables, $fail_on_invalid_names, $structure, $this->options['valid_types'], $this->options['force_defaults']);
+ $parser =& new $class_name($variables, $fail_on_invalid_names, $structure, $this->options['valid_types'], $this->options['force_defaults']);
$result = $parser->setInputFile($input_file);
if (PEAR::isError($result)) {
return $result;
@@ -425,6 +428,7 @@ class MDB2_Schema extends PEAR
return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null,
'it was not specified a valid database name');
}
+
$class_name = $this->options['validate'];
$result = MDB2::loadClass($class_name, $this->db->getOption('debug'));
@@ -432,7 +436,7 @@ class MDB2_Schema extends PEAR
return $result;
}
- $val =new $class_name($this->options['fail_on_invalid_names'], $this->options['valid_types'], $this->options['force_defaults']);
+ $val =& new $class_name($this->options['fail_on_invalid_names'], $this->options['valid_types'], $this->options['force_defaults']);
$database_definition = array(
'name' => $database,
@@ -1338,15 +1342,15 @@ class MDB2_Schema extends PEAR
if ($dbExists) {
$this->db->debug('Database already exists: ' . $db_name, __FUNCTION__);
-// if (!empty($dbOptions)) {
-// $errorcodes = array(MDB2_ERROR_UNSUPPORTED, MDB2_ERROR_NO_PERMISSION);
-// $this->db->expectError($errorcodes);
-// $result = $this->db->manager->alterDatabase($db_name, $dbOptions);
-// $this->db->popExpect();
-// if (PEAR::isError($result) && !MDB2::isError($result, $errorcodes)) {
-// return $result;
-// }
-// }
+ if (!empty($dbOptions)) {
+ $errorcodes = array(MDB2_ERROR_UNSUPPORTED, MDB2_ERROR_NO_PERMISSION);
+ $this->db->expectError($errorcodes);
+ $result = $this->db->manager->alterDatabase($db_name, $dbOptions);
+ $this->db->popExpect();
+ if (PEAR::isError($result) && !MDB2::isError($result, $errorcodes)) {
+ return $result;
+ }
+ }
$create = false;
} else {
$this->db->expectError(MDB2_ERROR_UNSUPPORTED);
@@ -2444,7 +2448,7 @@ class MDB2_Schema extends PEAR
}
}
- $writer = new $class_name($this->options['valid_types']);
+ $writer =& new $class_name($this->options['valid_types']);
return $writer->dumpDatabase($database_definition, $arguments, $dump);
}
@@ -2692,9 +2696,9 @@ class MDB2_Schema extends PEAR
* @access public
* @see PEAR_Error
*/
- function raiseError($code = null, $mode = null, $options = null, $userinfo = null,$a=null,$b=null,$c=null)
+ function &raiseError($code = null, $mode = null, $options = null, $userinfo = null)
{
- $err =PEAR::raiseError(null, $code, $mode, $options,
+ $err =& PEAR::raiseError(null, $code, $mode, $options,
$userinfo, 'MDB2_Schema_Error', true);
return $err;
}
@@ -2713,7 +2717,7 @@ class MDB2_Schema extends PEAR
* @return bool true if parameter is an error
* @access public
*/
- static function isError($data, $code = null)
+ function isError($data, $code = null)
{
if (is_a($data, 'MDB2_Schema_Error')) {
if (is_null($code)) {
diff --git a/3rdparty/MDB2/Schema/Parser.php b/3rdparty/MDB2/Schema/Parser.php
index b740ef55fa..9e8e74b631 100644
--- a/3rdparty/MDB2/Schema/Parser.php
+++ b/3rdparty/MDB2/Schema/Parser.php
@@ -54,8 +54,8 @@
*/
-require_once('XML/Parser.php');
-require_once('MDB2/Schema/Validate.php');
+require_once 'XML/Parser.php';
+require_once 'MDB2/Schema/Validate.php';
/**
* Parses an XML schema file
@@ -120,11 +120,18 @@ class MDB2_Schema_Parser extends XML_Parser
{
// force ISO-8859-1 due to different defaults for PHP4 and PHP5
// todo: this probably needs to be investigated some more andcleaned up
- parent::__construct('ISO-8859-1');
+ parent::XML_Parser('ISO-8859-1');
$this->variables = $variables;
$this->structure = $structure;
- $this->val =new MDB2_Schema_Validate($fail_on_invalid_names, $valid_types, $force_defaults);
+ $this->val =& new MDB2_Schema_Validate($fail_on_invalid_names, $valid_types, $force_defaults);
+ }
+
+ function MDB2_Schema_Parser($variables, $fail_on_invalid_names = true,
+ $structure = false, $valid_types = array(),
+ $force_defaults = true)
+ {
+ $this->__construct($variables, $fail_on_invalid_names, $structure, $valid_types, $force_defaults);
}
function startHandler($xp, $element, $attribs)
@@ -496,7 +503,7 @@ class MDB2_Schema_Parser extends XML_Parser
$this->element = implode('-', $this->elements);
}
- function raiseError($msg = null, $xmlecode = 0, $xp = null, $ecode = MDB2_SCHEMA_ERROR_PARSE,$a=null,$b=null,$c=null)
+ function &raiseError($msg = null, $xmlecode = 0, $xp = null, $ecode = MDB2_SCHEMA_ERROR_PARSE)
{
if (is_null($this->error)) {
$error = '';
diff --git a/3rdparty/MDB2/Schema/Validate.php b/3rdparty/MDB2/Schema/Validate.php
index 217cf51b95..21be024ce9 100644
--- a/3rdparty/MDB2/Schema/Validate.php
+++ b/3rdparty/MDB2/Schema/Validate.php
@@ -91,6 +91,11 @@ class MDB2_Schema_Validate
$this->force_defaults = $force_defaults;
}
+ function MDB2_Schema_Validate($fail_on_invalid_names = true, $valid_types = array(), $force_defaults = true)
+ {
+ $this->__construct($fail_on_invalid_names, $valid_types, $force_defaults);
+ }
+
// }}}
// {{{ raiseError()
diff --git a/3rdparty/OS/Guess.php b/3rdparty/OS/Guess.php
new file mode 100644
index 0000000000..d3f2cc764e
--- /dev/null
+++ b/3rdparty/OS/Guess.php
@@ -0,0 +1,338 @@
+
+ * @author Gregory Beaver
+ * @copyright 1997-2009 The Authors
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version CVS: $Id: Guess.php 313023 2011-07-06 19:17:11Z dufuz $
+ * @link http://pear.php.net/package/PEAR
+ * @since File available since PEAR 0.1
+ */
+
+// {{{ uname examples
+
+// php_uname() without args returns the same as 'uname -a', or a PHP-custom
+// string for Windows.
+// PHP versions prior to 4.3 return the uname of the host where PHP was built,
+// as of 4.3 it returns the uname of the host running the PHP code.
+//
+// PC RedHat Linux 7.1:
+// Linux host.example.com 2.4.2-2 #1 Sun Apr 8 20:41:30 EDT 2001 i686 unknown
+//
+// PC Debian Potato:
+// Linux host 2.4.17 #2 SMP Tue Feb 12 15:10:04 CET 2002 i686 unknown
+//
+// PC FreeBSD 3.3:
+// FreeBSD host.example.com 3.3-STABLE FreeBSD 3.3-STABLE #0: Mon Feb 21 00:42:31 CET 2000 root@example.com:/usr/src/sys/compile/CONFIG i386
+//
+// PC FreeBSD 4.3:
+// FreeBSD host.example.com 4.3-RELEASE FreeBSD 4.3-RELEASE #1: Mon Jun 25 11:19:43 EDT 2001 root@example.com:/usr/src/sys/compile/CONFIG i386
+//
+// PC FreeBSD 4.5:
+// FreeBSD host.example.com 4.5-STABLE FreeBSD 4.5-STABLE #0: Wed Feb 6 23:59:23 CET 2002 root@example.com:/usr/src/sys/compile/CONFIG i386
+//
+// PC FreeBSD 4.5 w/uname from GNU shellutils:
+// FreeBSD host.example.com 4.5-STABLE FreeBSD 4.5-STABLE #0: Wed Feb i386 unknown
+//
+// HP 9000/712 HP-UX 10:
+// HP-UX iq B.10.10 A 9000/712 2008429113 two-user license
+//
+// HP 9000/712 HP-UX 10 w/uname from GNU shellutils:
+// HP-UX host B.10.10 A 9000/712 unknown
+//
+// IBM RS6000/550 AIX 4.3:
+// AIX host 3 4 000003531C00
+//
+// AIX 4.3 w/uname from GNU shellutils:
+// AIX host 3 4 000003531C00 unknown
+//
+// SGI Onyx IRIX 6.5 w/uname from GNU shellutils:
+// IRIX64 host 6.5 01091820 IP19 mips
+//
+// SGI Onyx IRIX 6.5:
+// IRIX64 host 6.5 01091820 IP19
+//
+// SparcStation 20 Solaris 8 w/uname from GNU shellutils:
+// SunOS host.example.com 5.8 Generic_108528-12 sun4m sparc
+//
+// SparcStation 20 Solaris 8:
+// SunOS host.example.com 5.8 Generic_108528-12 sun4m sparc SUNW,SPARCstation-20
+//
+// Mac OS X (Darwin)
+// Darwin home-eden.local 7.5.0 Darwin Kernel Version 7.5.0: Thu Aug 5 19:26:16 PDT 2004; root:xnu/xnu-517.7.21.obj~3/RELEASE_PPC Power Macintosh
+//
+// Mac OS X early versions
+//
+
+// }}}
+
+/* TODO:
+ * - define endianness, to allow matchSignature("bigend") etc.
+ */
+
+/**
+ * Retrieves information about the current operating system
+ *
+ * This class uses php_uname() to grok information about the current OS
+ *
+ * @category pear
+ * @package PEAR
+ * @author Stig Bakken
+ * @author Gregory Beaver
+ * @copyright 1997-2009 The Authors
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version Release: 1.9.4
+ * @link http://pear.php.net/package/PEAR
+ * @since Class available since Release 0.1
+ */
+class OS_Guess
+{
+ var $sysname;
+ var $nodename;
+ var $cpu;
+ var $release;
+ var $extra;
+
+ function OS_Guess($uname = null)
+ {
+ list($this->sysname,
+ $this->release,
+ $this->cpu,
+ $this->extra,
+ $this->nodename) = $this->parseSignature($uname);
+ }
+
+ function parseSignature($uname = null)
+ {
+ static $sysmap = array(
+ 'HP-UX' => 'hpux',
+ 'IRIX64' => 'irix',
+ );
+ static $cpumap = array(
+ 'i586' => 'i386',
+ 'i686' => 'i386',
+ 'ppc' => 'powerpc',
+ );
+ if ($uname === null) {
+ $uname = php_uname();
+ }
+ $parts = preg_split('/\s+/', trim($uname));
+ $n = count($parts);
+
+ $release = $machine = $cpu = '';
+ $sysname = $parts[0];
+ $nodename = $parts[1];
+ $cpu = $parts[$n-1];
+ $extra = '';
+ if ($cpu == 'unknown') {
+ $cpu = $parts[$n - 2];
+ }
+
+ switch ($sysname) {
+ case 'AIX' :
+ $release = "$parts[3].$parts[2]";
+ break;
+ case 'Windows' :
+ switch ($parts[1]) {
+ case '95/98':
+ $release = '9x';
+ break;
+ default:
+ $release = $parts[1];
+ break;
+ }
+ $cpu = 'i386';
+ break;
+ case 'Linux' :
+ $extra = $this->_detectGlibcVersion();
+ // use only the first two digits from the kernel version
+ $release = preg_replace('/^([0-9]+\.[0-9]+).*/', '\1', $parts[2]);
+ break;
+ case 'Mac' :
+ $sysname = 'darwin';
+ $nodename = $parts[2];
+ $release = $parts[3];
+ if ($cpu == 'Macintosh') {
+ if ($parts[$n - 2] == 'Power') {
+ $cpu = 'powerpc';
+ }
+ }
+ break;
+ case 'Darwin' :
+ if ($cpu == 'Macintosh') {
+ if ($parts[$n - 2] == 'Power') {
+ $cpu = 'powerpc';
+ }
+ }
+ $release = preg_replace('/^([0-9]+\.[0-9]+).*/', '\1', $parts[2]);
+ break;
+ default:
+ $release = preg_replace('/-.*/', '', $parts[2]);
+ break;
+ }
+
+ if (isset($sysmap[$sysname])) {
+ $sysname = $sysmap[$sysname];
+ } else {
+ $sysname = strtolower($sysname);
+ }
+ if (isset($cpumap[$cpu])) {
+ $cpu = $cpumap[$cpu];
+ }
+ return array($sysname, $release, $cpu, $extra, $nodename);
+ }
+
+ function _detectGlibcVersion()
+ {
+ static $glibc = false;
+ if ($glibc !== false) {
+ return $glibc; // no need to run this multiple times
+ }
+ $major = $minor = 0;
+ include_once "System.php";
+ // Use glibc's header file to
+ // get major and minor version number:
+ if (@file_exists('/usr/include/features.h') &&
+ @is_readable('/usr/include/features.h')) {
+ if (!@file_exists('/usr/bin/cpp') || !@is_executable('/usr/bin/cpp')) {
+ $features_file = fopen('/usr/include/features.h', 'rb');
+ while (!feof($features_file)) {
+ $line = fgets($features_file, 8192);
+ if (!$line || (strpos($line, '#define') === false)) {
+ continue;
+ }
+ if (strpos($line, '__GLIBC__')) {
+ // major version number #define __GLIBC__ version
+ $line = preg_split('/\s+/', $line);
+ $glibc_major = trim($line[2]);
+ if (isset($glibc_minor)) {
+ break;
+ }
+ continue;
+ }
+
+ if (strpos($line, '__GLIBC_MINOR__')) {
+ // got the minor version number
+ // #define __GLIBC_MINOR__ version
+ $line = preg_split('/\s+/', $line);
+ $glibc_minor = trim($line[2]);
+ if (isset($glibc_major)) {
+ break;
+ }
+ continue;
+ }
+ }
+ fclose($features_file);
+ if (!isset($glibc_major) || !isset($glibc_minor)) {
+ return $glibc = '';
+ }
+ return $glibc = 'glibc' . trim($glibc_major) . "." . trim($glibc_minor) ;
+ } // no cpp
+
+ $tmpfile = System::mktemp("glibctest");
+ $fp = fopen($tmpfile, "w");
+ fwrite($fp, "#include \n__GLIBC__ __GLIBC_MINOR__\n");
+ fclose($fp);
+ $cpp = popen("/usr/bin/cpp $tmpfile", "r");
+ while ($line = fgets($cpp, 1024)) {
+ if ($line{0} == '#' || trim($line) == '') {
+ continue;
+ }
+
+ if (list($major, $minor) = explode(' ', trim($line))) {
+ break;
+ }
+ }
+ pclose($cpp);
+ unlink($tmpfile);
+ } // features.h
+
+ if (!($major && $minor) && @is_link('/lib/libc.so.6')) {
+ // Let's try reading the libc.so.6 symlink
+ if (preg_match('/^libc-(.*)\.so$/', basename(readlink('/lib/libc.so.6')), $matches)) {
+ list($major, $minor) = explode('.', $matches[1]);
+ }
+ }
+
+ if (!($major && $minor)) {
+ return $glibc = '';
+ }
+
+ return $glibc = "glibc{$major}.{$minor}";
+ }
+
+ function getSignature()
+ {
+ if (empty($this->extra)) {
+ return "{$this->sysname}-{$this->release}-{$this->cpu}";
+ }
+ return "{$this->sysname}-{$this->release}-{$this->cpu}-{$this->extra}";
+ }
+
+ function getSysname()
+ {
+ return $this->sysname;
+ }
+
+ function getNodename()
+ {
+ return $this->nodename;
+ }
+
+ function getCpu()
+ {
+ return $this->cpu;
+ }
+
+ function getRelease()
+ {
+ return $this->release;
+ }
+
+ function getExtra()
+ {
+ return $this->extra;
+ }
+
+ function matchSignature($match)
+ {
+ $fragments = is_array($match) ? $match : explode('-', $match);
+ $n = count($fragments);
+ $matches = 0;
+ if ($n > 0) {
+ $matches += $this->_matchFragment($fragments[0], $this->sysname);
+ }
+ if ($n > 1) {
+ $matches += $this->_matchFragment($fragments[1], $this->release);
+ }
+ if ($n > 2) {
+ $matches += $this->_matchFragment($fragments[2], $this->cpu);
+ }
+ if ($n > 3) {
+ $matches += $this->_matchFragment($fragments[3], $this->extra);
+ }
+ return ($matches == $n);
+ }
+
+ function _matchFragment($fragment, $value)
+ {
+ if (strcspn($fragment, '*?') < strlen($fragment)) {
+ $reg = '/^' . str_replace(array('*', '?', '/'), array('.*', '.', '\\/'), $fragment) . '\\z/';
+ return preg_match($reg, $value);
+ }
+ return ($fragment == '*' || !strcasecmp($fragment, $value));
+ }
+
+}
+/*
+ * Local Variables:
+ * indent-tabs-mode: nil
+ * c-basic-offset: 4
+ * End:
+ */
\ No newline at end of file
diff --git a/3rdparty/PEAR-LICENSE b/3rdparty/PEAR-LICENSE
new file mode 100644
index 0000000000..a00a2421fd
--- /dev/null
+++ b/3rdparty/PEAR-LICENSE
@@ -0,0 +1,27 @@
+Copyright (c) 1997-2009,
+ Stig Bakken ,
+ Gregory Beaver ,
+ Helgi Þormar Þorbjörnsson ,
+ Tomas V.V.Cox ,
+ Martin Jansen .
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/3rdparty/PEAR.php b/3rdparty/PEAR.php
index f832c0d491..2aa85259d6 100644
--- a/3rdparty/PEAR.php
+++ b/3rdparty/PEAR.php
@@ -1,26 +1,27 @@
|
-// | Stig Bakken |
-// | Tomas V.V.Cox |
-// +--------------------------------------------------------------------+
-//
-// $Id: PEAR.php,v 1.82.2.6 2005/01/01 05:24:51 cellog Exp $
-//
+/**
+ * PEAR, the PHP Extension and Application Repository
+ *
+ * PEAR class and PEAR_Error class
+ *
+ * PHP versions 4 and 5
+ *
+ * @category pear
+ * @package PEAR
+ * @author Sterling Hughes
+ * @author Stig Bakken
+ * @author Tomas V.V.Cox
+ * @author Greg Beaver
+ * @copyright 1997-2010 The Authors
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version CVS: $Id: PEAR.php 313023 2011-07-06 19:17:11Z dufuz $
+ * @link http://pear.php.net/package/PEAR
+ * @since File available since Release 0.1
+ */
+/**#@+
+ * ERROR constants
+ */
define('PEAR_ERROR_RETURN', 1);
define('PEAR_ERROR_PRINT', 2);
define('PEAR_ERROR_TRIGGER', 4);
@@ -31,6 +32,7 @@ define('PEAR_ERROR_CALLBACK', 16);
* @deprecated
*/
define('PEAR_ERROR_EXCEPTION', 32);
+/**#@-*/
define('PEAR_ZE2', (function_exists('version_compare') &&
version_compare(zend_version(), "2-dev", "ge")));
@@ -44,15 +46,6 @@ if (substr(PHP_OS, 0, 3) == 'WIN') {
define('PEAR_OS', 'Unix'); // blatant assumption
}
-// instant backwards compatibility
-if (!defined('PATH_SEPARATOR')) {
- if (OS_WINDOWS) {
- define('PATH_SEPARATOR', ';');
- } else {
- define('PATH_SEPARATOR', ':');
- }
-}
-
$GLOBALS['_PEAR_default_error_mode'] = PEAR_ERROR_RETURN;
$GLOBALS['_PEAR_default_error_options'] = E_USER_NOTICE;
$GLOBALS['_PEAR_destructor_object_list'] = array();
@@ -78,14 +71,21 @@ $GLOBALS['_PEAR_error_handler_stack'] = array();
* IMPORTANT! To use the emulated destructors you need to create the
* objects by reference: $obj =& new PEAR_child;
*
- * @since PHP 4.0.2
- * @author Stig Bakken
- * @see http://pear.php.net/manual/
+ * @category pear
+ * @package PEAR
+ * @author Stig Bakken
+ * @author Tomas V.V. Cox
+ * @author Greg Beaver
+ * @copyright 1997-2006 The PHP Group
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version Release: 1.9.4
+ * @link http://pear.php.net/package/PEAR
+ * @see PEAR_Error
+ * @since Class available since PHP 4.0.2
+ * @link http://pear.php.net/manual/en/core.pear.php#core.pear.pear
*/
class PEAR
{
- // {{{ properties
-
/**
* Whether to enable internal debug messages.
*
@@ -136,10 +136,6 @@ class PEAR
*/
var $_expected_errors = array();
- // }}}
-
- // {{{ constructor
-
/**
* Constructor. Registers this object in
* $_PEAR_destructor_object_list for destructor emulation if a
@@ -156,9 +152,11 @@ class PEAR
if ($this->_debug) {
print "PEAR constructor called, class=$classname\n";
}
+
if ($error_class !== null) {
$this->_error_class = $error_class;
}
+
while ($classname && strcasecmp($classname, "pear")) {
$destructor = "_$classname";
if (method_exists($this, $destructor)) {
@@ -175,9 +173,6 @@ class PEAR
}
}
- // }}}
- // {{{ destructor
-
/**
* Destructor (the emulated type of...). Does nothing right now,
* but is included for forward compatibility, so subclass
@@ -195,9 +190,6 @@ class PEAR
}
}
- // }}}
- // {{{ getStaticProperty()
-
/**
* If you have a class that's mostly/entirely static, and you need static
* properties, you can use this method to simulate them. Eg. in your method(s)
@@ -213,12 +205,17 @@ class PEAR
function &getStaticProperty($class, $var)
{
static $properties;
+ if (!isset($properties[$class])) {
+ $properties[$class] = array();
+ }
+
+ if (!array_key_exists($var, $properties[$class])) {
+ $properties[$class][$var] = null;
+ }
+
return $properties[$class][$var];
}
- // }}}
- // {{{ registerShutdownFunc()
-
/**
* Use this function to register a shutdown method for static
* classes.
@@ -230,12 +227,15 @@ class PEAR
*/
function registerShutdownFunc($func, $args = array())
{
+ // if we are called statically, there is a potential
+ // that no shutdown func is registered. Bug #6445
+ if (!isset($GLOBALS['_PEAR_SHUTDOWN_REGISTERED'])) {
+ register_shutdown_function("_PEAR_call_destructors");
+ $GLOBALS['_PEAR_SHUTDOWN_REGISTERED'] = true;
+ }
$GLOBALS['_PEAR_shutdown_funcs'][] = array($func, $args);
}
- // }}}
- // {{{ isError()
-
/**
* Tell whether a value is a PEAR error.
*
@@ -247,22 +247,20 @@ class PEAR
* @access public
* @return bool true if parameter is an error
*/
- static function isError($data, $code = null)
+ function isError($data, $code = null)
{
- if ($data instanceof PEAR_Error) {
- if (is_null($code)) {
- return true;
- } elseif (is_string($code)) {
- return $data->getMessage() == $code;
- } else {
- return $data->getCode() == $code;
- }
+ if (!is_a($data, 'PEAR_Error')) {
+ return false;
}
- return false;
- }
- // }}}
- // {{{ setErrorHandling()
+ if (is_null($code)) {
+ return true;
+ } elseif (is_string($code)) {
+ return $data->getMessage() == $code;
+ }
+
+ return $data->getCode() == $code;
+ }
/**
* Sets how errors generated by this object should be handled.
@@ -302,10 +300,9 @@ class PEAR
*
* @since PHP 4.0.5
*/
-
function setErrorHandling($mode = null, $options = null)
{
- if (isset($this) && $this instanceof PEAR) {
+ if (isset($this) && is_a($this, 'PEAR')) {
$setmode = &$this->_default_error_mode;
$setoptions = &$this->_default_error_options;
} else {
@@ -340,9 +337,6 @@ class PEAR
}
}
- // }}}
- // {{{ expectError()
-
/**
* This method is used to tell which errors you expect to get.
* Expected errors are always returned with error mode
@@ -365,12 +359,9 @@ class PEAR
} else {
array_push($this->_expected_errors, array($code));
}
- return sizeof($this->_expected_errors);
+ return count($this->_expected_errors);
}
- // }}}
- // {{{ popExpect()
-
/**
* This method pops one element off the expected error codes
* stack.
@@ -382,9 +373,6 @@ class PEAR
return array_pop($this->_expected_errors);
}
- // }}}
- // {{{ _checkDelExpect()
-
/**
* This method checks unsets an error code if available
*
@@ -396,8 +384,7 @@ class PEAR
function _checkDelExpect($error_code)
{
$deleted = false;
-
- foreach ($this->_expected_errors AS $key => $error_array) {
+ foreach ($this->_expected_errors as $key => $error_array) {
if (in_array($error_code, $error_array)) {
unset($this->_expected_errors[$key][array_search($error_code, $error_array)]);
$deleted = true;
@@ -408,12 +395,10 @@ class PEAR
unset($this->_expected_errors[$key]);
}
}
+
return $deleted;
}
- // }}}
- // {{{ delExpect()
-
/**
* This method deletes all occurences of the specified element from
* the expected error codes stack.
@@ -426,34 +411,26 @@ class PEAR
function delExpect($error_code)
{
$deleted = false;
-
if ((is_array($error_code) && (0 != count($error_code)))) {
- // $error_code is a non-empty array here;
- // we walk through it trying to unset all
- // values
- foreach($error_code as $key => $error) {
- if ($this->_checkDelExpect($error)) {
- $deleted = true;
- } else {
- $deleted = false;
- }
+ // $error_code is a non-empty array here; we walk through it trying
+ // to unset all values
+ foreach ($error_code as $key => $error) {
+ $deleted = $this->_checkDelExpect($error) ? true : false;
}
+
return $deleted ? true : PEAR::raiseError("The expected error you submitted does not exist"); // IMPROVE ME
} elseif (!empty($error_code)) {
// $error_code comes alone, trying to unset it
if ($this->_checkDelExpect($error_code)) {
return true;
- } else {
- return PEAR::raiseError("The expected error you submitted does not exist"); // IMPROVE ME
}
- } else {
- // $error_code is empty
- return PEAR::raiseError("The expected error you submitted is empty"); // IMPROVE ME
- }
- }
- // }}}
- // {{{ raiseError()
+ return PEAR::raiseError("The expected error you submitted does not exist"); // IMPROVE ME
+ }
+
+ // $error_code is empty
+ return PEAR::raiseError("The expected error you submitted is empty"); // IMPROVE ME
+ }
/**
* This method is a wrapper that returns an instance of the
@@ -492,7 +469,7 @@ class PEAR
* @see PEAR::setErrorHandling
* @since PHP 4.0.5
*/
- function raiseError($message = null,
+ function &raiseError($message = null,
$code = null,
$mode = null,
$options = null,
@@ -509,13 +486,20 @@ class PEAR
$message = $message->getMessage();
}
- if (isset($this) && isset($this->_expected_errors) && sizeof($this->_expected_errors) > 0 && sizeof($exp = end($this->_expected_errors))) {
+ if (
+ isset($this) &&
+ isset($this->_expected_errors) &&
+ count($this->_expected_errors) > 0 &&
+ count($exp = end($this->_expected_errors))
+ ) {
if ($exp[0] == "*" ||
(is_int(reset($exp)) && in_array($code, $exp)) ||
- (is_string(reset($exp)) && in_array($message, $exp))) {
+ (is_string(reset($exp)) && in_array($message, $exp))
+ ) {
$mode = PEAR_ERROR_RETURN;
}
}
+
// No mode given, try global ones
if ($mode === null) {
// Class error handler
@@ -536,38 +520,52 @@ class PEAR
} else {
$ec = 'PEAR_Error';
}
- if ($skipmsg) {
- return new $ec($code, $mode, $options, $userinfo);
- } else {
- return new $ec($message, $code, $mode, $options, $userinfo);
- }
- }
- // }}}
- // {{{ throwError()
+ if (intval(PHP_VERSION) < 5) {
+ // little non-eval hack to fix bug #12147
+ include 'PEAR/FixPHP5PEARWarnings.php';
+ return $a;
+ }
+
+ if ($skipmsg) {
+ $a = new $ec($code, $mode, $options, $userinfo);
+ } else {
+ $a = new $ec($message, $code, $mode, $options, $userinfo);
+ }
+
+ return $a;
+ }
/**
* Simpler form of raiseError with fewer options. In most cases
* message, code and userinfo are enough.
*
- * @param string $message
+ * @param mixed $message a text error message or a PEAR error object
*
+ * @param int $code a numeric error code (it is up to your class
+ * to define these if you want to use codes)
+ *
+ * @param string $userinfo If you need to pass along for example debug
+ * information, this parameter is meant for that.
+ *
+ * @access public
+ * @return object a PEAR error object
+ * @see PEAR::raiseError
*/
- function throwError($message = null,
- $code = null,
- $userinfo = null)
+ function &throwError($message = null, $code = null, $userinfo = null)
{
- if (isset($this) && $this instanceof PEAR) {
- return $this->raiseError($message, $code, null, null, $userinfo);
- } else {
- return PEAR::raiseError($message, $code, null, null, $userinfo);
+ if (isset($this) && is_a($this, 'PEAR')) {
+ $a = &$this->raiseError($message, $code, null, null, $userinfo);
+ return $a;
}
+
+ $a = &PEAR::raiseError($message, $code, null, null, $userinfo);
+ return $a;
}
- // }}}
function staticPushErrorHandling($mode, $options = null)
{
- $stack = &$GLOBALS['_PEAR_error_handler_stack'];
+ $stack = &$GLOBALS['_PEAR_error_handler_stack'];
$def_mode = &$GLOBALS['_PEAR_default_error_mode'];
$def_options = &$GLOBALS['_PEAR_default_error_options'];
$stack[] = array($def_mode, $def_options);
@@ -636,8 +634,6 @@ class PEAR
return true;
}
- // {{{ pushErrorHandling()
-
/**
* Push a new error handler on top of the error handler options stack. With this
* you can easily override the actual error handler for some code and restore
@@ -653,7 +649,7 @@ class PEAR
function pushErrorHandling($mode, $options = null)
{
$stack = &$GLOBALS['_PEAR_error_handler_stack'];
- if (isset($this) && $this instanceof PEAR) {
+ if (isset($this) && is_a($this, 'PEAR')) {
$def_mode = &$this->_default_error_mode;
$def_options = &$this->_default_error_options;
} else {
@@ -662,7 +658,7 @@ class PEAR
}
$stack[] = array($def_mode, $def_options);
- if (isset($this) && $this instanceof PEAR) {
+ if (isset($this) && is_a($this, 'PEAR')) {
$this->setErrorHandling($mode, $options);
} else {
PEAR::setErrorHandling($mode, $options);
@@ -671,9 +667,6 @@ class PEAR
return true;
}
- // }}}
- // {{{ popErrorHandling()
-
/**
* Pop the last error handler used
*
@@ -687,7 +680,7 @@ class PEAR
array_pop($stack);
list($mode, $options) = $stack[sizeof($stack) - 1];
array_pop($stack);
- if (isset($this) && $this instanceof PEAR) {
+ if (isset($this) && is_a($this, 'PEAR')) {
$this->setErrorHandling($mode, $options);
} else {
PEAR::setErrorHandling($mode, $options);
@@ -695,9 +688,6 @@ class PEAR
return true;
}
- // }}}
- // {{{ loadExtension()
-
/**
* OS independant PHP extension load. Remember to take care
* on the correct extension name for case sensitive OSes.
@@ -707,31 +697,38 @@ class PEAR
*/
function loadExtension($ext)
{
- if (!extension_loaded($ext)) {
- // if either returns true dl() will produce a FATAL error, stop that
- if ((ini_get('enable_dl') != 1) || (ini_get('safe_mode') == 1)) {
- return false;
- }
- if (OS_WINDOWS) {
- $suffix = '.dll';
- } elseif (PHP_OS == 'HP-UX') {
- $suffix = '.sl';
- } elseif (PHP_OS == 'AIX') {
- $suffix = '.a';
- } elseif (PHP_OS == 'OSX') {
- $suffix = '.bundle';
- } else {
- $suffix = '.so';
- }
- return @dl('php_'.$ext.$suffix) || @dl($ext.$suffix);
+ if (extension_loaded($ext)) {
+ return true;
}
- return true;
- }
- // }}}
+ // if either returns true dl() will produce a FATAL error, stop that
+ if (
+ function_exists('dl') === false ||
+ ini_get('enable_dl') != 1 ||
+ ini_get('safe_mode') == 1
+ ) {
+ return false;
+ }
+
+ if (OS_WINDOWS) {
+ $suffix = '.dll';
+ } elseif (PHP_OS == 'HP-UX') {
+ $suffix = '.sl';
+ } elseif (PHP_OS == 'AIX') {
+ $suffix = '.a';
+ } elseif (PHP_OS == 'OSX') {
+ $suffix = '.bundle';
+ } else {
+ $suffix = '.so';
+ }
+
+ return @dl('php_'.$ext.$suffix) || @dl($ext.$suffix);
+ }
}
-// {{{ _PEAR_call_destructors()
+if (PEAR_ZE2) {
+ include_once 'PEAR5.php';
+}
function _PEAR_call_destructors()
{
@@ -740,9 +737,16 @@ function _PEAR_call_destructors()
sizeof($_PEAR_destructor_object_list))
{
reset($_PEAR_destructor_object_list);
- if (@PEAR::getStaticProperty('PEAR', 'destructlifo')) {
+ if (PEAR_ZE2) {
+ $destructLifoExists = PEAR5::getStaticProperty('PEAR', 'destructlifo');
+ } else {
+ $destructLifoExists = PEAR::getStaticProperty('PEAR', 'destructlifo');
+ }
+
+ if ($destructLifoExists) {
$_PEAR_destructor_object_list = array_reverse($_PEAR_destructor_object_list);
}
+
while (list($k, $objref) = each($_PEAR_destructor_object_list)) {
$classname = get_class($objref);
while ($classname) {
@@ -761,19 +765,36 @@ function _PEAR_call_destructors()
}
// Now call the shutdown functions
- if (is_array($GLOBALS['_PEAR_shutdown_funcs']) AND !empty($GLOBALS['_PEAR_shutdown_funcs'])) {
+ if (
+ isset($GLOBALS['_PEAR_shutdown_funcs']) &&
+ is_array($GLOBALS['_PEAR_shutdown_funcs']) &&
+ !empty($GLOBALS['_PEAR_shutdown_funcs'])
+ ) {
foreach ($GLOBALS['_PEAR_shutdown_funcs'] as $value) {
call_user_func_array($value[0], $value[1]);
}
}
}
-// }}}
-
+/**
+ * Standard PEAR error class for PHP 4
+ *
+ * This class is supserseded by {@link PEAR_Exception} in PHP 5
+ *
+ * @category pear
+ * @package PEAR
+ * @author Stig Bakken
+ * @author Tomas V.V. Cox
+ * @author Gregory Beaver
+ * @copyright 1997-2006 The PHP Group
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version Release: 1.9.4
+ * @link http://pear.php.net/manual/en/core.pear.pear-error.php
+ * @see PEAR::raiseError(), PEAR::throwError()
+ * @since Class available since PHP 4.0.2
+ */
class PEAR_Error
{
- // {{{ properties
-
var $error_message_prefix = '';
var $mode = PEAR_ERROR_RETURN;
var $level = E_USER_NOTICE;
@@ -782,9 +803,6 @@ class PEAR_Error
var $userinfo = '';
var $backtrace = null;
- // }}}
- // {{{ constructor
-
/**
* PEAR_Error constructor
*
@@ -815,11 +833,20 @@ class PEAR_Error
$this->code = $code;
$this->mode = $mode;
$this->userinfo = $userinfo;
- if (function_exists("debug_backtrace")) {
- if (@!PEAR::getStaticProperty('PEAR_Error', 'skiptrace')) {
- $this->backtrace = debug_backtrace();
+
+ if (PEAR_ZE2) {
+ $skiptrace = PEAR5::getStaticProperty('PEAR_Error', 'skiptrace');
+ } else {
+ $skiptrace = PEAR::getStaticProperty('PEAR_Error', 'skiptrace');
+ }
+
+ if (!$skiptrace) {
+ $this->backtrace = debug_backtrace();
+ if (isset($this->backtrace[0]) && isset($this->backtrace[0]['object'])) {
+ unset($this->backtrace[0]['object']);
}
}
+
if ($mode & PEAR_ERROR_CALLBACK) {
$this->level = E_USER_NOTICE;
$this->callback = $options;
@@ -827,20 +854,25 @@ class PEAR_Error
if ($options === null) {
$options = E_USER_NOTICE;
}
+
$this->level = $options;
$this->callback = null;
}
+
if ($this->mode & PEAR_ERROR_PRINT) {
if (is_null($options) || is_int($options)) {
$format = "%s";
} else {
$format = $options;
}
+
printf($format, $this->getMessage());
}
+
if ($this->mode & PEAR_ERROR_TRIGGER) {
trigger_error($this->getMessage(), $this->level);
}
+
if ($this->mode & PEAR_ERROR_DIE) {
$msg = $this->getMessage();
if (is_null($options) || is_int($options)) {
@@ -853,47 +885,39 @@ class PEAR_Error
}
die(sprintf($format, $msg));
}
- if ($this->mode & PEAR_ERROR_CALLBACK) {
- if (is_callable($this->callback)) {
- call_user_func($this->callback, $this);
- }
+
+ if ($this->mode & PEAR_ERROR_CALLBACK && is_callable($this->callback)) {
+ call_user_func($this->callback, $this);
}
+
if ($this->mode & PEAR_ERROR_EXCEPTION) {
- trigger_error("PEAR_ERROR_EXCEPTION is obsolete, use class PEAR_ErrorStack for exceptions", E_USER_WARNING);
- eval('$e = new Exception($this->message, $this->code);$e->PEAR_Error = $this;throw($e);');
+ trigger_error("PEAR_ERROR_EXCEPTION is obsolete, use class PEAR_Exception for exceptions", E_USER_WARNING);
+ eval('$e = new Exception($this->message, $this->code);throw($e);');
}
}
- // }}}
- // {{{ getMode()
-
/**
* Get the error mode from an error object.
*
* @return int error mode
* @access public
*/
- function getMode() {
+ function getMode()
+ {
return $this->mode;
}
- // }}}
- // {{{ getCallback()
-
/**
* Get the callback function/method from an error object.
*
* @return mixed callback function or object/method array
* @access public
*/
- function getCallback() {
+ function getCallback()
+ {
return $this->callback;
}
- // }}}
- // {{{ getMessage()
-
-
/**
* Get the error message from an error object.
*
@@ -905,10 +929,6 @@ class PEAR_Error
return ($this->error_message_prefix . $this->message);
}
-
- // }}}
- // {{{ getCode()
-
/**
* Get error code from an error object
*
@@ -920,9 +940,6 @@ class PEAR_Error
return $this->code;
}
- // }}}
- // {{{ getType()
-
/**
* Get the name of this error/exception.
*
@@ -934,9 +951,6 @@ class PEAR_Error
return get_class($this);
}
- // }}}
- // {{{ getUserInfo()
-
/**
* Get additional user-supplied information.
*
@@ -948,9 +962,6 @@ class PEAR_Error
return $this->userinfo;
}
- // }}}
- // {{{ getDebugInfo()
-
/**
* Get additional debug information supplied by the application.
*
@@ -962,9 +973,6 @@ class PEAR_Error
return $this->getUserInfo();
}
- // }}}
- // {{{ getBacktrace()
-
/**
* Get the call backtrace from where the error was generated.
* Supported with PHP 4.3.0 or newer.
@@ -975,15 +983,15 @@ class PEAR_Error
*/
function getBacktrace($frame = null)
{
+ if (defined('PEAR_IGNORE_BACKTRACE')) {
+ return null;
+ }
if ($frame === null) {
return $this->backtrace;
}
return $this->backtrace[$frame];
}
- // }}}
- // {{{ addUserInfo()
-
function addUserInfo($info)
{
if (empty($this->userinfo)) {
@@ -993,8 +1001,10 @@ class PEAR_Error
}
}
- // }}}
- // {{{ toString()
+ function __toString()
+ {
+ return $this->getMessage();
+ }
/**
* Make a string representation of this object.
@@ -1002,7 +1012,8 @@ class PEAR_Error
* @return string a string with an object summary
* @access public
*/
- function toString() {
+ function toString()
+ {
$modes = array();
$levels = array(E_USER_NOTICE => 'notice',
E_USER_WARNING => 'warning',
@@ -1041,8 +1052,6 @@ class PEAR_Error
$this->error_message_prefix,
$this->userinfo);
}
-
- // }}}
}
/*
@@ -1052,4 +1061,3 @@ class PEAR_Error
* c-basic-offset: 4
* End:
*/
-?>
diff --git a/3rdparty/PEAR/Autoloader.php b/3rdparty/PEAR/Autoloader.php
index de0278d619..0ed707ec84 100644
--- a/3rdparty/PEAR/Autoloader.php
+++ b/3rdparty/PEAR/Autoloader.php
@@ -1,29 +1,31 @@
+ * @copyright 1997-2009 The Authors
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version CVS: $Id: Autoloader.php 313023 2011-07-06 19:17:11Z dufuz $
+ * @link http://pear.php.net/manual/en/core.ppm.php#core.ppm.pear-autoloader
+ * @since File available since Release 0.1
+ * @deprecated File deprecated in Release 1.4.0a1
+ */
+
// /* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available through the world-wide-web at the following url: |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Stig Bakken |
-// | |
-// +----------------------------------------------------------------------+
-//
-// $Id: Autoloader.php,v 1.11 2004/02/27 02:21:29 cellog Exp $
if (!extension_loaded("overload")) {
// die hard without ext/overload
die("Rebuild PHP with the `overload' extension to use PEAR_Autoloader");
}
+/**
+ * Include for PEAR_Error and PEAR classes
+ */
require_once "PEAR.php";
/**
@@ -38,7 +40,15 @@ require_once "PEAR.php";
* methods, an instance of each class providing separated methods is
* stored and called every time the aggregated method is called.
*
- * @author Stig Sther Bakken
+ * @category pear
+ * @package PEAR
+ * @author Stig Bakken
+ * @copyright 1997-2009 The Authors
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version Release: 1.9.4
+ * @link http://pear.php.net/manual/en/core.ppm.php#core.ppm.pear-autoloader
+ * @since File available since Release 0.1
+ * @deprecated File deprecated in Release 1.4.0a1
*/
class PEAR_Autoloader extends PEAR
{
diff --git a/3rdparty/PEAR/Builder.php b/3rdparty/PEAR/Builder.php
index 4f6cc135d1..90f3a14555 100644
--- a/3rdparty/PEAR/Builder.php
+++ b/3rdparty/PEAR/Builder.php
@@ -1,47 +1,60 @@
|
-// +----------------------------------------------------------------------+
-//
-// $Id: Builder.php,v 1.16.2.3 2005/02/17 17:55:01 cellog Exp $
+/**
+ * PEAR_Builder for building PHP extensions (PECL packages)
+ *
+ * PHP versions 4 and 5
+ *
+ * @category pear
+ * @package PEAR
+ * @author Stig Bakken
+ * @author Greg Beaver
+ * @copyright 1997-2009 The Authors
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version CVS: $Id: Builder.php 313024 2011-07-06 19:51:24Z dufuz $
+ * @link http://pear.php.net/package/PEAR
+ * @since File available since Release 0.1
+ *
+ * TODO: log output parameters in PECL command line
+ * TODO: msdev path in configuration
+ */
+/**
+ * Needed for extending PEAR_Builder
+ */
require_once 'PEAR/Common.php';
+require_once 'PEAR/PackageFile.php';
/**
* Class to handle building (compiling) extensions.
*
- * @author Stig Sther Bakken
+ * @category pear
+ * @package PEAR
+ * @author Stig Bakken
+ * @author Greg Beaver
+ * @copyright 1997-2009 The Authors
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version Release: 1.9.4
+ * @link http://pear.php.net/package/PEAR
+ * @since Class available since PHP 4.0.2
+ * @see http://pear.php.net/manual/en/core.ppm.pear-builder.php
*/
class PEAR_Builder extends PEAR_Common
{
- // {{{ properties
-
var $php_api_version = 0;
var $zend_module_api_no = 0;
var $zend_extension_api_no = 0;
var $extensions_built = array();
+ /**
+ * @var string Used for reporting when it is not possible to pass function
+ * via extra parameter, e.g. log, msdevCallback
+ */
var $current_callback = null;
// used for msdev builds
var $_lastline = null;
var $_firstline = null;
- // }}}
- // {{{ constructor
/**
* PEAR_Builder constructor.
@@ -56,35 +69,48 @@ class PEAR_Builder extends PEAR_Common
$this->setFrontendObject($ui);
}
- // }}}
-
- // {{{ _build_win32()
-
/**
* Build an extension from source on windows.
* requires msdev
*/
function _build_win32($descfile, $callback = null)
{
- if (PEAR::isError($info = $this->infoFromDescriptionFile($descfile))) {
- return $info;
+ if (is_object($descfile)) {
+ $pkg = $descfile;
+ $descfile = $pkg->getPackageFile();
+ } else {
+ $pf = &new PEAR_PackageFile($this->config, $this->debug);
+ $pkg = &$pf->fromPackageFile($descfile, PEAR_VALIDATE_NORMAL);
+ if (PEAR::isError($pkg)) {
+ return $pkg;
+ }
}
$dir = dirname($descfile);
$old_cwd = getcwd();
- if (!@chdir($dir)) {
+ if (!file_exists($dir) || !is_dir($dir) || !chdir($dir)) {
return $this->raiseError("could not chdir to $dir");
}
+
+ // packages that were in a .tar have the packagefile in this directory
+ $vdir = $pkg->getPackage() . '-' . $pkg->getVersion();
+ if (file_exists($dir) && is_dir($vdir)) {
+ if (!chdir($vdir)) {
+ return $this->raiseError("could not chdir to " . realpath($vdir));
+ }
+
+ $dir = getcwd();
+ }
+
$this->log(2, "building in $dir");
- $dsp = $info['package'].'.dsp';
- if (!@is_file("$dir/$dsp")) {
+ $dsp = $pkg->getPackage().'.dsp';
+ if (!file_exists("$dir/$dsp")) {
return $this->raiseError("The DSP $dsp does not exist.");
}
// XXX TODO: make release build type configurable
- $command = 'msdev '.$dsp.' /MAKE "'.$info['package']. ' - Release"';
+ $command = 'msdev '.$dsp.' /MAKE "'.$pkg->getPackage(). ' - Release"';
- $this->current_callback = $callback;
$err = $this->_runCommand($command, array(&$this, 'msdevCallback'));
if (PEAR::isError($err)) {
return $err;
@@ -93,12 +119,12 @@ class PEAR_Builder extends PEAR_Common
// figure out the build platform and type
$platform = 'Win32';
$buildtype = 'Release';
- if (preg_match('/.*?'.$info['package'].'\s-\s(\w+)\s(.*?)-+/i',$this->_firstline,$matches)) {
+ if (preg_match('/.*?'.$pkg->getPackage().'\s-\s(\w+)\s(.*?)-+/i',$this->_firstline,$matches)) {
$platform = $matches[1];
$buildtype = $matches[2];
}
- if (preg_match('/(.*)?\s-\s(\d+).*?(\d+)/',$this->_lastline,$matches)) {
+ if (preg_match('/(.*)?\s-\s(\d+).*?(\d+)/', $this->_lastline, $matches)) {
if ($matches[2]) {
// there were errors in the build
return $this->raiseError("There were errors during compilation.");
@@ -115,18 +141,19 @@ class PEAR_Builder extends PEAR_Common
// this regex depends on the build platform and type having been
// correctly identified above.
$regex ='/.*?!IF\s+"\$\(CFG\)"\s+==\s+("'.
- $info['package'].'\s-\s'.
+ $pkg->getPackage().'\s-\s'.
$platform.'\s'.
$buildtype.'").*?'.
'\/out:"(.*?)"/is';
- if ($dsptext && preg_match($regex,$dsptext,$matches)) {
+ if ($dsptext && preg_match($regex, $dsptext, $matches)) {
// what we get back is a relative path to the output file itself.
$outfile = realpath($matches[2]);
} else {
return $this->raiseError("Could not retrieve output information from $dsp.");
}
- if (@copy($outfile, "$dir/$out")) {
+ // realpath returns false if the file doesn't exist
+ if ($outfile && copy($outfile, "$dir/$out")) {
$outfile = "$dir/$out";
}
@@ -147,10 +174,9 @@ class PEAR_Builder extends PEAR_Common
if (!$this->_firstline)
$this->_firstline = $data;
$this->_lastline = $data;
+ call_user_func($this->current_callback, $what, $data);
}
- // }}}
- // {{{ _harventInstDir
/**
* @param string
* @param string
@@ -191,16 +217,13 @@ class PEAR_Builder extends PEAR_Common
return $ret;
}
- // }}}
-
- // {{{ build()
-
/**
* Build an extension from source. Runs "phpize" in the source
* directory, but compiles in a temporary directory
- * (/var/tmp/pear-build-USER/PACKAGE-VERSION).
+ * (TMPDIR/pear-build-USER/PACKAGE-VERSION).
*
- * @param string $descfile path to XML package description file
+ * @param string|PEAR_PackageFile_v* $descfile path to XML package description file, or
+ * a PEAR_PackageFile object
*
* @param mixed $callback callback function used to report output,
* see PEAR_Builder::_runCommand for details
@@ -216,48 +239,97 @@ class PEAR_Builder extends PEAR_Common
* @access public
*
* @see PEAR_Builder::_runCommand
- * @see PEAR_Common::infoFromDescriptionFile
*/
function build($descfile, $callback = null)
{
- if (PEAR_OS == "Windows") {
- return $this->_build_win32($descfile,$callback);
+ if (preg_match('/(\\/|\\\\|^)([^\\/\\\\]+)?php(.+)?$/',
+ $this->config->get('php_bin'), $matches)) {
+ if (isset($matches[2]) && strlen($matches[2]) &&
+ trim($matches[2]) != trim($this->config->get('php_prefix'))) {
+ $this->log(0, 'WARNING: php_bin ' . $this->config->get('php_bin') .
+ ' appears to have a prefix ' . $matches[2] . ', but' .
+ ' config variable php_prefix does not match');
+ }
+
+ if (isset($matches[3]) && strlen($matches[3]) &&
+ trim($matches[3]) != trim($this->config->get('php_suffix'))) {
+ $this->log(0, 'WARNING: php_bin ' . $this->config->get('php_bin') .
+ ' appears to have a suffix ' . $matches[3] . ', but' .
+ ' config variable php_suffix does not match');
+ }
}
+
+ $this->current_callback = $callback;
+ if (PEAR_OS == "Windows") {
+ return $this->_build_win32($descfile, $callback);
+ }
+
if (PEAR_OS != 'Unix') {
return $this->raiseError("building extensions not supported on this platform");
}
- if (PEAR::isError($info = $this->infoFromDescriptionFile($descfile))) {
- return $info;
+
+ if (is_object($descfile)) {
+ $pkg = $descfile;
+ $descfile = $pkg->getPackageFile();
+ if (is_a($pkg, 'PEAR_PackageFile_v1')) {
+ $dir = dirname($descfile);
+ } else {
+ $dir = $pkg->_config->get('temp_dir') . '/' . $pkg->getName();
+ // automatically delete at session end
+ $this->addTempFile($dir);
+ }
+ } else {
+ $pf = &new PEAR_PackageFile($this->config);
+ $pkg = &$pf->fromPackageFile($descfile, PEAR_VALIDATE_NORMAL);
+ if (PEAR::isError($pkg)) {
+ return $pkg;
+ }
+ $dir = dirname($descfile);
}
- $dir = dirname($descfile);
+
+ // Find config. outside of normal path - e.g. config.m4
+ foreach (array_keys($pkg->getInstallationFileList()) as $item) {
+ if (stristr(basename($item), 'config.m4') && dirname($item) != '.') {
+ $dir .= DIRECTORY_SEPARATOR . dirname($item);
+ break;
+ }
+ }
+
$old_cwd = getcwd();
- if (!@chdir($dir)) {
+ if (!file_exists($dir) || !is_dir($dir) || !chdir($dir)) {
return $this->raiseError("could not chdir to $dir");
}
- $vdir = "$info[package]-$info[version]";
+
+ $vdir = $pkg->getPackage() . '-' . $pkg->getVersion();
if (is_dir($vdir)) {
chdir($vdir);
}
+
$dir = getcwd();
$this->log(2, "building in $dir");
- $this->current_callback = $callback;
putenv('PATH=' . $this->config->get('bin_dir') . ':' . getenv('PATH'));
- $err = $this->_runCommand("phpize", array(&$this, 'phpizeCallback'));
+ $err = $this->_runCommand($this->config->get('php_prefix')
+ . "phpize" .
+ $this->config->get('php_suffix'),
+ array(&$this, 'phpizeCallback'));
if (PEAR::isError($err)) {
return $err;
}
+
if (!$err) {
return $this->raiseError("`phpize' failed");
}
// {{{ start of interactive part
$configure_command = "$dir/configure";
- if (isset($info['configure_options'])) {
- foreach ($info['configure_options'] as $o) {
+ $configure_options = $pkg->getConfigureOptions();
+ if ($configure_options) {
+ foreach ($configure_options as $o) {
+ $default = array_key_exists('default', $o) ? $o['default'] : null;
list($r) = $this->ui->userDialog('build',
array($o['prompt']),
array('text'),
- array(@$o['default']));
+ array($default));
if (substr($o['name'], 0, 5) == 'with-' &&
($r == 'yes' || $r == 'autodetect')) {
$configure_command .= " --$o[name]";
@@ -269,40 +341,41 @@ class PEAR_Builder extends PEAR_Common
// }}} end of interactive part
// FIXME make configurable
- if(!$user=getenv('USER')){
+ if (!$user=getenv('USER')) {
$user='defaultuser';
}
- $build_basedir = "/var/tmp/pear-build-$user";
- $build_dir = "$build_basedir/$info[package]-$info[version]";
- $inst_dir = "$build_basedir/install-$info[package]-$info[version]";
+
+ $tmpdir = $this->config->get('temp_dir');
+ $build_basedir = System::mktemp(' -t "' . $tmpdir . '" -d "pear-build-' . $user . '"');
+ $build_dir = "$build_basedir/$vdir";
+ $inst_dir = "$build_basedir/install-$vdir";
$this->log(1, "building in $build_dir");
if (is_dir($build_dir)) {
- System::rm('-rf', $build_dir);
+ System::rm(array('-rf', $build_dir));
}
+
if (!System::mkDir(array('-p', $build_dir))) {
return $this->raiseError("could not create build dir: $build_dir");
}
+
$this->addTempFile($build_dir);
if (!System::mkDir(array('-p', $inst_dir))) {
return $this->raiseError("could not create temporary install dir: $inst_dir");
}
$this->addTempFile($inst_dir);
- if (getenv('MAKE')) {
- $make_command = getenv('MAKE');
- } else {
- $make_command = 'make';
- }
+ $make_command = getenv('MAKE') ? getenv('MAKE') : 'make';
+
$to_run = array(
$configure_command,
$make_command,
"$make_command INSTALL_ROOT=\"$inst_dir\" install",
- "find \"$inst_dir\" -ls"
+ "find \"$inst_dir\" | xargs ls -dils"
);
- if (!@chdir($build_dir)) {
+ if (!file_exists($build_dir) || !is_dir($build_dir) || !chdir($build_dir)) {
return $this->raiseError("could not chdir to $build_dir");
}
- putenv('PHP_PEAR_VERSION=@PEAR-VER@');
+ putenv('PHP_PEAR_VERSION=1.9.4');
foreach ($to_run as $cmd) {
$err = $this->_runCommand($cmd, $callback);
if (PEAR::isError($err)) {
@@ -319,15 +392,14 @@ class PEAR_Builder extends PEAR_Common
return $this->raiseError("no `modules' directory found");
}
$built_files = array();
- $prefix = exec("php-config --prefix");
+ $prefix = exec($this->config->get('php_prefix')
+ . "php-config" .
+ $this->config->get('php_suffix') . " --prefix");
$this->_harvestInstDir($prefix, $inst_dir . DIRECTORY_SEPARATOR . $prefix, $built_files);
chdir($old_cwd);
return $built_files;
}
- // }}}
- // {{{ phpizeCallback()
-
/**
* Message callback function used when running the "phpize"
* program. Extracts the API numbers used. Ignores other message
@@ -361,9 +433,6 @@ class PEAR_Builder extends PEAR_Common
}
}
- // }}}
- // {{{ _runCommand()
-
/**
* Run an external command, using a message callback to report
* output. The command will be run through popen and output is
@@ -383,7 +452,7 @@ class PEAR_Builder extends PEAR_Common
function _runCommand($command, $callback = null)
{
$this->log(1, "running: $command");
- $pp = @popen("$command 2>&1", "r");
+ $pp = popen("$command 2>&1", "r");
if (!$pp) {
return $this->raiseError("failed to run `$command'");
}
@@ -402,13 +471,11 @@ class PEAR_Builder extends PEAR_Common
if ($callback && isset($olddbg)) {
$callback[0]->debug = $olddbg;
}
- $exitcode = @pclose($pp);
+
+ $exitcode = is_resource($pp) ? pclose($pp) : -1;
return ($exitcode == 0);
}
- // }}}
- // {{{ log()
-
function log($level, $msg)
{
if ($this->current_callback) {
@@ -419,8 +486,4 @@ class PEAR_Builder extends PEAR_Common
}
return PEAR_Common::log($level, $msg);
}
-
- // }}}
-}
-
-?>
+}
\ No newline at end of file
diff --git a/3rdparty/PEAR/ChannelFile.php b/3rdparty/PEAR/ChannelFile.php
new file mode 100644
index 0000000000..f2c02ab42b
--- /dev/null
+++ b/3rdparty/PEAR/ChannelFile.php
@@ -0,0 +1,1559 @@
+
+ * @copyright 1997-2009 The Authors
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version CVS: $Id: ChannelFile.php 313023 2011-07-06 19:17:11Z dufuz $
+ * @link http://pear.php.net/package/PEAR
+ * @since File available since Release 1.4.0a1
+ */
+
+/**
+ * Needed for error handling
+ */
+require_once 'PEAR/ErrorStack.php';
+require_once 'PEAR/XMLParser.php';
+require_once 'PEAR/Common.php';
+
+/**
+ * Error code if the channel.xml tag does not contain a valid version
+ */
+define('PEAR_CHANNELFILE_ERROR_NO_VERSION', 1);
+/**
+ * Error code if the channel.xml tag version is not supported (version 1.0 is the only supported version,
+ * currently
+ */
+define('PEAR_CHANNELFILE_ERROR_INVALID_VERSION', 2);
+
+/**
+ * Error code if parsing is attempted with no xml extension
+ */
+define('PEAR_CHANNELFILE_ERROR_NO_XML_EXT', 3);
+
+/**
+ * Error code if creating the xml parser resource fails
+ */
+define('PEAR_CHANNELFILE_ERROR_CANT_MAKE_PARSER', 4);
+
+/**
+ * Error code used for all sax xml parsing errors
+ */
+define('PEAR_CHANNELFILE_ERROR_PARSER_ERROR', 5);
+
+/**#@+
+ * Validation errors
+ */
+/**
+ * Error code when channel name is missing
+ */
+define('PEAR_CHANNELFILE_ERROR_NO_NAME', 6);
+/**
+ * Error code when channel name is invalid
+ */
+define('PEAR_CHANNELFILE_ERROR_INVALID_NAME', 7);
+/**
+ * Error code when channel summary is missing
+ */
+define('PEAR_CHANNELFILE_ERROR_NO_SUMMARY', 8);
+/**
+ * Error code when channel summary is multi-line
+ */
+define('PEAR_CHANNELFILE_ERROR_MULTILINE_SUMMARY', 9);
+/**
+ * Error code when channel server is missing for protocol
+ */
+define('PEAR_CHANNELFILE_ERROR_NO_HOST', 10);
+/**
+ * Error code when channel server is invalid for protocol
+ */
+define('PEAR_CHANNELFILE_ERROR_INVALID_HOST', 11);
+/**
+ * Error code when a mirror name is invalid
+ */
+define('PEAR_CHANNELFILE_ERROR_INVALID_MIRROR', 21);
+/**
+ * Error code when a mirror type is invalid
+ */
+define('PEAR_CHANNELFILE_ERROR_INVALID_MIRRORTYPE', 22);
+/**
+ * Error code when an attempt is made to generate xml, but the parsed content is invalid
+ */
+define('PEAR_CHANNELFILE_ERROR_INVALID', 23);
+/**
+ * Error code when an empty package name validate regex is passed in
+ */
+define('PEAR_CHANNELFILE_ERROR_EMPTY_REGEX', 24);
+/**
+ * Error code when a tag has no version
+ */
+define('PEAR_CHANNELFILE_ERROR_NO_FUNCTIONVERSION', 25);
+/**
+ * Error code when a tag has no name
+ */
+define('PEAR_CHANNELFILE_ERROR_NO_FUNCTIONNAME', 26);
+/**
+ * Error code when a tag has no name
+ */
+define('PEAR_CHANNELFILE_ERROR_NOVALIDATE_NAME', 27);
+/**
+ * Error code when a tag has no version attribute
+ */
+define('PEAR_CHANNELFILE_ERROR_NOVALIDATE_VERSION', 28);
+/**
+ * Error code when a mirror does not exist but is called for in one of the set*
+ * methods.
+ */
+define('PEAR_CHANNELFILE_ERROR_MIRROR_NOT_FOUND', 32);
+/**
+ * Error code when a server port is not numeric
+ */
+define('PEAR_CHANNELFILE_ERROR_INVALID_PORT', 33);
+/**
+ * Error code when contains no version attribute
+ */
+define('PEAR_CHANNELFILE_ERROR_NO_STATICVERSION', 34);
+/**
+ * Error code when contains no type attribute in a protocol definition
+ */
+define('PEAR_CHANNELFILE_ERROR_NOBASEURLTYPE', 35);
+/**
+ * Error code when a mirror is defined and the channel.xml represents the __uri pseudo-channel
+ */
+define('PEAR_CHANNELFILE_URI_CANT_MIRROR', 36);
+/**
+ * Error code when ssl attribute is present and is not "yes"
+ */
+define('PEAR_CHANNELFILE_ERROR_INVALID_SSL', 37);
+/**#@-*/
+
+/**
+ * Mirror types allowed. Currently only internet servers are recognized.
+ */
+$GLOBALS['_PEAR_CHANNELS_MIRROR_TYPES'] = array('server');
+
+
+/**
+ * The Channel handling class
+ *
+ * @category pear
+ * @package PEAR
+ * @author Greg Beaver
+ * @copyright 1997-2009 The Authors
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version Release: 1.9.4
+ * @link http://pear.php.net/package/PEAR
+ * @since Class available since Release 1.4.0a1
+ */
+class PEAR_ChannelFile
+{
+ /**
+ * @access private
+ * @var PEAR_ErrorStack
+ * @access private
+ */
+ var $_stack;
+
+ /**
+ * Supported channel.xml versions, for parsing
+ * @var array
+ * @access private
+ */
+ var $_supportedVersions = array('1.0');
+
+ /**
+ * Parsed channel information
+ * @var array
+ * @access private
+ */
+ var $_channelInfo;
+
+ /**
+ * index into the subchannels array, used for parsing xml
+ * @var int
+ * @access private
+ */
+ var $_subchannelIndex;
+
+ /**
+ * index into the mirrors array, used for parsing xml
+ * @var int
+ * @access private
+ */
+ var $_mirrorIndex;
+
+ /**
+ * Flag used to determine the validity of parsed content
+ * @var boolean
+ * @access private
+ */
+ var $_isValid = false;
+
+ function PEAR_ChannelFile()
+ {
+ $this->_stack = &new PEAR_ErrorStack('PEAR_ChannelFile');
+ $this->_stack->setErrorMessageTemplate($this->_getErrorMessage());
+ $this->_isValid = false;
+ }
+
+ /**
+ * @return array
+ * @access protected
+ */
+ function _getErrorMessage()
+ {
+ return
+ array(
+ PEAR_CHANNELFILE_ERROR_INVALID_VERSION =>
+ 'While parsing channel.xml, an invalid version number "%version% was passed in, expecting one of %versions%',
+ PEAR_CHANNELFILE_ERROR_NO_VERSION =>
+ 'No version number found in tag',
+ PEAR_CHANNELFILE_ERROR_NO_XML_EXT =>
+ '%error%',
+ PEAR_CHANNELFILE_ERROR_CANT_MAKE_PARSER =>
+ 'Unable to create XML parser',
+ PEAR_CHANNELFILE_ERROR_PARSER_ERROR =>
+ '%error%',
+ PEAR_CHANNELFILE_ERROR_NO_NAME =>
+ 'Missing channel name',
+ PEAR_CHANNELFILE_ERROR_INVALID_NAME =>
+ 'Invalid channel %tag% "%name%"',
+ PEAR_CHANNELFILE_ERROR_NO_SUMMARY =>
+ 'Missing channel summary',
+ PEAR_CHANNELFILE_ERROR_MULTILINE_SUMMARY =>
+ 'Channel summary should be on one line, but is multi-line',
+ PEAR_CHANNELFILE_ERROR_NO_HOST =>
+ 'Missing channel server for %type% server',
+ PEAR_CHANNELFILE_ERROR_INVALID_HOST =>
+ 'Server name "%server%" is invalid for %type% server',
+ PEAR_CHANNELFILE_ERROR_INVALID_MIRROR =>
+ 'Invalid mirror name "%name%", mirror type %type%',
+ PEAR_CHANNELFILE_ERROR_INVALID_MIRRORTYPE =>
+ 'Invalid mirror type "%type%"',
+ PEAR_CHANNELFILE_ERROR_INVALID =>
+ 'Cannot generate xml, contents are invalid',
+ PEAR_CHANNELFILE_ERROR_EMPTY_REGEX =>
+ 'packagenameregex cannot be empty',
+ PEAR_CHANNELFILE_ERROR_NO_FUNCTIONVERSION =>
+ '%parent% %protocol% function has no version',
+ PEAR_CHANNELFILE_ERROR_NO_FUNCTIONNAME =>
+ '%parent% %protocol% function has no name',
+ PEAR_CHANNELFILE_ERROR_NOBASEURLTYPE =>
+ '%parent% rest baseurl has no type',
+ PEAR_CHANNELFILE_ERROR_NOVALIDATE_NAME =>
+ 'Validation package has no name in tag',
+ PEAR_CHANNELFILE_ERROR_NOVALIDATE_VERSION =>
+ 'Validation package "%package%" has no version',
+ PEAR_CHANNELFILE_ERROR_MIRROR_NOT_FOUND =>
+ 'Mirror "%mirror%" does not exist',
+ PEAR_CHANNELFILE_ERROR_INVALID_PORT =>
+ 'Port "%port%" must be numeric',
+ PEAR_CHANNELFILE_ERROR_NO_STATICVERSION =>
+ ' tag must contain version attribute',
+ PEAR_CHANNELFILE_URI_CANT_MIRROR =>
+ 'The __uri pseudo-channel cannot have mirrors',
+ PEAR_CHANNELFILE_ERROR_INVALID_SSL =>
+ '%server% has invalid ssl attribute "%ssl%" can only be yes or not present',
+ );
+ }
+
+ /**
+ * @param string contents of package.xml file
+ * @return bool success of parsing
+ */
+ function fromXmlString($data)
+ {
+ if (preg_match('/_supportedVersions)) {
+ $this->_stack->push(PEAR_CHANNELFILE_ERROR_INVALID_VERSION, 'error',
+ array('version' => $channelversion[1]));
+ return false;
+ }
+ $parser = new PEAR_XMLParser;
+ $result = $parser->parse($data);
+ if ($result !== true) {
+ if ($result->getCode() == 1) {
+ $this->_stack->push(PEAR_CHANNELFILE_ERROR_NO_XML_EXT, 'error',
+ array('error' => $result->getMessage()));
+ } else {
+ $this->_stack->push(PEAR_CHANNELFILE_ERROR_CANT_MAKE_PARSER, 'error');
+ }
+ return false;
+ }
+ $this->_channelInfo = $parser->getData();
+ return true;
+ } else {
+ $this->_stack->push(PEAR_CHANNELFILE_ERROR_NO_VERSION, 'error', array('xml' => $data));
+ return false;
+ }
+ }
+
+ /**
+ * @return array
+ */
+ function toArray()
+ {
+ if (!$this->_isValid && !$this->validate()) {
+ return false;
+ }
+ return $this->_channelInfo;
+ }
+
+ /**
+ * @param array
+ * @static
+ * @return PEAR_ChannelFile|false false if invalid
+ */
+ function &fromArray($data, $compatibility = false, $stackClass = 'PEAR_ErrorStack')
+ {
+ $a = new PEAR_ChannelFile($compatibility, $stackClass);
+ $a->_fromArray($data);
+ if (!$a->validate()) {
+ $a = false;
+ return $a;
+ }
+ return $a;
+ }
+
+ /**
+ * Unlike {@link fromArray()} this does not do any validation
+ * @param array
+ * @static
+ * @return PEAR_ChannelFile
+ */
+ function &fromArrayWithErrors($data, $compatibility = false,
+ $stackClass = 'PEAR_ErrorStack')
+ {
+ $a = new PEAR_ChannelFile($compatibility, $stackClass);
+ $a->_fromArray($data);
+ return $a;
+ }
+
+ /**
+ * @param array
+ * @access private
+ */
+ function _fromArray($data)
+ {
+ $this->_channelInfo = $data;
+ }
+
+ /**
+ * Wrapper to {@link PEAR_ErrorStack::getErrors()}
+ * @param boolean determines whether to purge the error stack after retrieving
+ * @return array
+ */
+ function getErrors($purge = false)
+ {
+ return $this->_stack->getErrors($purge);
+ }
+
+ /**
+ * Unindent given string (?)
+ *
+ * @param string $str The string that has to be unindented.
+ * @return string
+ * @access private
+ */
+ function _unIndent($str)
+ {
+ // remove leading newlines
+ $str = preg_replace('/^[\r\n]+/', '', $str);
+ // find whitespace at the beginning of the first line
+ $indent_len = strspn($str, " \t");
+ $indent = substr($str, 0, $indent_len);
+ $data = '';
+ // remove the same amount of whitespace from following lines
+ foreach (explode("\n", $str) as $line) {
+ if (substr($line, 0, $indent_len) == $indent) {
+ $data .= substr($line, $indent_len) . "\n";
+ }
+ }
+ return $data;
+ }
+
+ /**
+ * Parse a channel.xml file. Expects the name of
+ * a channel xml file as input.
+ *
+ * @param string $descfile name of channel xml file
+ * @return bool success of parsing
+ */
+ function fromXmlFile($descfile)
+ {
+ if (!file_exists($descfile) || !is_file($descfile) || !is_readable($descfile) ||
+ (!$fp = fopen($descfile, 'r'))) {
+ require_once 'PEAR.php';
+ return PEAR::raiseError("Unable to open $descfile");
+ }
+
+ // read the whole thing so we only get one cdata callback
+ // for each block of cdata
+ fclose($fp);
+ $data = file_get_contents($descfile);
+ return $this->fromXmlString($data);
+ }
+
+ /**
+ * Parse channel information from different sources
+ *
+ * This method is able to extract information about a channel
+ * from an .xml file or a string
+ *
+ * @access public
+ * @param string Filename of the source or the source itself
+ * @return bool
+ */
+ function fromAny($info)
+ {
+ if (is_string($info) && file_exists($info) && strlen($info) < 255) {
+ $tmp = substr($info, -4);
+ if ($tmp == '.xml') {
+ $info = $this->fromXmlFile($info);
+ } else {
+ $fp = fopen($info, "r");
+ $test = fread($fp, 5);
+ fclose($fp);
+ if ($test == "fromXmlFile($info);
+ }
+ }
+ if (PEAR::isError($info)) {
+ require_once 'PEAR.php';
+ return PEAR::raiseError($info);
+ }
+ }
+ if (is_string($info)) {
+ $info = $this->fromXmlString($info);
+ }
+ return $info;
+ }
+
+ /**
+ * Return an XML document based on previous parsing and modifications
+ *
+ * @return string XML data
+ *
+ * @access public
+ */
+ function toXml()
+ {
+ if (!$this->_isValid && !$this->validate()) {
+ $this->_validateError(PEAR_CHANNELFILE_ERROR_INVALID);
+ return false;
+ }
+ if (!isset($this->_channelInfo['attribs']['version'])) {
+ $this->_channelInfo['attribs']['version'] = '1.0';
+ }
+ $channelInfo = $this->_channelInfo;
+ $ret = "\n";
+ $ret .= "
+ $channelInfo[name]
+ " . htmlspecialchars($channelInfo['summary'])."
+";
+ if (isset($channelInfo['suggestedalias'])) {
+ $ret .= ' ' . $channelInfo['suggestedalias'] . "\n";
+ }
+ if (isset($channelInfo['validatepackage'])) {
+ $ret .= ' ' .
+ htmlspecialchars($channelInfo['validatepackage']['_content']) .
+ "\n";
+ }
+ $ret .= " \n";
+ $ret .= ' _makeRestXml($channelInfo['servers']['primary']['rest'], ' ');
+ }
+ $ret .= " \n";
+ if (isset($channelInfo['servers']['mirror'])) {
+ $ret .= $this->_makeMirrorsXml($channelInfo);
+ }
+ $ret .= " \n";
+ $ret .= "";
+ return str_replace("\r", "\n", str_replace("\r\n", "\n", $ret));
+ }
+
+ /**
+ * Generate the tag
+ * @access private
+ */
+ function _makeRestXml($info, $indent)
+ {
+ $ret = $indent . "\n";
+ if (isset($info['baseurl']) && !isset($info['baseurl'][0])) {
+ $info['baseurl'] = array($info['baseurl']);
+ }
+
+ if (isset($info['baseurl'])) {
+ foreach ($info['baseurl'] as $url) {
+ $ret .= "$indent \n";
+ }
+ }
+ $ret .= $indent . "\n";
+ return $ret;
+ }
+
+ /**
+ * Generate the tag
+ * @access private
+ */
+ function _makeMirrorsXml($channelInfo)
+ {
+ $ret = "";
+ if (!isset($channelInfo['servers']['mirror'][0])) {
+ $channelInfo['servers']['mirror'] = array($channelInfo['servers']['mirror']);
+ }
+ foreach ($channelInfo['servers']['mirror'] as $mirror) {
+ $ret .= ' _makeRestXml($mirror['rest'], ' ');
+ }
+ $ret .= " \n";
+ } else {
+ $ret .= "/>\n";
+ }
+ }
+ return $ret;
+ }
+
+ /**
+ * Generate the tag
+ * @access private
+ */
+ function _makeFunctionsXml($functions, $indent, $rest = false)
+ {
+ $ret = '';
+ if (!isset($functions[0])) {
+ $functions = array($functions);
+ }
+ foreach ($functions as $function) {
+ $ret .= "$indent\n";
+ }
+ return $ret;
+ }
+
+ /**
+ * Validation error. Also marks the object contents as invalid
+ * @param error code
+ * @param array error information
+ * @access private
+ */
+ function _validateError($code, $params = array())
+ {
+ $this->_stack->push($code, 'error', $params);
+ $this->_isValid = false;
+ }
+
+ /**
+ * Validation warning. Does not mark the object contents invalid.
+ * @param error code
+ * @param array error information
+ * @access private
+ */
+ function _validateWarning($code, $params = array())
+ {
+ $this->_stack->push($code, 'warning', $params);
+ }
+
+ /**
+ * Validate parsed file.
+ *
+ * @access public
+ * @return boolean
+ */
+ function validate()
+ {
+ $this->_isValid = true;
+ $info = $this->_channelInfo;
+ if (empty($info['name'])) {
+ $this->_validateError(PEAR_CHANNELFILE_ERROR_NO_NAME);
+ } elseif (!$this->validChannelServer($info['name'])) {
+ if ($info['name'] != '__uri') {
+ $this->_validateError(PEAR_CHANNELFILE_ERROR_INVALID_NAME, array('tag' => 'name',
+ 'name' => $info['name']));
+ }
+ }
+ if (empty($info['summary'])) {
+ $this->_validateError(PEAR_CHANNELFILE_ERROR_NO_SUMMARY);
+ } elseif (strpos(trim($info['summary']), "\n") !== false) {
+ $this->_validateWarning(PEAR_CHANNELFILE_ERROR_MULTILINE_SUMMARY,
+ array('summary' => $info['summary']));
+ }
+ if (isset($info['suggestedalias'])) {
+ if (!$this->validChannelServer($info['suggestedalias'])) {
+ $this->_validateError(PEAR_CHANNELFILE_ERROR_INVALID_NAME,
+ array('tag' => 'suggestedalias', 'name' =>$info['suggestedalias']));
+ }
+ }
+ if (isset($info['localalias'])) {
+ if (!$this->validChannelServer($info['localalias'])) {
+ $this->_validateError(PEAR_CHANNELFILE_ERROR_INVALID_NAME,
+ array('tag' => 'localalias', 'name' =>$info['localalias']));
+ }
+ }
+ if (isset($info['validatepackage'])) {
+ if (!isset($info['validatepackage']['_content'])) {
+ $this->_validateError(PEAR_CHANNELFILE_ERROR_NOVALIDATE_NAME);
+ }
+ if (!isset($info['validatepackage']['attribs']['version'])) {
+ $content = isset($info['validatepackage']['_content']) ?
+ $info['validatepackage']['_content'] :
+ null;
+ $this->_validateError(PEAR_CHANNELFILE_ERROR_NOVALIDATE_VERSION,
+ array('package' => $content));
+ }
+ }
+
+ if (isset($info['servers']['primary']['attribs'], $info['servers']['primary']['attribs']['port']) &&
+ !is_numeric($info['servers']['primary']['attribs']['port'])) {
+ $this->_validateError(PEAR_CHANNELFILE_ERROR_INVALID_PORT,
+ array('port' => $info['servers']['primary']['attribs']['port']));
+ }
+
+ if (isset($info['servers']['primary']['attribs'], $info['servers']['primary']['attribs']['ssl']) &&
+ $info['servers']['primary']['attribs']['ssl'] != 'yes') {
+ $this->_validateError(PEAR_CHANNELFILE_ERROR_INVALID_SSL,
+ array('ssl' => $info['servers']['primary']['attribs']['ssl'],
+ 'server' => $info['name']));
+ }
+
+ if (isset($info['servers']['primary']['rest']) &&
+ isset($info['servers']['primary']['rest']['baseurl'])) {
+ $this->_validateFunctions('rest', $info['servers']['primary']['rest']['baseurl']);
+ }
+ if (isset($info['servers']['mirror'])) {
+ if ($this->_channelInfo['name'] == '__uri') {
+ $this->_validateError(PEAR_CHANNELFILE_URI_CANT_MIRROR);
+ }
+ if (!isset($info['servers']['mirror'][0])) {
+ $info['servers']['mirror'] = array($info['servers']['mirror']);
+ }
+ foreach ($info['servers']['mirror'] as $mirror) {
+ if (!isset($mirror['attribs']['host'])) {
+ $this->_validateError(PEAR_CHANNELFILE_ERROR_NO_HOST,
+ array('type' => 'mirror'));
+ } elseif (!$this->validChannelServer($mirror['attribs']['host'])) {
+ $this->_validateError(PEAR_CHANNELFILE_ERROR_INVALID_HOST,
+ array('server' => $mirror['attribs']['host'], 'type' => 'mirror'));
+ }
+ if (isset($mirror['attribs']['ssl']) && $mirror['attribs']['ssl'] != 'yes') {
+ $this->_validateError(PEAR_CHANNELFILE_ERROR_INVALID_SSL,
+ array('ssl' => $info['ssl'], 'server' => $mirror['attribs']['host']));
+ }
+ if (isset($mirror['rest'])) {
+ $this->_validateFunctions('rest', $mirror['rest']['baseurl'],
+ $mirror['attribs']['host']);
+ }
+ }
+ }
+ return $this->_isValid;
+ }
+
+ /**
+ * @param string rest - protocol name this function applies to
+ * @param array the functions
+ * @param string the name of the parent element (mirror name, for instance)
+ */
+ function _validateFunctions($protocol, $functions, $parent = '')
+ {
+ if (!isset($functions[0])) {
+ $functions = array($functions);
+ }
+
+ foreach ($functions as $function) {
+ if (!isset($function['_content']) || empty($function['_content'])) {
+ $this->_validateError(PEAR_CHANNELFILE_ERROR_NO_FUNCTIONNAME,
+ array('parent' => $parent, 'protocol' => $protocol));
+ }
+
+ if ($protocol == 'rest') {
+ if (!isset($function['attribs']['type']) ||
+ empty($function['attribs']['type'])) {
+ $this->_validateError(PEAR_CHANNELFILE_ERROR_NOBASEURLTYPE,
+ array('parent' => $parent, 'protocol' => $protocol));
+ }
+ } else {
+ if (!isset($function['attribs']['version']) ||
+ empty($function['attribs']['version'])) {
+ $this->_validateError(PEAR_CHANNELFILE_ERROR_NO_FUNCTIONVERSION,
+ array('parent' => $parent, 'protocol' => $protocol));
+ }
+ }
+ }
+ }
+
+ /**
+ * Test whether a string contains a valid channel server.
+ * @param string $ver the package version to test
+ * @return bool
+ */
+ function validChannelServer($server)
+ {
+ if ($server == '__uri') {
+ return true;
+ }
+ return (bool) preg_match(PEAR_CHANNELS_SERVER_PREG, $server);
+ }
+
+ /**
+ * @return string|false
+ */
+ function getName()
+ {
+ if (isset($this->_channelInfo['name'])) {
+ return $this->_channelInfo['name'];
+ }
+
+ return false;
+ }
+
+ /**
+ * @return string|false
+ */
+ function getServer()
+ {
+ if (isset($this->_channelInfo['name'])) {
+ return $this->_channelInfo['name'];
+ }
+
+ return false;
+ }
+
+ /**
+ * @return int|80 port number to connect to
+ */
+ function getPort($mirror = false)
+ {
+ if ($mirror) {
+ if ($mir = $this->getMirror($mirror)) {
+ if (isset($mir['attribs']['port'])) {
+ return $mir['attribs']['port'];
+ }
+
+ if ($this->getSSL($mirror)) {
+ return 443;
+ }
+
+ return 80;
+ }
+
+ return false;
+ }
+
+ if (isset($this->_channelInfo['servers']['primary']['attribs']['port'])) {
+ return $this->_channelInfo['servers']['primary']['attribs']['port'];
+ }
+
+ if ($this->getSSL()) {
+ return 443;
+ }
+
+ return 80;
+ }
+
+ /**
+ * @return bool Determines whether secure sockets layer (SSL) is used to connect to this channel
+ */
+ function getSSL($mirror = false)
+ {
+ if ($mirror) {
+ if ($mir = $this->getMirror($mirror)) {
+ if (isset($mir['attribs']['ssl'])) {
+ return true;
+ }
+
+ return false;
+ }
+
+ return false;
+ }
+
+ if (isset($this->_channelInfo['servers']['primary']['attribs']['ssl'])) {
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * @return string|false
+ */
+ function getSummary()
+ {
+ if (isset($this->_channelInfo['summary'])) {
+ return $this->_channelInfo['summary'];
+ }
+
+ return false;
+ }
+
+ /**
+ * @param string protocol type
+ * @param string Mirror name
+ * @return array|false
+ */
+ function getFunctions($protocol, $mirror = false)
+ {
+ if ($this->getName() == '__uri') {
+ return false;
+ }
+
+ $function = $protocol == 'rest' ? 'baseurl' : 'function';
+ if ($mirror) {
+ if ($mir = $this->getMirror($mirror)) {
+ if (isset($mir[$protocol][$function])) {
+ return $mir[$protocol][$function];
+ }
+ }
+
+ return false;
+ }
+
+ if (isset($this->_channelInfo['servers']['primary'][$protocol][$function])) {
+ return $this->_channelInfo['servers']['primary'][$protocol][$function];
+ }
+
+ return false;
+ }
+
+ /**
+ * @param string Protocol type
+ * @param string Function name (null to return the
+ * first protocol of the type requested)
+ * @param string Mirror name, if any
+ * @return array
+ */
+ function getFunction($type, $name = null, $mirror = false)
+ {
+ $protocols = $this->getFunctions($type, $mirror);
+ if (!$protocols) {
+ return false;
+ }
+
+ foreach ($protocols as $protocol) {
+ if ($name === null) {
+ return $protocol;
+ }
+
+ if ($protocol['_content'] != $name) {
+ continue;
+ }
+
+ return $protocol;
+ }
+
+ return false;
+ }
+
+ /**
+ * @param string protocol type
+ * @param string protocol name
+ * @param string version
+ * @param string mirror name
+ * @return boolean
+ */
+ function supports($type, $name = null, $mirror = false, $version = '1.0')
+ {
+ $protocols = $this->getFunctions($type, $mirror);
+ if (!$protocols) {
+ return false;
+ }
+
+ foreach ($protocols as $protocol) {
+ if ($protocol['attribs']['version'] != $version) {
+ continue;
+ }
+
+ if ($name === null) {
+ return true;
+ }
+
+ if ($protocol['_content'] != $name) {
+ continue;
+ }
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Determines whether a channel supports Representational State Transfer (REST) protocols
+ * for retrieving channel information
+ * @param string
+ * @return bool
+ */
+ function supportsREST($mirror = false)
+ {
+ if ($mirror == $this->_channelInfo['name']) {
+ $mirror = false;
+ }
+
+ if ($mirror) {
+ if ($mir = $this->getMirror($mirror)) {
+ return isset($mir['rest']);
+ }
+
+ return false;
+ }
+
+ return isset($this->_channelInfo['servers']['primary']['rest']);
+ }
+
+ /**
+ * Get the URL to access a base resource.
+ *
+ * Hyperlinks in the returned xml will be used to retrieve the proper information
+ * needed. This allows extreme extensibility and flexibility in implementation
+ * @param string Resource Type to retrieve
+ */
+ function getBaseURL($resourceType, $mirror = false)
+ {
+ if ($mirror == $this->_channelInfo['name']) {
+ $mirror = false;
+ }
+
+ if ($mirror) {
+ $mir = $this->getMirror($mirror);
+ if (!$mir) {
+ return false;
+ }
+
+ $rest = $mir['rest'];
+ } else {
+ $rest = $this->_channelInfo['servers']['primary']['rest'];
+ }
+
+ if (!isset($rest['baseurl'][0])) {
+ $rest['baseurl'] = array($rest['baseurl']);
+ }
+
+ foreach ($rest['baseurl'] as $baseurl) {
+ if (strtolower($baseurl['attribs']['type']) == strtolower($resourceType)) {
+ return $baseurl['_content'];
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Since REST does not implement RPC, provide this as a logical wrapper around
+ * resetFunctions for REST
+ * @param string|false mirror name, if any
+ */
+ function resetREST($mirror = false)
+ {
+ return $this->resetFunctions('rest', $mirror);
+ }
+
+ /**
+ * Empty all protocol definitions
+ * @param string protocol type
+ * @param string|false mirror name, if any
+ */
+ function resetFunctions($type, $mirror = false)
+ {
+ if ($mirror) {
+ if (isset($this->_channelInfo['servers']['mirror'])) {
+ $mirrors = $this->_channelInfo['servers']['mirror'];
+ if (!isset($mirrors[0])) {
+ $mirrors = array($mirrors);
+ }
+
+ foreach ($mirrors as $i => $mir) {
+ if ($mir['attribs']['host'] == $mirror) {
+ if (isset($this->_channelInfo['servers']['mirror'][$i][$type])) {
+ unset($this->_channelInfo['servers']['mirror'][$i][$type]);
+ }
+
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ return false;
+ }
+
+ if (isset($this->_channelInfo['servers']['primary'][$type])) {
+ unset($this->_channelInfo['servers']['primary'][$type]);
+ }
+
+ return true;
+ }
+
+ /**
+ * Set a channel's protocols to the protocols supported by pearweb
+ */
+ function setDefaultPEARProtocols($version = '1.0', $mirror = false)
+ {
+ switch ($version) {
+ case '1.0' :
+ $this->resetREST($mirror);
+
+ if (!isset($this->_channelInfo['servers'])) {
+ $this->_channelInfo['servers'] = array('primary' =>
+ array('rest' => array()));
+ } elseif (!isset($this->_channelInfo['servers']['primary'])) {
+ $this->_channelInfo['servers']['primary'] = array('rest' => array());
+ }
+
+ return true;
+ break;
+ default :
+ return false;
+ break;
+ }
+ }
+
+ /**
+ * @return array
+ */
+ function getMirrors()
+ {
+ if (isset($this->_channelInfo['servers']['mirror'])) {
+ $mirrors = $this->_channelInfo['servers']['mirror'];
+ if (!isset($mirrors[0])) {
+ $mirrors = array($mirrors);
+ }
+
+ return $mirrors;
+ }
+
+ return array();
+ }
+
+ /**
+ * Get the unserialized XML representing a mirror
+ * @return array|false
+ */
+ function getMirror($server)
+ {
+ foreach ($this->getMirrors() as $mirror) {
+ if ($mirror['attribs']['host'] == $server) {
+ return $mirror;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * @param string
+ * @return string|false
+ * @error PEAR_CHANNELFILE_ERROR_NO_NAME
+ * @error PEAR_CHANNELFILE_ERROR_INVALID_NAME
+ */
+ function setName($name)
+ {
+ return $this->setServer($name);
+ }
+
+ /**
+ * Set the socket number (port) that is used to connect to this channel
+ * @param integer
+ * @param string|false name of the mirror server, or false for the primary
+ */
+ function setPort($port, $mirror = false)
+ {
+ if ($mirror) {
+ if (!isset($this->_channelInfo['servers']['mirror'])) {
+ $this->_validateError(PEAR_CHANNELFILE_ERROR_MIRROR_NOT_FOUND,
+ array('mirror' => $mirror));
+ return false;
+ }
+
+ if (isset($this->_channelInfo['servers']['mirror'][0])) {
+ foreach ($this->_channelInfo['servers']['mirror'] as $i => $mir) {
+ if ($mirror == $mir['attribs']['host']) {
+ $this->_channelInfo['servers']['mirror'][$i]['attribs']['port'] = $port;
+ return true;
+ }
+ }
+
+ return false;
+ } elseif ($this->_channelInfo['servers']['mirror']['attribs']['host'] == $mirror) {
+ $this->_channelInfo['servers']['mirror']['attribs']['port'] = $port;
+ $this->_isValid = false;
+ return true;
+ }
+ }
+
+ $this->_channelInfo['servers']['primary']['attribs']['port'] = $port;
+ $this->_isValid = false;
+ return true;
+ }
+
+ /**
+ * Set the socket number (port) that is used to connect to this channel
+ * @param bool Determines whether to turn on SSL support or turn it off
+ * @param string|false name of the mirror server, or false for the primary
+ */
+ function setSSL($ssl = true, $mirror = false)
+ {
+ if ($mirror) {
+ if (!isset($this->_channelInfo['servers']['mirror'])) {
+ $this->_validateError(PEAR_CHANNELFILE_ERROR_MIRROR_NOT_FOUND,
+ array('mirror' => $mirror));
+ return false;
+ }
+
+ if (isset($this->_channelInfo['servers']['mirror'][0])) {
+ foreach ($this->_channelInfo['servers']['mirror'] as $i => $mir) {
+ if ($mirror == $mir['attribs']['host']) {
+ if (!$ssl) {
+ if (isset($this->_channelInfo['servers']['mirror'][$i]
+ ['attribs']['ssl'])) {
+ unset($this->_channelInfo['servers']['mirror'][$i]['attribs']['ssl']);
+ }
+ } else {
+ $this->_channelInfo['servers']['mirror'][$i]['attribs']['ssl'] = 'yes';
+ }
+
+ return true;
+ }
+ }
+
+ return false;
+ } elseif ($this->_channelInfo['servers']['mirror']['attribs']['host'] == $mirror) {
+ if (!$ssl) {
+ if (isset($this->_channelInfo['servers']['mirror']['attribs']['ssl'])) {
+ unset($this->_channelInfo['servers']['mirror']['attribs']['ssl']);
+ }
+ } else {
+ $this->_channelInfo['servers']['mirror']['attribs']['ssl'] = 'yes';
+ }
+
+ $this->_isValid = false;
+ return true;
+ }
+ }
+
+ if ($ssl) {
+ $this->_channelInfo['servers']['primary']['attribs']['ssl'] = 'yes';
+ } else {
+ if (isset($this->_channelInfo['servers']['primary']['attribs']['ssl'])) {
+ unset($this->_channelInfo['servers']['primary']['attribs']['ssl']);
+ }
+ }
+
+ $this->_isValid = false;
+ return true;
+ }
+
+ /**
+ * @param string
+ * @return string|false
+ * @error PEAR_CHANNELFILE_ERROR_NO_SERVER
+ * @error PEAR_CHANNELFILE_ERROR_INVALID_SERVER
+ */
+ function setServer($server, $mirror = false)
+ {
+ if (empty($server)) {
+ $this->_validateError(PEAR_CHANNELFILE_ERROR_NO_SERVER);
+ return false;
+ } elseif (!$this->validChannelServer($server)) {
+ $this->_validateError(PEAR_CHANNELFILE_ERROR_INVALID_NAME,
+ array('tag' => 'name', 'name' => $server));
+ return false;
+ }
+
+ if ($mirror) {
+ $found = false;
+ foreach ($this->_channelInfo['servers']['mirror'] as $i => $mir) {
+ if ($mirror == $mir['attribs']['host']) {
+ $found = true;
+ break;
+ }
+ }
+
+ if (!$found) {
+ $this->_validateError(PEAR_CHANNELFILE_ERROR_MIRROR_NOT_FOUND,
+ array('mirror' => $mirror));
+ return false;
+ }
+
+ $this->_channelInfo['mirror'][$i]['attribs']['host'] = $server;
+ return true;
+ }
+
+ $this->_channelInfo['name'] = $server;
+ return true;
+ }
+
+ /**
+ * @param string
+ * @return boolean success
+ * @error PEAR_CHANNELFILE_ERROR_NO_SUMMARY
+ * @warning PEAR_CHANNELFILE_ERROR_MULTILINE_SUMMARY
+ */
+ function setSummary($summary)
+ {
+ if (empty($summary)) {
+ $this->_validateError(PEAR_CHANNELFILE_ERROR_NO_SUMMARY);
+ return false;
+ } elseif (strpos(trim($summary), "\n") !== false) {
+ $this->_validateWarning(PEAR_CHANNELFILE_ERROR_MULTILINE_SUMMARY,
+ array('summary' => $summary));
+ }
+
+ $this->_channelInfo['summary'] = $summary;
+ return true;
+ }
+
+ /**
+ * @param string
+ * @param boolean determines whether the alias is in channel.xml or local
+ * @return boolean success
+ */
+ function setAlias($alias, $local = false)
+ {
+ if (!$this->validChannelServer($alias)) {
+ $this->_validateError(PEAR_CHANNELFILE_ERROR_INVALID_NAME,
+ array('tag' => 'suggestedalias', 'name' => $alias));
+ return false;
+ }
+
+ if ($local) {
+ $this->_channelInfo['localalias'] = $alias;
+ } else {
+ $this->_channelInfo['suggestedalias'] = $alias;
+ }
+
+ return true;
+ }
+
+ /**
+ * @return string
+ */
+ function getAlias()
+ {
+ if (isset($this->_channelInfo['localalias'])) {
+ return $this->_channelInfo['localalias'];
+ }
+ if (isset($this->_channelInfo['suggestedalias'])) {
+ return $this->_channelInfo['suggestedalias'];
+ }
+ if (isset($this->_channelInfo['name'])) {
+ return $this->_channelInfo['name'];
+ }
+ return '';
+ }
+
+ /**
+ * Set the package validation object if it differs from PEAR's default
+ * The class must be includeable via changing _ in the classname to path separator,
+ * but no checking of this is made.
+ * @param string|false pass in false to reset to the default packagename regex
+ * @return boolean success
+ */
+ function setValidationPackage($validateclass, $version)
+ {
+ if (empty($validateclass)) {
+ unset($this->_channelInfo['validatepackage']);
+ }
+ $this->_channelInfo['validatepackage'] = array('_content' => $validateclass);
+ $this->_channelInfo['validatepackage']['attribs'] = array('version' => $version);
+ }
+
+ /**
+ * Add a protocol to the provides section
+ * @param string protocol type
+ * @param string protocol version
+ * @param string protocol name, if any
+ * @param string mirror name, if this is a mirror's protocol
+ * @return bool
+ */
+ function addFunction($type, $version, $name = '', $mirror = false)
+ {
+ if ($mirror) {
+ return $this->addMirrorFunction($mirror, $type, $version, $name);
+ }
+
+ $set = array('attribs' => array('version' => $version), '_content' => $name);
+ if (!isset($this->_channelInfo['servers']['primary'][$type]['function'])) {
+ if (!isset($this->_channelInfo['servers'])) {
+ $this->_channelInfo['servers'] = array('primary' =>
+ array($type => array()));
+ } elseif (!isset($this->_channelInfo['servers']['primary'])) {
+ $this->_channelInfo['servers']['primary'] = array($type => array());
+ }
+
+ $this->_channelInfo['servers']['primary'][$type]['function'] = $set;
+ $this->_isValid = false;
+ return true;
+ } elseif (!isset($this->_channelInfo['servers']['primary'][$type]['function'][0])) {
+ $this->_channelInfo['servers']['primary'][$type]['function'] = array(
+ $this->_channelInfo['servers']['primary'][$type]['function']);
+ }
+
+ $this->_channelInfo['servers']['primary'][$type]['function'][] = $set;
+ return true;
+ }
+ /**
+ * Add a protocol to a mirror's provides section
+ * @param string mirror name (server)
+ * @param string protocol type
+ * @param string protocol version
+ * @param string protocol name, if any
+ */
+ function addMirrorFunction($mirror, $type, $version, $name = '')
+ {
+ if (!isset($this->_channelInfo['servers']['mirror'])) {
+ $this->_validateError(PEAR_CHANNELFILE_ERROR_MIRROR_NOT_FOUND,
+ array('mirror' => $mirror));
+ return false;
+ }
+
+ $setmirror = false;
+ if (isset($this->_channelInfo['servers']['mirror'][0])) {
+ foreach ($this->_channelInfo['servers']['mirror'] as $i => $mir) {
+ if ($mirror == $mir['attribs']['host']) {
+ $setmirror = &$this->_channelInfo['servers']['mirror'][$i];
+ break;
+ }
+ }
+ } else {
+ if ($this->_channelInfo['servers']['mirror']['attribs']['host'] == $mirror) {
+ $setmirror = &$this->_channelInfo['servers']['mirror'];
+ }
+ }
+
+ if (!$setmirror) {
+ $this->_validateError(PEAR_CHANNELFILE_ERROR_MIRROR_NOT_FOUND,
+ array('mirror' => $mirror));
+ return false;
+ }
+
+ $set = array('attribs' => array('version' => $version), '_content' => $name);
+ if (!isset($setmirror[$type]['function'])) {
+ $setmirror[$type]['function'] = $set;
+ $this->_isValid = false;
+ return true;
+ } elseif (!isset($setmirror[$type]['function'][0])) {
+ $setmirror[$type]['function'] = array($setmirror[$type]['function']);
+ }
+
+ $setmirror[$type]['function'][] = $set;
+ $this->_isValid = false;
+ return true;
+ }
+
+ /**
+ * @param string Resource Type this url links to
+ * @param string URL
+ * @param string|false mirror name, if this is not a primary server REST base URL
+ */
+ function setBaseURL($resourceType, $url, $mirror = false)
+ {
+ if ($mirror) {
+ if (!isset($this->_channelInfo['servers']['mirror'])) {
+ $this->_validateError(PEAR_CHANNELFILE_ERROR_MIRROR_NOT_FOUND,
+ array('mirror' => $mirror));
+ return false;
+ }
+
+ $setmirror = false;
+ if (isset($this->_channelInfo['servers']['mirror'][0])) {
+ foreach ($this->_channelInfo['servers']['mirror'] as $i => $mir) {
+ if ($mirror == $mir['attribs']['host']) {
+ $setmirror = &$this->_channelInfo['servers']['mirror'][$i];
+ break;
+ }
+ }
+ } else {
+ if ($this->_channelInfo['servers']['mirror']['attribs']['host'] == $mirror) {
+ $setmirror = &$this->_channelInfo['servers']['mirror'];
+ }
+ }
+ } else {
+ $setmirror = &$this->_channelInfo['servers']['primary'];
+ }
+
+ $set = array('attribs' => array('type' => $resourceType), '_content' => $url);
+ if (!isset($setmirror['rest'])) {
+ $setmirror['rest'] = array();
+ }
+
+ if (!isset($setmirror['rest']['baseurl'])) {
+ $setmirror['rest']['baseurl'] = $set;
+ $this->_isValid = false;
+ return true;
+ } elseif (!isset($setmirror['rest']['baseurl'][0])) {
+ $setmirror['rest']['baseurl'] = array($setmirror['rest']['baseurl']);
+ }
+
+ foreach ($setmirror['rest']['baseurl'] as $i => $url) {
+ if ($url['attribs']['type'] == $resourceType) {
+ $this->_isValid = false;
+ $setmirror['rest']['baseurl'][$i] = $set;
+ return true;
+ }
+ }
+
+ $setmirror['rest']['baseurl'][] = $set;
+ $this->_isValid = false;
+ return true;
+ }
+
+ /**
+ * @param string mirror server
+ * @param int mirror http port
+ * @return boolean
+ */
+ function addMirror($server, $port = null)
+ {
+ if ($this->_channelInfo['name'] == '__uri') {
+ return false; // the __uri channel cannot have mirrors by definition
+ }
+
+ $set = array('attribs' => array('host' => $server));
+ if (is_numeric($port)) {
+ $set['attribs']['port'] = $port;
+ }
+
+ if (!isset($this->_channelInfo['servers']['mirror'])) {
+ $this->_channelInfo['servers']['mirror'] = $set;
+ return true;
+ }
+
+ if (!isset($this->_channelInfo['servers']['mirror'][0])) {
+ $this->_channelInfo['servers']['mirror'] =
+ array($this->_channelInfo['servers']['mirror']);
+ }
+
+ $this->_channelInfo['servers']['mirror'][] = $set;
+ return true;
+ }
+
+ /**
+ * Retrieve the name of the validation package for this channel
+ * @return string|false
+ */
+ function getValidationPackage()
+ {
+ if (!$this->_isValid && !$this->validate()) {
+ return false;
+ }
+
+ if (!isset($this->_channelInfo['validatepackage'])) {
+ return array('attribs' => array('version' => 'default'),
+ '_content' => 'PEAR_Validate');
+ }
+
+ return $this->_channelInfo['validatepackage'];
+ }
+
+ /**
+ * Retrieve the object that can be used for custom validation
+ * @param string|false the name of the package to validate. If the package is
+ * the channel validation package, PEAR_Validate is returned
+ * @return PEAR_Validate|false false is returned if the validation package
+ * cannot be located
+ */
+ function &getValidationObject($package = false)
+ {
+ if (!class_exists('PEAR_Validate')) {
+ require_once 'PEAR/Validate.php';
+ }
+
+ if (!$this->_isValid) {
+ if (!$this->validate()) {
+ $a = false;
+ return $a;
+ }
+ }
+
+ if (isset($this->_channelInfo['validatepackage'])) {
+ if ($package == $this->_channelInfo['validatepackage']) {
+ // channel validation packages are always validated by PEAR_Validate
+ $val = &new PEAR_Validate;
+ return $val;
+ }
+
+ if (!class_exists(str_replace('.', '_',
+ $this->_channelInfo['validatepackage']['_content']))) {
+ if ($this->isIncludeable(str_replace('_', '/',
+ $this->_channelInfo['validatepackage']['_content']) . '.php')) {
+ include_once str_replace('_', '/',
+ $this->_channelInfo['validatepackage']['_content']) . '.php';
+ $vclass = str_replace('.', '_',
+ $this->_channelInfo['validatepackage']['_content']);
+ $val = &new $vclass;
+ } else {
+ $a = false;
+ return $a;
+ }
+ } else {
+ $vclass = str_replace('.', '_',
+ $this->_channelInfo['validatepackage']['_content']);
+ $val = &new $vclass;
+ }
+ } else {
+ $val = &new PEAR_Validate;
+ }
+
+ return $val;
+ }
+
+ function isIncludeable($path)
+ {
+ $possibilities = explode(PATH_SEPARATOR, ini_get('include_path'));
+ foreach ($possibilities as $dir) {
+ if (file_exists($dir . DIRECTORY_SEPARATOR . $path)
+ && is_readable($dir . DIRECTORY_SEPARATOR . $path)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * This function is used by the channel updater and retrieves a value set by
+ * the registry, or the current time if it has not been set
+ * @return string
+ */
+ function lastModified()
+ {
+ if (isset($this->_channelInfo['_lastmodified'])) {
+ return $this->_channelInfo['_lastmodified'];
+ }
+
+ return time();
+ }
+}
\ No newline at end of file
diff --git a/3rdparty/PEAR/ChannelFile/Parser.php b/3rdparty/PEAR/ChannelFile/Parser.php
new file mode 100644
index 0000000000..e630ace224
--- /dev/null
+++ b/3rdparty/PEAR/ChannelFile/Parser.php
@@ -0,0 +1,68 @@
+
+ * @copyright 1997-2009 The Authors
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version CVS: $Id: Parser.php 313023 2011-07-06 19:17:11Z dufuz $
+ * @link http://pear.php.net/package/PEAR
+ * @since File available since Release 1.4.0a1
+ */
+
+/**
+ * base xml parser class
+ */
+require_once 'PEAR/XMLParser.php';
+require_once 'PEAR/ChannelFile.php';
+/**
+ * Parser for channel.xml
+ * @category pear
+ * @package PEAR
+ * @author Greg Beaver
+ * @copyright 1997-2009 The Authors
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version Release: 1.9.4
+ * @link http://pear.php.net/package/PEAR
+ * @since Class available since Release 1.4.0a1
+ */
+class PEAR_ChannelFile_Parser extends PEAR_XMLParser
+{
+ var $_config;
+ var $_logger;
+ var $_registry;
+
+ function setConfig(&$c)
+ {
+ $this->_config = &$c;
+ $this->_registry = &$c->getRegistry();
+ }
+
+ function setLogger(&$l)
+ {
+ $this->_logger = &$l;
+ }
+
+ function parse($data, $file)
+ {
+ if (PEAR::isError($err = parent::parse($data, $file))) {
+ return $err;
+ }
+
+ $ret = new PEAR_ChannelFile;
+ $ret->setConfig($this->_config);
+ if (isset($this->_logger)) {
+ $ret->setLogger($this->_logger);
+ }
+
+ $ret->fromArray($this->_unserializedData);
+ // make sure the filelist is in the easy to read format needed
+ $ret->flattenFilelist();
+ $ret->setPackagefile($file, $archive);
+ return $ret;
+ }
+}
\ No newline at end of file
diff --git a/3rdparty/PEAR/Command.php b/3rdparty/PEAR/Command.php
index 2ea68743d2..db39b8f36f 100644
--- a/3rdparty/PEAR/Command.php
+++ b/3rdparty/PEAR/Command.php
@@ -1,25 +1,26 @@
|
-// +----------------------------------------------------------------------+
-//
-// $Id: Command.php,v 1.24 2004/05/16 15:43:30 pajoye Exp $
+/**
+ * PEAR_Command, command pattern class
+ *
+ * PHP versions 4 and 5
+ *
+ * @category pear
+ * @package PEAR
+ * @author Stig Bakken
+ * @author Greg Beaver
+ * @copyright 1997-2009 The Authors
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version CVS: $Id: Command.php 313023 2011-07-06 19:17:11Z dufuz $
+ * @link http://pear.php.net/package/PEAR
+ * @since File available since Release 0.1
+ */
-
-require_once "PEAR.php";
+/**
+ * Needed for error handling
+ */
+require_once 'PEAR.php';
+require_once 'PEAR/Frontend.php';
+require_once 'PEAR/XMLParser.php';
/**
* List of commands and what classes they are implemented in.
@@ -27,6 +28,12 @@ require_once "PEAR.php";
*/
$GLOBALS['_PEAR_Command_commandlist'] = array();
+/**
+ * List of commands and their descriptions
+ * @var array command => description
+ */
+$GLOBALS['_PEAR_Command_commanddesc'] = array();
+
/**
* List of shortcuts to common commands.
* @var array shortcut => command
@@ -39,18 +46,6 @@ $GLOBALS['_PEAR_Command_shortcuts'] = array();
*/
$GLOBALS['_PEAR_Command_objects'] = array();
-/**
- * Which user interface class is being used.
- * @var string class name
- */
-$GLOBALS['_PEAR_Command_uiclass'] = 'PEAR_Frontend_CLI';
-
-/**
- * Instance of $_PEAR_Command_uiclass.
- * @var object
- */
-$GLOBALS['_PEAR_Command_uiobject'] = null;
-
/**
* PEAR command class, a simple factory class for administrative
* commands.
@@ -93,6 +88,15 @@ $GLOBALS['_PEAR_Command_uiobject'] = null;
* - DON'T USE EXIT OR DIE! Always use pear errors. From static
* classes do PEAR::raiseError(), from other classes do
* $this->raiseError().
+ * @category pear
+ * @package PEAR
+ * @author Stig Bakken
+ * @author Greg Beaver
+ * @copyright 1997-2009 The Authors
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version Release: 1.9.4
+ * @link http://pear.php.net/package/PEAR
+ * @since Class available since Release 0.1
*/
class PEAR_Command
{
@@ -109,7 +113,7 @@ class PEAR_Command
* @access public
* @static
*/
- function factory($command, &$config)
+ function &factory($command, &$config)
{
if (empty($GLOBALS['_PEAR_Command_commandlist'])) {
PEAR_Command::registerCommands();
@@ -118,13 +122,35 @@ class PEAR_Command
$command = $GLOBALS['_PEAR_Command_shortcuts'][$command];
}
if (!isset($GLOBALS['_PEAR_Command_commandlist'][$command])) {
- return PEAR::raiseError("unknown command `$command'");
+ $a = PEAR::raiseError("unknown command `$command'");
+ return $a;
}
$class = $GLOBALS['_PEAR_Command_commandlist'][$command];
+ if (!class_exists($class)) {
+ require_once $GLOBALS['_PEAR_Command_objects'][$class];
+ }
+ if (!class_exists($class)) {
+ $a = PEAR::raiseError("unknown command `$command'");
+ return $a;
+ }
+ $ui =& PEAR_Command::getFrontendObject();
+ $obj = &new $class($ui, $config);
+ return $obj;
+ }
+
+ // }}}
+ // {{{ & getObject()
+ function &getObject($command)
+ {
+ $class = $GLOBALS['_PEAR_Command_commandlist'][$command];
+ if (!class_exists($class)) {
+ require_once $GLOBALS['_PEAR_Command_objects'][$class];
+ }
if (!class_exists($class)) {
return PEAR::raiseError("unknown command `$command'");
}
$ui =& PEAR_Command::getFrontendObject();
+ $config = &PEAR_Config::singleton();
$obj = &new $class($ui, $config);
return $obj;
}
@@ -135,15 +161,13 @@ class PEAR_Command
/**
* Get instance of frontend object.
*
- * @return object
+ * @return object|PEAR_Error
* @static
*/
function &getFrontendObject()
{
- if (empty($GLOBALS['_PEAR_Command_uiobject'])) {
- $GLOBALS['_PEAR_Command_uiobject'] = &new $GLOBALS['_PEAR_Command_uiclass'];
- }
- return $GLOBALS['_PEAR_Command_uiobject'];
+ $a = &PEAR_Frontend::singleton();
+ return $a;
}
// }}}
@@ -159,59 +183,13 @@ class PEAR_Command
*/
function &setFrontendClass($uiclass)
{
- if (is_object($GLOBALS['_PEAR_Command_uiobject']) &&
- is_a($GLOBALS['_PEAR_Command_uiobject'], $uiclass)) {
- return $GLOBALS['_PEAR_Command_uiobject'];
- }
- if (!class_exists($uiclass)) {
- $file = str_replace('_', '/', $uiclass) . '.php';
- if (PEAR_Command::isIncludeable($file)) {
- include_once $file;
- }
- }
- if (class_exists($uiclass)) {
- $obj = &new $uiclass;
- // quick test to see if this class implements a few of the most
- // important frontend methods
- if (method_exists($obj, 'userConfirm')) {
- $GLOBALS['_PEAR_Command_uiobject'] = &$obj;
- $GLOBALS['_PEAR_Command_uiclass'] = $uiclass;
- return $obj;
- } else {
- $err = PEAR::raiseError("not a frontend class: $uiclass");
- return $err;
- }
- }
- $err = PEAR::raiseError("no such class: $uiclass");
- return $err;
+ $a = &PEAR_Frontend::setFrontendClass($uiclass);
+ return $a;
}
// }}}
// {{{ setFrontendType()
- // }}}
- // {{{ isIncludeable()
-
- /**
- * @param string $path relative or absolute include path
- * @return boolean
- * @static
- */
- function isIncludeable($path)
- {
- if (file_exists($path) && is_readable($path)) {
- return true;
- }
- $ipath = explode(PATH_SEPARATOR, ini_get('include_path'));
- foreach ($ipath as $include) {
- $test = realpath($include . DIRECTORY_SEPARATOR . $path);
- if (file_exists($test) && is_readable($test)) {
- return true;
- }
- }
- return false;
- }
-
/**
* Set current frontend.
*
@@ -249,9 +227,13 @@ class PEAR_Command
*/
function registerCommands($merge = false, $dir = null)
{
+ $parser = new PEAR_XMLParser;
if ($dir === null) {
$dir = dirname(__FILE__) . '/Command';
}
+ if (!is_dir($dir)) {
+ return PEAR::raiseError("registerCommands: opendir($dir) '$dir' does not exist or is not a directory");
+ }
$dp = @opendir($dir);
if (empty($dp)) {
return PEAR::raiseError("registerCommands: opendir($dir) failed");
@@ -259,27 +241,58 @@ class PEAR_Command
if (!$merge) {
$GLOBALS['_PEAR_Command_commandlist'] = array();
}
- while ($entry = readdir($dp)) {
- if ($entry{0} == '.' || substr($entry, -4) != '.php' || $entry == 'Common.php') {
+
+ while ($file = readdir($dp)) {
+ if ($file{0} == '.' || substr($file, -4) != '.xml') {
continue;
}
- $class = "PEAR_Command_".substr($entry, 0, -4);
- $file = "$dir/$entry";
- include_once $file;
+
+ $f = substr($file, 0, -4);
+ $class = "PEAR_Command_" . $f;
// List of commands
if (empty($GLOBALS['_PEAR_Command_objects'][$class])) {
- $GLOBALS['_PEAR_Command_objects'][$class] = &new $class($ui, $config);
+ $GLOBALS['_PEAR_Command_objects'][$class] = "$dir/" . $f . '.php';
}
- $implements = $GLOBALS['_PEAR_Command_objects'][$class]->getCommands();
+
+ $parser->parse(file_get_contents("$dir/$file"));
+ $implements = $parser->getData();
foreach ($implements as $command => $desc) {
+ if ($command == 'attribs') {
+ continue;
+ }
+
+ if (isset($GLOBALS['_PEAR_Command_commandlist'][$command])) {
+ return PEAR::raiseError('Command "' . $command . '" already registered in ' .
+ 'class "' . $GLOBALS['_PEAR_Command_commandlist'][$command] . '"');
+ }
+
$GLOBALS['_PEAR_Command_commandlist'][$command] = $class;
- $GLOBALS['_PEAR_Command_commanddesc'][$command] = $desc;
- }
- $shortcuts = $GLOBALS['_PEAR_Command_objects'][$class]->getShortcuts();
- foreach ($shortcuts as $shortcut => $command) {
- $GLOBALS['_PEAR_Command_shortcuts'][$shortcut] = $command;
+ $GLOBALS['_PEAR_Command_commanddesc'][$command] = $desc['summary'];
+ if (isset($desc['shortcut'])) {
+ $shortcut = $desc['shortcut'];
+ if (isset($GLOBALS['_PEAR_Command_shortcuts'][$shortcut])) {
+ return PEAR::raiseError('Command shortcut "' . $shortcut . '" already ' .
+ 'registered to command "' . $command . '" in class "' .
+ $GLOBALS['_PEAR_Command_commandlist'][$command] . '"');
+ }
+ $GLOBALS['_PEAR_Command_shortcuts'][$shortcut] = $command;
+ }
+
+ if (isset($desc['options']) && $desc['options']) {
+ foreach ($desc['options'] as $oname => $option) {
+ if (isset($option['shortopt']) && strlen($option['shortopt']) > 1) {
+ return PEAR::raiseError('Option "' . $oname . '" short option "' .
+ $option['shortopt'] . '" must be ' .
+ 'only 1 character in Command "' . $command . '" in class "' .
+ $class . '"');
+ }
+ }
+ }
}
}
+
+ ksort($GLOBALS['_PEAR_Command_shortcuts']);
+ ksort($GLOBALS['_PEAR_Command_commandlist']);
@closedir($dp);
return true;
}
@@ -343,11 +356,13 @@ class PEAR_Command
if (empty($GLOBALS['_PEAR_Command_commandlist'])) {
PEAR_Command::registerCommands();
}
+ if (isset($GLOBALS['_PEAR_Command_shortcuts'][$command])) {
+ $command = $GLOBALS['_PEAR_Command_shortcuts'][$command];
+ }
if (!isset($GLOBALS['_PEAR_Command_commandlist'][$command])) {
return null;
}
- $class = $GLOBALS['_PEAR_Command_commandlist'][$command];
- $obj = &$GLOBALS['_PEAR_Command_objects'][$class];
+ $obj = &PEAR_Command::getObject($command);
return $obj->getGetoptArgs($command, $short_args, $long_args);
}
@@ -386,13 +401,14 @@ class PEAR_Command
function getHelp($command)
{
$cmds = PEAR_Command::getCommands();
+ if (isset($GLOBALS['_PEAR_Command_shortcuts'][$command])) {
+ $command = $GLOBALS['_PEAR_Command_shortcuts'][$command];
+ }
if (isset($cmds[$command])) {
- $class = $cmds[$command];
- return $GLOBALS['_PEAR_Command_objects'][$class]->getHelp($command);
+ $obj = &PEAR_Command::getObject($command);
+ return $obj->getHelp($command);
}
return false;
}
// }}}
-}
-
-?>
+}
\ No newline at end of file
diff --git a/3rdparty/PEAR/Command/Auth.php b/3rdparty/PEAR/Command/Auth.php
index 0b9d3d3965..63cd152b90 100644
--- a/3rdparty/PEAR/Command/Auth.php
+++ b/3rdparty/PEAR/Command/Auth.php
@@ -1,43 +1,53 @@
|
-// +----------------------------------------------------------------------+
-//
-// $Id: Auth.php,v 1.15 2004/01/08 17:33:13 sniper Exp $
-
-require_once "PEAR/Command/Common.php";
-require_once "PEAR/Remote.php";
-require_once "PEAR/Config.php";
+/**
+ * PEAR_Command_Auth (login, logout commands)
+ *
+ * PHP versions 4 and 5
+ *
+ * @category pear
+ * @package PEAR
+ * @author Stig Bakken
+ * @author Greg Beaver
+ * @copyright 1997-2009 The Authors
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version CVS: $Id: Auth.php 313023 2011-07-06 19:17:11Z dufuz $
+ * @link http://pear.php.net/package/PEAR
+ * @since File available since Release 0.1
+ * @deprecated since 1.8.0alpha1
+ */
/**
- * PEAR commands for managing configuration data.
- *
+ * base class
*/
-class PEAR_Command_Auth extends PEAR_Command_Common
-{
- // {{{ properties
+require_once 'PEAR/Command/Channels.php';
+/**
+ * PEAR commands for login/logout
+ *
+ * @category pear
+ * @package PEAR
+ * @author Stig Bakken
+ * @author Greg Beaver
+ * @copyright 1997-2009 The Authors
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version Release: 1.9.4
+ * @link http://pear.php.net/package/PEAR
+ * @since Class available since Release 0.1
+ * @deprecated since 1.8.0alpha1
+ */
+class PEAR_Command_Auth extends PEAR_Command_Channels
+{
var $commands = array(
'login' => array(
- 'summary' => 'Connects and authenticates to remote server',
+ 'summary' => 'Connects and authenticates to remote server [Deprecated in favor of channel-login]',
'shortcut' => 'li',
'function' => 'doLogin',
'options' => array(),
- 'doc' => '
-Log in to the remote server. To use remote functions in the installer
+ 'doc' => '
+WARNING: This function is deprecated in favor of using channel-login
+
+Log in to a remote channel server. If is not supplied,
+the default channel is used. To use remote functions in the installer
that require any kind of privileges, you need to log in first. The
username and password you enter here will be stored in your per-user
PEAR configuration (~/.pearrc on Unix-like systems). After logging
@@ -45,11 +55,13 @@ in, your username and password will be sent along in subsequent
operations on the remote server.',
),
'logout' => array(
- 'summary' => 'Logs out from the remote server',
+ 'summary' => 'Logs out from the remote server [Deprecated in favor of channel-logout]',
'shortcut' => 'lo',
'function' => 'doLogout',
'options' => array(),
'doc' => '
+WARNING: This function is deprecated in favor of using channel-logout
+
Logs out from the remote server. This command does not actually
connect to the remote server, it only deletes the stored username and
password from your user configuration.',
@@ -57,10 +69,6 @@ password from your user configuration.',
);
- // }}}
-
- // {{{ constructor
-
/**
* PEAR_Command_Auth constructor.
*
@@ -68,88 +76,6 @@ password from your user configuration.',
*/
function PEAR_Command_Auth(&$ui, &$config)
{
- parent::PEAR_Command_Common($ui, $config);
+ parent::PEAR_Command_Channels($ui, $config);
}
-
- // }}}
-
- // {{{ doLogin()
-
- /**
- * Execute the 'login' command.
- *
- * @param string $command command name
- *
- * @param array $options option_name => value
- *
- * @param array $params list of additional parameters
- *
- * @return bool TRUE on success, FALSE for unknown commands, or
- * a PEAR error on failure
- *
- * @access public
- */
- function doLogin($command, $options, $params)
- {
- $server = $this->config->get('master_server');
- $remote = new PEAR_Remote($this->config);
- $username = $this->config->get('username');
- if (empty($username)) {
- $username = @$_ENV['USER'];
- }
- $this->ui->outputData("Logging in to $server.", $command);
-
- list($username, $password) = $this->ui->userDialog(
- $command,
- array('Username', 'Password'),
- array('text', 'password'),
- array($username, '')
- );
- $username = trim($username);
- $password = trim($password);
-
- $this->config->set('username', $username);
- $this->config->set('password', $password);
-
- $remote->expectError(401);
- $ok = $remote->call('logintest');
- $remote->popExpect();
- if ($ok === true) {
- $this->ui->outputData("Logged in.", $command);
- $this->config->store();
- } else {
- return $this->raiseError("Login failed!");
- }
-
- }
-
- // }}}
- // {{{ doLogout()
-
- /**
- * Execute the 'logout' command.
- *
- * @param string $command command name
- *
- * @param array $options option_name => value
- *
- * @param array $params list of additional parameters
- *
- * @return bool TRUE on success, FALSE for unknown commands, or
- * a PEAR error on failure
- *
- * @access public
- */
- function doLogout($command, $options, $params)
- {
- $server = $this->config->get('master_server');
- $this->ui->outputData("Logging out from $server.", $command);
- $this->config->remove('username');
- $this->config->remove('password');
- $this->config->store();
- }
-
- // }}}
-}
-
-?>
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/3rdparty/PEAR/Command/Auth.xml b/3rdparty/PEAR/Command/Auth.xml
new file mode 100644
index 0000000000..590193d142
--- /dev/null
+++ b/3rdparty/PEAR/Command/Auth.xml
@@ -0,0 +1,30 @@
+
+
+ Connects and authenticates to remote server [Deprecated in favor of channel-login]
+ doLogin
+ li
+
+ <channel name>
+WARNING: This function is deprecated in favor of using channel-login
+
+Log in to a remote channel server. If <channel name> is not supplied,
+the default channel is used. To use remote functions in the installer
+that require any kind of privileges, you need to log in first. The
+username and password you enter here will be stored in your per-user
+PEAR configuration (~/.pearrc on Unix-like systems). After logging
+in, your username and password will be sent along in subsequent
+operations on the remote server.
+
+
+ Logs out from the remote server [Deprecated in favor of channel-logout]
+ doLogout
+ lo
+
+
+WARNING: This function is deprecated in favor of using channel-logout
+
+Logs out from the remote server. This command does not actually
+connect to the remote server, it only deletes the stored username and
+password from your user configuration.
+
+
\ No newline at end of file
diff --git a/3rdparty/PEAR/Command/Build.php b/3rdparty/PEAR/Command/Build.php
index 2ecbbc92f5..1de7320246 100644
--- a/3rdparty/PEAR/Command/Build.php
+++ b/3rdparty/PEAR/Command/Build.php
@@ -1,36 +1,42 @@
|
-// | Tomas V.V.Cox |
-// | |
-// +----------------------------------------------------------------------+
-//
-// $Id: Build.php,v 1.9 2004/01/08 17:33:13 sniper Exp $
+/**
+ * PEAR_Command_Auth (build command)
+ *
+ * PHP versions 4 and 5
+ *
+ * @category pear
+ * @package PEAR
+ * @author Stig Bakken
+ * @author Tomas V.V.Cox
+ * @author Greg Beaver
+ * @copyright 1997-2009 The Authors
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version CVS: $Id: Build.php 313023 2011-07-06 19:17:11Z dufuz $
+ * @link http://pear.php.net/package/PEAR
+ * @since File available since Release 0.1
+ */
-require_once "PEAR/Command/Common.php";
-require_once "PEAR/Builder.php";
+/**
+ * base class
+ */
+require_once 'PEAR/Command/Common.php';
/**
* PEAR commands for building extensions.
*
+ * @category pear
+ * @package PEAR
+ * @author Stig Bakken
+ * @author Tomas V.V.Cox
+ * @author Greg Beaver
+ * @copyright 1997-2009 The Authors
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version Release: 1.9.4
+ * @link http://pear.php.net/package/PEAR
+ * @since Class available since Release 0.1
*/
class PEAR_Command_Build extends PEAR_Command_Common
{
- // {{{ properties
-
var $commands = array(
'build' => array(
'summary' => 'Build an Extension From C Source',
@@ -42,10 +48,6 @@ Builds one or more extensions contained in a package.'
),
);
- // }}}
-
- // {{{ constructor
-
/**
* PEAR_Command_Build constructor.
*
@@ -56,27 +58,23 @@ Builds one or more extensions contained in a package.'
parent::PEAR_Command_Common($ui, $config);
}
- // }}}
-
- // {{{ doBuild()
-
function doBuild($command, $options, $params)
{
+ require_once 'PEAR/Builder.php';
if (sizeof($params) < 1) {
$params[0] = 'package.xml';
}
+
$builder = &new PEAR_Builder($this->ui);
$this->debug = $this->config->get('verbose');
$err = $builder->build($params[0], array(&$this, 'buildCallback'));
if (PEAR::isError($err)) {
return $err;
}
+
return true;
}
- // }}}
- // {{{ buildCallback()
-
function buildCallback($what, $data)
{
if (($what == 'cmdoutput' && $this->debug > 1) ||
@@ -84,6 +82,4 @@ Builds one or more extensions contained in a package.'
$this->ui->outputData(rtrim($data), 'build');
}
}
-
- // }}}
-}
+}
\ No newline at end of file
diff --git a/3rdparty/PEAR/Command/Build.xml b/3rdparty/PEAR/Command/Build.xml
new file mode 100644
index 0000000000..ec4e6f554c
--- /dev/null
+++ b/3rdparty/PEAR/Command/Build.xml
@@ -0,0 +1,10 @@
+
+
+ Build an Extension From C Source
+ doBuild
+ b
+
+ [package.xml]
+Builds one or more extensions contained in a package.
+
+
\ No newline at end of file
diff --git a/3rdparty/PEAR/Command/Channels.php b/3rdparty/PEAR/Command/Channels.php
new file mode 100644
index 0000000000..fcf01b5039
--- /dev/null
+++ b/3rdparty/PEAR/Command/Channels.php
@@ -0,0 +1,883 @@
+
+ * @author Greg Beaver
+ * @copyright 1997-2009 The Authors
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version CVS: $Id: Channels.php 313023 2011-07-06 19:17:11Z dufuz $
+ * @link http://pear.php.net/package/PEAR
+ * @since File available since Release 1.4.0a1
+ */
+
+/**
+ * base class
+ */
+require_once 'PEAR/Command/Common.php';
+
+define('PEAR_COMMAND_CHANNELS_CHANNEL_EXISTS', -500);
+
+/**
+ * PEAR commands for managing channels.
+ *
+ * @category pear
+ * @package PEAR
+ * @author Greg Beaver
+ * @copyright 1997-2009 The Authors
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version Release: 1.9.4
+ * @link http://pear.php.net/package/PEAR
+ * @since Class available since Release 1.4.0a1
+ */
+class PEAR_Command_Channels extends PEAR_Command_Common
+{
+ var $commands = array(
+ 'list-channels' => array(
+ 'summary' => 'List Available Channels',
+ 'function' => 'doList',
+ 'shortcut' => 'lc',
+ 'options' => array(),
+ 'doc' => '
+List all available channels for installation.
+',
+ ),
+ 'update-channels' => array(
+ 'summary' => 'Update the Channel List',
+ 'function' => 'doUpdateAll',
+ 'shortcut' => 'uc',
+ 'options' => array(),
+ 'doc' => '
+List all installed packages in all channels.
+'
+ ),
+ 'channel-delete' => array(
+ 'summary' => 'Remove a Channel From the List',
+ 'function' => 'doDelete',
+ 'shortcut' => 'cde',
+ 'options' => array(),
+ 'doc' => '
+Delete a channel from the registry. You may not
+remove any channel that has installed packages.
+'
+ ),
+ 'channel-add' => array(
+ 'summary' => 'Add a Channel',
+ 'function' => 'doAdd',
+ 'shortcut' => 'ca',
+ 'options' => array(),
+ 'doc' => '
+Add a private channel to the channel list. Note that all
+public channels should be synced using "update-channels".
+Parameter may be either a local file or remote URL to a
+channel.xml.
+'
+ ),
+ 'channel-update' => array(
+ 'summary' => 'Update an Existing Channel',
+ 'function' => 'doUpdate',
+ 'shortcut' => 'cu',
+ 'options' => array(
+ 'force' => array(
+ 'shortopt' => 'f',
+ 'doc' => 'will force download of new channel.xml if an existing channel name is used',
+ ),
+ 'channel' => array(
+ 'shortopt' => 'c',
+ 'arg' => 'CHANNEL',
+ 'doc' => 'will force download of new channel.xml if an existing channel name is used',
+ ),
+),
+ 'doc' => '[|]
+Update a channel in the channel list directly. Note that all
+public channels can be synced using "update-channels".
+Parameter may be a local or remote channel.xml, or the name of
+an existing channel.
+'
+ ),
+ 'channel-info' => array(
+ 'summary' => 'Retrieve Information on a Channel',
+ 'function' => 'doInfo',
+ 'shortcut' => 'ci',
+ 'options' => array(),
+ 'doc' => '
+List the files in an installed package.
+'
+ ),
+ 'channel-alias' => array(
+ 'summary' => 'Specify an alias to a channel name',
+ 'function' => 'doAlias',
+ 'shortcut' => 'cha',
+ 'options' => array(),
+ 'doc' => '
+Specify a specific alias to use for a channel name.
+The alias may not be an existing channel name or
+alias.
+'
+ ),
+ 'channel-discover' => array(
+ 'summary' => 'Initialize a Channel from its server',
+ 'function' => 'doDiscover',
+ 'shortcut' => 'di',
+ 'options' => array(),
+ 'doc' => '[|]
+Initialize a channel from its server and create a local channel.xml.
+If is in the format ":@" then
+ and will be set as the login username/password for
+. Use caution when passing the username/password in this way, as
+it may allow other users on your computer to briefly view your username/
+password via the system\'s process list.
+'
+ ),
+ 'channel-login' => array(
+ 'summary' => 'Connects and authenticates to remote channel server',
+ 'shortcut' => 'cli',
+ 'function' => 'doLogin',
+ 'options' => array(),
+ 'doc' => '
+Log in to a remote channel server. If is not supplied,
+the default channel is used. To use remote functions in the installer
+that require any kind of privileges, you need to log in first. The
+username and password you enter here will be stored in your per-user
+PEAR configuration (~/.pearrc on Unix-like systems). After logging
+in, your username and password will be sent along in subsequent
+operations on the remote server.',
+ ),
+ 'channel-logout' => array(
+ 'summary' => 'Logs out from the remote channel server',
+ 'shortcut' => 'clo',
+ 'function' => 'doLogout',
+ 'options' => array(),
+ 'doc' => '
+Logs out from a remote channel server. If is not supplied,
+the default channel is used. This command does not actually connect to the
+remote server, it only deletes the stored username and password from your user
+configuration.',
+ ),
+ );
+
+ /**
+ * PEAR_Command_Registry constructor.
+ *
+ * @access public
+ */
+ function PEAR_Command_Channels(&$ui, &$config)
+ {
+ parent::PEAR_Command_Common($ui, $config);
+ }
+
+ function _sortChannels($a, $b)
+ {
+ return strnatcasecmp($a->getName(), $b->getName());
+ }
+
+ function doList($command, $options, $params)
+ {
+ $reg = &$this->config->getRegistry();
+ $registered = $reg->getChannels();
+ usort($registered, array(&$this, '_sortchannels'));
+ $i = $j = 0;
+ $data = array(
+ 'caption' => 'Registered Channels:',
+ 'border' => true,
+ 'headline' => array('Channel', 'Alias', 'Summary')
+ );
+ foreach ($registered as $channel) {
+ $data['data'][] = array($channel->getName(),
+ $channel->getAlias(),
+ $channel->getSummary());
+ }
+
+ if (count($registered) === 0) {
+ $data = '(no registered channels)';
+ }
+ $this->ui->outputData($data, $command);
+ return true;
+ }
+
+ function doUpdateAll($command, $options, $params)
+ {
+ $reg = &$this->config->getRegistry();
+ $channels = $reg->getChannels();
+
+ $success = true;
+ foreach ($channels as $channel) {
+ if ($channel->getName() != '__uri') {
+ PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
+ $err = $this->doUpdate('channel-update',
+ $options,
+ array($channel->getName()));
+ if (PEAR::isError($err)) {
+ $this->ui->outputData($err->getMessage(), $command);
+ $success = false;
+ } else {
+ $success &= $err;
+ }
+ }
+ }
+ return $success;
+ }
+
+ function doInfo($command, $options, $params)
+ {
+ if (count($params) !== 1) {
+ return $this->raiseError("No channel specified");
+ }
+
+ $reg = &$this->config->getRegistry();
+ $channel = strtolower($params[0]);
+ if ($reg->channelExists($channel)) {
+ $chan = $reg->getChannel($channel);
+ if (PEAR::isError($chan)) {
+ return $this->raiseError($chan);
+ }
+ } else {
+ if (strpos($channel, '://')) {
+ $downloader = &$this->getDownloader();
+ $tmpdir = $this->config->get('temp_dir');
+ PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
+ $loc = $downloader->downloadHttp($channel, $this->ui, $tmpdir);
+ PEAR::staticPopErrorHandling();
+ if (PEAR::isError($loc)) {
+ return $this->raiseError('Cannot open "' . $channel .
+ '" (' . $loc->getMessage() . ')');
+ } else {
+ $contents = implode('', file($loc));
+ }
+ } else {
+ if (!file_exists($params[0])) {
+ return $this->raiseError('Unknown channel "' . $channel . '"');
+ }
+
+ $fp = fopen($params[0], 'r');
+ if (!$fp) {
+ return $this->raiseError('Cannot open "' . $params[0] . '"');
+ }
+
+ $contents = '';
+ while (!feof($fp)) {
+ $contents .= fread($fp, 1024);
+ }
+ fclose($fp);
+ }
+
+ if (!class_exists('PEAR_ChannelFile')) {
+ require_once 'PEAR/ChannelFile.php';
+ }
+
+ $chan = new PEAR_ChannelFile;
+ $chan->fromXmlString($contents);
+ $chan->validate();
+ if ($errs = $chan->getErrors(true)) {
+ foreach ($errs as $err) {
+ $this->ui->outputData($err['level'] . ': ' . $err['message']);
+ }
+ return $this->raiseError('Channel file "' . $params[0] . '" is not valid');
+ }
+ }
+
+ if (!$chan) {
+ return $this->raiseError('Serious error: Channel "' . $params[0] .
+ '" has a corrupted registry entry');
+ }
+
+ $channel = $chan->getName();
+ $caption = 'Channel ' . $channel . ' Information:';
+ $data1 = array(
+ 'caption' => $caption,
+ 'border' => true);
+ $data1['data']['server'] = array('Name and Server', $chan->getName());
+ if ($chan->getAlias() != $chan->getName()) {
+ $data1['data']['alias'] = array('Alias', $chan->getAlias());
+ }
+
+ $data1['data']['summary'] = array('Summary', $chan->getSummary());
+ $validate = $chan->getValidationPackage();
+ $data1['data']['vpackage'] = array('Validation Package Name', $validate['_content']);
+ $data1['data']['vpackageversion'] =
+ array('Validation Package Version', $validate['attribs']['version']);
+ $d = array();
+ $d['main'] = $data1;
+
+ $data['data'] = array();
+ $data['caption'] = 'Server Capabilities';
+ $data['headline'] = array('Type', 'Version/REST type', 'Function Name/REST base');
+ if ($chan->supportsREST()) {
+ if ($chan->supportsREST()) {
+ $funcs = $chan->getFunctions('rest');
+ if (!isset($funcs[0])) {
+ $funcs = array($funcs);
+ }
+ foreach ($funcs as $protocol) {
+ $data['data'][] = array('rest', $protocol['attribs']['type'],
+ $protocol['_content']);
+ }
+ }
+ } else {
+ $data['data'][] = array('No supported protocols');
+ }
+
+ $d['protocols'] = $data;
+ $data['data'] = array();
+ $mirrors = $chan->getMirrors();
+ if ($mirrors) {
+ $data['caption'] = 'Channel ' . $channel . ' Mirrors:';
+ unset($data['headline']);
+ foreach ($mirrors as $mirror) {
+ $data['data'][] = array($mirror['attribs']['host']);
+ $d['mirrors'] = $data;
+ }
+
+ foreach ($mirrors as $i => $mirror) {
+ $data['data'] = array();
+ $data['caption'] = 'Mirror ' . $mirror['attribs']['host'] . ' Capabilities';
+ $data['headline'] = array('Type', 'Version/REST type', 'Function Name/REST base');
+ if ($chan->supportsREST($mirror['attribs']['host'])) {
+ if ($chan->supportsREST($mirror['attribs']['host'])) {
+ $funcs = $chan->getFunctions('rest', $mirror['attribs']['host']);
+ if (!isset($funcs[0])) {
+ $funcs = array($funcs);
+ }
+
+ foreach ($funcs as $protocol) {
+ $data['data'][] = array('rest', $protocol['attribs']['type'],
+ $protocol['_content']);
+ }
+ }
+ } else {
+ $data['data'][] = array('No supported protocols');
+ }
+ $d['mirrorprotocols' . $i] = $data;
+ }
+ }
+ $this->ui->outputData($d, 'channel-info');
+ }
+
+ // }}}
+
+ function doDelete($command, $options, $params)
+ {
+ if (count($params) !== 1) {
+ return $this->raiseError('channel-delete: no channel specified');
+ }
+
+ $reg = &$this->config->getRegistry();
+ if (!$reg->channelExists($params[0])) {
+ return $this->raiseError('channel-delete: channel "' . $params[0] . '" does not exist');
+ }
+
+ $channel = $reg->channelName($params[0]);
+ if ($channel == 'pear.php.net') {
+ return $this->raiseError('Cannot delete the pear.php.net channel');
+ }
+
+ if ($channel == 'pecl.php.net') {
+ return $this->raiseError('Cannot delete the pecl.php.net channel');
+ }
+
+ if ($channel == 'doc.php.net') {
+ return $this->raiseError('Cannot delete the doc.php.net channel');
+ }
+
+ if ($channel == '__uri') {
+ return $this->raiseError('Cannot delete the __uri pseudo-channel');
+ }
+
+ if (PEAR::isError($err = $reg->listPackages($channel))) {
+ return $err;
+ }
+
+ if (count($err)) {
+ return $this->raiseError('Channel "' . $channel .
+ '" has installed packages, cannot delete');
+ }
+
+ if (!$reg->deleteChannel($channel)) {
+ return $this->raiseError('Channel "' . $channel . '" deletion failed');
+ } else {
+ $this->config->deleteChannel($channel);
+ $this->ui->outputData('Channel "' . $channel . '" deleted', $command);
+ }
+ }
+
+ function doAdd($command, $options, $params)
+ {
+ if (count($params) !== 1) {
+ return $this->raiseError('channel-add: no channel file specified');
+ }
+
+ if (strpos($params[0], '://')) {
+ $downloader = &$this->getDownloader();
+ $tmpdir = $this->config->get('temp_dir');
+ if (!file_exists($tmpdir)) {
+ require_once 'System.php';
+ PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
+ $err = System::mkdir(array('-p', $tmpdir));
+ PEAR::staticPopErrorHandling();
+ if (PEAR::isError($err)) {
+ return $this->raiseError('channel-add: temp_dir does not exist: "' .
+ $tmpdir .
+ '" - You can change this location with "pear config-set temp_dir"');
+ }
+ }
+
+ if (!is_writable($tmpdir)) {
+ return $this->raiseError('channel-add: temp_dir is not writable: "' .
+ $tmpdir .
+ '" - You can change this location with "pear config-set temp_dir"');
+ }
+
+ PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
+ $loc = $downloader->downloadHttp($params[0], $this->ui, $tmpdir, null, false);
+ PEAR::staticPopErrorHandling();
+ if (PEAR::isError($loc)) {
+ return $this->raiseError('channel-add: Cannot open "' . $params[0] .
+ '" (' . $loc->getMessage() . ')');
+ }
+
+ list($loc, $lastmodified) = $loc;
+ $contents = implode('', file($loc));
+ } else {
+ $lastmodified = $fp = false;
+ if (file_exists($params[0])) {
+ $fp = fopen($params[0], 'r');
+ }
+
+ if (!$fp) {
+ return $this->raiseError('channel-add: cannot open "' . $params[0] . '"');
+ }
+
+ $contents = '';
+ while (!feof($fp)) {
+ $contents .= fread($fp, 1024);
+ }
+ fclose($fp);
+ }
+
+ if (!class_exists('PEAR_ChannelFile')) {
+ require_once 'PEAR/ChannelFile.php';
+ }
+
+ $channel = new PEAR_ChannelFile;
+ PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
+ $result = $channel->fromXmlString($contents);
+ PEAR::staticPopErrorHandling();
+ if (!$result) {
+ $exit = false;
+ if (count($errors = $channel->getErrors(true))) {
+ foreach ($errors as $error) {
+ $this->ui->outputData(ucfirst($error['level'] . ': ' . $error['message']));
+ if (!$exit) {
+ $exit = $error['level'] == 'error' ? true : false;
+ }
+ }
+ if ($exit) {
+ return $this->raiseError('channel-add: invalid channel.xml file');
+ }
+ }
+ }
+
+ $reg = &$this->config->getRegistry();
+ if ($reg->channelExists($channel->getName())) {
+ return $this->raiseError('channel-add: Channel "' . $channel->getName() .
+ '" exists, use channel-update to update entry', PEAR_COMMAND_CHANNELS_CHANNEL_EXISTS);
+ }
+
+ $ret = $reg->addChannel($channel, $lastmodified);
+ if (PEAR::isError($ret)) {
+ return $ret;
+ }
+
+ if (!$ret) {
+ return $this->raiseError('channel-add: adding Channel "' . $channel->getName() .
+ '" to registry failed');
+ }
+
+ $this->config->setChannels($reg->listChannels());
+ $this->config->writeConfigFile();
+ $this->ui->outputData('Adding Channel "' . $channel->getName() . '" succeeded', $command);
+ }
+
+ function doUpdate($command, $options, $params)
+ {
+ if (count($params) !== 1) {
+ return $this->raiseError("No channel file specified");
+ }
+
+ $tmpdir = $this->config->get('temp_dir');
+ if (!file_exists($tmpdir)) {
+ require_once 'System.php';
+ PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
+ $err = System::mkdir(array('-p', $tmpdir));
+ PEAR::staticPopErrorHandling();
+ if (PEAR::isError($err)) {
+ return $this->raiseError('channel-add: temp_dir does not exist: "' .
+ $tmpdir .
+ '" - You can change this location with "pear config-set temp_dir"');
+ }
+ }
+
+ if (!is_writable($tmpdir)) {
+ return $this->raiseError('channel-add: temp_dir is not writable: "' .
+ $tmpdir .
+ '" - You can change this location with "pear config-set temp_dir"');
+ }
+
+ $reg = &$this->config->getRegistry();
+ $lastmodified = false;
+ if ((!file_exists($params[0]) || is_dir($params[0]))
+ && $reg->channelExists(strtolower($params[0]))) {
+ $c = $reg->getChannel(strtolower($params[0]));
+ if (PEAR::isError($c)) {
+ return $this->raiseError($c);
+ }
+
+ $this->ui->outputData("Updating channel \"$params[0]\"", $command);
+ $dl = &$this->getDownloader(array());
+ // if force is specified, use a timestamp of "1" to force retrieval
+ $lastmodified = isset($options['force']) ? false : $c->lastModified();
+ PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
+ $contents = $dl->downloadHttp('http://' . $c->getName() . '/channel.xml',
+ $this->ui, $tmpdir, null, $lastmodified);
+ PEAR::staticPopErrorHandling();
+ if (PEAR::isError($contents)) {
+ // Attempt to fall back to https
+ $this->ui->outputData("Channel \"$params[0]\" is not responding over http://, failed with message: " . $contents->getMessage());
+ $this->ui->outputData("Trying channel \"$params[0]\" over https:// instead");
+ PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
+ $contents = $dl->downloadHttp('https://' . $c->getName() . '/channel.xml',
+ $this->ui, $tmpdir, null, $lastmodified);
+ PEAR::staticPopErrorHandling();
+ if (PEAR::isError($contents)) {
+ return $this->raiseError('Cannot retrieve channel.xml for channel "' .
+ $c->getName() . '" (' . $contents->getMessage() . ')');
+ }
+ }
+
+ list($contents, $lastmodified) = $contents;
+ if (!$contents) {
+ $this->ui->outputData("Channel \"$params[0]\" is up to date");
+ return;
+ }
+
+ $contents = implode('', file($contents));
+ if (!class_exists('PEAR_ChannelFile')) {
+ require_once 'PEAR/ChannelFile.php';
+ }
+
+ $channel = new PEAR_ChannelFile;
+ $channel->fromXmlString($contents);
+ if (!$channel->getErrors()) {
+ // security check: is the downloaded file for the channel we got it from?
+ if (strtolower($channel->getName()) != strtolower($c->getName())) {
+ if (!isset($options['force'])) {
+ return $this->raiseError('ERROR: downloaded channel definition file' .
+ ' for channel "' . $channel->getName() . '" from channel "' .
+ strtolower($c->getName()) . '"');
+ }
+
+ $this->ui->log(0, 'WARNING: downloaded channel definition file' .
+ ' for channel "' . $channel->getName() . '" from channel "' .
+ strtolower($c->getName()) . '"');
+ }
+ }
+ } else {
+ if (strpos($params[0], '://')) {
+ $dl = &$this->getDownloader();
+ PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
+ $loc = $dl->downloadHttp($params[0],
+ $this->ui, $tmpdir, null, $lastmodified);
+ PEAR::staticPopErrorHandling();
+ if (PEAR::isError($loc)) {
+ return $this->raiseError("Cannot open " . $params[0] .
+ ' (' . $loc->getMessage() . ')');
+ }
+
+ list($loc, $lastmodified) = $loc;
+ $contents = implode('', file($loc));
+ } else {
+ $fp = false;
+ if (file_exists($params[0])) {
+ $fp = fopen($params[0], 'r');
+ }
+
+ if (!$fp) {
+ return $this->raiseError("Cannot open " . $params[0]);
+ }
+
+ $contents = '';
+ while (!feof($fp)) {
+ $contents .= fread($fp, 1024);
+ }
+ fclose($fp);
+ }
+
+ if (!class_exists('PEAR_ChannelFile')) {
+ require_once 'PEAR/ChannelFile.php';
+ }
+
+ $channel = new PEAR_ChannelFile;
+ $channel->fromXmlString($contents);
+ }
+
+ $exit = false;
+ if (count($errors = $channel->getErrors(true))) {
+ foreach ($errors as $error) {
+ $this->ui->outputData(ucfirst($error['level'] . ': ' . $error['message']));
+ if (!$exit) {
+ $exit = $error['level'] == 'error' ? true : false;
+ }
+ }
+ if ($exit) {
+ return $this->raiseError('Invalid channel.xml file');
+ }
+ }
+
+ if (!$reg->channelExists($channel->getName())) {
+ return $this->raiseError('Error: Channel "' . $channel->getName() .
+ '" does not exist, use channel-add to add an entry');
+ }
+
+ $ret = $reg->updateChannel($channel, $lastmodified);
+ if (PEAR::isError($ret)) {
+ return $ret;
+ }
+
+ if (!$ret) {
+ return $this->raiseError('Updating Channel "' . $channel->getName() .
+ '" in registry failed');
+ }
+
+ $this->config->setChannels($reg->listChannels());
+ $this->config->writeConfigFile();
+ $this->ui->outputData('Update of Channel "' . $channel->getName() . '" succeeded');
+ }
+
+ function &getDownloader()
+ {
+ if (!class_exists('PEAR_Downloader')) {
+ require_once 'PEAR/Downloader.php';
+ }
+ $a = new PEAR_Downloader($this->ui, array(), $this->config);
+ return $a;
+ }
+
+ function doAlias($command, $options, $params)
+ {
+ if (count($params) === 1) {
+ return $this->raiseError('No channel alias specified');
+ }
+
+ if (count($params) !== 2 || (!empty($params[1]) && $params[1]{0} == '-')) {
+ return $this->raiseError(
+ 'Invalid format, correct is: channel-alias channel alias');
+ }
+
+ $reg = &$this->config->getRegistry();
+ if (!$reg->channelExists($params[0], true)) {
+ $extra = '';
+ if ($reg->isAlias($params[0])) {
+ $extra = ' (use "channel-alias ' . $reg->channelName($params[0]) . ' ' .
+ strtolower($params[1]) . '")';
+ }
+
+ return $this->raiseError('"' . $params[0] . '" is not a valid channel' . $extra);
+ }
+
+ if ($reg->isAlias($params[1])) {
+ return $this->raiseError('Channel "' . $reg->channelName($params[1]) . '" is ' .
+ 'already aliased to "' . strtolower($params[1]) . '", cannot re-alias');
+ }
+
+ $chan = &$reg->getChannel($params[0]);
+ if (PEAR::isError($chan)) {
+ return $this->raiseError('Corrupt registry? Error retrieving channel "' . $params[0] .
+ '" information (' . $chan->getMessage() . ')');
+ }
+
+ // make it a local alias
+ if (!$chan->setAlias(strtolower($params[1]), true)) {
+ return $this->raiseError('Alias "' . strtolower($params[1]) .
+ '" is not a valid channel alias');
+ }
+
+ $reg->updateChannel($chan);
+ $this->ui->outputData('Channel "' . $chan->getName() . '" aliased successfully to "' .
+ strtolower($params[1]) . '"');
+ }
+
+ /**
+ * The channel-discover command
+ *
+ * @param string $command command name
+ * @param array $options option_name => value
+ * @param array $params list of additional parameters.
+ * $params[0] should contain a string with either:
+ * - or
+ * - :@
+ * @return null|PEAR_Error
+ */
+ function doDiscover($command, $options, $params)
+ {
+ if (count($params) !== 1) {
+ return $this->raiseError("No channel server specified");
+ }
+
+ // Look for the possible input format ":@"
+ if (preg_match('/^(.+):(.+)@(.+)\\z/', $params[0], $matches)) {
+ $username = $matches[1];
+ $password = $matches[2];
+ $channel = $matches[3];
+ } else {
+ $channel = $params[0];
+ }
+
+ $reg = &$this->config->getRegistry();
+ if ($reg->channelExists($channel)) {
+ if (!$reg->isAlias($channel)) {
+ return $this->raiseError("Channel \"$channel\" is already initialized", PEAR_COMMAND_CHANNELS_CHANNEL_EXISTS);
+ }
+
+ return $this->raiseError("A channel alias named \"$channel\" " .
+ 'already exists, aliasing channel "' . $reg->channelName($channel)
+ . '"');
+ }
+
+ $this->pushErrorHandling(PEAR_ERROR_RETURN);
+ $err = $this->doAdd($command, $options, array('http://' . $channel . '/channel.xml'));
+ $this->popErrorHandling();
+ if (PEAR::isError($err)) {
+ if ($err->getCode() === PEAR_COMMAND_CHANNELS_CHANNEL_EXISTS) {
+ return $this->raiseError("Discovery of channel \"$channel\" failed (" .
+ $err->getMessage() . ')');
+ }
+ // Attempt fetch via https
+ $this->ui->outputData("Discovering channel $channel over http:// failed with message: " . $err->getMessage());
+ $this->ui->outputData("Trying to discover channel $channel over https:// instead");
+ $this->pushErrorHandling(PEAR_ERROR_RETURN);
+ $err = $this->doAdd($command, $options, array('https://' . $channel . '/channel.xml'));
+ $this->popErrorHandling();
+ if (PEAR::isError($err)) {
+ return $this->raiseError("Discovery of channel \"$channel\" failed (" .
+ $err->getMessage() . ')');
+ }
+ }
+
+ // Store username/password if they were given
+ // Arguably we should do a logintest on the channel here, but since
+ // that's awkward on a REST-based channel (even "pear login" doesn't
+ // do it for those), and XML-RPC is deprecated, it's fairly pointless.
+ if (isset($username)) {
+ $this->config->set('username', $username, 'user', $channel);
+ $this->config->set('password', $password, 'user', $channel);
+ $this->config->store();
+ $this->ui->outputData("Stored login for channel \"$channel\" using username \"$username\"", $command);
+ }
+
+ $this->ui->outputData("Discovery of channel \"$channel\" succeeded", $command);
+ }
+
+ /**
+ * Execute the 'login' command.
+ *
+ * @param string $command command name
+ * @param array $options option_name => value
+ * @param array $params list of additional parameters
+ *
+ * @return bool TRUE on success or
+ * a PEAR error on failure
+ *
+ * @access public
+ */
+ function doLogin($command, $options, $params)
+ {
+ $reg = &$this->config->getRegistry();
+
+ // If a parameter is supplied, use that as the channel to log in to
+ $channel = isset($params[0]) ? $params[0] : $this->config->get('default_channel');
+
+ $chan = $reg->getChannel($channel);
+ if (PEAR::isError($chan)) {
+ return $this->raiseError($chan);
+ }
+
+ $server = $this->config->get('preferred_mirror', null, $channel);
+ $username = $this->config->get('username', null, $channel);
+ if (empty($username)) {
+ $username = isset($_ENV['USER']) ? $_ENV['USER'] : null;
+ }
+ $this->ui->outputData("Logging in to $server.", $command);
+
+ list($username, $password) = $this->ui->userDialog(
+ $command,
+ array('Username', 'Password'),
+ array('text', 'password'),
+ array($username, '')
+ );
+ $username = trim($username);
+ $password = trim($password);
+
+ $ourfile = $this->config->getConfFile('user');
+ if (!$ourfile) {
+ $ourfile = $this->config->getConfFile('system');
+ }
+
+ $this->config->set('username', $username, 'user', $channel);
+ $this->config->set('password', $password, 'user', $channel);
+
+ if ($chan->supportsREST()) {
+ $ok = true;
+ }
+
+ if ($ok !== true) {
+ return $this->raiseError('Login failed!');
+ }
+
+ $this->ui->outputData("Logged in.", $command);
+ // avoid changing any temporary settings changed with -d
+ $ourconfig = new PEAR_Config($ourfile, $ourfile);
+ $ourconfig->set('username', $username, 'user', $channel);
+ $ourconfig->set('password', $password, 'user', $channel);
+ $ourconfig->store();
+
+ return true;
+ }
+
+ /**
+ * Execute the 'logout' command.
+ *
+ * @param string $command command name
+ * @param array $options option_name => value
+ * @param array $params list of additional parameters
+ *
+ * @return bool TRUE on success or
+ * a PEAR error on failure
+ *
+ * @access public
+ */
+ function doLogout($command, $options, $params)
+ {
+ $reg = &$this->config->getRegistry();
+
+ // If a parameter is supplied, use that as the channel to log in to
+ $channel = isset($params[0]) ? $params[0] : $this->config->get('default_channel');
+
+ $chan = $reg->getChannel($channel);
+ if (PEAR::isError($chan)) {
+ return $this->raiseError($chan);
+ }
+
+ $server = $this->config->get('preferred_mirror', null, $channel);
+ $this->ui->outputData("Logging out from $server.", $command);
+ $this->config->remove('username', 'user', $channel);
+ $this->config->remove('password', 'user', $channel);
+ $this->config->store();
+ return true;
+ }
+}
\ No newline at end of file
diff --git a/3rdparty/PEAR/Command/Channels.xml b/3rdparty/PEAR/Command/Channels.xml
new file mode 100644
index 0000000000..47b72066ab
--- /dev/null
+++ b/3rdparty/PEAR/Command/Channels.xml
@@ -0,0 +1,123 @@
+
+
+ List Available Channels
+ doList
+ lc
+
+
+List all available channels for installation.
+
+
+
+ Update the Channel List
+ doUpdateAll
+ uc
+
+
+List all installed packages in all channels.
+
+
+
+ Remove a Channel From the List
+ doDelete
+ cde
+
+ <channel name>
+Delete a channel from the registry. You may not
+remove any channel that has installed packages.
+
+
+
+ Add a Channel
+ doAdd
+ ca
+
+ <channel.xml>
+Add a private channel to the channel list. Note that all
+public channels should be synced using "update-channels".
+Parameter may be either a local file or remote URL to a
+channel.xml.
+
+
+
+ Update an Existing Channel
+ doUpdate
+ cu
+
+
+ f
+ will force download of new channel.xml if an existing channel name is used
+
+
+ c
+ will force download of new channel.xml if an existing channel name is used
+ CHANNEL
+
+
+ [<channel.xml>|<channel name>]
+Update a channel in the channel list directly. Note that all
+public channels can be synced using "update-channels".
+Parameter may be a local or remote channel.xml, or the name of
+an existing channel.
+
+
+
+ Retrieve Information on a Channel
+ doInfo
+ ci
+
+ <package>
+List the files in an installed package.
+
+
+
+ Specify an alias to a channel name
+ doAlias
+ cha
+
+ <channel> <alias>
+Specify a specific alias to use for a channel name.
+The alias may not be an existing channel name or
+alias.
+
+
+
+ Initialize a Channel from its server
+ doDiscover
+ di
+
+ [<channel.xml>|<channel name>]
+Initialize a channel from its server and create a local channel.xml.
+If <channel name> is in the format "<username>:<password>@<channel>" then
+<username> and <password> will be set as the login username/password for
+<channel>. Use caution when passing the username/password in this way, as
+it may allow other users on your computer to briefly view your username/
+password via the system's process list.
+
+
+
+ Connects and authenticates to remote channel server
+ doLogin
+ cli
+
+ <channel name>
+Log in to a remote channel server. If <channel name> is not supplied,
+the default channel is used. To use remote functions in the installer
+that require any kind of privileges, you need to log in first. The
+username and password you enter here will be stored in your per-user
+PEAR configuration (~/.pearrc on Unix-like systems). After logging
+in, your username and password will be sent along in subsequent
+operations on the remote server.
+
+
+ Logs out from the remote channel server
+ doLogout
+ clo
+
+ <channel name>
+Logs out from a remote channel server. If <channel name> is not supplied,
+the default channel is used. This command does not actually connect to the
+remote server, it only deletes the stored username and password from your user
+configuration.
+
+
\ No newline at end of file
diff --git a/3rdparty/PEAR/Command/Common.php b/3rdparty/PEAR/Command/Common.php
index c6ace694ca..279a716623 100644
--- a/3rdparty/PEAR/Command/Common.php
+++ b/3rdparty/PEAR/Command/Common.php
@@ -1,36 +1,52 @@
|
-// +----------------------------------------------------------------------+
-//
-// $Id: Common.php,v 1.24 2004/01/08 17:33:13 sniper Exp $
+/**
+ * PEAR_Command_Common base class
+ *
+ * PHP versions 4 and 5
+ *
+ * @category pear
+ * @package PEAR
+ * @author Stig Bakken
+ * @author Greg Beaver
+ * @copyright 1997-2009 The Authors
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version CVS: $Id: Common.php 313023 2011-07-06 19:17:11Z dufuz $
+ * @link http://pear.php.net/package/PEAR
+ * @since File available since Release 0.1
+ */
-require_once "PEAR.php";
+/**
+ * base class
+ */
+require_once 'PEAR.php';
+/**
+ * PEAR commands base class
+ *
+ * @category pear
+ * @package PEAR
+ * @author Stig Bakken
+ * @author Greg Beaver
+ * @copyright 1997-2009 The Authors
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version Release: 1.9.4
+ * @link http://pear.php.net/package/PEAR
+ * @since Class available since Release 0.1
+ */
class PEAR_Command_Common extends PEAR
{
- // {{{ properties
-
/**
* PEAR_Config object used to pass user system and configuration
* on when executing commands
*
- * @var object
+ * @var PEAR_Config
*/
var $config;
+ /**
+ * @var PEAR_Registry
+ * @access protected
+ */
+ var $_registry;
/**
* User Interface object, for all interaction with the user.
@@ -50,7 +66,7 @@ class PEAR_Command_Common extends PEAR
var $_deps_type_trans = array(
'pkg' => 'package',
- 'extension' => 'extension',
+ 'ext' => 'extension',
'php' => 'PHP',
'prog' => 'external program',
'ldlib' => 'external library for linking',
@@ -60,9 +76,6 @@ class PEAR_Command_Common extends PEAR
'sapi' => 'SAPI backend'
);
- // }}}
- // {{{ constructor
-
/**
* PEAR_Command_Common constructor.
*
@@ -75,10 +88,6 @@ class PEAR_Command_Common extends PEAR
$this->ui = &$ui;
}
- // }}}
-
- // {{{ getCommands()
-
/**
* Return a list of all the commands defined by this class.
* @return array list of commands
@@ -90,12 +99,10 @@ class PEAR_Command_Common extends PEAR
foreach (array_keys($this->commands) as $command) {
$ret[$command] = $this->commands[$command]['summary'];
}
+
return $ret;
}
- // }}}
- // {{{ getShortcuts()
-
/**
* Return a list of all the command shortcuts defined by this class.
* @return array shortcut => command
@@ -109,28 +116,34 @@ class PEAR_Command_Common extends PEAR
$ret[$this->commands[$command]['shortcut']] = $command;
}
}
+
return $ret;
}
- // }}}
- // {{{ getOptions()
-
function getOptions($command)
{
- return @$this->commands[$command]['options'];
- }
+ $shortcuts = $this->getShortcuts();
+ if (isset($shortcuts[$command])) {
+ $command = $shortcuts[$command];
+ }
- // }}}
- // {{{ getGetoptArgs()
+ if (isset($this->commands[$command]) &&
+ isset($this->commands[$command]['options'])) {
+ return $this->commands[$command]['options'];
+ }
+
+ return null;
+ }
function getGetoptArgs($command, &$short_args, &$long_args)
{
- $short_args = "";
+ $short_args = '';
$long_args = array();
- if (empty($this->commands[$command])) {
+ if (empty($this->commands[$command]) || empty($this->commands[$command]['options'])) {
return;
}
- reset($this->commands[$command]);
+
+ reset($this->commands[$command]['options']);
while (list($option, $info) = each($this->commands[$command]['options'])) {
$larg = $sarg = '';
if (isset($info['arg'])) {
@@ -144,15 +157,15 @@ class PEAR_Command_Common extends PEAR
$arg = $info['arg'];
}
}
+
if (isset($info['shortopt'])) {
$short_args .= $info['shortopt'] . $sarg;
}
+
$long_args[] = $option . $larg;
}
}
- // }}}
- // {{{ getHelp()
/**
* Returns the help message for the given command
*
@@ -164,29 +177,38 @@ class PEAR_Command_Common extends PEAR
function getHelp($command)
{
$config = &PEAR_Config::singleton();
- $help = @$this->commands[$command]['doc'];
+ if (!isset($this->commands[$command])) {
+ return "No such command \"$command\"";
+ }
+
+ $help = null;
+ if (isset($this->commands[$command]['doc'])) {
+ $help = $this->commands[$command]['doc'];
+ }
+
if (empty($help)) {
// XXX (cox) Fallback to summary if there is no doc (show both?)
- if (!$help = @$this->commands[$command]['summary']) {
+ if (!isset($this->commands[$command]['summary'])) {
return "No help for command \"$command\"";
}
+ $help = $this->commands[$command]['summary'];
}
+
if (preg_match_all('/{config\s+([^\}]+)}/e', $help, $matches)) {
foreach($matches[0] as $k => $v) {
$help = preg_replace("/$v/", $config->get($matches[1][$k]), $help);
}
}
+
return array($help, $this->getHelpArgs($command));
}
- // }}}
- // {{{ getHelpArgs()
/**
- * Returns the help for the accepted arguments of a command
- *
- * @param string $command
- * @return string The help string
- */
+ * Returns the help for the accepted arguments of a command
+ *
+ * @param string $command
+ * @return string The help string
+ */
function getHelpArgs($command)
{
if (isset($this->commands[$command]['options']) &&
@@ -195,7 +217,7 @@ class PEAR_Command_Common extends PEAR
$help = "Options:\n";
foreach ($this->commands[$command]['options'] as $k => $v) {
if (isset($v['arg'])) {
- if ($v['arg']{0} == '(') {
+ if ($v['arg'][0] == '(') {
$arg = substr($v['arg'], 1, -1);
$sapp = " [$arg]";
$lapp = "[=$arg]";
@@ -206,44 +228,46 @@ class PEAR_Command_Common extends PEAR
} else {
$sapp = $lapp = "";
}
+
if (isset($v['shortopt'])) {
$s = $v['shortopt'];
- @$help .= " -$s$sapp, --$k$lapp\n";
+ $help .= " -$s$sapp, --$k$lapp\n";
} else {
- @$help .= " --$k$lapp\n";
+ $help .= " --$k$lapp\n";
}
+
$p = " ";
$doc = rtrim(str_replace("\n", "\n$p", $v['doc']));
$help .= " $doc\n";
}
+
return $help;
}
+
return null;
}
- // }}}
- // {{{ run()
-
function run($command, $options, $params)
{
- $func = @$this->commands[$command]['function'];
- if (empty($func)) {
+ if (empty($this->commands[$command]['function'])) {
// look for shortcuts
foreach (array_keys($this->commands) as $cmd) {
- if (@$this->commands[$cmd]['shortcut'] == $command) {
- $command = $cmd;
- $func = @$this->commands[$command]['function'];
- if (empty($func)) {
+ if (isset($this->commands[$cmd]['shortcut']) && $this->commands[$cmd]['shortcut'] == $command) {
+ if (empty($this->commands[$cmd]['function'])) {
return $this->raiseError("unknown command `$command'");
+ } else {
+ $func = $this->commands[$cmd]['function'];
}
+ $command = $cmd;
+
+ //$command = $this->commands[$cmd]['function'];
break;
}
}
+ } else {
+ $func = $this->commands[$command]['function'];
}
+
return $this->$func($command, $options, $params);
}
-
- // }}}
-}
-
-?>
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/3rdparty/PEAR/Command/Config.php b/3rdparty/PEAR/Command/Config.php
index 474a234517..a761b277f5 100644
--- a/3rdparty/PEAR/Command/Config.php
+++ b/3rdparty/PEAR/Command/Config.php
@@ -1,74 +1,101 @@
|
-// | Tomas V.V.Cox |
-// | |
-// +----------------------------------------------------------------------+
-//
-// $Id: Config.php,v 1.27 2004/06/15 16:48:49 pajoye Exp $
+/**
+ * PEAR_Command_Config (config-show, config-get, config-set, config-help, config-create commands)
+ *
+ * PHP versions 4 and 5
+ *
+ * @category pear
+ * @package PEAR
+ * @author Stig Bakken
+ * @author Greg Beaver
+ * @copyright 1997-2009 The Authors
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version CVS: $Id: Config.php 313024 2011-07-06 19:51:24Z dufuz $
+ * @link http://pear.php.net/package/PEAR
+ * @since File available since Release 0.1
+ */
-require_once "PEAR/Command/Common.php";
-require_once "PEAR/Config.php";
+/**
+ * base class
+ */
+require_once 'PEAR/Command/Common.php';
/**
* PEAR commands for managing configuration data.
*
+ * @category pear
+ * @package PEAR
+ * @author Stig Bakken
+ * @author Greg Beaver
+ * @copyright 1997-2009 The Authors
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version Release: 1.9.4
+ * @link http://pear.php.net/package/PEAR
+ * @since Class available since Release 0.1
*/
class PEAR_Command_Config extends PEAR_Command_Common
{
- // {{{ properties
-
var $commands = array(
'config-show' => array(
'summary' => 'Show All Settings',
'function' => 'doConfigShow',
'shortcut' => 'csh',
- 'options' => array(),
- 'doc' => '
+ 'options' => array(
+ 'channel' => array(
+ 'shortopt' => 'c',
+ 'doc' => 'show configuration variables for another channel',
+ 'arg' => 'CHAN',
+ ),
+),
+ 'doc' => '[layer]
Displays all configuration values. An optional argument
may be used to tell which configuration layer to display. Valid
-configuration layers are "user", "system" and "default".
+configuration layers are "user", "system" and "default". To display
+configurations for different channels, set the default_channel
+configuration variable and run config-show again.
',
),
'config-get' => array(
'summary' => 'Show One Setting',
'function' => 'doConfigGet',
'shortcut' => 'cg',
- 'options' => array(),
+ 'options' => array(
+ 'channel' => array(
+ 'shortopt' => 'c',
+ 'doc' => 'show configuration variables for another channel',
+ 'arg' => 'CHAN',
+ ),
+),
'doc' => ' [layer]
Displays the value of one configuration parameter. The
first argument is the name of the parameter, an optional second argument
may be used to tell which configuration layer to look in. Valid configuration
layers are "user", "system" and "default". If no layer is specified, a value
will be picked from the first layer that defines the parameter, in the order
-just specified.
+just specified. The configuration value will be retrieved for the channel
+specified by the default_channel configuration variable.
',
),
'config-set' => array(
'summary' => 'Change Setting',
'function' => 'doConfigSet',
'shortcut' => 'cs',
- 'options' => array(),
+ 'options' => array(
+ 'channel' => array(
+ 'shortopt' => 'c',
+ 'doc' => 'show configuration variables for another channel',
+ 'arg' => 'CHAN',
+ ),
+),
'doc' => ' [layer]
Sets the value of one configuration parameter. The first argument is
the name of the parameter, the second argument is the new value. Some
parameters are subject to validation, and the command will fail with
an error message if the new value does not make sense. An optional
third argument may be used to specify in which layer to set the
-configuration parameter. The default layer is "user".
+configuration parameter. The default layer is "user". The
+configuration value will be set for the current channel, which
+is controlled by the default_channel configuration variable.
',
),
'config-help' => array(
@@ -81,11 +108,26 @@ Displays help for a configuration parameter. Without arguments it
displays help for all configuration parameters.
',
),
+ 'config-create' => array(
+ 'summary' => 'Create a Default configuration file',
+ 'function' => 'doConfigCreate',
+ 'shortcut' => 'coc',
+ 'options' => array(
+ 'windows' => array(
+ 'shortopt' => 'w',
+ 'doc' => 'create a config file for a windows install',
+ ),
+ ),
+ 'doc' => '
+Create a default configuration file with all directory configuration
+variables set to subdirectories of , and save it as .
+This is useful especially for creating a configuration file for a remote
+PEAR installation (using the --remoteconfig option of install, upgrade,
+and uninstall).
+',
+ ),
);
- // }}}
- // {{{ constructor
-
/**
* PEAR_Command_Config constructor.
*
@@ -96,94 +138,154 @@ displays help for all configuration parameters.
parent::PEAR_Command_Common($ui, $config);
}
- // }}}
-
- // {{{ doConfigShow()
-
function doConfigShow($command, $options, $params)
{
- // $params[0] -> the layer
- if ($error = $this->_checkLayer(@$params[0])) {
- return $this->raiseError($error);
+ $layer = null;
+ if (is_array($params)) {
+ $layer = isset($params[0]) ? $params[0] : null;
}
+
+ // $params[0] -> the layer
+ if ($error = $this->_checkLayer($layer)) {
+ return $this->raiseError("config-show:$error");
+ }
+
$keys = $this->config->getKeys();
sort($keys);
- $data = array('caption' => 'Configuration:');
+ $channel = isset($options['channel']) ? $options['channel'] :
+ $this->config->get('default_channel');
+ $reg = &$this->config->getRegistry();
+ if (!$reg->channelExists($channel)) {
+ return $this->raiseError('Channel "' . $channel . '" does not exist');
+ }
+
+ $channel = $reg->channelName($channel);
+ $data = array('caption' => 'Configuration (channel ' . $channel . '):');
foreach ($keys as $key) {
$type = $this->config->getType($key);
- $value = $this->config->get($key, @$params[0]);
+ $value = $this->config->get($key, $layer, $channel);
if ($type == 'password' && $value) {
$value = '********';
}
+
if ($value === false) {
$value = 'false';
} elseif ($value === true) {
$value = 'true';
}
+
$data['data'][$this->config->getGroup($key)][] = array($this->config->getPrompt($key) , $key, $value);
}
+
+ foreach ($this->config->getLayers() as $layer) {
+ $data['data']['Config Files'][] = array(ucfirst($layer) . ' Configuration File', 'Filename' , $this->config->getConfFile($layer));
+ }
+
$this->ui->outputData($data, $command);
return true;
}
- // }}}
- // {{{ doConfigGet()
-
function doConfigGet($command, $options, $params)
{
- // $params[0] -> the parameter
- // $params[1] -> the layer
- if ($error = $this->_checkLayer(@$params[1])) {
- return $this->raiseError($error);
+ $args_cnt = is_array($params) ? count($params) : 0;
+ switch ($args_cnt) {
+ case 1:
+ $config_key = $params[0];
+ $layer = null;
+ break;
+ case 2:
+ $config_key = $params[0];
+ $layer = $params[1];
+ if ($error = $this->_checkLayer($layer)) {
+ return $this->raiseError("config-get:$error");
+ }
+ break;
+ case 0:
+ default:
+ return $this->raiseError("config-get expects 1 or 2 parameters");
}
- if (sizeof($params) < 1 || sizeof($params) > 2) {
- return $this->raiseError("config-get expects 1 or 2 parameters");
- } elseif (sizeof($params) == 1) {
- $this->ui->outputData($this->config->get($params[0]), $command);
- } else {
- $data = $this->config->get($params[0], $params[1]);
- $this->ui->outputData($data, $command);
+
+ $reg = &$this->config->getRegistry();
+ $channel = isset($options['channel']) ? $options['channel'] : $this->config->get('default_channel');
+ if (!$reg->channelExists($channel)) {
+ return $this->raiseError('Channel "' . $channel . '" does not exist');
}
+
+ $channel = $reg->channelName($channel);
+ $this->ui->outputData($this->config->get($config_key, $layer, $channel), $command);
return true;
}
- // }}}
- // {{{ doConfigSet()
-
function doConfigSet($command, $options, $params)
{
// $param[0] -> a parameter to set
// $param[1] -> the value for the parameter
// $param[2] -> the layer
$failmsg = '';
- if (sizeof($params) < 2 || sizeof($params) > 3) {
+ if (count($params) < 2 || count($params) > 3) {
$failmsg .= "config-set expects 2 or 3 parameters";
return PEAR::raiseError($failmsg);
}
- if ($error = $this->_checkLayer(@$params[2])) {
+
+ if (isset($params[2]) && ($error = $this->_checkLayer($params[2]))) {
$failmsg .= $error;
- return PEAR::raiseError($failmsg);
+ return PEAR::raiseError("config-set:$failmsg");
}
- if (!call_user_func_array(array(&$this->config, 'set'), $params))
- {
- $failmsg = "config-set (" . implode(", ", $params) . ") failed";
+
+ $channel = isset($options['channel']) ? $options['channel'] : $this->config->get('default_channel');
+ $reg = &$this->config->getRegistry();
+ if (!$reg->channelExists($channel)) {
+ return $this->raiseError('Channel "' . $channel . '" does not exist');
+ }
+
+ $channel = $reg->channelName($channel);
+ if ($params[0] == 'default_channel' && !$reg->channelExists($params[1])) {
+ return $this->raiseError('Channel "' . $params[1] . '" does not exist');
+ }
+
+ if ($params[0] == 'preferred_mirror'
+ && (
+ !$reg->mirrorExists($channel, $params[1]) &&
+ (!$reg->channelExists($params[1]) || $channel != $params[1])
+ )
+ ) {
+ $msg = 'Channel Mirror "' . $params[1] . '" does not exist';
+ $msg .= ' in your registry for channel "' . $channel . '".';
+ $msg .= "\n" . 'Attempt to run "pear channel-update ' . $channel .'"';
+ $msg .= ' if you believe this mirror should exist as you may';
+ $msg .= ' have outdated channel information.';
+ return $this->raiseError($msg);
+ }
+
+ if (count($params) == 2) {
+ array_push($params, 'user');
+ $layer = 'user';
} else {
- $this->config->store();
+ $layer = $params[2];
}
+
+ array_push($params, $channel);
+ if (!call_user_func_array(array(&$this->config, 'set'), $params)) {
+ array_pop($params);
+ $failmsg = "config-set (" . implode(", ", $params) . ") failed, channel $channel";
+ } else {
+ $this->config->store($layer);
+ }
+
if ($failmsg) {
return $this->raiseError($failmsg);
}
+
+ $this->ui->outputData('config-set succeeded', $command);
return true;
}
- // }}}
- // {{{ doConfigHelp()
-
function doConfigHelp($command, $options, $params)
{
if (empty($params)) {
$params = $this->config->getKeys();
}
+
$data['caption'] = "Config help" . ((count($params) == 1) ? " for $params[0]" : '');
$data['headline'] = array('Name', 'Type', 'Description');
$data['border'] = true;
@@ -194,13 +296,103 @@ displays help for all configuration parameters.
$docs = rtrim($docs) . "\nValid set: " .
implode(' ', $this->config->getSetValues($name));
}
+
$data['data'][] = array($name, $type, $docs);
}
+
$this->ui->outputData($data, $command);
}
- // }}}
- // {{{ _checkLayer()
+ function doConfigCreate($command, $options, $params)
+ {
+ if (count($params) != 2) {
+ return PEAR::raiseError('config-create: must have 2 parameters, root path and ' .
+ 'filename to save as');
+ }
+
+ $root = $params[0];
+ // Clean up the DIRECTORY_SEPARATOR mess
+ $ds2 = DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR;
+ $root = preg_replace(array('!\\\\+!', '!/+!', "!$ds2+!"),
+ array('/', '/', '/'),
+ $root);
+ if ($root{0} != '/') {
+ if (!isset($options['windows'])) {
+ return PEAR::raiseError('Root directory must be an absolute path beginning ' .
+ 'with "/", was: "' . $root . '"');
+ }
+
+ if (!preg_match('/^[A-Za-z]:/', $root)) {
+ return PEAR::raiseError('Root directory must be an absolute path beginning ' .
+ 'with "\\" or "C:\\", was: "' . $root . '"');
+ }
+ }
+
+ $windows = isset($options['windows']);
+ if ($windows) {
+ $root = str_replace('/', '\\', $root);
+ }
+
+ if (!file_exists($params[1]) && !@touch($params[1])) {
+ return PEAR::raiseError('Could not create "' . $params[1] . '"');
+ }
+
+ $params[1] = realpath($params[1]);
+ $config = &new PEAR_Config($params[1], '#no#system#config#', false, false);
+ if ($root{strlen($root) - 1} == '/') {
+ $root = substr($root, 0, strlen($root) - 1);
+ }
+
+ $config->noRegistry();
+ $config->set('php_dir', $windows ? "$root\\pear\\php" : "$root/pear/php", 'user');
+ $config->set('data_dir', $windows ? "$root\\pear\\data" : "$root/pear/data");
+ $config->set('www_dir', $windows ? "$root\\pear\\www" : "$root/pear/www");
+ $config->set('cfg_dir', $windows ? "$root\\pear\\cfg" : "$root/pear/cfg");
+ $config->set('ext_dir', $windows ? "$root\\pear\\ext" : "$root/pear/ext");
+ $config->set('doc_dir', $windows ? "$root\\pear\\docs" : "$root/pear/docs");
+ $config->set('test_dir', $windows ? "$root\\pear\\tests" : "$root/pear/tests");
+ $config->set('cache_dir', $windows ? "$root\\pear\\cache" : "$root/pear/cache");
+ $config->set('download_dir', $windows ? "$root\\pear\\download" : "$root/pear/download");
+ $config->set('temp_dir', $windows ? "$root\\pear\\temp" : "$root/pear/temp");
+ $config->set('bin_dir', $windows ? "$root\\pear" : "$root/pear");
+ $config->writeConfigFile();
+ $this->_showConfig($config);
+ $this->ui->outputData('Successfully created default configuration file "' . $params[1] . '"',
+ $command);
+ }
+
+ function _showConfig(&$config)
+ {
+ $params = array('user');
+ $keys = $config->getKeys();
+ sort($keys);
+ $channel = 'pear.php.net';
+ $data = array('caption' => 'Configuration (channel ' . $channel . '):');
+ foreach ($keys as $key) {
+ $type = $config->getType($key);
+ $value = $config->get($key, 'user', $channel);
+ if ($type == 'password' && $value) {
+ $value = '********';
+ }
+
+ if ($value === false) {
+ $value = 'false';
+ } elseif ($value === true) {
+ $value = 'true';
+ }
+ $data['data'][$config->getGroup($key)][] =
+ array($config->getPrompt($key) , $key, $value);
+ }
+
+ foreach ($config->getLayers() as $layer) {
+ $data['data']['Config Files'][] =
+ array(ucfirst($layer) . ' Configuration File', 'Filename' ,
+ $config->getConfFile($layer));
+ }
+
+ $this->ui->outputData($data, 'config-show');
+ return true;
+ }
/**
* Checks if a layer is defined or not
@@ -216,10 +408,7 @@ displays help for all configuration parameters.
return " only the layers: \"" . implode('" or "', $layers) . "\" are supported";
}
}
+
return false;
}
-
- // }}}
-}
-
-?>
+}
\ No newline at end of file
diff --git a/3rdparty/PEAR/Command/Config.xml b/3rdparty/PEAR/Command/Config.xml
new file mode 100644
index 0000000000..f64a925f52
--- /dev/null
+++ b/3rdparty/PEAR/Command/Config.xml
@@ -0,0 +1,92 @@
+
+
+ Show All Settings
+ doConfigShow
+ csh
+
+
+ c
+ show configuration variables for another channel
+ CHAN
+
+
+ [layer]
+Displays all configuration values. An optional argument
+may be used to tell which configuration layer to display. Valid
+configuration layers are "user", "system" and "default". To display
+configurations for different channels, set the default_channel
+configuration variable and run config-show again.
+
+
+
+ Show One Setting
+ doConfigGet
+ cg
+
+
+ c
+ show configuration variables for another channel
+ CHAN
+
+
+ <parameter> [layer]
+Displays the value of one configuration parameter. The
+first argument is the name of the parameter, an optional second argument
+may be used to tell which configuration layer to look in. Valid configuration
+layers are "user", "system" and "default". If no layer is specified, a value
+will be picked from the first layer that defines the parameter, in the order
+just specified. The configuration value will be retrieved for the channel
+specified by the default_channel configuration variable.
+
+
+
+ Change Setting
+ doConfigSet
+ cs
+
+
+ c
+ show configuration variables for another channel
+ CHAN
+
+
+ <parameter> <value> [layer]
+Sets the value of one configuration parameter. The first argument is
+the name of the parameter, the second argument is the new value. Some
+parameters are subject to validation, and the command will fail with
+an error message if the new value does not make sense. An optional
+third argument may be used to specify in which layer to set the
+configuration parameter. The default layer is "user". The
+configuration value will be set for the current channel, which
+is controlled by the default_channel configuration variable.
+
+
+
+ Show Information About Setting
+ doConfigHelp
+ ch
+
+ [parameter]
+Displays help for a configuration parameter. Without arguments it
+displays help for all configuration parameters.
+
+
+
+ Create a Default configuration file
+ doConfigCreate
+ coc
+
+
+ w
+ create a config file for a windows install
+
+
+ <root path> <filename>
+Create a default configuration file with all directory configuration
+variables set to subdirectories of <root path>, and save it as <filename>.
+This is useful especially for creating a configuration file for a remote
+PEAR installation (using the --remoteconfig option of install, upgrade,
+and uninstall).
+
+
+
\ No newline at end of file
diff --git a/3rdparty/PEAR/Command/Install.php b/3rdparty/PEAR/Command/Install.php
index dce52f017e..c035f6d20d 100644
--- a/3rdparty/PEAR/Command/Install.php
+++ b/3rdparty/PEAR/Command/Install.php
@@ -1,30 +1,38 @@
|
-// +----------------------------------------------------------------------+
-//
-// $Id: Install.php,v 1.53.2.1 2004/10/19 04:08:42 cellog Exp $
+/**
+ * PEAR_Command_Install (install, upgrade, upgrade-all, uninstall, bundle, run-scripts commands)
+ *
+ * PHP versions 4 and 5
+ *
+ * @category pear
+ * @package PEAR
+ * @author Stig Bakken
+ * @author Greg Beaver
+ * @copyright 1997-2009 The Authors
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version CVS: $Id: Install.php 313023 2011-07-06 19:17:11Z dufuz $
+ * @link http://pear.php.net/package/PEAR
+ * @since File available since Release 0.1
+ */
-require_once "PEAR/Command/Common.php";
-require_once "PEAR/Installer.php";
+/**
+ * base class
+ */
+require_once 'PEAR/Command/Common.php';
/**
* PEAR commands for installation or deinstallation/upgrading of
* packages.
*
+ * @category pear
+ * @package PEAR
+ * @author Stig Bakken
+ * @author Greg Beaver
+ * @copyright 1997-2009 The Authors
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version Release: 1.9.4
+ * @link http://pear.php.net/package/PEAR
+ * @since Class available since Release 0.1
*/
class PEAR_Command_Install extends PEAR_Command_Common
{
@@ -40,6 +48,10 @@ class PEAR_Command_Install extends PEAR_Command_Common
'shortopt' => 'f',
'doc' => 'will overwrite newer installed packages',
),
+ 'loose' => array(
+ 'shortopt' => 'l',
+ 'doc' => 'do not check for recommended dependency version',
+ ),
'nodeps' => array(
'shortopt' => 'n',
'doc' => 'ignore dependencies, install anyway',
@@ -63,7 +75,12 @@ class PEAR_Command_Install extends PEAR_Command_Common
'installroot' => array(
'shortopt' => 'R',
'arg' => 'DIR',
- 'doc' => 'root directory used when installing files (ala PHP\'s INSTALL_ROOT)',
+ 'doc' => 'root directory used when installing files (ala PHP\'s INSTALL_ROOT), use packagingroot for RPM',
+ ),
+ 'packagingroot' => array(
+ 'shortopt' => 'P',
+ 'arg' => 'DIR',
+ 'doc' => 'root directory used when packaging files, like RPM packaging',
),
'ignore-errors' => array(
'doc' => 'force install even if there were errors',
@@ -76,8 +93,16 @@ class PEAR_Command_Install extends PEAR_Command_Common
'shortopt' => 'o',
'doc' => 'install all required dependencies',
),
+ 'offline' => array(
+ 'shortopt' => 'O',
+ 'doc' => 'do not attempt to download any urls or contact channels',
+ ),
+ 'pretend' => array(
+ 'shortopt' => 'p',
+ 'doc' => 'Only list the packages that would be downloaded',
+ ),
),
- 'doc' => ' ...
+ 'doc' => '[channel/] ...
Installs one or more PEAR packages. You can specify a package to
install in four ways:
@@ -90,10 +115,17 @@ anywhere on the net.
package.xml. Useful for testing, or for wrapping a PEAR package in
another package manager such as RPM.
-"Package" : queries your configured server
+"Package[-version/state][.tar]" : queries your default channel\'s server
({config master_server}) and downloads the newest package with
the preferred quality/state ({config preferred_state}).
+To retrieve Package version 1.1, use "Package-1.1," to retrieve
+Package state beta, use "Package-beta." To retrieve an uncompressed
+file, append .tar (make sure there is no file by the same name first)
+
+To download a package from another channel, prefix with the channel name like
+"channel/Package"
+
More than one package may be specified at once. It is ok to mix these
four ways of specifying packages.
'),
@@ -102,10 +134,19 @@ four ways of specifying packages.
'function' => 'doInstall',
'shortcut' => 'up',
'options' => array(
+ 'channel' => array(
+ 'shortopt' => 'c',
+ 'doc' => 'upgrade packages from a specific channel',
+ 'arg' => 'CHAN',
+ ),
'force' => array(
'shortopt' => 'f',
'doc' => 'overwrite newer installed packages',
),
+ 'loose' => array(
+ 'shortopt' => 'l',
+ 'doc' => 'do not check for recommended dependency version',
+ ),
'nodeps' => array(
'shortopt' => 'n',
'doc' => 'ignore dependencies, upgrade anyway',
@@ -138,6 +179,14 @@ four ways of specifying packages.
'shortopt' => 'o',
'doc' => 'install all required dependencies',
),
+ 'offline' => array(
+ 'shortopt' => 'O',
+ 'doc' => 'do not attempt to download any urls or contact channels',
+ ),
+ 'pretend' => array(
+ 'shortopt' => 'p',
+ 'doc' => 'Only list the packages that would be downloaded',
+ ),
),
'doc' => ' ...
Upgrades one or more PEAR packages. See documentation for the
@@ -150,10 +199,15 @@ upgrade anyway).
More than one package may be specified at once.
'),
'upgrade-all' => array(
- 'summary' => 'Upgrade All Packages',
- 'function' => 'doInstall',
+ 'summary' => 'Upgrade All Packages [Deprecated in favor of calling upgrade with no parameters]',
+ 'function' => 'doUpgradeAll',
'shortcut' => 'ua',
'options' => array(
+ 'channel' => array(
+ 'shortopt' => 'c',
+ 'doc' => 'upgrade packages from a specific channel',
+ 'arg' => 'CHAN',
+ ),
'nodeps' => array(
'shortopt' => 'n',
'doc' => 'ignore dependencies, upgrade anyway',
@@ -173,13 +227,18 @@ More than one package may be specified at once.
'installroot' => array(
'shortopt' => 'R',
'arg' => 'DIR',
- 'doc' => 'root directory used when installing files (ala PHP\'s INSTALL_ROOT)',
+ 'doc' => 'root directory used when installing files (ala PHP\'s INSTALL_ROOT), use packagingroot for RPM',
),
'ignore-errors' => array(
'doc' => 'force install even if there were errors',
),
+ 'loose' => array(
+ 'doc' => 'do not check for recommended dependency version',
+ ),
),
'doc' => '
+WARNING: This function is deprecated in favor of using the upgrade command with no params
+
Upgrades all packages that have a newer release available. Upgrades are
done only if there is a release available of the state specified in
"preferred_state" (currently {config preferred_state}), or a state considered
@@ -206,10 +265,15 @@ more stable.
'ignore-errors' => array(
'doc' => 'force install even if there were errors',
),
+ 'offline' => array(
+ 'shortopt' => 'O',
+ 'doc' => 'do not attempt to uninstall remotely',
+ ),
),
- 'doc' => ' ...
+ 'doc' => '[channel/] ...
Uninstalls one or more PEAR packages. More than one package may be
-specified at once.
+specified at once. Prefix with channel name to uninstall from a
+channel not in your default channel ({config default_channel})
'),
'bundle' => array(
'summary' => 'Unpacks a Pecl Package',
@@ -229,6 +293,15 @@ specified at once.
'doc' => '
Unpacks a Pecl Package into the selected location. It will download the
package if needed.
+'),
+ 'run-scripts' => array(
+ 'summary' => 'Run Post-Install Scripts bundled with a package',
+ 'function' => 'doRunScripts',
+ 'shortcut' => 'rs',
+ 'options' => array(
+ ),
+ 'doc' => '
+Run post-installation scripts in package , if any exist.
'),
);
@@ -247,123 +320,763 @@ package if needed.
// }}}
+ /**
+ * For unit testing purposes
+ */
+ function &getDownloader(&$ui, $options, &$config)
+ {
+ if (!class_exists('PEAR_Downloader')) {
+ require_once 'PEAR/Downloader.php';
+ }
+ $a = &new PEAR_Downloader($ui, $options, $config);
+ return $a;
+ }
+
+ /**
+ * For unit testing purposes
+ */
+ function &getInstaller(&$ui)
+ {
+ if (!class_exists('PEAR_Installer')) {
+ require_once 'PEAR/Installer.php';
+ }
+ $a = &new PEAR_Installer($ui);
+ return $a;
+ }
+
+ function enableExtension($binaries, $type)
+ {
+ if (!($phpini = $this->config->get('php_ini', null, 'pear.php.net'))) {
+ return PEAR::raiseError('configuration option "php_ini" is not set to php.ini location');
+ }
+ $ini = $this->_parseIni($phpini);
+ if (PEAR::isError($ini)) {
+ return $ini;
+ }
+ $line = 0;
+ if ($type == 'extsrc' || $type == 'extbin') {
+ $search = 'extensions';
+ $enable = 'extension';
+ } else {
+ $search = 'zend_extensions';
+ ob_start();
+ phpinfo(INFO_GENERAL);
+ $info = ob_get_contents();
+ ob_end_clean();
+ $debug = function_exists('leak') ? '_debug' : '';
+ $ts = preg_match('/Thread Safety.+enabled/', $info) ? '_ts' : '';
+ $enable = 'zend_extension' . $debug . $ts;
+ }
+ foreach ($ini[$search] as $line => $extension) {
+ if (in_array($extension, $binaries, true) || in_array(
+ $ini['extension_dir'] . DIRECTORY_SEPARATOR . $extension, $binaries, true)) {
+ // already enabled - assume if one is, all are
+ return true;
+ }
+ }
+ if ($line) {
+ $newini = array_slice($ini['all'], 0, $line);
+ } else {
+ $newini = array();
+ }
+ foreach ($binaries as $binary) {
+ if ($ini['extension_dir']) {
+ $binary = basename($binary);
+ }
+ $newini[] = $enable . '="' . $binary . '"' . (OS_UNIX ? "\n" : "\r\n");
+ }
+ $newini = array_merge($newini, array_slice($ini['all'], $line));
+ $fp = @fopen($phpini, 'wb');
+ if (!$fp) {
+ return PEAR::raiseError('cannot open php.ini "' . $phpini . '" for writing');
+ }
+ foreach ($newini as $line) {
+ fwrite($fp, $line);
+ }
+ fclose($fp);
+ return true;
+ }
+
+ function disableExtension($binaries, $type)
+ {
+ if (!($phpini = $this->config->get('php_ini', null, 'pear.php.net'))) {
+ return PEAR::raiseError('configuration option "php_ini" is not set to php.ini location');
+ }
+ $ini = $this->_parseIni($phpini);
+ if (PEAR::isError($ini)) {
+ return $ini;
+ }
+ $line = 0;
+ if ($type == 'extsrc' || $type == 'extbin') {
+ $search = 'extensions';
+ $enable = 'extension';
+ } else {
+ $search = 'zend_extensions';
+ ob_start();
+ phpinfo(INFO_GENERAL);
+ $info = ob_get_contents();
+ ob_end_clean();
+ $debug = function_exists('leak') ? '_debug' : '';
+ $ts = preg_match('/Thread Safety.+enabled/', $info) ? '_ts' : '';
+ $enable = 'zend_extension' . $debug . $ts;
+ }
+ $found = false;
+ foreach ($ini[$search] as $line => $extension) {
+ if (in_array($extension, $binaries, true) || in_array(
+ $ini['extension_dir'] . DIRECTORY_SEPARATOR . $extension, $binaries, true)) {
+ $found = true;
+ break;
+ }
+ }
+ if (!$found) {
+ // not enabled
+ return true;
+ }
+ $fp = @fopen($phpini, 'wb');
+ if (!$fp) {
+ return PEAR::raiseError('cannot open php.ini "' . $phpini . '" for writing');
+ }
+ if ($line) {
+ $newini = array_slice($ini['all'], 0, $line);
+ // delete the enable line
+ $newini = array_merge($newini, array_slice($ini['all'], $line + 1));
+ } else {
+ $newini = array_slice($ini['all'], 1);
+ }
+ foreach ($newini as $line) {
+ fwrite($fp, $line);
+ }
+ fclose($fp);
+ return true;
+ }
+
+ function _parseIni($filename)
+ {
+ if (!file_exists($filename)) {
+ return PEAR::raiseError('php.ini "' . $filename . '" does not exist');
+ }
+
+ if (filesize($filename) > 300000) {
+ return PEAR::raiseError('php.ini "' . $filename . '" is too large, aborting');
+ }
+
+ ob_start();
+ phpinfo(INFO_GENERAL);
+ $info = ob_get_contents();
+ ob_end_clean();
+ $debug = function_exists('leak') ? '_debug' : '';
+ $ts = preg_match('/Thread Safety.+enabled/', $info) ? '_ts' : '';
+ $zend_extension_line = 'zend_extension' . $debug . $ts;
+ $all = @file($filename);
+ if (!$all) {
+ return PEAR::raiseError('php.ini "' . $filename .'" could not be read');
+ }
+ $zend_extensions = $extensions = array();
+ // assume this is right, but pull from the php.ini if it is found
+ $extension_dir = ini_get('extension_dir');
+ foreach ($all as $linenum => $line) {
+ $line = trim($line);
+ if (!$line) {
+ continue;
+ }
+ if ($line[0] == ';') {
+ continue;
+ }
+ if (strtolower(substr($line, 0, 13)) == 'extension_dir') {
+ $line = trim(substr($line, 13));
+ if ($line[0] == '=') {
+ $x = trim(substr($line, 1));
+ $x = explode(';', $x);
+ $extension_dir = str_replace('"', '', array_shift($x));
+ continue;
+ }
+ }
+ if (strtolower(substr($line, 0, 9)) == 'extension') {
+ $line = trim(substr($line, 9));
+ if ($line[0] == '=') {
+ $x = trim(substr($line, 1));
+ $x = explode(';', $x);
+ $extensions[$linenum] = str_replace('"', '', array_shift($x));
+ continue;
+ }
+ }
+ if (strtolower(substr($line, 0, strlen($zend_extension_line))) ==
+ $zend_extension_line) {
+ $line = trim(substr($line, strlen($zend_extension_line)));
+ if ($line[0] == '=') {
+ $x = trim(substr($line, 1));
+ $x = explode(';', $x);
+ $zend_extensions[$linenum] = str_replace('"', '', array_shift($x));
+ continue;
+ }
+ }
+ }
+ return array(
+ 'extensions' => $extensions,
+ 'zend_extensions' => $zend_extensions,
+ 'extension_dir' => $extension_dir,
+ 'all' => $all,
+ );
+ }
+
// {{{ doInstall()
function doInstall($command, $options, $params)
{
- require_once 'PEAR/Downloader.php';
+ if (!class_exists('PEAR_PackageFile')) {
+ require_once 'PEAR/PackageFile.php';
+ }
+
+ if (isset($options['installroot']) && isset($options['packagingroot'])) {
+ return $this->raiseError('ERROR: cannot use both --installroot and --packagingroot');
+ }
+
+ $reg = &$this->config->getRegistry();
+ $channel = isset($options['channel']) ? $options['channel'] : $this->config->get('default_channel');
+ if (!$reg->channelExists($channel)) {
+ return $this->raiseError('Channel "' . $channel . '" does not exist');
+ }
+
if (empty($this->installer)) {
- $this->installer = &new PEAR_Installer($this->ui);
+ $this->installer = &$this->getInstaller($this->ui);
}
- if ($command == 'upgrade') {
+
+ if ($command == 'upgrade' || $command == 'upgrade-all') {
+ // If people run the upgrade command but pass nothing, emulate a upgrade-all
+ if ($command == 'upgrade' && empty($params)) {
+ return $this->doUpgradeAll($command, $options, $params);
+ }
$options['upgrade'] = true;
+ } else {
+ $packages = $params;
}
- if ($command == 'upgrade-all') {
- include_once "PEAR/Remote.php";
- $options['upgrade'] = true;
- $remote = &new PEAR_Remote($this->config);
- $state = $this->config->get('preferred_state');
- if (empty($state) || $state == 'any') {
- $latest = $remote->call("package.listLatestReleases");
- } else {
- $latest = $remote->call("package.listLatestReleases", $state);
- }
- if (PEAR::isError($latest)) {
- return $latest;
- }
- $reg = new PEAR_Registry($this->config->get('php_dir'));
- $installed = array_flip($reg->listPackages());
- $params = array();
- foreach ($latest as $package => $info) {
- $package = strtolower($package);
- if (!isset($installed[$package])) {
- // skip packages we don't have installed
- continue;
- }
- $inst_version = $reg->packageInfo($package, 'version');
- if (version_compare("$info[version]", "$inst_version", "le")) {
- // installed version is up-to-date
- continue;
- }
- $params[] = $package;
- $this->ui->outputData(array('data' => "Will upgrade $package"), $command);
+
+ $instreg = &$reg; // instreg used to check if package is installed
+ if (isset($options['packagingroot']) && !isset($options['upgrade'])) {
+ $packrootphp_dir = $this->installer->_prependPath(
+ $this->config->get('php_dir', null, 'pear.php.net'),
+ $options['packagingroot']);
+ $instreg = new PEAR_Registry($packrootphp_dir); // other instreg!
+
+ if ($this->config->get('verbose') > 2) {
+ $this->ui->outputData('using package root: ' . $options['packagingroot']);
}
}
- $this->downloader = &new PEAR_Downloader($this->ui, $options, $this->config);
- $errors = array();
- $downloaded = array();
- $this->downloader->download($params);
- $errors = $this->downloader->getErrorMsgs();
- if (count($errors)) {
- $err['data'] = array($errors);
- $err['headline'] = 'Install Errors';
- $this->ui->outputData($err);
- return $this->raiseError("$command failed");
- }
- $downloaded = $this->downloader->getDownloadedPackages();
- $this->installer->sortPkgDeps($downloaded);
- foreach ($downloaded as $pkg) {
- PEAR::pushErrorHandling(PEAR_ERROR_RETURN);
- $info = $this->installer->install($pkg['file'], $options, $this->config);
- PEAR::popErrorHandling();
- if (PEAR::isError($info)) {
- $this->ui->outputData('ERROR: ' .$info->getMessage());
+
+ $abstractpackages = $otherpackages = array();
+ // parse params
+ PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
+
+ foreach ($params as $param) {
+ if (strpos($param, 'http://') === 0) {
+ $otherpackages[] = $param;
continue;
}
- if (is_array($info)) {
- if ($this->config->get('verbose') > 0) {
- $label = "$info[package] $info[version]";
- $out = array('data' => "$command ok: $label");
- if (isset($info['release_warnings'])) {
- $out['release_warnings'] = $info['release_warnings'];
- }
- $this->ui->outputData($out, $command);
+
+ if (strpos($param, 'channel://') === false && @file_exists($param)) {
+ if (isset($options['force'])) {
+ $otherpackages[] = $param;
+ continue;
}
+
+ $pkg = new PEAR_PackageFile($this->config);
+ $pf = $pkg->fromAnyFile($param, PEAR_VALIDATE_DOWNLOADING);
+ if (PEAR::isError($pf)) {
+ $otherpackages[] = $param;
+ continue;
+ }
+
+ $exists = $reg->packageExists($pf->getPackage(), $pf->getChannel());
+ $pversion = $reg->packageInfo($pf->getPackage(), 'version', $pf->getChannel());
+ $version_compare = version_compare($pf->getVersion(), $pversion, '<=');
+ if ($exists && $version_compare) {
+ if ($this->config->get('verbose')) {
+ $this->ui->outputData('Ignoring installed package ' .
+ $reg->parsedPackageNameToString(
+ array('package' => $pf->getPackage(),
+ 'channel' => $pf->getChannel()), true));
+ }
+ continue;
+ }
+ $otherpackages[] = $param;
+ continue;
+ }
+
+ $e = $reg->parsePackageName($param, $channel);
+ if (PEAR::isError($e)) {
+ $otherpackages[] = $param;
} else {
+ $abstractpackages[] = $e;
+ }
+ }
+ PEAR::staticPopErrorHandling();
+
+ // if there are any local package .tgz or remote static url, we can't
+ // filter. The filter only works for abstract packages
+ if (count($abstractpackages) && !isset($options['force'])) {
+ // when not being forced, only do necessary upgrades/installs
+ if (isset($options['upgrade'])) {
+ $abstractpackages = $this->_filterUptodatePackages($abstractpackages, $command);
+ } else {
+ $count = count($abstractpackages);
+ foreach ($abstractpackages as $i => $package) {
+ if (isset($package['group'])) {
+ // do not filter out install groups
+ continue;
+ }
+
+ if ($instreg->packageExists($package['package'], $package['channel'])) {
+ if ($count > 1) {
+ if ($this->config->get('verbose')) {
+ $this->ui->outputData('Ignoring installed package ' .
+ $reg->parsedPackageNameToString($package, true));
+ }
+ unset($abstractpackages[$i]);
+ } elseif ($count === 1) {
+ // Lets try to upgrade it since it's already installed
+ $options['upgrade'] = true;
+ }
+ }
+ }
+ }
+ $abstractpackages =
+ array_map(array($reg, 'parsedPackageNameToString'), $abstractpackages);
+ } elseif (count($abstractpackages)) {
+ $abstractpackages =
+ array_map(array($reg, 'parsedPackageNameToString'), $abstractpackages);
+ }
+
+ $packages = array_merge($abstractpackages, $otherpackages);
+ if (!count($packages)) {
+ $c = '';
+ if (isset($options['channel'])){
+ $c .= ' in channel "' . $options['channel'] . '"';
+ }
+ $this->ui->outputData('Nothing to ' . $command . $c);
+ return true;
+ }
+
+ $this->downloader = &$this->getDownloader($this->ui, $options, $this->config);
+ $errors = $downloaded = $binaries = array();
+ $downloaded = &$this->downloader->download($packages);
+ if (PEAR::isError($downloaded)) {
+ return $this->raiseError($downloaded);
+ }
+
+ $errors = $this->downloader->getErrorMsgs();
+ if (count($errors)) {
+ $err = array();
+ $err['data'] = array();
+ foreach ($errors as $error) {
+ if ($error !== null) {
+ $err['data'][] = array($error);
+ }
+ }
+
+ if (!empty($err['data'])) {
+ $err['headline'] = 'Install Errors';
+ $this->ui->outputData($err);
+ }
+
+ if (!count($downloaded)) {
return $this->raiseError("$command failed");
}
}
+
+ $data = array(
+ 'headline' => 'Packages that would be Installed'
+ );
+
+ if (isset($options['pretend'])) {
+ foreach ($downloaded as $package) {
+ $data['data'][] = array($reg->parsedPackageNameToString($package->getParsedPackage()));
+ }
+ $this->ui->outputData($data, 'pretend');
+ return true;
+ }
+
+ $this->installer->setOptions($options);
+ $this->installer->sortPackagesForInstall($downloaded);
+ if (PEAR::isError($err = $this->installer->setDownloadedPackages($downloaded))) {
+ $this->raiseError($err->getMessage());
+ return true;
+ }
+
+ $binaries = $extrainfo = array();
+ foreach ($downloaded as $param) {
+ PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
+ $info = $this->installer->install($param, $options);
+ PEAR::staticPopErrorHandling();
+ if (PEAR::isError($info)) {
+ $oldinfo = $info;
+ $pkg = &$param->getPackageFile();
+ if ($info->getCode() != PEAR_INSTALLER_NOBINARY) {
+ if (!($info = $pkg->installBinary($this->installer))) {
+ $this->ui->outputData('ERROR: ' .$oldinfo->getMessage());
+ continue;
+ }
+
+ // we just installed a different package than requested,
+ // let's change the param and info so that the rest of this works
+ $param = $info[0];
+ $info = $info[1];
+ }
+ }
+
+ if (!is_array($info)) {
+ return $this->raiseError("$command failed");
+ }
+
+ if ($param->getPackageType() == 'extsrc' ||
+ $param->getPackageType() == 'extbin' ||
+ $param->getPackageType() == 'zendextsrc' ||
+ $param->getPackageType() == 'zendextbin'
+ ) {
+ $pkg = &$param->getPackageFile();
+ if ($instbin = $pkg->getInstalledBinary()) {
+ $instpkg = &$instreg->getPackage($instbin, $pkg->getChannel());
+ } else {
+ $instpkg = &$instreg->getPackage($pkg->getPackage(), $pkg->getChannel());
+ }
+
+ foreach ($instpkg->getFilelist() as $name => $atts) {
+ $pinfo = pathinfo($atts['installed_as']);
+ if (!isset($pinfo['extension']) ||
+ in_array($pinfo['extension'], array('c', 'h'))
+ ) {
+ continue; // make sure we don't match php_blah.h
+ }
+
+ if ((strpos($pinfo['basename'], 'php_') === 0 &&
+ $pinfo['extension'] == 'dll') ||
+ // most unices
+ $pinfo['extension'] == 'so' ||
+ // hp-ux
+ $pinfo['extension'] == 'sl') {
+ $binaries[] = array($atts['installed_as'], $pinfo);
+ break;
+ }
+ }
+
+ if (count($binaries)) {
+ foreach ($binaries as $pinfo) {
+ PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
+ $ret = $this->enableExtension(array($pinfo[0]), $param->getPackageType());
+ PEAR::staticPopErrorHandling();
+ if (PEAR::isError($ret)) {
+ $extrainfo[] = $ret->getMessage();
+ if ($param->getPackageType() == 'extsrc' ||
+ $param->getPackageType() == 'extbin') {
+ $exttype = 'extension';
+ } else {
+ ob_start();
+ phpinfo(INFO_GENERAL);
+ $info = ob_get_contents();
+ ob_end_clean();
+ $debug = function_exists('leak') ? '_debug' : '';
+ $ts = preg_match('/Thread Safety.+enabled/', $info) ? '_ts' : '';
+ $exttype = 'zend_extension' . $debug . $ts;
+ }
+ $extrainfo[] = 'You should add "' . $exttype . '=' .
+ $pinfo[1]['basename'] . '" to php.ini';
+ } else {
+ $extrainfo[] = 'Extension ' . $instpkg->getProvidesExtension() .
+ ' enabled in php.ini';
+ }
+ }
+ }
+ }
+
+ if ($this->config->get('verbose') > 0) {
+ $chan = $param->getChannel();
+ $label = $reg->parsedPackageNameToString(
+ array(
+ 'channel' => $chan,
+ 'package' => $param->getPackage(),
+ 'version' => $param->getVersion(),
+ ));
+ $out = array('data' => "$command ok: $label");
+ if (isset($info['release_warnings'])) {
+ $out['release_warnings'] = $info['release_warnings'];
+ }
+ $this->ui->outputData($out, $command);
+
+ if (!isset($options['register-only']) && !isset($options['offline'])) {
+ if ($this->config->isDefinedLayer('ftp')) {
+ PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
+ $info = $this->installer->ftpInstall($param);
+ PEAR::staticPopErrorHandling();
+ if (PEAR::isError($info)) {
+ $this->ui->outputData($info->getMessage());
+ $this->ui->outputData("remote install failed: $label");
+ } else {
+ $this->ui->outputData("remote install ok: $label");
+ }
+ }
+ }
+ }
+
+ $deps = $param->getDeps();
+ if ($deps) {
+ if (isset($deps['group'])) {
+ $groups = $deps['group'];
+ if (!isset($groups[0])) {
+ $groups = array($groups);
+ }
+
+ foreach ($groups as $group) {
+ if ($group['attribs']['name'] == 'default') {
+ // default group is always installed, unless the user
+ // explicitly chooses to install another group
+ continue;
+ }
+ $extrainfo[] = $param->getPackage() . ': Optional feature ' .
+ $group['attribs']['name'] . ' available (' .
+ $group['attribs']['hint'] . ')';
+ }
+
+ $extrainfo[] = $param->getPackage() .
+ ': To install optional features use "pear install ' .
+ $reg->parsedPackageNameToString(
+ array('package' => $param->getPackage(),
+ 'channel' => $param->getChannel()), true) .
+ '#featurename"';
+ }
+ }
+
+ $pkg = &$instreg->getPackage($param->getPackage(), $param->getChannel());
+ // $pkg may be NULL if install is a 'fake' install via --packagingroot
+ if (is_object($pkg)) {
+ $pkg->setConfig($this->config);
+ if ($list = $pkg->listPostinstallScripts()) {
+ $pn = $reg->parsedPackageNameToString(array('channel' =>
+ $param->getChannel(), 'package' => $param->getPackage()), true);
+ $extrainfo[] = $pn . ' has post-install scripts:';
+ foreach ($list as $file) {
+ $extrainfo[] = $file;
+ }
+ $extrainfo[] = $param->getPackage() .
+ ': Use "pear run-scripts ' . $pn . '" to finish setup.';
+ $extrainfo[] = 'DO NOT RUN SCRIPTS FROM UNTRUSTED SOURCES';
+ }
+ }
+ }
+
+ if (count($extrainfo)) {
+ foreach ($extrainfo as $info) {
+ $this->ui->outputData($info);
+ }
+ }
+
return true;
}
+ // }}}
+ // {{{ doUpgradeAll()
+
+ function doUpgradeAll($command, $options, $params)
+ {
+ $reg = &$this->config->getRegistry();
+ $upgrade = array();
+
+ if (isset($options['channel'])) {
+ $channels = array($options['channel']);
+ } else {
+ $channels = $reg->listChannels();
+ }
+
+ foreach ($channels as $channel) {
+ if ($channel == '__uri') {
+ continue;
+ }
+
+ // parse name with channel
+ foreach ($reg->listPackages($channel) as $name) {
+ $upgrade[] = $reg->parsedPackageNameToString(array(
+ 'channel' => $channel,
+ 'package' => $name
+ ));
+ }
+ }
+
+ $err = $this->doInstall($command, $options, $upgrade);
+ if (PEAR::isError($err)) {
+ $this->ui->outputData($err->getMessage(), $command);
+ }
+ }
+
// }}}
// {{{ doUninstall()
function doUninstall($command, $options, $params)
{
- if (empty($this->installer)) {
- $this->installer = &new PEAR_Installer($this->ui);
- }
- if (sizeof($params) < 1) {
+ if (count($params) < 1) {
return $this->raiseError("Please supply the package(s) you want to uninstall");
}
- include_once 'PEAR/Registry.php';
- $reg = new PEAR_Registry($this->config->get('php_dir'));
+
+ if (empty($this->installer)) {
+ $this->installer = &$this->getInstaller($this->ui);
+ }
+
+ if (isset($options['remoteconfig'])) {
+ $e = $this->config->readFTPConfigFile($options['remoteconfig']);
+ if (!PEAR::isError($e)) {
+ $this->installer->setConfig($this->config);
+ }
+ }
+
+ $reg = &$this->config->getRegistry();
$newparams = array();
+ $binaries = array();
$badparams = array();
foreach ($params as $pkg) {
- $info = $reg->packageInfo($pkg);
+ $channel = $this->config->get('default_channel');
+ PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
+ $parsed = $reg->parsePackageName($pkg, $channel);
+ PEAR::staticPopErrorHandling();
+ if (!$parsed || PEAR::isError($parsed)) {
+ $badparams[] = $pkg;
+ continue;
+ }
+ $package = $parsed['package'];
+ $channel = $parsed['channel'];
+ $info = &$reg->getPackage($package, $channel);
+ if ($info === null &&
+ ($channel == 'pear.php.net' || $channel == 'pecl.php.net')) {
+ // make sure this isn't a package that has flipped from pear to pecl but
+ // used a package.xml 1.0
+ $testc = ($channel == 'pear.php.net') ? 'pecl.php.net' : 'pear.php.net';
+ $info = &$reg->getPackage($package, $testc);
+ if ($info !== null) {
+ $channel = $testc;
+ }
+ }
if ($info === null) {
$badparams[] = $pkg;
} else {
- $newparams[] = $info;
+ $newparams[] = &$info;
+ // check for binary packages (this is an alias for those packages if so)
+ if ($installedbinary = $info->getInstalledBinary()) {
+ $this->ui->log('adding binary package ' .
+ $reg->parsedPackageNameToString(array('channel' => $channel,
+ 'package' => $installedbinary), true));
+ $newparams[] = &$reg->getPackage($installedbinary, $channel);
+ }
+ // add the contents of a dependency group to the list of installed packages
+ if (isset($parsed['group'])) {
+ $group = $info->getDependencyGroup($parsed['group']);
+ if ($group) {
+ $installed = $reg->getInstalledGroup($group);
+ if ($installed) {
+ foreach ($installed as $i => $p) {
+ $newparams[] = &$installed[$i];
+ }
+ }
+ }
+ }
}
}
- $this->installer->sortPkgDeps($newparams, true);
- $params = array();
- foreach($newparams as $info) {
- $params[] = $info['info']['package'];
+ $err = $this->installer->sortPackagesForUninstall($newparams);
+ if (PEAR::isError($err)) {
+ $this->ui->outputData($err->getMessage(), $command);
+ return true;
}
+ $params = $newparams;
+ // twist this to use it to check on whether dependent packages are also being uninstalled
+ // for circular dependencies like subpackages
+ $this->installer->setUninstallPackages($newparams);
$params = array_merge($params, $badparams);
+ $binaries = array();
foreach ($params as $pkg) {
- if ($this->installer->uninstall($pkg, $options)) {
+ $this->installer->pushErrorHandling(PEAR_ERROR_RETURN);
+ if ($err = $this->installer->uninstall($pkg, $options)) {
+ $this->installer->popErrorHandling();
+ if (PEAR::isError($err)) {
+ $this->ui->outputData($err->getMessage(), $command);
+ continue;
+ }
+ if ($pkg->getPackageType() == 'extsrc' ||
+ $pkg->getPackageType() == 'extbin' ||
+ $pkg->getPackageType() == 'zendextsrc' ||
+ $pkg->getPackageType() == 'zendextbin') {
+ if ($instbin = $pkg->getInstalledBinary()) {
+ continue; // this will be uninstalled later
+ }
+
+ foreach ($pkg->getFilelist() as $name => $atts) {
+ $pinfo = pathinfo($atts['installed_as']);
+ if (!isset($pinfo['extension']) ||
+ in_array($pinfo['extension'], array('c', 'h'))) {
+ continue; // make sure we don't match php_blah.h
+ }
+ if ((strpos($pinfo['basename'], 'php_') === 0 &&
+ $pinfo['extension'] == 'dll') ||
+ // most unices
+ $pinfo['extension'] == 'so' ||
+ // hp-ux
+ $pinfo['extension'] == 'sl') {
+ $binaries[] = array($atts['installed_as'], $pinfo);
+ break;
+ }
+ }
+ if (count($binaries)) {
+ foreach ($binaries as $pinfo) {
+ PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
+ $ret = $this->disableExtension(array($pinfo[0]), $pkg->getPackageType());
+ PEAR::staticPopErrorHandling();
+ if (PEAR::isError($ret)) {
+ $extrainfo[] = $ret->getMessage();
+ if ($pkg->getPackageType() == 'extsrc' ||
+ $pkg->getPackageType() == 'extbin') {
+ $exttype = 'extension';
+ } else {
+ ob_start();
+ phpinfo(INFO_GENERAL);
+ $info = ob_get_contents();
+ ob_end_clean();
+ $debug = function_exists('leak') ? '_debug' : '';
+ $ts = preg_match('/Thread Safety.+enabled/', $info) ? '_ts' : '';
+ $exttype = 'zend_extension' . $debug . $ts;
+ }
+ $this->ui->outputData('Unable to remove "' . $exttype . '=' .
+ $pinfo[1]['basename'] . '" from php.ini', $command);
+ } else {
+ $this->ui->outputData('Extension ' . $pkg->getProvidesExtension() .
+ ' disabled in php.ini', $command);
+ }
+ }
+ }
+ }
+ $savepkg = $pkg;
if ($this->config->get('verbose') > 0) {
+ if (is_object($pkg)) {
+ $pkg = $reg->parsedPackageNameToString($pkg);
+ }
$this->ui->outputData("uninstall ok: $pkg", $command);
}
+ if (!isset($options['offline']) && is_object($savepkg) &&
+ defined('PEAR_REMOTEINSTALL_OK')) {
+ if ($this->config->isDefinedLayer('ftp')) {
+ $this->installer->pushErrorHandling(PEAR_ERROR_RETURN);
+ $info = $this->installer->ftpUninstall($savepkg);
+ $this->installer->popErrorHandling();
+ if (PEAR::isError($info)) {
+ $this->ui->outputData($info->getMessage());
+ $this->ui->outputData("remote uninstall failed: $pkg");
+ } else {
+ $this->ui->outputData("remote uninstall ok: $pkg");
+ }
+ }
+ }
} else {
- return $this->raiseError("uninstall failed: $pkg");
+ $this->installer->popErrorHandling();
+ if (!is_object($pkg)) {
+ return $this->raiseError("uninstall failed: $pkg");
+ }
+ $pkg = $reg->parsedPackageNameToString($pkg);
}
}
+
return true;
}
@@ -379,66 +1092,17 @@ package if needed.
function doBundle($command, $options, $params)
{
- if (empty($this->installer)) {
- $this->installer = &new PEAR_Downloader($this->ui);
- }
- $installer = &$this->installer;
- if (sizeof($params) < 1) {
+ $opts = array(
+ 'force' => true,
+ 'nodeps' => true,
+ 'soft' => true,
+ 'downloadonly' => true
+ );
+ $downloader = &$this->getDownloader($this->ui, $opts, $this->config);
+ $reg = &$this->config->getRegistry();
+ if (count($params) < 1) {
return $this->raiseError("Please supply the package you want to bundle");
}
- $pkgfile = $params[0];
- $need_download = false;
- if (preg_match('#^(http|ftp)://#', $pkgfile)) {
- $need_download = true;
- } elseif (!@is_file($pkgfile)) {
- if ($installer->validPackageName($pkgfile)) {
- $pkgfile = $installer->getPackageDownloadUrl($pkgfile);
- $need_download = true;
- } else {
- if (strlen($pkgfile)) {
- return $this->raiseError("Could not open the package file: $pkgfile");
- } else {
- return $this->raiseError("No package file given");
- }
- }
- }
-
- // Download package -----------------------------------------------
- if ($need_download) {
- $downloaddir = $installer->config->get('download_dir');
- if (empty($downloaddir)) {
- if (PEAR::isError($downloaddir = System::mktemp('-d'))) {
- return $downloaddir;
- }
- $installer->log(2, '+ tmp dir created at ' . $downloaddir);
- }
- $callback = $this->ui ? array(&$installer, '_downloadCallback') : null;
- $file = $installer->downloadHttp($pkgfile, $this->ui, $downloaddir, $callback);
- if (PEAR::isError($file)) {
- return $this->raiseError($file);
- }
- $pkgfile = $file;
- }
-
- // Parse xml file -----------------------------------------------
- $pkginfo = $installer->infoFromTgzFile($pkgfile);
- if (PEAR::isError($pkginfo)) {
- return $this->raiseError($pkginfo);
- }
- $installer->validatePackageInfo($pkginfo, $errors, $warnings);
- // XXX We allow warnings, do we have to do it?
- if (count($errors)) {
- if (empty($options['force'])) {
- return $this->raiseError("The following errors where found:\n".
- implode("\n", $errors));
- } else {
- $this->log(0, "warning : the following errors were found:\n".
- implode("\n", $errors));
- }
- }
- $pkgname = $pkginfo['package'];
-
- // Unpacking -------------------------------------------------
if (isset($options['destination'])) {
if (!is_dir($options['destination'])) {
@@ -446,19 +1110,35 @@ package if needed.
}
$dest = realpath($options['destination']);
} else {
- $pwd = getcwd();
- if (is_dir($pwd . DIRECTORY_SEPARATOR . 'ext')) {
- $dest = $pwd . DIRECTORY_SEPARATOR . 'ext';
- } else {
- $dest = $pwd;
- }
+ $pwd = getcwd();
+ $dir = $pwd . DIRECTORY_SEPARATOR . 'ext';
+ $dest = is_dir($dir) ? $dir : $pwd;
}
- $dest .= DIRECTORY_SEPARATOR . $pkgname;
- $orig = $pkgname . '-' . $pkginfo['version'];
+ PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
+ $err = $downloader->setDownloadDir($dest);
+ PEAR::staticPopErrorHandling();
+ if (PEAR::isError($err)) {
+ return PEAR::raiseError('download directory "' . $dest .
+ '" is not writeable.');
+ }
+ $result = &$downloader->download(array($params[0]));
+ if (PEAR::isError($result)) {
+ return $result;
+ }
+ if (!isset($result[0])) {
+ return $this->raiseError('unable to unpack ' . $params[0]);
+ }
+ $pkgfile = &$result[0]->getPackageFile();
+ $pkgname = $pkgfile->getName();
+ $pkgversion = $pkgfile->getVersion();
- $tar = new Archive_Tar($pkgfile);
- if (!@$tar->extractModify($dest, $orig)) {
- return $this->raiseError("unable to unpack $pkgfile");
+ // Unpacking -------------------------------------------------
+ $dest .= DIRECTORY_SEPARATOR . $pkgname;
+ $orig = $pkgname . '-' . $pkgversion;
+
+ $tar = &new Archive_Tar($pkgfile->getArchiveFile());
+ if (!$tar->extractModify($dest, $orig)) {
+ return $this->raiseError('unable to unpack ' . $pkgfile->getArchiveFile());
}
$this->ui->outputData("Package ready at '$dest'");
// }}}
@@ -466,5 +1146,123 @@ package if needed.
// }}}
-}
-?>
+ function doRunScripts($command, $options, $params)
+ {
+ if (!isset($params[0])) {
+ return $this->raiseError('run-scripts expects 1 parameter: a package name');
+ }
+
+ $reg = &$this->config->getRegistry();
+ PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
+ $parsed = $reg->parsePackageName($params[0], $this->config->get('default_channel'));
+ PEAR::staticPopErrorHandling();
+ if (PEAR::isError($parsed)) {
+ return $this->raiseError($parsed);
+ }
+
+ $package = &$reg->getPackage($parsed['package'], $parsed['channel']);
+ if (!is_object($package)) {
+ return $this->raiseError('Could not retrieve package "' . $params[0] . '" from registry');
+ }
+
+ $package->setConfig($this->config);
+ $package->runPostinstallScripts();
+ $this->ui->outputData('Install scripts complete', $command);
+ return true;
+ }
+
+ /**
+ * Given a list of packages, filter out those ones that are already up to date
+ *
+ * @param $packages: packages, in parsed array format !
+ * @return list of packages that can be upgraded
+ */
+ function _filterUptodatePackages($packages, $command)
+ {
+ $reg = &$this->config->getRegistry();
+ $latestReleases = array();
+
+ $ret = array();
+ foreach ($packages as $package) {
+ if (isset($package['group'])) {
+ $ret[] = $package;
+ continue;
+ }
+
+ $channel = $package['channel'];
+ $name = $package['package'];
+ if (!$reg->packageExists($name, $channel)) {
+ $ret[] = $package;
+ continue;
+ }
+
+ if (!isset($latestReleases[$channel])) {
+ // fill in cache for this channel
+ $chan = &$reg->getChannel($channel);
+ if (PEAR::isError($chan)) {
+ return $this->raiseError($chan);
+ }
+
+ $base2 = false;
+ $preferred_mirror = $this->config->get('preferred_mirror', null, $channel);
+ if ($chan->supportsREST($preferred_mirror) &&
+ (
+ //($base2 = $chan->getBaseURL('REST1.4', $preferred_mirror)) ||
+ ($base = $chan->getBaseURL('REST1.0', $preferred_mirror))
+ )
+ ) {
+ $dorest = true;
+ }
+
+ PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
+ if (!isset($package['state'])) {
+ $state = $this->config->get('preferred_state', null, $channel);
+ } else {
+ $state = $package['state'];
+ }
+
+ if ($dorest) {
+ if ($base2) {
+ $rest = &$this->config->getREST('1.4', array());
+ $base = $base2;
+ } else {
+ $rest = &$this->config->getREST('1.0', array());
+ }
+
+ $installed = array_flip($reg->listPackages($channel));
+ $latest = $rest->listLatestUpgrades($base, $state, $installed, $channel, $reg);
+ }
+
+ PEAR::staticPopErrorHandling();
+ if (PEAR::isError($latest)) {
+ $this->ui->outputData('Error getting channel info from ' . $channel .
+ ': ' . $latest->getMessage());
+ continue;
+ }
+
+ $latestReleases[$channel] = array_change_key_case($latest);
+ }
+
+ // check package for latest release
+ $name_lower = strtolower($name);
+ if (isset($latestReleases[$channel][$name_lower])) {
+ // if not set, up to date
+ $inst_version = $reg->packageInfo($name, 'version', $channel);
+ $channel_version = $latestReleases[$channel][$name_lower]['version'];
+ if (version_compare($channel_version, $inst_version, 'le')) {
+ // installed version is up-to-date
+ continue;
+ }
+
+ // maintain BC
+ if ($command == 'upgrade-all') {
+ $this->ui->outputData(array('data' => 'Will upgrade ' .
+ $reg->parsedPackageNameToString($package)), $command);
+ }
+ $ret[] = $package;
+ }
+ }
+
+ return $ret;
+ }
+}
\ No newline at end of file
diff --git a/3rdparty/PEAR/Command/Install.xml b/3rdparty/PEAR/Command/Install.xml
new file mode 100644
index 0000000000..1b1e933c22
--- /dev/null
+++ b/3rdparty/PEAR/Command/Install.xml
@@ -0,0 +1,276 @@
+
+
+