Merge "Localisation updates from http://translatewiki.net."
[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 * @license 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 $name string: Field name
142 * @param $default mixed: Default value to return when none is found
143 * (default: null)
144 *
145 * @throws MWException
146 * @return mixed
147 */
148 public function getField( $name, $default = null ) {
149 if ( $this->hasField( $name ) ) {
150 return $this->fields[$name];
151 } elseif ( !is_null( $default ) ) {
152 return $default;
153 } else {
154 throw new MWException( 'Attempted to get not-set field ' . $name );
155 }
156 }
157
158 /**
159 * Gets the value of a field but first loads it if not done so already.
160 *
161 * @since 1.20
162 *
163 * @param $name string
164 *
165 * @return mixed
166 */
167 public function loadAndGetField( $name ) {
168 if ( !$this->hasField( $name ) ) {
169 $this->loadFields( array( $name ) );
170 }
171
172 return $this->getField( $name );
173 }
174
175 /**
176 * Remove a field.
177 *
178 * @since 1.20
179 *
180 * @param string $name
181 */
182 public function removeField( $name ) {
183 unset( $this->fields[$name] );
184 }
185
186 /**
187 * Returns the objects database id.
188 *
189 * @since 1.20
190 *
191 * @return integer|null
192 */
193 public function getId() {
194 return $this->getField( 'id' );
195 }
196
197 /**
198 * Sets the objects database id.
199 *
200 * @since 1.20
201 *
202 * @param integer|null $id
203 */
204 public function setId( $id ) {
205 $this->setField( 'id', $id );
206 }
207
208 /**
209 * Gets if a certain field is set.
210 *
211 * @since 1.20
212 *
213 * @param string $name
214 *
215 * @return boolean
216 */
217 public function hasField( $name ) {
218 return array_key_exists( $name, $this->fields );
219 }
220
221 /**
222 * Gets if the id field is set.
223 *
224 * @since 1.20
225 *
226 * @return boolean
227 */
228 public function hasIdField() {
229 return $this->hasField( 'id' )
230 && !is_null( $this->getField( 'id' ) );
231 }
232
233 /**
234 * Sets multiple fields.
235 *
236 * @since 1.20
237 *
238 * @param array $fields The fields to set
239 * @param boolean $override Override already set fields with the provided values?
240 */
241 public function setFields( array $fields, $override = true ) {
242 foreach ( $fields as $name => $value ) {
243 if ( $override || !$this->hasField( $name ) ) {
244 $this->setField( $name, $value );
245 }
246 }
247 }
248
249 /**
250 * Gets the fields => values to write to the table.
251 *
252 * @since 1.20
253 *
254 * @return array
255 */
256 protected function getWriteValues() {
257 $values = array();
258
259 foreach ( $this->table->getFields() as $name => $type ) {
260 if ( array_key_exists( $name, $this->fields ) ) {
261 $value = $this->fields[$name];
262
263 switch ( $type ) {
264 case 'array':
265 $value = (array)$value;
266 // fall-through!
267 case 'blob':
268 $value = serialize( $value );
269 // fall-through!
270 }
271
272 $values[$this->table->getPrefixedField( $name )] = $value;
273 }
274 }
275
276 return $values;
277 }
278
279 /**
280 * Serializes the object to an associative array which
281 * can then easily be converted into JSON or similar.
282 *
283 * @since 1.20
284 *
285 * @param null|array $fields
286 * @param boolean $incNullId
287 *
288 * @return array
289 */
290 public function toArray( $fields = null, $incNullId = false ) {
291 $data = array();
292 $setFields = array();
293
294 if ( !is_array( $fields ) ) {
295 $setFields = $this->getSetFieldNames();
296 } else {
297 foreach ( $fields as $field ) {
298 if ( $this->hasField( $field ) ) {
299 $setFields[] = $field;
300 }
301 }
302 }
303
304 foreach ( $setFields as $field ) {
305 if ( $incNullId || $field != 'id' || $this->hasIdField() ) {
306 $data[$field] = $this->getField( $field );
307 }
308 }
309
310 return $data;
311 }
312
313 /**
314 * Load the default values, via getDefaults.
315 *
316 * @since 1.20
317 *
318 * @param boolean $override
319 */
320 public function loadDefaults( $override = true ) {
321 $this->setFields( $this->table->getDefaults(), $override );
322 }
323
324 /**
325 * Writes the answer to the database, either updating it
326 * when it already exists, or inserting it when it doesn't.
327 *
328 * @since 1.20
329 *
330 * @param string|null $functionName
331 *
332 * @return boolean Success indicator
333 */
334 public function save( $functionName = null ) {
335 if ( $this->hasIdField() ) {
336 return $this->saveExisting( $functionName );
337 } else {
338 return $this->insert( $functionName );
339 }
340 }
341
342 /**
343 * Updates the object in the database.
344 *
345 * @since 1.20
346 *
347 * @param string|null $functionName
348 *
349 * @return boolean Success indicator
350 */
351 protected function saveExisting( $functionName = null ) {
352 $dbw = $this->table->getWriteDbConnection();
353
354 $success = $dbw->update(
355 $this->table->getName(),
356 $this->getWriteValues(),
357 $this->table->getPrefixedValues( $this->getUpdateConditions() ),
358 is_null( $functionName ) ? __METHOD__ : $functionName
359 );
360
361 $this->table->releaseConnection( $dbw );
362
363 // DatabaseBase::update does not always return true for success as documented...
364 return $success !== false;
365 }
366
367 /**
368 * Returns the WHERE considtions needed to identify this object so
369 * it can be updated.
370 *
371 * @since 1.20
372 *
373 * @return array
374 */
375 protected function getUpdateConditions() {
376 return array( 'id' => $this->getId() );
377 }
378
379 /**
380 * Inserts the object into the database.
381 *
382 * @since 1.20
383 *
384 * @param string|null $functionName
385 * @param array|null $options
386 *
387 * @return boolean Success indicator
388 */
389 protected function insert( $functionName = null, array $options = null ) {
390 $dbw = $this->table->getWriteDbConnection();
391
392 $success = $dbw->insert(
393 $this->table->getName(),
394 $this->getWriteValues(),
395 is_null( $functionName ) ? __METHOD__ : $functionName,
396 $options
397 );
398
399 // DatabaseBase::insert does not always return true for success as documented...
400 $success = $success !== false;
401
402 if ( $success ) {
403 $this->setField( 'id', $dbw->insertId() );
404 }
405
406 $this->table->releaseConnection( $dbw );
407
408 return $success;
409 }
410
411 /**
412 * Removes the object from the database.
413 *
414 * @since 1.20
415 *
416 * @return boolean Success indicator
417 */
418 public function remove() {
419 $this->beforeRemove();
420
421 $success = $this->table->delete( array( 'id' => $this->getId() ) );
422
423 // DatabaseBase::delete does not always return true for success as documented...
424 $success = $success !== false;
425
426 if ( $success ) {
427 $this->onRemoved();
428 }
429
430 return $success;
431 }
432
433 /**
434 * Gets called before an object is removed from the database.
435 *
436 * @since 1.20
437 */
438 protected function beforeRemove() {
439 $this->loadFields( $this->getBeforeRemoveFields(), false, true );
440 }
441
442 /**
443 * Before removal of an object happens, @see beforeRemove gets called.
444 * This method loads the fields of which the names have been returned by this one (or all fields if null is returned).
445 * This allows for loading info needed after removal to get rid of linked data and the like.
446 *
447 * @since 1.20
448 *
449 * @return array|null
450 */
451 protected function getBeforeRemoveFields() {
452 return array();
453 }
454
455 /**
456 * Gets called after successfull removal.
457 * Can be overriden to get rid of linked data.
458 *
459 * @since 1.20
460 */
461 protected function onRemoved() {
462 $this->setField( 'id', null );
463 }
464
465 /**
466 * Return the names and values of the fields.
467 *
468 * @since 1.20
469 *
470 * @return array
471 */
472 public function getFields() {
473 return $this->fields;
474 }
475
476 /**
477 * Return the names of the fields.
478 *
479 * @since 1.20
480 *
481 * @return array
482 */
483 public function getSetFieldNames() {
484 return array_keys( $this->fields );
485 }
486
487 /**
488 * Sets the value of a field.
489 * Strings can be provided for other types,
490 * so this method can be called from unserialization handlers.
491 *
492 * @since 1.20
493 *
494 * @param string $name
495 * @param mixed $value
496 *
497 * @throws MWException
498 */
499 public function setField( $name, $value ) {
500 $fields = $this->table->getFields();
501
502 if ( array_key_exists( $name, $fields ) ) {
503 switch ( $fields[$name] ) {
504 case 'int':
505 $value = (int)$value;
506 break;
507 case 'float':
508 $value = (float)$value;
509 break;
510 case 'bool':
511 if ( is_string( $value ) ) {
512 $value = $value !== '0';
513 } elseif ( is_int( $value ) ) {
514 $value = $value !== 0;
515 }
516 break;
517 case 'array':
518 if ( is_string( $value ) ) {
519 $value = unserialize( $value );
520 }
521
522 if ( !is_array( $value ) ) {
523 $value = array();
524 }
525 break;
526 case 'blob':
527 if ( is_string( $value ) ) {
528 $value = unserialize( $value );
529 }
530 break;
531 case 'id':
532 if ( is_string( $value ) ) {
533 $value = (int)$value;
534 }
535 break;
536 }
537
538 $this->fields[$name] = $value;
539 } else {
540 throw new MWException( 'Attempted to set unknown field ' . $name );
541 }
542 }
543
544 /**
545 * Add an amount (can be negative) to the specified field (needs to be numeric).
546 * TODO: most off this stuff makes more sense in the table class
547 *
548 * @since 1.20
549 *
550 * @param string $field
551 * @param integer $amount
552 *
553 * @return boolean Success indicator
554 */
555 public function addToField( $field, $amount ) {
556 if ( $amount == 0 ) {
557 return true;
558 }
559
560 if ( !$this->hasIdField() ) {
561 return false;
562 }
563
564 $absoluteAmount = abs( $amount );
565 $isNegative = $amount < 0;
566
567 $dbw = $this->table->getWriteDbConnection();
568
569 $fullField = $this->table->getPrefixedField( $field );
570
571 $success = $dbw->update(
572 $this->table->getName(),
573 array( "$fullField=$fullField" . ( $isNegative ? '-' : '+' ) . $absoluteAmount ),
574 array( $this->table->getPrefixedField( 'id' ) => $this->getId() ),
575 __METHOD__
576 );
577
578 if ( $success && $this->hasField( $field ) ) {
579 $this->setField( $field, $this->getField( $field ) + $amount );
580 }
581
582 $this->table->releaseConnection( $dbw );
583
584 return $success;
585 }
586
587 /**
588 * Return the names of the fields.
589 *
590 * @since 1.20
591 *
592 * @return array
593 */
594 public function getFieldNames() {
595 return array_keys( $this->table->getFields() );
596 }
597
598 /**
599 * Computes and updates the values of the summary fields.
600 *
601 * @since 1.20
602 *
603 * @param array|string|null $summaryFields
604 */
605 public function loadSummaryFields( $summaryFields = null ) {
606
607 }
608
609 /**
610 * Sets the value for the @see $updateSummaries field.
611 *
612 * @since 1.20
613 *
614 * @param boolean $update
615 */
616 public function setUpdateSummaries( $update ) {
617 $this->updateSummaries = $update;
618 }
619
620 /**
621 * Sets the value for the @see $inSummaryMode field.
622 *
623 * @since 1.20
624 *
625 * @param boolean $summaryMode
626 */
627 public function setSummaryMode( $summaryMode ) {
628 $this->inSummaryMode = $summaryMode;
629 }
630
631 /**
632 * Return if any fields got changed.
633 *
634 * @since 1.20
635 *
636 * @param IORMRow $object
637 * @param boolean|array $excludeSummaryFields
638 * When set to true, summary field changes are ignored.
639 * Can also be an array of fields to ignore.
640 *
641 * @return boolean
642 */
643 protected function fieldsChanged( IORMRow $object, $excludeSummaryFields = false ) {
644 $exclusionFields = array();
645
646 if ( $excludeSummaryFields !== false ) {
647 $exclusionFields = is_array( $excludeSummaryFields ) ? $excludeSummaryFields : $this->table->getSummaryFields();
648 }
649
650 foreach ( $this->fields as $name => $value ) {
651 $excluded = $excludeSummaryFields && in_array( $name, $exclusionFields );
652
653 if ( !$excluded && $object->getField( $name ) !== $value ) {
654 return true;
655 }
656 }
657
658 return false;
659 }
660
661 /**
662 * Returns the table this IORMRow is a row in.
663 *
664 * @since 1.20
665 *
666 * @return IORMTable
667 */
668 public function getTable() {
669 return $this->table;
670 }
671
672 }