]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Managed_DataObject.php
Properly attach activityobjects
[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 (empty($id)) {
387             throw new EmptyIdException(get_called_class());
388         }
389         // getByPK throws exception if id is null
390         // or if the class does not have a single 'id' column as primary key
391         return static::getByPK(array('id' => $id));
392     }
393
394     /**
395      * Returns an ID, checked that it is set and reasonably valid
396      *
397      * If this dataobject uses a special id field (not 'id'), just
398      * implement your ID getting method in the child class.
399      *
400      * @return int ID of dataobject
401      * @throws Exception (when ID is not available or not set yet)
402      */
403     public function getID()
404     {
405         // FIXME: Make these exceptions more specific (their own classes)
406         if (!isset($this->id)) {
407             throw new Exception('No ID set.');
408         } elseif (empty($this->id)) {
409             throw new Exception('Empty ID for object! (not inserted yet?).');
410         }
411
412         return intval($this->id);
413     }
414
415     /**
416      * WARNING: Only use this on Profile and Notice. We should probably do
417      * this with traits/"implements" or whatever, but that's over the top
418      * right now, I'm just throwing this in here to avoid code duplication
419      * in Profile and Notice classes.
420      */
421     public function getAliases()
422     {
423         return array_keys($this->getAliasesWithIDs());
424     }
425
426     public function getAliasesWithIDs()
427     {
428         $aliases = array();
429         $aliases[$this->getUri()] = $this->getID();
430
431         try {
432             $aliases[$this->getUrl()] = $this->getID();
433         } catch (InvalidUrlException $e) {
434             // getUrl failed because no valid URL could be returned, just ignore it
435         }
436
437         if (common_config('fix', 'fancyurls')) {
438             /**
439              * Here we add some hacky hotfixes for remote lookups that have been taught the
440              * (at least now) wrong URI but it's still obviously the same user. Such as:
441              * - https://site.example/user/1 even if the client requests https://site.example/index.php/user/1
442              * - https://site.example/user/1 even if the client requests https://site.example//index.php/user/1
443              * - https://site.example/index.php/user/1 even if the client requests https://site.example/user/1
444              * - https://site.example/index.php/user/1 even if the client requests https://site.example///index.php/user/1
445              */
446             foreach ($aliases as $alias=>$id) {
447                 try {
448                     // get a "fancy url" version of the alias, even without index.php/
449                     $alt_url = common_fake_local_fancy_url($alias);
450                     // store this as well so remote sites can be sure we really are the same profile
451                     $aliases[$alt_url] = $id;
452                 } catch (Exception $e) {
453                     // Apparently we couldn't rewrite that, the $alias was as the function wanted it to be
454                 }
455
456                 try {
457                     // get a non-"fancy url" version of the alias, i.e. add index.php/
458                     $alt_url = common_fake_local_nonfancy_url($alias);
459                     // store this as well so remote sites can be sure we really are the same profile
460                     $aliases[$alt_url] = $id;
461                 } catch (Exception $e) {
462                     // Apparently we couldn't rewrite that, the $alias was as the function wanted it to be
463                 }
464             }
465         }
466         return $aliases;
467     }
468
469     // 'update' won't write key columns, so we have to do it ourselves.
470     // This also automatically calls "update" _before_ it sets the keys.
471     // FIXME: This only works with single-column primary keys so far! Beware!
472     /**
473      * @param DB_DataObject &$orig  Must be "instanceof" $this
474      * @param string         $pid   Primary ID column (no escaping is done on column name!)
475      */
476     public function updateWithKeys(Managed_DataObject $orig, $pid=null)
477     {
478         if (!$orig instanceof $this) {
479             throw new ServerException('Tried updating a DataObject with a different class than itself.');
480         }
481
482         if ($this->N <1) {
483             throw new ServerException('DataObject must be the result of a query (N>=1) before updateWithKeys()');
484         }
485
486         // do it in a transaction
487         $this->query('BEGIN');
488
489         $parts = array();
490         foreach ($this->keys() as $k) {
491             if (strcmp($this->$k, $orig->$k) != 0) {
492                 $parts[] = $k . ' = ' . $this->_quote($this->$k);
493             }
494         }
495         if (count($parts) == 0) {
496             // No changes to keys, it's safe to run ->update(...)
497             if ($this->update($orig) === false) {
498                 common_log_db_error($this, 'UPDATE', __FILE__);
499                 // rollback as something bad occurred
500                 $this->query('ROLLBACK');
501                 throw new ServerException("Could not UPDATE non-keys for {$this->tableName()}");
502             }
503             $orig->decache();
504             $this->encache();
505
506             // commit our db transaction since we won't reach the COMMIT below
507             $this->query('COMMIT');
508             // @FIXME return true only if something changed (otherwise 0)
509             return true;
510         }
511
512         if ($pid === null) {
513             $schema = static::schemaDef();
514             $pid = $schema['primary key'];
515             unset($schema);
516         }
517         $pidWhere = array();
518         foreach((array)$pid as $pidCol) { 
519             $pidWhere[] = sprintf('%1$s = %2$s', $pidCol, $this->_quote($orig->$pidCol));
520         }
521         if (empty($pidWhere)) {
522             throw new ServerException('No primary ID column(s) set for updateWithKeys');
523         }
524
525         $qry = sprintf('UPDATE %1$s SET %2$s WHERE %3$s',
526                             common_database_tablename($this->tableName()),
527                             implode(', ', $parts),
528                             implode(' AND ', $pidWhere));
529
530         $result = $this->query($qry);
531         if ($result === false) {
532             common_log_db_error($this, 'UPDATE', __FILE__);
533             // rollback as something bad occurred
534             $this->query('ROLLBACK');
535             throw new ServerException("Could not UPDATE key fields for {$this->tableName()}");
536         }
537
538         // Update non-keys too, if the previous endeavour worked.
539         // The ->update call uses "$this" values for keys, that's why we can't do this until
540         // the keys are updated (because they might differ from $orig and update the wrong entries).
541         if ($this->update($orig) === false) {
542             common_log_db_error($this, 'UPDATE', __FILE__);
543             // rollback as something bad occurred
544             $this->query('ROLLBACK');
545             throw new ServerException("Could not UPDATE non-keys for {$this->tableName()}");
546         }
547         $orig->decache();
548         $this->encache();
549
550         // commit our db transaction
551         $this->query('COMMIT');
552         // @FIXME return true only if something changed (otherwise 0)
553         return $result;
554     }
555
556     static public function beforeSchemaUpdate()
557     {
558         // NOOP
559     }
560
561     static function newUri(Profile $actor, Managed_DataObject $object, $created=null)
562     {
563         if (is_null($created)) {
564             $created = common_sql_now();
565         }
566         return TagURI::mint(strtolower(get_called_class()).':%d:%s:%d:%s',
567                                         $actor->getID(),
568                                         ActivityUtils::resolveUri($object->getObjectType(), true),
569                                         $object->getID(),
570                                         common_date_iso8601($created));
571     }
572
573     protected function onInsert()
574     {
575         // NOOP by default
576     }
577
578     protected function onUpdate($dataObject=false)
579     {
580         // NOOP by default
581     }
582
583     public function insert()
584     {
585         $this->onInsert();
586         return parent::insert();
587     }
588
589     public function update($dataObject=false)
590     {
591         $this->onUpdate($dataObject);
592         return parent::update($dataObject);
593     }
594 }