]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Managed_DataObject.php
Added type-hint for StartShowNoticeFormData hook
[quix0rs-gnu-social.git] / classes / Managed_DataObject.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2010, StatusNet, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 /**
21  * Wrapper for Memcached_DataObject which knows its own schema definition.
22  * Builds its own damn settings from a schema definition.
23  *
24  * @author Brion Vibber <brion@status.net>
25  */
26 abstract class Managed_DataObject extends Memcached_DataObject
27 {
28     /**
29      * The One True Thingy that must be defined and declared.
30      */
31     public static function schemaDef()
32     {
33         throw new MethodNotImplementedException(__METHOD__);
34     }
35
36     /**
37      * Get an instance by key
38      *
39      * @param string $k Key to use to lookup (usually 'id' for this class)
40      * @param mixed  $v Value to lookup
41      *
42      * @return get_called_class() object if found, or null for no hits
43      *
44      */
45     static function getKV($k,$v=NULL)
46     {
47         return parent::getClassKV(get_called_class(), $k, $v);
48     }
49
50     /**
51      * Get an instance by compound key
52      *
53      * This is a utility method to get a single instance with a given set of
54      * key-value pairs. Usually used for the primary key for a compound key; thus
55      * the name.
56      *
57      * @param array $kv array of key-value mappings
58      *
59      * @return get_called_class() object if found, or null for no hits
60      *
61      */
62     static function pkeyGet(array $kv)
63     {
64         return parent::pkeyGetClass(get_called_class(), $kv);
65     }
66
67     static function pkeyCols()
68     {
69         return parent::pkeyColsClass(get_called_class());
70     }
71
72     /**
73      * Get multiple items from the database by key
74      *
75      * @param string  $keyCol    name of column for key
76      * @param array   $keyVals   key values to fetch
77      * @param boolean $skipNulls return only non-null results?
78      *
79      * @return array Array of objects, in order
80      */
81         static function multiGet($keyCol, array $keyVals, $skipNulls=true)
82         {
83             return parent::multiGetClass(get_called_class(), $keyCol, $keyVals, $skipNulls);
84         }
85
86     /**
87      * Get multiple items from the database by key
88      *
89      * @param string  $keyCol    name of column for key
90      * @param array   $keyVals   key values to fetch
91      * @param array   $otherCols Other columns to hold fixed
92      *
93      * @return array Array mapping $keyVals to objects, or null if not found
94      */
95         static function pivotGet($keyCol, array $keyVals, array $otherCols=array())
96         {
97             return parent::pivotGetClass(get_called_class(), $keyCol, $keyVals, $otherCols);
98         }
99
100     /**
101      * Get a multi-instance object
102      *
103      * This is a utility method to get multiple instances with a given set of
104      * values for a specific column.
105      *
106      * @param string $keyCol  key column name
107      * @param array  $keyVals array of key values
108      *
109      * @return get_called_class() object with multiple instances if found,
110      *         Exception is thrown when no entries are found.
111      *
112      */
113     static function listFind($keyCol, array $keyVals)
114     {
115         return parent::listFindClass(get_called_class(), $keyCol, $keyVals);
116     }
117
118     /**
119      * Get a multi-instance object separated into an array
120      *
121      * This is a utility method to get multiple instances with a given set of
122      * values for a specific key column. Usually used for the primary key when
123      * multiple values are desired. Result is an array.
124      *
125      * @param string $keyCol  key column name
126      * @param array  $keyVals array of key values
127      *
128      * @return array with an get_called_class() object for each $keyVals entry
129      *
130      */
131     static function listGet($keyCol, array $keyVals)
132     {
133         return parent::listGetClass(get_called_class(), $keyCol, $keyVals);
134     }
135
136     /**
137      * get/set an associative array of table columns
138      *
139      * @access public
140      * @return array (associative)
141      */
142     public function table()
143     {
144         $table = static::schemaDef();
145         return array_map(array($this, 'columnBitmap'), $table['fields']);
146     }
147
148     /**
149      * get/set an  array of table primary keys
150      *
151      * Key info is pulled from the table definition array.
152      * 
153      * @access private
154      * @return array
155      */
156     function keys()
157     {
158         return array_keys($this->keyTypes());
159     }
160
161     /**
162      * Get a sequence key
163      *
164      * Returns the first serial column defined in the table, if any.
165      *
166      * @access private
167      * @return array (column,use_native,sequence_name)
168      */
169
170     function sequenceKey()
171     {
172         $table = static::schemaDef();
173         foreach ($table['fields'] as $name => $column) {
174             if ($column['type'] == 'serial') {
175                 // We have a serial/autoincrement column.
176                 // Declare it to be a native sequence!
177                 return array($name, true, false);
178             }
179         }
180
181         // No sequence key on this table.
182         return array(false, false, false);
183     }
184
185     /**
186      * Return key definitions for DB_DataObject and Memcache_DataObject.
187      *
188      * DB_DataObject needs to know about keys that the table has; this function
189      * defines them.
190      *
191      * @return array key definitions
192      */
193
194     function keyTypes()
195     {
196         $table = static::schemaDef();
197         $keys = array();
198
199         if (!empty($table['unique keys'])) {
200             foreach ($table['unique keys'] as $idx => $fields) {
201                 foreach ($fields as $name) {
202                     $keys[$name] = 'U';
203                 }
204             }
205         }
206
207         if (!empty($table['primary key'])) {
208             foreach ($table['primary key'] as $name) {
209                 $keys[$name] = 'K';
210             }
211         }
212         return $keys;
213     }
214
215     /**
216      * Build the appropriate DB_DataObject bitfield map for this field.
217      *
218      * @param array $column
219      * @return int
220      */
221     function columnBitmap($column)
222     {
223         $type = $column['type'];
224
225         // For quoting style...
226         $intTypes = array('int',
227                           'integer',
228                           'float',
229                           'serial',
230                           'numeric');
231         if (in_array($type, $intTypes)) {
232             $style = DB_DATAOBJECT_INT;
233         } else {
234             $style = DB_DATAOBJECT_STR;
235         }
236
237         // Data type formatting style...
238         $formatStyles = array('blob' => DB_DATAOBJECT_BLOB,
239                               'text' => DB_DATAOBJECT_TXT,
240                               'date' => DB_DATAOBJECT_DATE,
241                               'time' => DB_DATAOBJECT_TIME,
242                               'datetime' => DB_DATAOBJECT_DATE | DB_DATAOBJECT_TIME,
243                               'timestamp' => DB_DATAOBJECT_MYSQLTIMESTAMP);
244
245         if (isset($formatStyles[$type])) {
246             $style |= $formatStyles[$type];
247         }
248
249         // Nullable?
250         if (!empty($column['not null'])) {
251             $style |= DB_DATAOBJECT_NOTNULL;
252         }
253
254         return $style;
255     }
256
257     function links()
258     {
259         $links = array();
260
261         $table = static::schemaDef();
262
263         foreach ($table['foreign keys'] as $keyname => $keydef) {
264             if (count($keydef) == 2 && is_string($keydef[0]) && is_array($keydef[1]) && count($keydef[1]) == 1) {
265                 if (isset($keydef[1][0])) {
266                     $links[$keydef[1][0]] = $keydef[0].':'.$keydef[1][1];
267                 }
268             }
269         }
270         return $links;
271     }
272
273     /**
274      * Return a list of all primary/unique keys / vals that will be used for
275      * caching. This will understand compound unique keys, which
276      * Memcached_DataObject doesn't have enough info to handle properly.
277      *
278      * @return array of strings
279      */
280     function _allCacheKeys()
281     {
282         $table = static::schemaDef();
283         $ckeys = array();
284
285         if (!empty($table['unique keys'])) {
286             $keyNames = $table['unique keys'];
287             foreach ($keyNames as $idx => $fields) {
288                 $val = array();
289                 foreach ($fields as $name) {
290                     $val[$name] = self::valueString($this->$name);
291                 }
292                 $ckeys[] = self::multicacheKey($this->tableName(), $val);
293             }
294         }
295
296         if (!empty($table['primary key'])) {
297             $fields = $table['primary key'];
298             $val = array();
299             foreach ($fields as $name) {
300                 $val[$name] = self::valueString($this->$name);
301             }
302             $ckeys[] = self::multicacheKey($this->tableName(), $val);
303         }
304         return $ckeys;
305     }
306
307     public function escapedTableName()
308     {
309         return common_database_tablename($this->tableName());
310     }
311
312     /**
313      * Returns an object by looking at the primary key column(s).
314      *
315      * Will require all primary key columns to be defined in an associative array
316      * and ignore any keys which are not part of the primary key.
317      *
318      * Will NOT accept NULL values as part of primary key.
319      *
320      * @param   array   $vals       Must match all primary key columns for the dataobject.
321      *
322      * @return  Managed_DataObject  of the get_called_class() type
323      * @throws  NoResultException   if no object with that primary key
324      */
325     static function getByPK(array $vals)
326     {
327         $classname = get_called_class();
328
329         $pkey = static::pkeyCols();
330         if (is_null($pkey)) {
331             throw new ServerException("Failed to get primary key columns for class '{$classname}'");
332         }
333
334         $object = new $classname();
335         foreach ($pkey as $col) {
336             if (!array_key_exists($col, $vals)) {
337                 throw new ServerException("Missing primary key column '{$col}' for ".get_called_class()." among provided keys: ".implode(',', array_keys($vals)));
338             } elseif (is_null($vals[$col])) {
339                 throw new ServerException("NULL values not allowed in getByPK for column '{$col}'");
340             }
341             $object->$col = $vals[$col];
342         }
343         if (!$object->find(true)) {
344             throw new NoResultException($object);
345         }
346         return $object;
347     }
348
349     /**
350      * Returns an object by looking at given unique key columns.
351      *
352      * Will NOT accept NULL values for a unique key column. Ignores non-key values.
353      *
354      * @param   array   $vals       All array keys which are set must be non-null.
355      *
356      * @return  Managed_DataObject  of the get_called_class() type
357      * @throws  NoResultException   if no object with that primary key
358      */
359     static function getByKeys(array $vals)
360     {
361         $classname = get_called_class();
362
363         $object = new $classname();
364
365         $keys = $object->keys();
366         if (is_null($keys)) {
367             throw new ServerException("Failed to get key columns for class '{$classname}'");
368         }
369
370         foreach ($keys as $col) {
371             if (!array_key_exists($col, $vals)) {
372                 continue;
373             } elseif (is_null($vals[$col])) {
374                 throw new ServerException("NULL values not allowed in getByKeys for column '{$col}'");
375             }
376             $object->$col = $vals[$col];
377         }
378         if (!$object->find(true)) {
379             throw new NoResultException($object);
380         }
381         return $object;
382     }
383
384     static function getByID($id)
385     {
386         if (!property_exists(get_called_class(), 'id')) {
387             throw new ServerException('Trying to get undefined property of dataobject class.');
388         }
389         if (empty($id)) {
390             throw new EmptyPkeyValueException(get_called_class(), 'id');
391         }
392         // getByPK throws exception if id is null
393         // or if the class does not have a single 'id' column as primary key
394         return static::getByPK(array('id' => $id));
395     }
396
397     static function getByUri($uri)
398     {
399         if (!property_exists(get_called_class(), 'uri')) {
400             throw new ServerException('Trying to get undefined property of dataobject class.');
401         }
402         if (empty($uri)) {
403             throw new EmptyPkeyValueException(get_called_class(), 'uri');
404         }
405
406         $class = get_called_class();
407         $obj = new $class();
408         $obj->uri = $uri;
409         if (!$obj->find(true)) {
410             throw new NoResultException($obj);
411         }
412         return $obj;
413     }
414
415     /**
416      * Returns an ID, checked that it is set and reasonably valid
417      *
418      * If this dataobject uses a special id field (not 'id'), just
419      * implement your ID getting method in the child class.
420      *
421      * @return int ID of dataobject
422      * @throws Exception (when ID is not available or not set yet)
423      */
424     public function getID()
425     {
426         // FIXME: Make these exceptions more specific (their own classes)
427         if (!isset($this->id)) {
428             throw new Exception('No ID set.');
429         } elseif (empty($this->id)) {
430             throw new Exception('Empty ID for object! (not inserted yet?).');
431         }
432
433         return intval($this->id);
434     }
435
436     /**
437      * WARNING: Only use this on Profile and Notice. We should probably do
438      * this with traits/"implements" or whatever, but that's over the top
439      * right now, I'm just throwing this in here to avoid code duplication
440      * in Profile and Notice classes.
441      */
442     public function getAliases()
443     {
444         return array_keys($this->getAliasesWithIDs());
445     }
446
447     public function getAliasesWithIDs()
448     {
449         $aliases = array();
450         $aliases[$this->getUri()] = $this->getID();
451
452         try {
453             $aliases[$this->getUrl()] = $this->getID();
454         } catch (InvalidUrlException $e) {
455             // getUrl failed because no valid URL could be returned, just ignore it
456         }
457
458         if (common_config('fix', 'fancyurls')) {
459             /**
460              * Here we add some hacky hotfixes for remote lookups that have been taught the
461              * (at least now) wrong URI but it's still obviously the same user. Such as:
462              * - https://site.example/user/1 even if the client requests https://site.example/index.php/user/1
463              * - https://site.example/user/1 even if the client requests https://site.example//index.php/user/1
464              * - https://site.example/index.php/user/1 even if the client requests https://site.example/user/1
465              * - https://site.example/index.php/user/1 even if the client requests https://site.example///index.php/user/1
466              */
467             foreach ($aliases as $alias=>$id) {
468                 try {
469                     // get a "fancy url" version of the alias, even without index.php/
470                     $alt_url = common_fake_local_fancy_url($alias);
471                     // store this as well so remote sites can be sure we really are the same profile
472                     $aliases[$alt_url] = $id;
473                 } catch (Exception $e) {
474                     // Apparently we couldn't rewrite that, the $alias was as the function wanted it to be
475                 }
476
477                 try {
478                     // get a non-"fancy url" version of the alias, i.e. add index.php/
479                     $alt_url = common_fake_local_nonfancy_url($alias);
480                     // store this as well so remote sites can be sure we really are the same profile
481                     $aliases[$alt_url] = $id;
482                 } catch (Exception $e) {
483                     // Apparently we couldn't rewrite that, the $alias was as the function wanted it to be
484                 }
485             }
486         }
487         return $aliases;
488     }
489
490     // 'update' won't write key columns, so we have to do it ourselves.
491     // This also automatically calls "update" _before_ it sets the keys.
492     // FIXME: This only works with single-column primary keys so far! Beware!
493     /**
494      * @param DB_DataObject &$orig  Must be "instanceof" $this
495      * @param string         $pid   Primary ID column (no escaping is done on column name!)
496      */
497     public function updateWithKeys(Managed_DataObject $orig, $pid=null)
498     {
499         if (!$orig instanceof $this) {
500             throw new ServerException('Tried updating a DataObject with a different class than itself.');
501         }
502
503         if ($this->N <1) {
504             throw new ServerException('DataObject must be the result of a query (N>=1) before updateWithKeys()');
505         }
506
507         $this->onUpdateKeys($orig);
508
509         // do it in a transaction
510         $this->query('BEGIN');
511
512         $parts = array();
513         foreach ($this->keys() as $k) {
514             if (strcmp($this->$k, $orig->$k) != 0) {
515                 $parts[] = $k . ' = ' . $this->_quote($this->$k);
516             }
517         }
518         if (count($parts) == 0) {
519             // No changes to keys, it's safe to run ->update(...)
520             if ($this->update($orig) === false) {
521                 common_log_db_error($this, 'UPDATE', __FILE__);
522                 // rollback as something bad occurred
523                 $this->query('ROLLBACK');
524                 throw new ServerException("Could not UPDATE non-keys for {$this->tableName()}");
525             }
526             $orig->decache();
527             $this->encache();
528
529             // commit our db transaction since we won't reach the COMMIT below
530             $this->query('COMMIT');
531             // @FIXME return true only if something changed (otherwise 0)
532             return true;
533         }
534
535         if ($pid === null) {
536             $schema = static::schemaDef();
537             $pid = $schema['primary key'];
538             unset($schema);
539         }
540         $pidWhere = array();
541         foreach((array)$pid as $pidCol) { 
542             $pidWhere[] = sprintf('%1$s = %2$s', $pidCol, $this->_quote($orig->$pidCol));
543         }
544         if (empty($pidWhere)) {
545             throw new ServerException('No primary ID column(s) set for updateWithKeys');
546         }
547
548         $qry = sprintf('UPDATE %1$s SET %2$s WHERE %3$s',
549                             common_database_tablename($this->tableName()),
550                             implode(', ', $parts),
551                             implode(' AND ', $pidWhere));
552
553         $result = $this->query($qry);
554         if ($result === false) {
555             common_log_db_error($this, 'UPDATE', __FILE__);
556             // rollback as something bad occurred
557             $this->query('ROLLBACK');
558             throw new ServerException("Could not UPDATE key fields for {$this->tableName()}");
559         }
560
561         // Update non-keys too, if the previous endeavour worked.
562         // The ->update call uses "$this" values for keys, that's why we can't do this until
563         // the keys are updated (because they might differ from $orig and update the wrong entries).
564         if ($this->update($orig) === false) {
565             common_log_db_error($this, 'UPDATE', __FILE__);
566             // rollback as something bad occurred
567             $this->query('ROLLBACK');
568             throw new ServerException("Could not UPDATE non-keys for {$this->tableName()}");
569         }
570         $orig->decache();
571         $this->encache();
572
573         // commit our db transaction
574         $this->query('COMMIT');
575         // @FIXME return true only if something changed (otherwise 0)
576         return $result;
577     }
578
579     static public function beforeSchemaUpdate()
580     {
581         // NOOP
582     }
583
584     static function newUri(Profile $actor, Managed_DataObject $object, $created=null)
585     {
586         if (is_null($created)) {
587             $created = common_sql_now();
588         }
589         return TagURI::mint(strtolower(get_called_class()).':%d:%s:%d:%s',
590                                         $actor->getID(),
591                                         ActivityUtils::resolveUri($object->getObjectType(), true),
592                                         $object->getID(),
593                                         common_date_iso8601($created));
594     }
595
596     protected function onInsert()
597     {
598         // NOOP by default
599     }
600
601     protected function onUpdate($dataObject=false)
602     {
603         // NOOP by default
604     }
605
606     protected function onUpdateKeys(Managed_DataObject $orig)
607     {
608         // NOOP by default
609     }
610
611     public function insert()
612     {
613         $this->onInsert();
614         return parent::insert();
615     }
616
617     public function update($dataObject=false)
618     {
619         $this->onUpdate($dataObject);
620         return parent::update($dataObject);
621     }
622 }