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