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