Merge "(bug 19195) Make user IDs more readily available with the API"
[lhc/web/wiklou.git] / includes / db / ORMTable.php
1 <?php
2 /**
3 * Abstract base class for representing a single database table.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @since 1.20
21 *
22 * @file ORMTable.php
23 *
24 * @licence GNU GPL v2 or later
25 * @author Jeroen De Dauw < jeroendedauw@gmail.com >
26 */
27
28 abstract class ORMTable {
29
30 /**
31 * Returns the name of the database table objects of this type are stored in.
32 *
33 * @since 1.20
34 *
35 * @return string
36 */
37 public abstract function getName();
38
39 /**
40 * Returns the name of a ORMRow deriving class that
41 * represents single rows in this table.
42 *
43 * @since 1.20
44 *
45 * @return string
46 */
47 public abstract function getRowClass();
48
49 /**
50 * Gets the db field prefix.
51 *
52 * @since 1.20
53 *
54 * @return string
55 */
56 protected abstract function getFieldPrefix();
57
58 /**
59 * Returns an array with the fields and their types this object contains.
60 * This corresponds directly to the fields in the database, without prefix.
61 *
62 * field name => type
63 *
64 * Allowed types:
65 * * id
66 * * str
67 * * int
68 * * float
69 * * bool
70 * * array
71 *
72 * @since 1.20
73 *
74 * @return array
75 */
76 public abstract function getFields();
77
78 /**
79 * Cache for instances, used by the singleton method.
80 *
81 * @since 1.20
82 * @var array of DBTable
83 */
84 protected static $instanceCache = array();
85
86 /**
87 * The database connection to use for read operations.
88 * Can be changed via @see setReadDb.
89 *
90 * @since 1.20
91 * @var integer DB_ enum
92 */
93 protected $readDb = DB_SLAVE;
94
95 /**
96 * Returns a list of default field values.
97 * field name => field value
98 *
99 * @since 1.20
100 *
101 * @return array
102 */
103 public function getDefaults() {
104 return array();
105 }
106
107 /**
108 * Returns a list of the summary fields.
109 * These are fields that cache computed values, such as the amount of linked objects of $type.
110 * This is relevant as one might not want to do actions such as log changes when these get updated.
111 *
112 * @since 1.20
113 *
114 * @return array
115 */
116 public function getSummaryFields() {
117 return array();
118 }
119
120 /**
121 * Selects the the specified fields of the records matching the provided
122 * conditions and returns them as DBDataObject. Field names get prefixed.
123 *
124 * @since 1.20
125 *
126 * @param array|string|null $fields
127 * @param array $conditions
128 * @param array $options
129 * @param string|null $functionName
130 *
131 * @return ORMResult
132 */
133 public function select( $fields = null, array $conditions = array(),
134 array $options = array(), $functionName = null ) {
135 return new ORMResult( $this, $this->rawSelect( $fields, $conditions, $options, $functionName ) );
136 }
137
138 /**
139 * Selects the the specified fields of the records matching the provided
140 * conditions and returns them as DBDataObject. Field names get prefixed.
141 *
142 * @since 1.20
143 *
144 * @param array|string|null $fields
145 * @param array $conditions
146 * @param array $options
147 * @param string|null $functionName
148 *
149 * @return array of self
150 */
151 public function selectObjects( $fields = null, array $conditions = array(),
152 array $options = array(), $functionName = null ) {
153 $result = $this->selectFields( $fields, $conditions, $options, false, $functionName );
154
155 $objects = array();
156
157 foreach ( $result as $record ) {
158 $objects[] = $this->newFromArray( $record );
159 }
160
161 return $objects;
162 }
163
164 /**
165 * Do the actual select.
166 *
167 * @since 1.20
168 *
169 * @param null|string|array $fields
170 * @param array $conditions
171 * @param array $options
172 * @param null|string $functionName
173 *
174 * @return ResultWrapper
175 */
176 public function rawSelect( $fields = null, array $conditions = array(),
177 array $options = array(), $functionName = null ) {
178 if ( is_null( $fields ) ) {
179 $fields = array_keys( $this->getFields() );
180 }
181 else {
182 $fields = (array)$fields;
183 }
184
185 return wfGetDB( $this->getReadDb() )->select(
186 $this->getName(),
187 $this->getPrefixedFields( $fields ),
188 $this->getPrefixedValues( $conditions ),
189 is_null( $functionName ) ? __METHOD__ : $functionName,
190 $options
191 );
192 }
193
194 /**
195 * Selects the the specified fields of the records matching the provided
196 * conditions and returns them as associative arrays.
197 * Provided field names get prefixed.
198 * Returned field names will not have a prefix.
199 *
200 * When $collapse is true:
201 * If one field is selected, each item in the result array will be this field.
202 * If two fields are selected, each item in the result array will have as key
203 * the first field and as value the second field.
204 * If more then two fields are selected, each item will be an associative array.
205 *
206 * @since 1.20
207 *
208 * @param array|string|null $fields
209 * @param array $conditions
210 * @param array $options
211 * @param boolean $collapse Set to false to always return each result row as associative array.
212 * @param string|null $functionName
213 *
214 * @return array of array
215 */
216 public function selectFields( $fields = null, array $conditions = array(),
217 array $options = array(), $collapse = true, $functionName = null ) {
218 $objects = array();
219
220 $result = $this->rawSelect( $fields, $conditions, $options, $functionName );
221
222 foreach ( $result as $record ) {
223 $objects[] = $this->getFieldsFromDBResult( $record );
224 }
225
226 if ( $collapse ) {
227 if ( count( $fields ) === 1 ) {
228 $objects = array_map( 'array_shift', $objects );
229 }
230 elseif ( count( $fields ) === 2 ) {
231 $o = array();
232
233 foreach ( $objects as $object ) {
234 $o[array_shift( $object )] = array_shift( $object );
235 }
236
237 $objects = $o;
238 }
239 }
240
241 return $objects;
242 }
243
244 /**
245 * Selects the the specified fields of the first matching record.
246 * Field names get prefixed.
247 *
248 * @since 1.20
249 *
250 * @param array|string|null $fields
251 * @param array $conditions
252 * @param array $options
253 * @param string|null $functionName
254 *
255 * @return DBObject|bool False on failure
256 */
257 public function selectRow( $fields = null, array $conditions = array(),
258 array $options = array(), $functionName = null ) {
259 $options['LIMIT'] = 1;
260
261 $objects = $this->select( $fields, $conditions, $options, $functionName );
262
263 return $objects->isEmpty() ? false : $objects->current();
264 }
265
266 /**
267 * Selects the the specified fields of the records matching the provided
268 * conditions. Field names do NOT get prefixed.
269 *
270 * @since 1.20
271 *
272 * @param array $fields
273 * @param array $conditions
274 * @param array $options
275 * @param string|null $functionName
276 *
277 * @return ResultWrapper
278 */
279 public function rawSelectRow( array $fields, array $conditions = array(),
280 array $options = array(), $functionName = null ) {
281 $dbr = wfGetDB( $this->getReadDb() );
282
283 return $dbr->selectRow(
284 $this->getName(),
285 $fields,
286 $conditions,
287 is_null( $functionName ) ? __METHOD__ : $functionName,
288 $options
289 );
290 }
291
292 /**
293 * Selects the the specified fields of the first record matching the provided
294 * conditions and returns it as an associative array, or false when nothing matches.
295 * This method makes use of selectFields and expects the same parameters and
296 * returns the same results (if there are any, if there are none, this method returns false).
297 * @see ORMTable::selectFields
298 *
299 * @since 1.20
300 *
301 * @param array|string|null $fields
302 * @param array $conditions
303 * @param array $options
304 * @param boolean $collapse Set to false to always return each result row as associative array.
305 * @param string|null $functionName
306 *
307 * @return mixed|array|bool False on failure
308 */
309 public function selectFieldsRow( $fields = null, array $conditions = array(),
310 array $options = array(), $collapse = true, $functionName = null ) {
311 $options['LIMIT'] = 1;
312
313 $objects = $this->selectFields( $fields, $conditions, $options, $collapse, $functionName );
314
315 return empty( $objects ) ? false : $objects[0];
316 }
317
318 /**
319 * Returns if there is at least one record matching the provided conditions.
320 * Condition field names get prefixed.
321 *
322 * @since 1.20
323 *
324 * @param array $conditions
325 *
326 * @return boolean
327 */
328 public function has( array $conditions = array() ) {
329 return $this->selectRow( array( 'id' ), $conditions ) !== false;
330 }
331
332 /**
333 * Returns the amount of matching records.
334 * Condition field names get prefixed.
335 *
336 * Note that this can be expensive on large tables.
337 * In such cases you might want to use DatabaseBase::estimateRowCount instead.
338 *
339 * @since 1.20
340 *
341 * @param array $conditions
342 * @param array $options
343 *
344 * @return integer
345 */
346 public function count( array $conditions = array(), array $options = array() ) {
347 $res = $this->rawSelectRow(
348 array( 'COUNT(*) AS rowcount' ),
349 $this->getPrefixedValues( $conditions ),
350 $options
351 );
352
353 return $res->rowcount;
354 }
355
356 /**
357 * Removes the object from the database.
358 *
359 * @since 1.20
360 *
361 * @param array $conditions
362 * @param string|null $functionName
363 *
364 * @return boolean Success indicator
365 */
366 public function delete( array $conditions, $functionName = null ) {
367 return wfGetDB( DB_MASTER )->delete(
368 $this->getName(),
369 $this->getPrefixedValues( $conditions ),
370 $functionName
371 );
372 }
373
374 /**
375 * Get API parameters for the fields supported by this object.
376 *
377 * @since 1.20
378 *
379 * @param boolean $requireParams
380 * @param boolean $setDefaults
381 *
382 * @return array
383 */
384 public function getAPIParams( $requireParams = false, $setDefaults = false ) {
385 $typeMap = array(
386 'id' => 'integer',
387 'int' => 'integer',
388 'float' => 'NULL',
389 'str' => 'string',
390 'bool' => 'integer',
391 'array' => 'string',
392 'blob' => 'string',
393 );
394
395 $params = array();
396 $defaults = $this->getDefaults();
397
398 foreach ( $this->getFields() as $field => $type ) {
399 if ( $field == 'id' ) {
400 continue;
401 }
402
403 $hasDefault = array_key_exists( $field, $defaults );
404
405 $params[$field] = array(
406 ApiBase::PARAM_TYPE => $typeMap[$type],
407 ApiBase::PARAM_REQUIRED => $requireParams && !$hasDefault
408 );
409
410 if ( $type == 'array' ) {
411 $params[$field][ApiBase::PARAM_ISMULTI] = true;
412 }
413
414 if ( $setDefaults && $hasDefault ) {
415 $default = is_array( $defaults[$field] ) ? implode( '|', $defaults[$field] ) : $defaults[$field];
416 $params[$field][ApiBase::PARAM_DFLT] = $default;
417 }
418 }
419
420 return $params;
421 }
422
423 /**
424 * Returns an array with the fields and their descriptions.
425 *
426 * field name => field description
427 *
428 * @since 1.20
429 *
430 * @return array
431 */
432 public function getFieldDescriptions() {
433 return array();
434 }
435
436 /**
437 * Get the database type used for read operations.
438 *
439 * @since 1.20
440 *
441 * @return integer DB_ enum
442 */
443 public function getReadDb() {
444 return $this->readDb;
445 }
446
447 /**
448 * Set the database type to use for read operations.
449 *
450 * @param integer $db
451 *
452 * @since 1.20
453 */
454 public function setReadDb( $db ) {
455 $this->readDb = $db;
456 }
457
458 /**
459 * Update the records matching the provided conditions by
460 * setting the fields that are keys in the $values param to
461 * their corresponding values.
462 *
463 * @since 1.20
464 *
465 * @param array $values
466 * @param array $conditions
467 *
468 * @return boolean Success indicator
469 */
470 public function update( array $values, array $conditions = array() ) {
471 $dbw = wfGetDB( DB_MASTER );
472
473 return $dbw->update(
474 $this->getName(),
475 $this->getPrefixedValues( $values ),
476 $this->getPrefixedValues( $conditions ),
477 __METHOD__
478 );
479 }
480
481 /**
482 * Computes the values of the summary fields of the objects matching the provided conditions.
483 *
484 * @since 1.20
485 *
486 * @param array|string|null $summaryFields
487 * @param array $conditions
488 */
489 public function updateSummaryFields( $summaryFields = null, array $conditions = array() ) {
490 $this->setReadDb( DB_MASTER );
491
492 foreach ( $this->select( null, $conditions ) as /* ORMRow */ $item ) {
493 $item->loadSummaryFields( $summaryFields );
494 $item->setSummaryMode( true );
495 $item->save();
496 }
497
498 $this->setReadDb( DB_SLAVE );
499 }
500
501 /**
502 * Takes in an associative array with field names as keys and
503 * their values as value. The field names are prefixed with the
504 * db field prefix.
505 *
506 * Field names can also be provided as an array with as first element a table name, such as
507 * $conditions = array(
508 * array( array( 'tablename', 'fieldname' ), $value ),
509 * );
510 *
511 * @since 1.20
512 *
513 * @param array $values
514 *
515 * @return array
516 */
517 public function getPrefixedValues( array $values ) {
518 $prefixedValues = array();
519
520 foreach ( $values as $field => $value ) {
521 if ( is_integer( $field ) ) {
522 if ( is_array( $value ) ) {
523 $field = $value[0];
524 $value = $value[1];
525 }
526 else {
527 $value = explode( ' ', $value, 2 );
528 $value[0] = $this->getPrefixedField( $value[0] );
529 $prefixedValues[] = implode( ' ', $value );
530 continue;
531 }
532 }
533
534 $prefixedValues[$this->getPrefixedField( $field )] = $value;
535 }
536
537 return $prefixedValues;
538 }
539
540 /**
541 * Takes in a field or array of fields and returns an
542 * array with their prefixed versions, ready for db usage.
543 *
544 * @since 1.20
545 *
546 * @param array|string $fields
547 *
548 * @return array
549 */
550 public function getPrefixedFields( array $fields ) {
551 foreach ( $fields as &$field ) {
552 $field = $this->getPrefixedField( $field );
553 }
554
555 return $fields;
556 }
557
558 /**
559 * Takes in a field and returns an it's prefixed version, ready for db usage.
560 *
561 * @since 1.20
562 *
563 * @param string|array $field
564 *
565 * @return string
566 */
567 public function getPrefixedField( $field ) {
568 return $this->getFieldPrefix() . $field;
569 }
570
571 /**
572 * Takes an array of field names with prefix and returns the unprefixed equivalent.
573 *
574 * @since 1.20
575 *
576 * @param array $fieldNames
577 *
578 * @return array
579 */
580 public function unprefixFieldNames( array $fieldNames ) {
581 return array_map( array( $this, 'unprefixFieldName' ), $fieldNames );
582 }
583
584 /**
585 * Takes a field name with prefix and returns the unprefixed equivalent.
586 *
587 * @since 1.20
588 *
589 * @param string $fieldName
590 *
591 * @return string
592 */
593 public function unprefixFieldName( $fieldName ) {
594 return substr( $fieldName, strlen( $this->getFieldPrefix() ) );
595 }
596
597 /**
598 * Get an instance of this class.
599 *
600 * @since 1.20
601 *
602 * @return ORMTable
603 */
604 public static function singleton() {
605 $class = function_exists( 'get_called_class' ) ? get_called_class() : self::get_called_class();
606
607 if ( !array_key_exists( $class, self::$instanceCache ) ) {
608 self::$instanceCache[$class] = new $class;
609 }
610
611 return self::$instanceCache[$class];
612 }
613
614 /**
615 * Compatibility fallback function so the singleton method works on PHP < 5.3.
616 * Code borrowed from http://www.php.net/manual/en/function.get-called-class.php#107445
617 *
618 * @since 1.20
619 *
620 * @return string
621 */
622 protected static function get_called_class() {
623 $bt = debug_backtrace();
624 $l = count($bt) - 1;
625 $matches = array();
626 while(empty($matches) && $l > -1){
627 $lines = file($bt[$l]['file']);
628 $callerLine = $lines[$bt[$l]['line']-1];
629 preg_match('/([a-zA-Z0-9\_]+)::'.$bt[$l--]['function'].'/',
630 $callerLine,
631 $matches);
632 }
633 if (!isset($matches[1])) $matches[1]=NULL; //for notices
634 if ($matches[1] == 'self') {
635 $line = $bt[$l]['line']-1;
636 while ($line > 0 && strpos($lines[$line], 'class') === false) {
637 $line--;
638 }
639 preg_match('/class[\s]+(.+?)[\s]+/si', $lines[$line], $matches);
640 }
641 return $matches[1];
642 }
643
644 /**
645 * Get an array with fields from a database result,
646 * that can be fed directly to the constructor or
647 * to setFields.
648 *
649 * @since 1.20
650 *
651 * @param stdClass $result
652 *
653 * @return array
654 */
655 public function getFieldsFromDBResult( stdClass $result ) {
656 $result = (array)$result;
657 return array_combine(
658 $this->unprefixFieldNames( array_keys( $result ) ),
659 array_values( $result )
660 );
661 }
662
663 /**
664 * Get a new instance of the class from a database result.
665 *
666 * @since 1.20
667 *
668 * @param stdClass $result
669 *
670 * @return ORMRow
671 */
672 public function newFromDBResult( stdClass $result ) {
673 return $this->newFromArray( $this->getFieldsFromDBResult( $result ) );
674 }
675
676 /**
677 * Get a new instance of the class from an array.
678 *
679 * @since 1.20
680 *
681 * @param array $data
682 * @param boolean $loadDefaults
683 *
684 * @return ORMRow
685 */
686 public function newFromArray( array $data, $loadDefaults = false ) {
687 $class = $this->getRowClass();
688 return new $class( $this, $data, $loadDefaults );
689 }
690
691 /**
692 * Return the names of the fields.
693 *
694 * @since 1.20
695 *
696 * @return array
697 */
698 public function getFieldNames() {
699 return array_keys( $this->getFields() );
700 }
701
702 /**
703 * Gets if the object can take a certain field.
704 *
705 * @since 1.20
706 *
707 * @param string $name
708 *
709 * @return boolean
710 */
711 public function canHaveField( $name ) {
712 return array_key_exists( $name, $this->getFields() );
713 }
714
715 }