# $Id$ # Index is just a stub to redirect to the appropriate view # as defined in config.inc.php using the variable $default_view # If $default_room is defined in config.inc.php then this will # be used to redirect to a particular room. require_once "grab_globals.inc.php"; include "config.inc.php"; require_once "database.inc.php"; require "{$dbsys}.inc"; $day = date("d"); $month = date("m"); $year = date("Y"); switch ($default_view) { case "month": $redirect_str = "month.php?year={$year}&month={$month}"; break; case "week": $redirect_str = "week.php?year={$year}&month={$month}&day={$day}"; break; default: $redirect_str = "day.php?day={$day}&month={$month}&year={$year}"; } if (!empty($default_room)) { $sql = "SELECT area_id FROM mrbs_room WHERE id={$default_room}"; $area = $mdb->queryOne($sql); if (!MDB::isError($area)) { $room = $default_room; $redirect_str .= "&area={$area}&room={$room}"; } } header("Location: {$redirect_str}");
if (!empty($creatormatch)) { $sql .= " AND" . sql_syntax_caseless_contains("e.create_by", $creatormatch); } if ($sortby == "r") { # Order by Area, Room, Start date/time $sql .= " ORDER BY 9,10,2"; } else { # Order by Start date/time, Area, Room $sql .= " ORDER BY 2,9,10"; } if ($debug_flag) { echo "<p>DEBUG: SQL: <tt> {$sql} </tt>\n"; } $types = array('integer', 'integer', 'integer', 'text', 'text', 'text', 'text', 'timestamp', 'text', 'text'); $res = $mdb->query($sql, $types); if (MDB::isError($res)) { fatal_error(0, $res->getMessage() . "\n" . $res->getUserInfo() . "\n"); } $nmatch = $mdb->numRows($res); if ($nmatch == 0) { echo "<P><B>" . get_vocab("nothing_found") . "</B>\n"; $mdb->freeResult($res); } else { $last_area_room = ""; $last_date = ""; echo "<P><B>" . $nmatch . " " . ($nmatch == 1 ? get_vocab("entry_found") : get_vocab("entries_found")) . "</B>\n"; while ($row = $mdb->fetchInto($res)) { if ($summarize & 1) { reporton($row, $last_area_room, $last_date, $sortby, $display); } if ($summarize & 2) {
/** * Change password for user in the storage container * * @param string Username * @param string The new password (plain text) */ function changePassword($username, $password) { $err = $this->_prepare(); if ($err !== true) { return PEAR::raiseError($err->getMessage(), $err->getCode()); } if (isset($this->options['cryptType']) && $this->options['cryptType'] == 'none') { $cryptFunction = 'strval'; } elseif (isset($this->options['cryptType']) && function_exists($this->options['cryptType'])) { $cryptFunction = $this->options['cryptType']; } else { $cryptFunction = 'md5'; } $password = $cryptFunction($password); $query = sprintf("UPDATE %s SET %s = %s WHERE %s = %s", $this->options['table'], $this->options['passwordcol'], $this->db->getTextValue($password), $this->options['usernamecol'], $this->db->getTextValue($username)); $res = $this->query($query); if (MDB::isError($res)) { return PEAR::raiseError($res->getMessage(), $res->code); } return true; }
require_once 'PHPUnit/GUI/HTML.php'; define('DB_DSN', 'mysql://root@localhost/mdb_qt'); define('TABLE_USER', 'QueryTool_user'); define('TABLE_ADDRESS', 'QueryTool_address'); define('TABLE_QUESTION', 'question'); define('TABLE_ANSWER', 'answer'); $allTables = array(TABLE_USER, TABLE_ADDRESS, TABLE_QUESTION, TABLE_ANSWER); require_once 'sql.php'; require_once 'UnitTest.php'; require_once 'Common.php'; // // common setup (this actually also does the tearDown, since we have the DROP TABLE queries in the setup too // $querytool = new tests_Common(); foreach ($dbStructure[$querytool->db->phptype]['setup'] as $aQuery) { if (MDB::isError($ret = $querytool->db->query($aQuery))) { //include_once 'Var_Dump.php'; //var_dump::display($ret); die($ret->getUserInfo()); } } // // run the test suite // require_once 'PHPUnit/GUI/SetupDecorator.php'; $gui = new PHPUnit_GUI_SetupDecorator(new PHPUnit_GUI_HTML()); $gui->getSuitesFromDir(dirname(__FILE__), '.*\\.php', array('UnitTest.php', 'Common.php', 'sql.php', 'index.php')); $gui->show(); /* require_once 'Get.php'; require_once 'GetAll.php';
include "trailer.inc"; exit; } if (!isset($search_pos) || $search_pos <= 0) { $search_pos = 0; } elseif ($search_pos >= $total) { $search_pos = $total - $total % $search["count"]; } # Now we set up the "real" query using LIMIT to just get the stuff we want. $sql = "SELECT E.id, E.create_by, E.name, E.description, E.start_time, R.area_id\n FROM mrbs_entry E, mrbs_room R\n WHERE {$sql_pred}\n AND E.room_id = R.id\n ORDER BY E.start_time asc"; if ($debug_flag) { echo "<p>DEBUG: SQL: <tt> {$sql} </tt><BR>"; } $types = array('integer', 'text', 'text', 'text', 'integer', 'integer'); $result = $mdb->limitQuery($sql, $types, $search_pos, $search["count"]); if (MDB::isError($mdb)) { fatal_error(0, $result->getMessage() . "\n" . $result->getUserInfo() . "\n"); } $num_records = $mdb->numRows($result); $has_prev = $search_pos > 0; $has_next = $search_pos < $total - $search["count"]; if ($has_prev || $has_next) { echo "<B>" . get_vocab("records") . ($search_pos + 1) . get_vocab("through") . ($search_pos + $num_records) . get_vocab("of") . $total . "</B><BR>"; # display a "Previous" button if necessary if ($has_prev) { echo "<A HREF=\"search.php?search_str={$search_url}&search_pos="; echo max(0, $search_pos - $search["count"]); echo "&total={$total}&year={$year}&month={$month}&day={$day}\">"; } echo "<B>" . get_vocab("previous") . "</B>"; if ($has_prev) {
// Set $db_create to 0 to NOT create the database. $db_create = 1; // Communication protocol tu use. For pgsql, you can use 'unix' instead of // 'tcp' to use Unix Domain Sockets instead of TCP/IP. $db_protocol = "tcp"; /************************** * DBMS specific options ***************************/ //****ORACLE***** // Home directory path where Oracle is installed if it is running in the local machine. // Default value: value of the environment variable ORACLE_HOME $oci8_home = ""; /************************** * End of database settings ***************************/ include_once "MDB.php"; MDB::loadFile("Manager"); $schema_file = "mrbs.schema.xml"; $variables = array("database_name" => $db_database, "database_create" => $db_create); $dsn = array("phptype" => $dbsys, "username" => $db_login, "password" => $db_password, "hostspec" => $db_host, "protocol" => $db_protocol, "port" => $db_port); $options = array("HOME" => $oci8_home, "optimize" => 'portability'); $manager = new MDB_manager(); $manager->connect($dsn, $options); $success = $manager->updateDatabase($schema_file, $schema_file . ".before", $variables); if (MDB::isError($success)) { echo "Error: " . $success->getMessage() . "<BR>"; echo "Error: " . $success->getUserInfo() . "<BR>"; } if (count($manager->warnings) > 0) { echo "WARNING:<BR>", implode($manager->getWarnings(), "!\n"), "\n"; }
function testUpdateDatabase() { if (!$this->methodExists($this->manager, 'updateDatabase')) { return; } $backup_file = $this->driver_input_file . $this->backup_extension; if (!file_exists($backup_file)) { copy($this->driver_input_file, $backup_file); } $result = $this->manager->updateDatabase($this->driver_input_file, $backup_file, array('create' => '0', 'name' => $this->database)); if (!MDB::isError($result)) { $backup_file = $this->lob_input_file . $this->backup_extension; if (!file_exists($backup_file)) { copy($this->lob_input_file, $backup_file); } $result = $this->manager->updateDatabase($this->lob_input_file, $backup_file, array('create' => '0', 'name' => $this->database)); } $this->assertFalse(MDB::isError($result), 'Error updating database'); }
/** * LiveUser_Perm_Container_MDB_Complex::readGroups() * * Reads all the group ids in that the user is also a member of * (all groups that are subgroups of these are also added recursively) * * @access private * @see readRights() * @return void */ function readGroups() { parent::readGroups(); $result = $this->groupIds; // get all subgroups recursively while (count($result) > 0) { $query = ' SELECT DISTINCT SG.subgroup_id FROM ' . $this->prefix . 'groups G, ' . $this->prefix . 'group_subgroups SG WHERE SG.subgroup_id = G.group_id AND SG.group_id IN (' . implode(', ', $result) . ') AND SG.subgroup_id NOT IN (' . implode(', ', $this->groupIds) . ') AND G.is_active=' . $this->dbc->getValue('boolean', true); $result = $this->dbc->queryCol($query); if (MDB::isError($result)) { break; } else { $this->groupIds = array_merge($result, $this->groupIds); } } }
/** * * @param string $query * @param string method * @return resultSet or false on error * @access public */ function execute($query = null, $method = 'getAll') { $this->writeLog(); if (is_null($query)) { $query = $this->_buildSelectQuery(); } $this->writeLog('query built: ' . $query); // FIXXME on ORACLE this doesnt work, since we return joined columns as _TABLE_COLNAME and the _ in front // doesnt work on oracle, add a letter before it!!! $this->_lastQuery = $query; $this->debug($query); $this->writeLog('start query'); if (MDB::isError($res = $this->db->{$method}($query))) { if ($this->getOption('verbose')) { //$this->_errorSet($this->db->errorMessage($res->getCode())); $this->_errorSet($res->getMessage() . '-' . $res->getUserInfo()); } else { //$this->_errorLog($this->db->errorMessage($res->getCode())); $this->_errorLog($res->getMessage()); } $this->_errorLog($res->getUserInfo(), __LINE__); return false; } else { $this->writeLog('end query'); } return $this->_makeIndexed($res); }
/** * Get QuerySim text from appropriate source and return * the parsed text. * * @param string The QuerySim text * @param mixed $types array that contains the types of the columns in * the result set * * @access public * * @return mixed Simulated result set as a multidimentional * array if valid QuerySim text was passed in. A MDB error * is returned on failure. */ function query($query, $types = null) { if ($this->database_name) { $query = $this->_readFile(); } $this->debug("Query: {$query}"); $ismanip = false; $first = $this->first_selected_row; $limit = $this->selected_row_limit; $this->last_query = $query; if ($result = $this->_buildResult($query)) { if ($types != null) { if (!is_array($types)) { $types = array($types); } if (MDB::isError($err = $this->setResultTypes($result, $types))) { $this->freeResult($result); return $err; } } if ($limit > 0) { $result[1] = array_slice($result[1], $first - 1, $limit); } $this->highest_fetched_row[$this->_querySimSignature($result)] = -1; return $result; } return $this->raiseError(); }
# this page will display the start time of the series # but edit_entry.php will display the start time of the entry $types = array('integer'); $row = $mdb->queryRow("SELECT id\nFROM {$tbl_entry}\nWHERE repeat_id=\"{$id}\"\nORDER BY start_time", $types); if (MDB::isError($row)) { fatal_error(0, $row->getMessage() . "\n" . $row->getUserInfo() . "\n"); } } $id = $row[0]; sql_free($res); } else { $repeat_id = $row[11]; if ($repeat_id != 0) { $types = array('integer', 'integer', 'text', 'integer'); $row = $mdb->queryRow("SELECT rep_type, end_date, rep_opt, rep_num_weeks\nFROM {$tbl_repeat} WHERE id={$repeat_id}", $types); if (MDB::isError($row)) { fatal_error(0, $row->getMessage() . "\n" . $row->getUserInfo() . "\n"); } if (NULL != $row) { $rep_type = $row[0]; $rep_end_date = utf8_strftime('%A %d %B %Y', $row[1]); $rep_opt = $row[2]; $rep_num_weeks = $row[3]; } } } $enable_periods ? toPeriodString($start_period, $duration, $dur_units) : toTimeString($duration, $dur_units); $repeat_key = "rep_type_" . $rep_type; # Now that we know all the data we start drawing it ?>
/** * get the stucture of a field into an array; this method is still alpha quality! * * @param object $db database object that is extended by this class * @param string $table 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 MDB error on failure * @access public */ function getTableFieldDefinition(&$db, $table, $field_name) { $columns = $db->queryRow("EXEC sp_columns @table_name='{$table}',\n @column_name='{$field_name}'", NULL, MDB_FETCHMODE_ASSOC); if (MDB::isError($columns)) { return $columns; } if ($db->options['optimize'] != 'portability') { array_change_key_case($columns); } if (!isset($columns[$column = 'column_name']) || !isset($columns[$column = 'type_name'])) { return $db->raiseError(MDB_ERROR_MANAGER, NULL, NULL, 'Get table field definition: no result, please check table ' . $table . ' and field ' . $field_name . ' are correct'); } $field_column = $columns['column_name']; $type_column = $columns['type_name']; $db_type = strtolower($type_column); if (strpos($type_column, ' ') !== FALSE) { $db_type = strtok($db_type, ' '); } $length = $columns['precision']; $decimal = $columns['scale']; $type = array(); switch ($db_type) { case 'bigint': case 'int': case 'smallint': case 'tinyint': $type[0] = 'integer'; if ($length == '1') { $type[1] = 'boolean'; } break; case 'bit': $type[0] = 'integer'; $type[1] = 'boolean'; break; case 'decimal': case 'numeric': $type[0] = 'decimal'; break; case 'money': case 'smallmoney': $type[0] = 'decimal'; $type[1] = 'float'; break; case 'float': case 'real': $type[0] = 'float'; break; case 'datetime': case 'smalldatetime': $type[0] = 'timestamp'; break; case 'char': case 'varchar': case 'nchar': case 'nvarchar': $type[0] = 'text'; if ($length == '1') { $type[1] = 'boolean'; } break; case 'text': case 'ntext': $type[0] = 'clob'; $type[1] = 'text'; break; case 'binary': case 'varbinary': case 'image': $type[0] = 'blob'; break; case 'timestamp': $type[0] = 'blob'; break; default: return $db->raiseError(MDB_ERROR_MANAGER, NULL, NULL, 'List table fields: unknown database attribute type'); } unset($notnull); if ($columns['nullable'] == 0) { $notnull = 1; } unset($default); if (isset($columns['column_def']) && $columns['column_def'] != NULL) { if ($type[0] = 'integer' or $type[0] = 'boolean') { $columns['column_def'] = str_replace('(', '', $columns['column_def']); $columns['column_def'] = str_replace(')', '', $columns['column_def']); } $default = $columns['column_def']; } $definition = array(); for ($field_choices = array(), $datatype = 0; $datatype < count($type); $datatype++) { $field_choices[$datatype] = array('type' => $type[$datatype]); if (isset($notnull)) { $field_choices[$datatype]['notnull'] = 1; } if (isset($default)) { $field_choices[$datatype]['default'] = $default; } if ($type[$datatype] != 'boolean' && $type[$datatype] != 'time' && $type[$datatype] != 'date' && $type[$datatype] != 'timestamp') { if (strlen($length)) { $field_choices[$datatype]['length'] = $length; } } } $definition[0] = $field_choices; if (strpos($type_column, 'identity') !== FALSE) { $implicit_sequence = array(); $implicit_sequence['on'] = array(); $implicit_sequence['on']['table'] = $table; $implicit_sequence['on']['field'] = $field_name; $definition[1]['name'] = $table . '_' . $field_name; $definition[1]['definition'] = $implicit_sequence; } if (MDB::isError($indexes = $db->queryAll("EXEC sp_pkeys @table_name='{$table}'", NULL, MDB_FETCHMODE_ASSOC))) { return $indexes; } if ($indexes != NULL) { $is_primary = FALSE; foreach ($indexes as $index) { if ($index['column_name'] == $field_name) { $is_primary = TRUE; break; } } if ($is_primary) { $implicit_index = array(); $implicit_index['unique'] = 1; $implicit_index['FIELDS'][$field_name] = ''; $definition[2]['name'] = $field_name; $definition[2]['definition'] = $implicit_index; } } return $definition; }
/** * Reads the group rights * and put them in the array * * right => 1 * * @access public * @return mixed MDB_Error on failure or nothing */ function readGroupRights() { $this->groupRights = array(); if (count($this->groupIds)) { $query = ' SELECT GR.right_id, MAX(GR.right_level) FROM ' . $this->prefix . 'grouprights GR WHERE GR.group_id IN(' . implode(',', $this->groupIds) . ') GROUP BY GR.right_id'; $types = array('integer', 'integer'); $result = $this->dbc->queryAll($query, $types, MDB_FETCHMODE_ORDERED, true); if (MDB::isError($result)) { return $result; } if (is_array($result)) { $this->groupRights = $result; } } }
function endHandler($xp, $element) { if (strtolower($element) == 'variable') { $this->var_mode = FALSE; return; } switch ($this->element) { /* Initialization */ case 'database-table-initialization-insert-field': if (!$this->init_name) { $this->raiseError('field-name has to be specified', $xp); } if (isset($this->init['FIELDS'][$this->init_name])) { $this->raiseError('field "' . $this->init_name . '" already filled', $xp); } if (!isset($this->table['FIELDS'][$this->init_name])) { $this->raiseError('unkown field "' . $this->init_name . '"', $xp); } if ($this->init_value !== '' && !$this->validateFieldValue($this->init_name, $this->init_value, $xp)) { $this->raiseError('field "' . $this->init_name . '" has wrong value', $xp); } $this->init['FIELDS'][$this->init_name] = $this->init_value; break; case 'database-table-initialization-insert': $this->table['initialization'][] = $this->init; break; /* Table definition */ /* Table definition */ case 'database-table': if (!isset($this->table['was'])) { $this->table['was'] = $this->table_name; } if (!$this->table_name) { $this->raiseError('tables need names', $xp); } if (isset($this->database_definition['TABLES'][$this->table_name])) { $this->raiseError('table "' . $this->table_name . '" already exists', $xp); } if (!isset($this->table['FIELDS'])) { $this->raiseError('tables need one or more fields', $xp); } if (isset($this->table['INDEXES'])) { foreach ($this->table['INDEXES'] as $index_name => $index) { foreach ($index['FIELDS'] as $field_name => $field) { if (!isset($this->table['FIELDS'][$field_name])) { $this->raiseError('index field "' . $field_name . '" does not exist', $xp); } if (!(isset($this->table['FIELDS'][$field_name]['notnull']) && $this->table['FIELDS'][$field_name]['notnull'] == 1)) { $this->raiseError('index field "' . $field_name . '" has to be "notnull"', $xp); } } } } $this->database_definition['TABLES'][$this->table_name] = $this->table; break; /* Field declaration */ /* Field declaration */ case 'database-table-declaration-field': if (!$this->field_name || !isset($this->field['type'])) { $this->raiseError('field "' . $this->field_name . '" was not properly specified', $xp); } if (isset($this->table['FIELDS'][$this->field_name])) { $this->raiseError('field "' . $this->field_name . '" already exists', $xp); } /* Invalidname check */ if ($this->fail_on_invalid_names && isset($this->invalid_names[$this->field_name])) { $this->raiseError('fieldname "' . $this->field_name . '" not allowed', $xp); } /* Type check */ switch ($this->field['type']) { case 'integer': if (isset($this->field['unsigned']) && $this->field['unsigned'] !== '1' && $this->field['unsigned'] !== '0') { $this->raiseError('unsigned has to be 1 or 0', $xp); } break; case 'text': case 'clob': case 'blob': if (isset($this->field['length']) && (int) $this->field['length'] <= 0) { $this->raiseError('length has to be an integer greater 0', $xp); } break; case 'boolean': case 'date': case 'timestamp': case 'time': case 'float': case 'decimal': break; default: $this->raiseError('no valid field type ("' . $this->field['type'] . '") specified', $xp); } if (!isset($this->field['was'])) { $this->field['was'] = $this->field_name; } if (isset($this->field['notnull']) && !$this->is_boolean($this->field['notnull'])) { $this->raiseError('field "notnull" has to be 1 or 0', $xp); } if (isset($this->field['notnull']) && !isset($this->field['default'])) { $this->raiseError('if field is "notnull", it needs a default value', $xp); } if (isset($this->field['unsigned']) && !$this->is_boolean($this->field['unsigned'])) { $this->raiseError('field "notnull" has to be 1 or 0', $xp); } $this->table['FIELDS'][$this->field_name] = $this->field; if (isset($this->field['default'])) { if ($this->field['type'] == 'clob' || $this->field['type'] == 'blob') { $this->raiseError('"' . $this->field['type'] . '"-fields are not allowed to have a default value', $xp); } if ($this->field['default'] !== '' && !$this->validateFieldValue($this->field_name, $this->field['default'], $xp)) { $this->raiseError('default value of "' . $this->field_name . '" is of wrong type', $xp); } } break; /* Index declaration */ /* Index declaration */ case 'database-table-declaration-index': if (!$this->index_name) { $this->raiseError('an index needs a name', $xp); } if (isset($this->table['INDEXES'][$this->index_name])) { $this->raiseError('index "' . $this->index_name . '" already exists', $xp); } if (isset($this->index['unique']) && !$this->is_boolean($this->index['unique'])) { $this->raiseError('field "unique" has to be 1 or 0', $xp); } if (!isset($this->index['was'])) { $this->index['was'] = $this->index_name; } $this->table['INDEXES'][$this->index_name] = $this->index; break; case 'database-table-declaration-index-field': if (!$this->field_name) { $this->raiseError('the index-field-name is required', $xp); } if (isset($this->field['sorting']) && $this->field['sorting'] !== 'ascending' && $this->field['sorting'] !== 'descending') { $this->raiseError('sorting type unknown', $xp); } $this->index['FIELDS'][$this->field_name] = $this->field; break; /* Sequence declaration */ /* Sequence declaration */ case 'database-sequence': if (!$this->seq_name) { $this->raiseError('a sequence has to have a name', $xp); } if (isset($this->database_definition['SEQUENCES'][$this->seq_name])) { $this->raiseError('sequence "' . $this->seq_name . '" already exists', $xp); } if (!isset($this->seq['was'])) { $this->seq['was'] = $this->seq_name; } if (isset($this->seq['on'])) { if (!isset($this->seq['on']['table']) || !$this->seq['on']['table'] || (!isset($this->seq['on']['field']) || !$this->seq['on']['field'])) { $this->raiseError('sequence "' . $this->seq_name . '" was not properly defined', $xp); } } $this->database_definition['SEQUENCES'][$this->seq_name] = $this->seq; break; /* End of File */ /* End of File */ case 'database': if (isset($this->database_definition['create']) && !$this->is_boolean($this->database_definition['create'])) { $this->raiseError('field "create" has to be 1 or 0', $xp); } if (isset($this->database_definition['overwrite']) && !$this->is_boolean($this->database_definition['overwrite'])) { $this->raiseError('field "overwrite" has to be 1 or 0', $xp); } if (!isset($this->database_definition['name']) || !$this->database_definition['name']) { $this->raiseError('database needs a name', $xp); } if (isset($this->database_definition['SEQUENCES'])) { foreach ($this->database_definition['SEQUENCES'] as $seq_name => $seq) { if (isset($seq['on']) && !isset($this->database_definition['TABLES'][$seq['on']['table']]['FIELDS'][$seq['on']['field']])) { $this->raiseError('sequence "' . $seq_name . '" was assigned on unexisting field/table', $xp); } } } if (MDB::isError($this->error)) { $this->database_definition = $this->error; } break; } unset($this->elements[--$this->count]); $this->element = implode('-', $this->elements); }
/** * list all sequences in the current database * * @param object $dbs database object that is extended by this class * @return mixed data array on success, a MDB error on failure * @access public */ function listSequences(&$db) { $table_names = $db->queryCol('SHOW TABLES'); if (MDB::isError($table_names)) { return $table_names; } for ($i = 0, $j = count($table_names), $sequences = array(); $i < $j; ++$i) { if ($sqn = $this->_isSequenceName($db, $table_names[$i])) { $sequences[] = $sqn; } } return $sequences; }
/** * @param object PEAR::MDB instance * @param string db query * @param array PEAR::Pager options * @param boolean Disable pagination (get all results) * @return array with links and paged data */ function Pager_Wrapper_MDB(&$db, $query, $pager_options = array(), $disabled = false) { if (!array_key_exists('totalItems', $pager_options)) { //be smart and try to guess the total number of records if (stristr($query, 'GROUP BY') === false) { //no GROUP BY => do a fast COUNT(*) on the rewritten query $queryCount = 'SELECT COUNT(*)' . stristr($query, ' FROM '); list($queryCount, ) = spliti('ORDER BY ', $queryCount); list($queryCount, ) = spliti('LIMIT ', $queryCount); $totalItems = $db->queryOne($queryCount); if (MDB::isError($totalItems)) { return $totalItems; } } else { //GROUP BY => fetch the whole resultset and count the rows returned $res = $db->query($query); if (MDB::isError($res)) { return $res; } $totalItems = (int) $db->numRows($res); $db->freeResult($res); } $pager_options['totalItems'] = $totalItems; } require_once 'Pager/Pager.php'; $pager = Pager::factory($pager_options); $page = array(); $page['totalItems'] = $pager_options['totalItems']; $page['links'] = $pager->links; $page['page_numbers'] = array('current' => $pager->getCurrentPageID(), 'total' => $pager->numPages()); list($page['from'], $page['to']) = $pager->getOffsetByPageId(); $res = $disabled ? $db->limitQuery($query, null, 0, $totalItems) : $db->limitQuery($query, null, $page['from'] - 1, $pager_options['perPage']); if (MDB::isError($res)) { return $res; } $page['data'] = array(); while ($row = $db->fetchInto($res, MDB_FETCHMODE_ASSOC)) { $page['data'][] = $row; } if ($disabled) { $page['links'] = ''; $page['page_numbers'] = array('current' => 1, 'total' => 1); } return $page; }
/** * test tableInfo() */ function testTableInfo() { if (!$this->methodExists('tableInfo')) { return; } $table_info = $this->db->tableInfo('users'); if (MDB::isError($table_info)) { $this->assertTrue(false, 'Error in tableInfo(): ' . $table_info->getMessage()); } else { $this->assertEquals(count($this->fields), count($table_info), 'The number of fields retrieved (' . count($table_info) . ') is different from the expected one (' . count($this->fields) . ')'); foreach ($table_info as $field_info) { $this->assertEquals($field_info['table'], 'users', "the table name is not correct (expected: 'users'; actual: {$field_info['table']})"); if (!in_array(strtolower($field_info['name']), $this->fields)) { $this->assertTrue(false, 'Field names do not match (' . $field_info['name'] . ' not recognized'); } //add check on types... } } }
function readLob(&$data, $length) { $buffer_length = $length == 0 ? $this->buffer_length : $length; $written_full = 0; do { for ($written = 0; !$this->database->endOfLob($this->input_lob) && $written < $buffer_length; $written += $read) { if (MDB::isError($result = $this->database->readLob($this->input_lob, $buffer, $buffer_length))) { return $result; } $read = strlen($buffer); if (@fwrite($this->file, $buffer, $read) != $read) { return PEAR::raiseError(NULL, MDB_ERROR, NULL, NULL, 'could not write to the output file', 'MDB_Error', TRUE); } } $written_full += $written; } while ($length == 0 && !$this->database->endOfLob($this->input_lob)); return $written_full; }
/** * get the stucture of a field into an array * * @param object $db database object that is extended by this class * @param string $table 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 MDB error on failure * @access public */ function getTableFieldDefinition(&$db, $table, $field_name) { $result = $db->query("SELECT \n attnum,attname,typname,attlen,attnotnull,\n atttypmod,usename,usesysid,pg_class.oid,relpages,\n reltuples,relhaspkey,relhasrules,relacl,adsrc\n FROM pg_class,pg_user,pg_type,\n pg_attribute left outer join pg_attrdef on\n pg_attribute.attrelid=pg_attrdef.adrelid \n WHERE (pg_class.relname='{$table}') \n and (pg_class.oid=pg_attribute.attrelid) \n and (pg_class.relowner=pg_user.usesysid) \n and (pg_attribute.atttypid=pg_type.oid)\n and attnum > 0\n and attname = '{$field_name}'\n ORDER BY attnum\n "); if (MDB::isError($result)) { return $result; } $columns = $db->fetchInto($result, MDB_FETCHMODE_ASSOC); $field_column = $columns['attname']; $type_column = $columns['typname']; $db_type = preg_replace('/\\d/', '', strtolower($type_column)); $length = $columns['attlen']; if ($length == -1) { $length = $columns['atttypmod'] - 4; } //$decimal = strtok('(), '); = eh? $type = array(); switch ($db_type) { case 'int': $type[0] = 'integer'; if ($length == '1') { $type[1] = 'boolean'; } break; case 'text': case 'char': case 'varchar': case 'bpchar': $type[0] = 'text'; if ($length == '1') { $type[1] = 'boolean'; } elseif (strstr($db_type, 'text')) { $type[1] = 'clob'; } break; /* case 'enum': preg_match_all('/\'.+\'/U',$row[$type_column], $matches); $length = 0; if(is_array($matches)) { foreach($matches[0] as $value) { $length = max($length, strlen($value)-2); } } unset($decimal); case 'set': $type[0] = 'text'; $type[1] = 'integer'; break; */ /* case 'enum': preg_match_all('/\'.+\'/U',$row[$type_column], $matches); $length = 0; if(is_array($matches)) { foreach($matches[0] as $value) { $length = max($length, strlen($value)-2); } } unset($decimal); case 'set': $type[0] = 'text'; $type[1] = 'integer'; break; */ case 'date': $type[0] = 'date'; break; case 'datetime': case 'timestamp': $type[0] = 'timestamp'; break; case 'time': $type[0] = 'time'; break; case 'float': case 'double': case 'real': $type[0] = 'float'; break; case 'decimal': case 'money': case 'numeric': $type[0] = 'decimal'; break; case 'oid': case 'tinyblob': case 'mediumblob': case 'longblob': case 'blob': $type[0] = 'blob'; $type[1] = 'text'; break; case 'year': $type[0] = 'integer'; $type[1] = 'date'; break; default: return $db->raiseError(MDB_ERROR_MANAGER, NULL, NULL, 'List table fields: unknown database attribute type'); } if ($columns['attnotnull'] == 'f') { $notnull = 1; } if (!preg_match("/nextval\\('([^']+)'/", $columns['adsrc'])) { $default = substr($columns['adsrc'], 1, -1); } $definition = array(); for ($field_choices = array(), $datatype = 0; $datatype < count($type); $datatype++) { $field_choices[$datatype] = array('type' => $type[$datatype]); if (isset($notnull)) { $field_choices[$datatype]['notnull'] = 1; } if (isset($default)) { $field_choices[$datatype]['default'] = $default; } if ($type[$datatype] != 'boolean' && $type[$datatype] != 'time' && $type[$datatype] != 'date' && $type[$datatype] != 'timestamp') { if (strlen($length)) { $field_choices[$datatype]['length'] = $length; } } } $definition[0] = $field_choices; if (preg_match("/nextval\\('([^']+)'/", $columns['adsrc'], $nextvals)) { $implicit_sequence = array(); $implicit_sequence['on'] = array(); $implicit_sequence['on']['table'] = $table; $implicit_sequence['on']['field'] = $field_name; $definition[1]['name'] = $nextvals[1]; $definition[1]['definition'] = $implicit_sequence; } // check that its not just a unique field if (MDB::isError($indexes = $db->queryAll("SELECT \n oid,indexrelid,indrelid,indkey,indisunique,indisprimary \n FROm pg_index, pg_class \n WHERE (pg_class.relname='{$table}') \n AND (pg_class.oid=pg_index.indrelid)", NULL, MDB_FETCHMODE_ASSOC))) { return $indexes; } $indkeys = explode(' ', $indexes['indkey']); if (in_array($columns['attnum'], $indkeys)) { if (MDB::isError($indexname = $db->queryAll("SELECT \n relname FROM pg_class WHERE oid={$columns['indexrelid']}"))) { return $indexname; } $is_primary = $indexes['isdisprimary'] == 't'; $is_unique = $indexes['isdisunique'] == 't'; $implicit_index = array(); $implicit_index['unique'] = 1; $implicit_index['FIELDS'][$field_name] = $indexname['relname']; $definition[2]['name'] = $field_name; $definition[2]['definition'] = $implicit_index; } $db->freeResult($result); return $definition; }
echo Var_Dump::display($array) . '<br>'; // save some time with this function // lets just get all and free the result $array = $db->queryAll($query); echo '<br>all with just one call:<br>'; echo Var_Dump::display($array) . '<br>'; // run the query with the offset 1 and count 1 and get a result handler $result = $db->limitQuery($query, NULL, 1, 1); // lets just get everything but with an associative array and free the result $array = $db->fetchAll($result, MDB_FETCHMODE_ASSOC); echo '<br>associative array with offset 1 and count 1:<br>'; echo Var_Dump::display($array) . '<br>'; // lets create a sequence echo '<br>create a new seq with start 3 name real_funky_id<br>'; $err = $db->createSequence('real_funky_id', 3); if (MDB::isError($err)) { echo '<br>could not create sequence again<br>'; } echo '<br>get the next id:<br>'; $value = $db->nextId('real_funky_id'); echo $value . '<br>'; // lets try an prepare execute combo $alldata = array(array(1, 'one', 'un'), array(2, 'two', 'deux'), array(3, 'three', 'trois'), array(4, 'four', 'quatre')); $prepared_query = $db->prepareQuery('INSERT INTO numbers VALUES(?,?,?)'); foreach ($alldata as $row) { echo 'running execute<br>'; $db->execute($prepared_query, NULL, $row); } // lets try an prepare execute combo $alldata = array(array(5, 'five', 'cinq'), array(6, 'six', 'six'), array(7, 'seven', 'sept'), array(8, 'eight', 'huit')); $prepared_query = $db->prepareQuery('INSERT INTO numbers VALUES(?,?,?)');
function _isDBError($err) { if (!MDB::isError($err)) { return false; } return true; }
/** * Fetch users from the database. * * The only supported filter is perm_user_id => 'value' * * The array will look like this: * <code> * $userData[0]['perm_user_id'] = 1; * ['type'] = 1; * ['container'] = ''; * ['rights'] = array(); // the array returned by getRights() * </code> * * @access public * @param array filters to apply to fetched data * @param boolean If true the rights for each user will be retrieved. * @param boolean will return an associative array with the auth_user_id * as the key by using the $rekey param in MDB::fetchAll() * @return mixed Array with user data or error object. * @see LiveUser_Admin_Perm_DB_Common::getRights() */ function getUsers($filters = array(), $options = array(), $rekey = false) { $query = 'SELECT users.perm_user_id AS perm_user_id, users.auth_user_id AS auth_user_id, users.perm_type AS type, users.auth_container_name AS container FROM ' . $this->prefix . 'perm_users users'; if (isset($filters['group_id'])) { $query .= ', ' . $this->prefix . 'groupusers groupusers'; } if (isset($filters['group_id'])) { $filter_array[] = 'groupusers.perm_user_id=users.perm_user_id'; $filter_array[] = 'groupusers.group_id IN (' . implode(', ', $filters['group_id']) . ')'; } if (isset($filters['perm_user_id'])) { $filter_array[] = 'users.perm_user_id=' . $filters['perm_user_id']; } if (isset($filter_array) && count($filter_array)) { $query .= ' WHERE ' . implode(' AND ', $filter_array); } $types = array('integer', 'text', 'integer', 'text'); $res = $this->dbc->queryAll($query, $types, MDB_FETCHMODE_ASSOC, $rekey); if (is_array($res)) { foreach ($res as $k => $v) { if (isset($options['with_rights'])) { $res[$k]['rights'] = $this->getRights(array('where_user_id' => $v['perm_user_id'])); } if (isset($options['with_groups'])) { $res[$k]['groups'] = $this->getGroups(array('where_user_id' => $v['perm_user_id'])); } } } else { if (!MDB::isError($res)) { $res = array(); } } return $res; }
/** * Change password for user in the storage container * * @param string Username * @param string The new password (plain text) */ function changePassword($username, $password) { $this->log('Auth_Container_MDB::changePassword() called.', AUTH_LOG_DEBUG); $err = $this->_prepare(); if ($err !== true) { return PEAR::raiseError($err->getMessage(), $err->getCode()); } if (isset($this->options['cryptType']) && $this->options['cryptType'] == 'none') { $cryptFunction = 'strval'; } elseif (isset($this->options['cryptType']) && function_exists($this->options['cryptType'])) { $cryptFunction = $this->options['cryptType']; } else { $cryptFunction = 'md5'; } $password = $cryptFunction($password); $query = sprintf("UPDATE %s SET %s = %s WHERE %s = %s", $this->options['final_table'], $this->options['final_passwordcol'], $this->db->getTextValue($password), $this->options['final_usernamecol'], $this->db->getTextValue($username)); // check if there is an optional parameter db_where if ($this->options['db_where'] != '') { // there is one, so add it to the query $query .= " AND " . $this->options['db_where']; } $this->log('Running SQL against MDB: ' . $query, AUTH_LOG_DEBUG); $res = $this->query($query); if (MDB::isError($res)) { return PEAR::raiseError($res->getMessage(), $res->code); } return true; }
/** * Helper function that checks if there is a user in * the database who's matching the given parameters. * If $checkHandle is given and $checkPW is set to * false, it only checks if a user with that handle * exists. If only $checkPW is given and $checkHandle * is set to false, it will check if there exists a * user with that password. If both values are set to * anything but false, it will find the first user in * the database with both values matching. * Please note: * - If no match was found, the return value is false * - If a match was found, the auth_user_id from the database * is being returned * Whatever is returned, please keep in mind that this * function only searches for the _first_ occurence * of the search values in the database. So when you * have multiple users with the same handle, only the * ID of the first one is returned. Same goes for * passwords. Searching for both password and handle * should be pretty safe, though - having more than * one user with the same handle/password combination * in the database would be pretty stupid anyway. * * @param boolean The handle (username) to search * @param boolean The password to check against * @return mixed auth_user_id DB error or false if the user does not exist */ function userExists($checkHandle = false, $checkPW = false) { if (!$this->init_ok) { return false; } if ($checkHandle !== false && $checkPW === false) { // only search for the first user with the given handle $sql = 'SELECT ' . $this->authTableCols['required']['auth_user_id']['name'] . ' FROM ' . $this->authTable . ' WHERE ' . $this->authTableCols['required']['handle']['name'] . '=' . $this->dbc->getValue($this->authTableCols['required']['handle']['type'], $checkHandle); } elseif ($checkHandle === false && $checkPW !== false) { // only search for the first user with the given password $sql = 'SELECT ' . $this->authTableCols['required']['auth_user_id']['name'] . ' FROM ' . $this->authTable . ' WHERE ' . $this->authTableCols['required']['handle']['name'] . '=' . $this->dbc->getValue($this->authTableCols['required']['passwd']['type'], $this->encryptPW($checkPW)); } else { // check for a user with both handle and password matching $sql = 'SELECT ' . $this->authTableCols['required']['auth_user_id']['name'] . ' FROM ' . $this->authTable . ' WHERE ' . $this->authTableCols['required']['handle']['name'] . '=' . $this->dbc->getValue($this->authTableCols['required']['handle']['type'], $checkHandle) . ' AND ' . $this->authTableCols['required']['passwd']['name'] . '=' . $this->dbc->getValue($this->authTableCols['required']['passwd']['type'], $this->encryptPW($checkPW)); } $result = $this->dbc->queryOne($sql, $this->authTableCols['required']['auth_user_id']['type']); if (MDB::isError($result)) { return $result; } if (is_null($result)) { return false; } return true; }
/** * Garbage collector. * * @param int maxlifetime */ function garbageCollection($maxlifetime) { $this->flushPreload(); $query = 'DELETE FROM ' . $this->cache_table . ' WHERE (expires <= ' . time() . ' AND expires > 0) OR changed <= ' . time() - $maxlifetime; $res = $this->db->query($query); $query = 'SELECT sum(length(cachedata)) as CacheSize FROM ' . $this->cache_table; $cachesize = $this->db->getOne($query); if (MDB::isError($cachesize)) { return new Cache_Error('MDB::query failed: ' . $this->db->errorMessage($cachesize), __FILE__, __LINE__); } //if cache is to big. if ($cachesize > $this->highwater) { //find the lowwater mark. $query = 'SELECT length(cachedata) as size, changed FROM ' . $this->cache_table . ' ORDER BY changed DESC'; $res = $this->db->query($query); if (MDB::isError($res)) { return new Cache_Error('MDB::query failed: ' . $this->db->errorMessage($res), __FILE__, __LINE__); } $numrows = $this->db->numRows($res); $keep_size = 0; while ($keep_size < $this->lowwater && $numrows--) { $entry = $this->db->fetchInto($res, MDB_FETCHMODE_ASSOC); $keep_size += $entry['size']; } //delete all entries, which were changed before the "lowwater mark" $query = 'DELETE FROM ' . $this->cache_table . ' WHERE changed<=' . ($entry['changed'] ? $entry['changed'] : 0); $res = $this->db->query($query); if (MDB::isError($res)) { return new Cache_Error('MDB::query failed: ' . $this->db->errorMessage($res), __FILE__, __LINE__); } } }
/** * Remove from queue mail with $id identifier. * * @param integer $id Mail ID * @return bool True on success else Mail_Queue_Error class * @access public */ function deleteMail($id) { $query = 'DELETE FROM ' . $this->mail_table . ' WHERE id = ' . $this->db->getTextValue($id); $res = $this->db->query($query); if (MDB::isError($res)) { return new Mail_Queue_Error(MAILQUEUE_ERROR_QUERY_FAILED, $this->pearErrorMode, E_USER_ERROR, __FILE__, __LINE__, 'MDB: query failed - "' . $query . '" - ' . $res->getMessage()); } return true; }
/** * Changes user data in auth table. * * @access public * @param string Auth user ID. * @param string Handle (username) (optional). * @param string Password (optional). * @param boolean Sets the user active (1) or not (0) (optional). * @param integer ID of the owning user. * @param integer ID of the owning group. * @param array Array of custom fields to be updated * @return mixed True on success, DB error if not. */ function updateUser($authId, $handle = '', $password = '', $active = null, $owner_user_id = null, $owner_group_id = null, $customFields = array()) { if (!$this->init_ok) { return false; } $updateValues = array(); // Create query. $query = ' UPDATE ' . $this->authTable . ' SET '; if (!empty($handle)) { $updateValues[] = $this->authTableCols['handle']['name'] . ' = ' . $this->dbc->getValue($this->authTableCols['handle']['type'], $handle); } if (!empty($password)) { $updateValues[] = $this->authTableCols['passwd']['name'] . ' = ' . $this->dbc->getValue($this->authTableCols['passwd']['type'], $this->encryptPW($password)); } if (isset($active)) { $updateValues[] = $this->authTableCols['is_active']['name'] . ' = ' . $this->dbc->getValue($this->authTableCols['is_active']['type'], $active); } if (isset($owner_user_id)) { $updateValues[] = $this->authTableCols['owner_user_id'] . ' = ' . $this->dbc->getValue($this->authTableCols['owner_user_id']['type'], $owner_user_id); } if (isset($owner_group_id)) { $updateValues[] = $this->authTableCols['owner_group_id'] . ' = ' . $this->dbc->getValue($this->authTableCols['owner_group_id']['type'], $owner_group_id); } if (sizeof($customFields) > 0) { foreach ($customFields as $k => $v) { $updateValues[] = $v['name'] . ' = ' . $this->dbc->getValue($v['type'], $v['value']); } } if (count($updateValues) >= 1) { $query .= implode(', ', $updateValues); } else { return false; } $query .= ' WHERE ' . $this->authTableCols['user_id']['name'] . '=' . $this->dbc->getValue($this->authTableCols['user_id']['type'], $authId); $result = $this->dbc->query($query); if (MDB::isError($result)) { return $result; } return true; }
/** * Garbage collection * * @param int $maxlifetime Maximum lifetime * * @return bool */ function gc($maxlifetime) { $query = sprintf("DELETE FROM %s WHERE expiry < %d", $this->options['table'], time()); $result = $this->db->query($query); if (MDB::isError($result)) { new MDB_Error($result->code, PEAR_ERROR_DIE); return false; } if ($this->options['autooptimize']) { switch ($this->db->phptype) { case 'mysql': $query = sprintf("OPTIMIZE TABLE %s", $this->options['table']); break; case 'pgsql': $query = sprintf("VACUUM %s", $this->options['table']); break; default: $query = null; break; } if (isset($query)) { $result = $this->db->query($query); if (MDB::isError($result)) { new MDB_Error($result->code, PEAR_ERROR_DIE); return false; } } } return true; }
<?php require_once 'MDB.php'; require_once 'LiveUser.php'; // Plase configure the following file according to your environment $db_user = '******'; $db_pass = '******'; $db_host = 'localhost'; $db_name = 'pear_test'; $dsn = "mysql://{$db_user}:{$db_pass}@{$db_host}/{$db_name}"; $db = MDB::connect($dsn, array('sequence_col_name' => 'id')); if (MDB::isError($db)) { echo $db->getMessage() . ' ' . $db->getUserInfo(); } $db->setFetchMode(MDB_FETCHMODE_ASSOC); $conf = array('autoInit' => true, 'session' => array('name' => 'PHPSESSION', 'varname' => 'ludata'), 'login' => array('method' => 'post', 'username' => 'handle', 'password' => 'passwd', 'force' => false, 'function' => '', 'remember' => 'rememberMe'), 'logout' => array('trigger' => 'logout', 'redirect' => 'home.php', 'destroy' => true, 'method' => 'get', 'function' => ''), 'authContainers' => array(array('type' => 'MDB', 'name' => 'MDB_Local', 'loginTimeout' => 0, 'expireTime' => 3600, 'idleTime' => 1800, 'dsn' => $dsn, 'allowDuplicateHandles' => 0, 'authTable' => 'liveuser_users', 'authTableCols' => array('user_id' => array('name' => 'auth_user_id', 'type' => 'text'), 'handle' => array('name' => 'handle', 'type' => 'text'), 'passwd' => array('name' => 'passwd', 'type' => 'text'), 'lastlogin' => array('name' => 'lastlogin', 'type' => 'timestamp'), 'is_active' => array('name' => 'is_active', 'type' => 'boolean'), 'owner_user_id' => array('name' => 'owner_user_id', 'type' => 'integer'), 'owner_group_id' => array('name' => 'owner_group_id', 'type' => 'integer')))), 'permContainer' => array('dsn' => $dsn, 'type' => 'MDB_Medium', 'prefix' => 'liveuser_')); function logOut() { } function logIn() { } PEAR::setErrorHandling(PEAR_ERROR_RETURN); $usr = LiveUser::singleton($conf); $usr->setLoginFunction('logIn'); $usr->setLogOutFunction('logOut'); $e = $usr->init(); if (PEAR::isError($e)) { //var_dump($usr); die($e->getMessage() . ' ' . $e->getUserinfo()); }
/** * list all fields in a tables in the current database * * @param object $db database object that is extended by this class * @param string $table name of table that should be used in method * @return mixed data array on success, a MDB error on failure * @access public */ function listTableFields(&$db, $table) { $table = strtoupper($table); $query = "SELECT column_name FROM user_tab_columns WHERE table_name='{$table}' ORDER BY column_id"; $columns = $db->queryCol($query); if (MDB::isError($result)) { return $result; } if ($db->options['optimize'] == 'portability') { $columns = array_flip($columns); $columns = array_change_key_case($columns, CASE_LOWER); $columns = array_flip($columns); } return $columns; }