1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
|
<?php
/**
* Base abstract class for data source drivers
*
* PHP version 5
*
* LICENSE:
*
* Copyright (c) 1997-2007, Andrew Nagy <asnagy@webitecture.org>,
* Olivier Guilyardi <olivier@samalyse.com>,
* Mark Wiesemann <wiesemann@php.net>
* 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.
* * The names of the authors may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* 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.
*
* CVS file id: $Id$
*
* @version $Revision$
* @package Structures_DataGrid
* @category Structures
* @license http://opensource.org/licenses/bsd-license.php New BSD License
*/
require_once 'Structures/DataGrid/Exception.php';
/**
* Base abstract class for DataSource drivers
*
* SUPPORTED OPTIONS:
*
* - fields: (array) Which data fields to fetch from the datasource.
* An empty array means: all fields.
* Form: array(field1, field2, ...)
* - primaryKey: (array) Name(s), or numerical index(es) of the
* field(s) which contain a unique record
* identifier (only use several fields in case
* of a multiple-fields primary key)
* - generate_columns: (bool) Generate Structures_DataGrid_Column objects
* with labels. See the 'labels' option.
* DEPRECATED:
* use Structures_DataGrid::generateColumns() instead
* - labels: (array) Data field to column label mapping. Only used
* when 'generate_columns' is true.
* Form: array(field => label, ...)
* DEPRECATED:
* use Structures_DataGrid::generateColumns() instead
*
* @author Olivier Guilyardi <olivier@samalyse.com>
* @author Andrew Nagy <asnagy@webitecture.org>
* @author Mark Wiesemann <wiesemann@php.net>
* @package Structures_DataGrid
* @category Structures
* @version $Revision$
*/
class Structures_DataGrid_DataSource
{
/**
* Common and driver-specific options
*
* @var array
* @access protected
* @see Structures_DataGrid_DataSource::_setOption()
* @see Structures_DataGrid_DataSource::addDefaultOptions()
*/
var $_options = array();
/**
* Special driver features
*
* @var array
* @access protected
*/
var $_features = array();
/**
* Constructor
*
*/
function Structures_DataGrid_DataSource()
{
$this->_options = array('generate_columns' => false,
'labels' => array(),
'fields' => array(),
'primaryKey' => null,
);
$this->_features = array(
'multiSort' => false, // Multiple field sorting
'writeMode' => false, // insert, update and delete records
);
}
/**
* Adds some default options.
*
* This method is meant to be called by drivers. It allows adding some
* default options.
*
* @access protected
* @param array $options An associative array of the form:
* array(optionName => optionValue, ...)
* @return void
* @see Structures_DataGrid_DataSource::_setOption
*/
function _addDefaultOptions($options)
{
$this->_options = array_merge($this->_options, $options);
}
/**
* Add special driver features
*
* This method is meant to be called by drivers. It allows specifying
* the special features that are supported by the current driver.
*
* @access protected
* @param array $features An associative array of the form:
* array(feature => true|false, ...)
* @return void
*/
function _setFeatures($features)
{
$this->_features = array_merge($this->_features, $features);
}
/**
* Set options
*
* @param mixed $options An associative array of the form:
* array("option_name" => "option_value",...)
* @access protected
*/
function setOptions($options)
{
$this->_options = array_merge($this->_options, $options);
}
/**
* Set a single option
*
* @param string $name Option name
* @param mixed $value Option value
* @access public
*/
function setOption($name, $value)
{
$this->_options[$name] = $value;
}
/**
* Generate columns if options are properly set
*
* Note: must be called after fetch()
*
* @access public
* @return array Array of Column objects. Empty array if irrelevant.
* @deprecated This method relates to the deprecated "generate_columns" option.
*/
function getColumns()
{
$columns = array();
if ($this->_options['generate_columns']
and $fieldList = $this->_options['fields']) {
include_once 'Structures/DataGrid/Column.php';
foreach ($fieldList as $field) {
$label = strtr($field, $this->_options['labels']);
$col = new Structures_DataGrid_Column($label, $field, $field);
$columns[] = $col;
}
}
return $columns;
}
// Begin driver method prototypes DocBook template
/**#@+
*
* This method is public, but please note that it is not intended to be
* called by user-space code. It is meant to be called by the main
* Structures_DataGrid class.
*
* It is an abstract method, part of the DataGrid Datasource driver
* interface, and must/may be overloaded by drivers.
*/
/**
* Fetching method prototype
*
* When overloaded this method must return an array of records.
* Each record can be either an associative array of field name/value
* pairs, or an object carrying fields as properties.
*
* This method must return a PEAR_Error object on failure.
*
* @abstract
* @param integer $offset Limit offset (starting from 0)
* @param integer $len Limit length
* @return object PEAR_Error with message
* "No data source driver loaded"
* @access public
*/
function fetch($offset = 0, $len = null)
{
return PEAR::raiseError("No data source driver loaded");
}
/**
* Counting method prototype
*
* Note: must be called before fetch()
*
* When overloaded, this method must return the total number or records
* or a PEAR_Error object on failure
*
* @abstract
* @return object PEAR_Error with message
* "No data source driver loaded"
* @access public
*/
function count()
{
return PEAR::raiseError("No data source driver loaded");
}
/**
* Sorting method prototype
*
* When overloaded this method must return true on success or a PEAR_Error
* object on failure.
*
* Note: must be called before fetch()
*
* @abstract
* @param string $sortSpec If the driver supports the "multiSort"
* feature this can be either a single field
* (string), or a sort specification array of
* the form: array(field => direction, ...)
* If "multiSort" is not supported, then this
* can only be a string.
* @param string $sortDir Sort direction: 'ASC' or 'DESC'
* @return object PEAR_Error with message
* "No data source driver loaded"
* @access public
*/
function sort($sortSpec, $sortDir = null)
{
return PEAR::raiseError("No data source driver loaded");
}
/**
* Datasource binding method prototype
*
* When overloaded this method must return true on success or a PEAR_Error
* object on failure.
*
* @abstract
* @param mixed $container The datasource container
* @param array $options Binding options
* @return object PEAR_Error with message
* "No data source driver loaded"
* @access public
*/
function bind($container, $options = array())
{
return PEAR::raiseError("No data source driver loaded");
}
/**
* Record insertion method prototype
*
* Drivers that support the "writeMode" feature must implement this method.
*
* When overloaded this method must return true on success or a PEAR_Error
* object on failure.
*
* @abstract
* @param array $data Associative array of the form:
* array(field => value, ..)
* @return object PEAR_Error with message
* "No data source driver loaded or write mode not
* supported by the current driver"
* @access public
*/
function insert($data)
{
return PEAR::raiseError("No data source driver loaded or write mode not".
"supported by the current driver");
}
/**
* Return the primary key specification
*
* This method always returns an array containing:
* - either one field name or index in case of a single-field key
* - or several field names or indexes in case of a multiple-fields key
*
* Drivers that support the "writeMode" feature should overload this method
* if the key can be detected. However, the detection must not override the
* "primaryKey" option.
*
* @return array Field(s) name(s) or numerical index(es)
* @access protected
*/
function getPrimaryKey()
{
return $this->_options['primaryKey'];
}
/**
* Record updating method prototype
*
* Drivers that support the "writeMode" feature must implement this method.
*
* When overloaded this method must return true on success or a PEAR_Error
* object on failure.
*
* @abstract
* @param array $key Unique record identifier
* @param array $data Associative array of the form:
* array(field => value, ..)
* @return object PEAR_Error with message
* "No data source driver loaded or write mode
* not supported by the current driver"
* @access public
*/
function update($key, $data)
{
return PEAR::raiseError("No data source driver loaded or write mode not".
"supported by the current driver");
}
/**
* Record deletion method prototype
*
* Drivers that support the "writeMode" feature must implement this method.
*
* When overloaded this method must return true on success or a PEAR_Error
* object on failure.
*
* @abstract
* @param array $key Unique record identifier
* @return object PEAR_Error with message
* "No data source driver loaded or write mode
* not supported by the current driver"
* @access public
*/
function delete($key)
{
return PEAR::raiseError("No data source driver loaded or write mode not".
"supported by the current driver");
}
/**
* Resources cleanup method prototype
*
* This is where drivers should close sql connections, files, etc...
* if needed.
*
* @abstract
* @return void
* @access public
*/
function free()
{
}
/**#@-*/
// End DocBook template
/**
* List special driver features
*
* @return array Of the form: array(feature => true|false, etc...)
* @access public
*/
function getFeatures()
{
return $this->_features;
}
/**
* Tell if the driver as a specific feature
*
* @param string $name Feature name
* @return bool
* @access public
*/
function hasFeature($name)
{
return $this->_features[$name];
}
/**
* Dump the data as returned by fetch().
*
* This method is meant for debugging purposes. It returns what fetch()
* would return to its DataGrid host as a nicely formatted console-style
* table.
*
* @param integer $offset Limit offset (starting from 0)
* @param integer $len Limit length
* @param string $sortField Field to sort by
* @param string $sortDir Sort direction: 'ASC' or 'DESC'
* @return string The table string, ready to be printed
* @uses Structures_DataGrid_DataSource::fetch()
* @access public
*/
function dump($offset=0, $len=null, $sortField=null, $sortDir='ASC')
{
$records = $this->fetch($offset, $len, $sortField, $sortDir);
$columns = $this->getColumns();
if (!$columns and !$records) {
return "<Empty set>\n";
}
include_once 'Console/Table.php';
$table = new Console_Table();
$headers = array();
if ($columns) {
foreach ($columns as $col) {
$headers[] = is_null($col->fieldName)
? $col->columnName
: "{$col->columnName} ({$col->fieldName})";
}
} else {
$headers = array_keys($records[0]);
}
$table->setHeaders($headers);
foreach ($records as $rec) {
$table->addRow($rec);
}
return $table->getTable();
}
}
/**
* Base abstract class for SQL query based DataSource drivers
*
* SUPPORTED OPTIONS:
*
* - db_options: (array) Options for the created database object. This option
* is only used when the 'dsn' option is given.
* - count_query: (string) Query that calculates the number of rows. See below
* for more information about when such a count query
* is needed.
*
* @author Olivier Guilyardi <olivier@samalyse.com>
* @author Mark Wiesemann <wiesemann@php.net>
* @package Structures_DataGrid
* @category Structures
* @version $Revision$
*/
class Structures_DataGrid_DataSource_SQLQuery
extends Structures_DataGrid_DataSource
{
/**
* SQL query
* @var string
* @access protected
*/
var $_query;
/**
* Fields/directions to sort the data by
* @var array
* @access protected
*/
var $_sortSpec;
/**
* Instantiated database object
* @var object
* @access protected
*/
var $_handle;
/**
* Total number of rows
*
* This property caches the result of count() to avoid running the same
* database query multiple times.
*
* @var int
* @access private
*/
var $_rowNum = null;
/**
* Constructor
*
*/
public function __construct()
{
parent::Structures_DataGrid_DataSource();
$this->_addDefaultOptions(array('dbc' => null,
'dsn' => null,
'db_options' => array(),
'count_query' => ''));
$this->_setFeatures(array('multiSort' => true));
}
/**
* Bind
*
* @param string $query The query string
* @param mixed $options array('dbc' => [connection object])
* or
* array('dsn' => [dsn string])
* @access public
* @return mixed True on success, PEAR_Error on failure
*/
function bind($query, $options = array())
{
if ($options) {
$this->setOptions($options);
}
if (isset($this->_options['dbc']) &&
$this->_isConnection($this->_options['dbc'])) {
$this->_handle = $this->_options['dbc'];
} elseif (isset($this->_options['dsn'])) {
$dbOptions = array();
if (array_key_exists('db_options', $options)) {
$dbOptions = $options['db_options'];
}
$this->_handle = $this->_connect();
if (PEAR::isError($this->_handle)) {
throw new Structures_DataGrid_Exception(
'Could not create connection: ' .
$this->_handle->getMessage() . ', ' .
$this->_handle->getUserInfo()
);
}
} else {
return PEAR::raiseError('No Database object or dsn string specified');
}
if (is_string($query)) {
$this->_query = $query;
return true;
} else {
return PEAR::raiseError('Query parameter must be a string');
}
}
/**
* Fetch
*
* @param integer $offset Offset (starting from 0)
* @param integer $limit Limit
* @access public
* @return mixed The 2D Array of the records on success,
* PEAR_Error on failure
*/
function fetch($offset = 0, $limit = null)
{
if (!empty($this->_sortSpec)) {
foreach ($this->_sortSpec as $field => $direction) {
$fields = preg_split('#\.#', $field);
$fields = array_map(array($this, '_quoteIdentifier'), $fields);
$sortArray[] = join('.', $fields) . ' ' . $direction;
}
$sortString = join(', ', $sortArray);
} else {
$sortString = '';
}
$query = $this->_query;
// drop LIMIT statement
$query = preg_replace('#\sLIMIT\s.*$#isD', ' ', $query);
// if we have a sort string, we need to add it to the query string
if ($sortString != '') {
$appendOrderBy = false;
// search for the last ORDER BY statement
$orderByPos = strripos($query, 'ORDER BY');
// does another (sub)query or from clause follow after this ORDER BY statement?
if ( $orderByPos !== false
&& preg_match('/[ \t\n]FROM[ \t\n]/i', substr($query, $orderByPos))
) {
// yes => new ORDER BY statement needs to be appended
$appendOrderBy = true;
}
// if no ORDER BY statement exists, a new one needs to be appended
if ($orderByPos === false) {
$appendOrderBy = true;
}
if ($appendOrderBy === true) {
$query .= ' ORDER BY ' . $sortString;
} else {
$query .= ', ' . $sortString;
}
}
//FIXME: What about SQL injection ?
$recordSet = $this->_getRecords($query, $limit, $offset);
if (PEAR::isError($recordSet)) {
return $recordSet;
}
// Determine fields to render
if (!$this->_options['fields'] && count($recordSet)) {
$this->setOptions(array('fields' => array_keys($recordSet[0])));
}
return $recordSet;
}
/**
* Count
*
* @access public
* @return mixed The number or records (int),
* PEAR_Error on failure
*/
function count()
{
// do we already have the cached number of records? (if yes, return it)
if (!is_null($this->_rowNum)) {
return $this->_rowNum;
}
// try to fetch the number of records
if ($this->_options['count_query'] != '') {
// complex queries might require special queries to get the
// right row count
$count = $this->_getOne($this->_options['count_query']);
// $count has an integer value with number of rows or is a
// PEAR_Error instance on failure
}
elseif (preg_match('#GROUP\s+BY#is', $this->_query) === 1 ||
preg_match('#SELECT.+SELECT#is', $this->_query) === 1 ||
preg_match('#\sUNION\s#is', $this->_query) === 1 ||
preg_match('#SELECT.+DISTINCT.+FROM#is', $this->_query) === 1
) {
// GROUP BY, DISTINCT, UNION and subqueries are special cases
// ==> use the normal query and then numRows()
$count = $this->_getRecordsNum($this->_query);
if (PEAR::isError($count)) {
return $count;
}
} else {
// don't query the whole table, just get the number of rows
$query = preg_replace('#SELECT\s.+\sFROM#is',
'SELECT COUNT(*) FROM',
$this->_query);
$query = preg_replace(
'#ORDER\s+BY\s.+sc#',
'',
$query
);
$count = $this->_getOne($query);
// $count has an integer value with number of rows or is a
// PEAR_Error instance on failure
}
// if we've got a number of records, save it to avoid running the same
// query multiple times
if (!PEAR::isError($count)) {
$this->_rowNum = $count;
}
return $count;
}
/**
* Disconnect from the database, if needed
*
* @abstract
* @return void
* @access public
*/
function free()
{
if ($this->_handle && is_null($this->_options['dbc'])) {
$this->_disconnect();
unset($this->_handle);
}
}
/**
* This can only be called prior to the fetch method.
*
* @access public
* @param mixed $sortSpec A single field (string) to sort by, or a
* sort specification array of the form:
* array(field => direction, ...)
* @param string $sortDir Sort direction: 'ASC' or 'DESC'
* This is ignored if $sortDesc is an array
*/
function sort($sortSpec, $sortDir = 'ASC')
{
if (is_array($sortSpec)) {
$this->_sortSpec = $sortSpec;
} else {
$this->_sortSpec[$sortSpec] = $sortDir;
}
}
}
/**
* Replace strripos()
*
* @category PHP
* @package PHP_Compat
* @license LGPL - http://www.gnu.org/licenses/lgpl.html
* @copyright 2004-2007 Aidan Lister <aidan@php.net>, Arpad Ray <arpad@php.net>
* @link http://php.net/function.strripos
* @author Aidan Lister <aidan@php.net>
* @version $Revision$
* @since PHP 5
* @require PHP 4.0.0 (user_error)
*/
function structures_datagrid_strripos($haystack, $needle, $offset = null)
{
// Sanity check
if (!is_scalar($haystack)) {
user_error('strripos() expects parameter 1 to be scalar, ' .
gettype($haystack) . ' given', E_USER_WARNING);
return false;
}
if (!is_scalar($needle)) {
user_error('strripos() expects parameter 2 to be scalar, ' .
gettype($needle) . ' given', E_USER_WARNING);
return false;
}
if (!is_int($offset) && !is_bool($offset) && !is_null($offset)) {
user_error('strripos() expects parameter 3 to be long, ' .
gettype($offset) . ' given', E_USER_WARNING);
return false;
}
// Initialise variables
$needle = strtolower($needle);
$haystack = strtolower($haystack);
$needle_fc = $needle{0};
$needle_len = strlen($needle);
$haystack_len = strlen($haystack);
$offset = (int) $offset;
$leftlimit = ($offset >= 0) ? $offset : 0;
$p = ($offset >= 0) ?
$haystack_len :
$haystack_len + $offset + 1;
// Reverse iterate haystack
while (--$p >= $leftlimit) {
if ($needle_fc === $haystack{$p} &&
substr($haystack, $p, $needle_len) === $needle) {
return $p;
}
}
return false;
}
if (!function_exists('strripos')) {
function strripos($haystack, $needle, $offset = null)
{
return structures_datagrid_strripos($haystack, $needle, $offset);
}
}
/* vim: set expandtab tabstop=4 shiftwidth=4: */
?>
|