Merge "Use the MWDebug class to display debug log back in the request."
[lhc/web/wiklou.git] / includes / db / ORMRow.php
1 <?php
2 /**
3 * Abstract base class for representing objects that are stored in some DB table.
4 * This is basically an ORM-like wrapper around rows in database tables that
5 * aims to be both simple and very flexible. It is centered around an associative
6 * array of fields and various methods to do common interaction with the database.
7 *
8 * Documentation inline and at https://www.mediawiki.org/wiki/Manual:ORMTable
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
23 * http://www.gnu.org/copyleft/gpl.html
24 *
25 * @since 1.20
26 *
27 * @file ORMRow.php
28 * @ingroup ORM
29 *
30 * @licence GNU GPL v2 or later
31 * @author Jeroen De Dauw < jeroendedauw@gmail.com >
32 */
33
34 abstract class ORMRow implements IORMRow {
35
36 /**
37 * The fields of the object.
38 * field name (w/o prefix) => value
39 *
40 * @since 1.20
41 * @var array
42 */
43 protected $fields = array( 'id' => null );
44
45 /**
46 * @since 1.20
47 * @var ORMTable
48 */
49 protected $table;
50
51 /**
52 * If the object should update summaries of linked items when changed.
53 * For example, update the course_count field in universities when a course in courses is deleted.
54 * Settings this to false can prevent needless updating work in situations
55 * such as deleting a university, which will then delete all it's courses.
56 *
57 * @since 1.20
58 * @var bool
59 */
60 protected $updateSummaries = true;
61
62 /**
63 * Indicates if the object is in summary mode.
64 * This mode indicates that only summary fields got updated,
65 * which allows for optimizations.
66 *
67 * @since 1.20
68 * @var bool
69 */
70 protected $inSummaryMode = false;
71
72 /**
73 * Constructor.
74 *
75 * @since 1.20
76 *
77 * @param IORMTable $table
78 * @param array|null $fields
79 * @param boolean $loadDefaults
80 */
81 public function __construct( IORMTable $table, $fields = null, $loadDefaults = false ) {
82 $this->table = $table;
83
84 if ( !is_array( $fields ) ) {
85 $fields = array();
86 }
87
88 if ( $loadDefaults ) {
89 $fields = array_merge( $this->table->getDefaults(), $fields );
90 }
91
92 $this->setFields( $fields );
93 }
94
95 /**
96 * Load the specified fields from the database.
97 *
98 * @since 1.20
99 *
100 * @param array|null $fields
101 * @param boolean $override
102 * @param boolean $skipLoaded
103 *
104 * @return bool Success indicator
105 */
106 public function loadFields( $fields = null, $override = true, $skipLoaded = false ) {
107 if ( is_null( $this->getId() ) ) {
108 return false;
109 }
110
111 if ( is_null( $fields ) ) {
112 $fields = array_keys( $this->table->getFields() );
113 }
114
115 if ( $skipLoaded ) {
116 $fields = array_diff( $fields, array_keys( $this->fields ) );
117 }
118
119 if ( !empty( $fields ) ) {
120 $result = $this->table->rawSelectRow(
121 $this->table->getPrefixedFields( $fields ),
122 array( $this->table->getPrefixedField( 'id' ) => $this->getId() ),
123 array( 'LIMIT' => 1 )
124 );
125
126 if ( $result !== false ) {
127 $this->setFields( $this->table->getFieldsFromDBResult( $result ), $override );
128 return true;
129 }
130 return false;
131 }
132
133 return true;
134 }
135
136 /**
137 * Gets the value of a field.
138 *
139 * @since 1.20
140 *
141 * @param string $name
142 * @param mixed $default
143 *
144 * @throws MWException
145 * @return mixed
146 */
147 public function getField( $name, $default = null ) {
148 if ( $this->hasField( $name ) ) {
149 return $this->fields[$name];
150 } elseif ( !is_null( $default ) ) {
151 return $default;
152 } else {
153 throw new MWException( 'Attempted to get not-set field ' . $name );
154 }
155 }
156
157 /**
158 * Gets the value of a field but first loads it if not done so already.
159 *
160 * @since 1.20
161 *
162 * @param string$name
163 *
164 * @return mixed
165 */
166 public function loadAndGetField( $name ) {
167 if ( !$this->hasField( $name ) ) {
168 $this->loadFields( array( $name ) );
169 }
170
171 return $this->getField( $name );
172 }
173
174 /**
175 * Remove a field.
176 *
177 * @since 1.20
178 *
179 * @param string $name
180 */
181 public function removeField( $name ) {
182 unset( $this->fields[$name] );
183 }
184
185 /**
186 * Returns the objects database id.
187 *
188 * @since 1.20
189 *
190 * @return integer|null
191 */
192 public function getId() {
193 return $this->getField( 'id' );
194 }
195
196 /**
197 * Sets the objects database id.
198 *
199 * @since 1.20
200 *
201 * @param integer|null $id
202 */
203 public function setId( $id ) {
204 $this->setField( 'id', $id );
205 }
206
207 /**
208 * Gets if a certain field is set.
209 *
210 * @since 1.20
211 *
212 * @param string $name
213 *
214 * @return boolean
215 */
216 public function hasField( $name ) {
217 return array_key_exists( $name, $this->fields );
218 }
219
220 /**
221 * Gets if the id field is set.
222 *
223 * @since 1.20
224 *
225 * @return boolean
226 */
227 public function hasIdField() {
228 return $this->hasField( 'id' )
229 && !is_null( $this->getField( 'id' ) );
230 }
231
232 /**
233 * Sets multiple fields.
234 *
235 * @since 1.20
236 *
237 * @param array $fields The fields to set
238 * @param boolean $override Override already set fields with the provided values?
239 */
240 public function setFields( array $fields, $override = true ) {
241 foreach ( $fields as $name => $value ) {
242 if ( $override || !$this->hasField( $name ) ) {
243 $this->setField( $name, $value );
244 }
245 }
246 }
247
248 /**
249 * Gets the fields => values to write to the table.
250 *
251 * @since 1.20
252 *
253 * @return array
254 */
255 protected function getWriteValues() {
256 $values = array();
257
258 foreach ( $this->table->getFields() as $name => $type ) {
259 if ( array_key_exists( $name, $this->fields ) ) {
260 $value = $this->fields[$name];
261
262 switch ( $type ) {
263 case 'array':
264 $value = (array)$value;
265 case 'blob':
266 $value = serialize( $value );
267 }
268
269 $values[$this->table->getPrefixedField( $name )] = $value;
270 }
271 }
272
273 return $values;
274 }
275
276 /**
277 * Serializes the object to an associative array which
278 * can then easily be converted into JSON or similar.
279 *
280 * @since 1.20
281 *
282 * @param null|array $fields
283 * @param boolean $incNullId
284 *
285 * @return array
286 */
287 public function toArray( $fields = null, $incNullId = false ) {
288 $data = array();
289 $setFields = array();
290
291 if ( !is_array( $fields ) ) {
292 $setFields = $this->getSetFieldNames();
293 } else {
294 foreach ( $fields as $field ) {
295 if ( $this->hasField( $field ) ) {
296 $setFields[] = $field;
297 }
298 }
299 }
300
301 foreach ( $setFields as $field ) {
302 if ( $incNullId || $field != 'id' || $this->hasIdField() ) {
303 $data[$field] = $this->getField( $field );
304 }
305 }
306
307 return $data;
308 }
309
310 /**
311 * Load the default values, via getDefaults.
312 *
313 * @since 1.20
314 *
315 * @param boolean $override
316 */
317 public function loadDefaults( $override = true ) {
318 $this->setFields( $this->table->getDefaults(), $override );
319 }
320
321 /**
322 * Writes the answer to the database, either updating it
323 * when it already exists, or inserting it when it doesn't.
324 *
325 * @since 1.20
326 *
327 * @param string|null $functionName
328 *
329 * @return boolean Success indicator
330 */
331 public function save( $functionName = null ) {
332 if ( $this->hasIdField() ) {
333 return $this->saveExisting( $functionName );
334 } else {
335 return $this->insert( $functionName );
336 }
337 }
338
339 /**
340 * Updates the object in the database.
341 *
342 * @since 1.20
343 *
344 * @param string|null $functionName
345 *
346 * @return boolean Success indicator
347 */
348 protected function saveExisting( $functionName = null ) {
349 $dbw = wfGetDB( DB_MASTER );
350
351 $success = $dbw->update(
352 $this->table->getName(),
353 $this->getWriteValues(),
354 $this->table->getPrefixedValues( $this->getUpdateConditions() ),
355 is_null( $functionName ) ? __METHOD__ : $functionName
356 );
357
358 // DatabaseBase::update does not always return true for success as documented...
359 return $success !== false;
360 }
361
362 /**
363 * Returns the WHERE considtions needed to identify this object so
364 * it can be updated.
365 *
366 * @since 1.20
367 *
368 * @return array
369 */
370 protected function getUpdateConditions() {
371 return array( 'id' => $this->getId() );
372 }
373
374 /**
375 * Inserts the object into the database.
376 *
377 * @since 1.20
378 *
379 * @param string|null $functionName
380 * @param array|null $options
381 *
382 * @return boolean Success indicator
383 */
384 protected function insert( $functionName = null, array $options = null ) {
385 $dbw = wfGetDB( DB_MASTER );
386
387 $success = $dbw->insert(
388 $this->table->getName(),
389 $this->getWriteValues(),
390 is_null( $functionName ) ? __METHOD__ : $functionName,
391 is_null( $options ) ? array( 'IGNORE' ) : $options
392 );
393
394 // DatabaseBase::insert does not always return true for success as documented...
395 $success = $success !== false;
396
397 if ( $success ) {
398 $this->setField( 'id', $dbw->insertId() );
399 }
400
401 return $success;
402 }
403
404 /**
405 * Removes the object from the database.
406 *
407 * @since 1.20
408 *
409 * @return boolean Success indicator
410 */
411 public function remove() {
412 $this->beforeRemove();
413
414 $success = $this->table->delete( array( 'id' => $this->getId() ) );
415
416 // DatabaseBase::delete does not always return true for success as documented...
417 $success = $success !== false;
418
419 if ( $success ) {
420 $this->onRemoved();
421 }
422
423 return $success;
424 }
425
426 /**
427 * Gets called before an object is removed from the database.
428 *
429 * @since 1.20
430 */
431 protected function beforeRemove() {
432 $this->loadFields( $this->getBeforeRemoveFields(), false, true );
433 }
434
435 /**
436 * Before removal of an object happens, @see beforeRemove gets called.
437 * This method loads the fields of which the names have been returned by this one (or all fields if null is returned).
438 * This allows for loading info needed after removal to get rid of linked data and the like.
439 *
440 * @since 1.20
441 *
442 * @return array|null
443 */
444 protected function getBeforeRemoveFields() {
445 return array();
446 }
447
448 /**
449 * Gets called after successfull removal.
450 * Can be overriden to get rid of linked data.
451 *
452 * @since 1.20
453 */
454 protected function onRemoved() {
455 $this->setField( 'id', null );
456 }
457
458 /**
459 * Return the names and values of the fields.
460 *
461 * @since 1.20
462 *
463 * @return array
464 */
465 public function getFields() {
466 return $this->fields;
467 }
468
469 /**
470 * Return the names of the fields.
471 *
472 * @since 1.20
473 *
474 * @return array
475 */
476 public function getSetFieldNames() {
477 return array_keys( $this->fields );
478 }
479
480 /**
481 * Sets the value of a field.
482 * Strings can be provided for other types,
483 * so this method can be called from unserialization handlers.
484 *
485 * @since 1.20
486 *
487 * @param string $name
488 * @param mixed $value
489 *
490 * @throws MWException
491 */
492 public function setField( $name, $value ) {
493 $fields = $this->table->getFields();
494
495 if ( array_key_exists( $name, $fields ) ) {
496 switch ( $fields[$name] ) {
497 case 'int':
498 $value = (int)$value;
499 break;
500 case 'float':
501 $value = (float)$value;
502 break;
503 case 'bool':
504 if ( is_string( $value ) ) {
505 $value = $value !== '0';
506 } elseif ( is_int( $value ) ) {
507 $value = $value !== 0;
508 }
509 break;
510 case 'array':
511 if ( is_string( $value ) ) {
512 $value = unserialize( $value );
513 }
514
515 if ( !is_array( $value ) ) {
516 $value = array();
517 }
518 break;
519 case 'blob':
520 if ( is_string( $value ) ) {
521 $value = unserialize( $value );
522 }
523 break;
524 case 'id':
525 if ( is_string( $value ) ) {
526 $value = (int)$value;
527 }
528 break;
529 }
530
531 $this->fields[$name] = $value;
532 } else {
533 throw new MWException( 'Attempted to set unknown field ' . $name );
534 }
535 }
536
537 /**
538 * Add an amount (can be negative) to the specified field (needs to be numeric).
539 * TODO: most off this stuff makes more sense in the table class
540 *
541 * @since 1.20
542 *
543 * @param string $field
544 * @param integer $amount
545 *
546 * @return boolean Success indicator
547 */
548 public function addToField( $field, $amount ) {
549 if ( $amount == 0 ) {
550 return true;
551 }
552
553 if ( !$this->hasIdField() ) {
554 return false;
555 }
556
557 $absoluteAmount = abs( $amount );
558 $isNegative = $amount < 0;
559
560 $dbw = wfGetDB( DB_MASTER );
561
562 $fullField = $this->table->getPrefixedField( $field );
563
564 $success = $dbw->update(
565 $this->table->getName(),
566 array( "$fullField=$fullField" . ( $isNegative ? '-' : '+' ) . $absoluteAmount ),
567 array( $this->table->getPrefixedField( 'id' ) => $this->getId() ),
568 __METHOD__
569 );
570
571 if ( $success && $this->hasField( $field ) ) {
572 $this->setField( $field, $this->getField( $field ) + $amount );
573 }
574
575 return $success;
576 }
577
578 /**
579 * Return the names of the fields.
580 *
581 * @since 1.20
582 *
583 * @return array
584 */
585 public function getFieldNames() {
586 return array_keys( $this->table->getFields() );
587 }
588
589 /**
590 * Computes and updates the values of the summary fields.
591 *
592 * @since 1.20
593 *
594 * @param array|string|null $summaryFields
595 */
596 public function loadSummaryFields( $summaryFields = null ) {
597
598 }
599
600 /**
601 * Sets the value for the @see $updateSummaries field.
602 *
603 * @since 1.20
604 *
605 * @param boolean $update
606 */
607 public function setUpdateSummaries( $update ) {
608 $this->updateSummaries = $update;
609 }
610
611 /**
612 * Sets the value for the @see $inSummaryMode field.
613 *
614 * @since 1.20
615 *
616 * @param boolean $summaryMode
617 */
618 public function setSummaryMode( $summaryMode ) {
619 $this->inSummaryMode = $summaryMode;
620 }
621
622 /**
623 * Return if any fields got changed.
624 *
625 * @since 1.20
626 *
627 * @param IORMRow $object
628 * @param boolean|array $excludeSummaryFields
629 * When set to true, summary field changes are ignored.
630 * Can also be an array of fields to ignore.
631 *
632 * @return boolean
633 */
634 protected function fieldsChanged( IORMRow $object, $excludeSummaryFields = false ) {
635 $exclusionFields = array();
636
637 if ( $excludeSummaryFields !== false ) {
638 $exclusionFields = is_array( $excludeSummaryFields ) ? $excludeSummaryFields : $this->table->getSummaryFields();
639 }
640
641 foreach ( $this->fields as $name => $value ) {
642 $excluded = $excludeSummaryFields && in_array( $name, $exclusionFields );
643
644 if ( !$excluded && $object->getField( $name ) !== $value ) {
645 return true;
646 }
647 }
648
649 return false;
650 }
651
652 /**
653 * Returns the table this IORMRow is a row in.
654 *
655 * @since 1.20
656 *
657 * @return IORMTable
658 */
659 public function getTable() {
660 return $this->table;
661 }
662
663 }