]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Managed_DataObject.php
Only serve tagprofile HTML if we aren't POSTing via ajax
[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     /**
68      * Get multiple items from the database by key
69      *
70      * @param string  $keyCol    name of column for key
71      * @param array   $keyVals   key values to fetch
72      * @param boolean $skipNulls return only non-null results?
73      *
74      * @return array Array of objects, in order
75      */
76         static function multiGet($keyCol, array $keyVals, $skipNulls=true)
77         {
78             return parent::multiGetClass(get_called_class(), $keyCol, $keyVals, $skipNulls);
79         }
80
81     /**
82      * Get multiple items from the database by key
83      *
84      * @param string  $keyCol    name of column for key
85      * @param array   $keyVals   key values to fetch
86      * @param array   $otherCols Other columns to hold fixed
87      *
88      * @return array Array mapping $keyVals to objects, or null if not found
89      */
90         static function pivotGet($keyCol, array $keyVals, array $otherCols=array())
91         {
92             return parent::pivotGetClass(get_called_class(), $keyCol, $keyVals, $otherCols);
93         }
94
95     /**
96      * Get a multi-instance object
97      *
98      * This is a utility method to get multiple instances with a given set of
99      * values for a specific column.
100      *
101      * @param string $keyCol  key column name
102      * @param array  $keyVals array of key values
103      *
104      * @return get_called_class() object with multiple instances if found,
105      *         Exception is thrown when no entries are found.
106      *
107      */
108     static function listFind($keyCol, array $keyVals)
109     {
110         return parent::listFindClass(get_called_class(), $keyCol, $keyVals);
111     }
112
113     /**
114      * Get a multi-instance object separated into an array
115      *
116      * This is a utility method to get multiple instances with a given set of
117      * values for a specific key column. Usually used for the primary key when
118      * multiple values are desired. Result is an array.
119      *
120      * @param string $keyCol  key column name
121      * @param array  $keyVals array of key values
122      *
123      * @return array with an get_called_class() object for each $keyVals entry
124      *
125      */
126     static function listGet($keyCol, array $keyVals)
127     {
128         return parent::listGetClass(get_called_class(), $keyCol, $keyVals);
129     }
130
131     /**
132      * get/set an associative array of table columns
133      *
134      * @access public
135      * @return array (associative)
136      */
137     public function table()
138     {
139         $table = static::schemaDef();
140         return array_map(array($this, 'columnBitmap'), $table['fields']);
141     }
142
143     /**
144      * get/set an  array of table primary keys
145      *
146      * Key info is pulled from the table definition array.
147      * 
148      * @access private
149      * @return array
150      */
151     function keys()
152     {
153         return array_keys($this->keyTypes());
154     }
155
156     /**
157      * Get a sequence key
158      *
159      * Returns the first serial column defined in the table, if any.
160      *
161      * @access private
162      * @return array (column,use_native,sequence_name)
163      */
164
165     function sequenceKey()
166     {
167         $table = static::schemaDef();
168         foreach ($table['fields'] as $name => $column) {
169             if ($column['type'] == 'serial') {
170                 // We have a serial/autoincrement column.
171                 // Declare it to be a native sequence!
172                 return array($name, true, false);
173             }
174         }
175
176         // No sequence key on this table.
177         return array(false, false, false);
178     }
179
180     /**
181      * Return key definitions for DB_DataObject and Memcache_DataObject.
182      *
183      * DB_DataObject needs to know about keys that the table has; this function
184      * defines them.
185      *
186      * @return array key definitions
187      */
188
189     function keyTypes()
190     {
191         $table = static::schemaDef();
192         $keys = array();
193
194         if (!empty($table['unique keys'])) {
195             foreach ($table['unique keys'] as $idx => $fields) {
196                 foreach ($fields as $name) {
197                     $keys[$name] = 'U';
198                 }
199             }
200         }
201
202         if (!empty($table['primary key'])) {
203             foreach ($table['primary key'] as $name) {
204                 $keys[$name] = 'K';
205             }
206         }
207         return $keys;
208     }
209
210     /**
211      * Build the appropriate DB_DataObject bitfield map for this field.
212      *
213      * @param array $column
214      * @return int
215      */
216     function columnBitmap($column)
217     {
218         $type = $column['type'];
219
220         // For quoting style...
221         $intTypes = array('int',
222                           'integer',
223                           'float',
224                           'serial',
225                           'numeric');
226         if (in_array($type, $intTypes)) {
227             $style = DB_DATAOBJECT_INT;
228         } else {
229             $style = DB_DATAOBJECT_STR;
230         }
231
232         // Data type formatting style...
233         $formatStyles = array('blob' => DB_DATAOBJECT_BLOB,
234                               'text' => DB_DATAOBJECT_TXT,
235                               'date' => DB_DATAOBJECT_DATE,
236                               'time' => DB_DATAOBJECT_TIME,
237                               'datetime' => DB_DATAOBJECT_DATE | DB_DATAOBJECT_TIME,
238                               'timestamp' => DB_DATAOBJECT_MYSQLTIMESTAMP);
239
240         if (isset($formatStyles[$type])) {
241             $style |= $formatStyles[$type];
242         }
243
244         // Nullable?
245         if (!empty($column['not null'])) {
246             $style |= DB_DATAOBJECT_NOTNULL;
247         }
248
249         return $style;
250     }
251
252     function links()
253     {
254         $links = array();
255
256         $table = static::schemaDef();
257
258         foreach ($table['foreign keys'] as $keyname => $keydef) {
259             if (count($keydef) == 2 && is_string($keydef[0]) && is_array($keydef[1]) && count($keydef[1]) == 1) {
260                 if (isset($keydef[1][0])) {
261                     $links[$keydef[1][0]] = $keydef[0].':'.$keydef[1][1];
262                 }
263             }
264         }
265         return $links;
266     }
267
268     /**
269      * Return a list of all primary/unique keys / vals that will be used for
270      * caching. This will understand compound unique keys, which
271      * Memcached_DataObject doesn't have enough info to handle properly.
272      *
273      * @return array of strings
274      */
275     function _allCacheKeys()
276     {
277         $table = static::schemaDef();
278         $ckeys = array();
279
280         if (!empty($table['unique keys'])) {
281             $keyNames = $table['unique keys'];
282             foreach ($keyNames as $idx => $fields) {
283                 $val = array();
284                 foreach ($fields as $name) {
285                     $val[$name] = self::valueString($this->$name);
286                 }
287                 $ckeys[] = self::multicacheKey($this->tableName(), $val);
288             }
289         }
290
291         if (!empty($table['primary key'])) {
292             $fields = $table['primary key'];
293             $val = array();
294             foreach ($fields as $name) {
295                 $val[$name] = self::valueString($this->$name);
296             }
297             $ckeys[] = self::multicacheKey($this->tableName(), $val);
298         }
299         return $ckeys;
300     }
301
302     public function escapedTableName()
303     {
304         return common_database_tablename($this->tableName());
305     }
306
307     /**
308      * Returns an ID, checked that it is set and reasonably valid
309      *
310      * If this dataobject uses a special id field (not 'id'), just
311      * implement your ID getting method in the child class.
312      *
313      * @return int ID of dataobject
314      * @throws Exception (when ID is not available or not set yet)
315      */
316     public function getID()
317     {
318         // FIXME: Make these exceptions more specific (their own classes)
319         if (!isset($this->id)) {
320             throw new Exception('No ID set.');
321         } elseif (empty($this->id)) {
322             throw new Exception('Empty ID for object! (not inserted yet?).');
323         }
324
325         // FIXME: How about forcing to return an int? Or will that overflow eventually?
326         return $this->id;
327     }
328
329     // 'update' won't write key columns, so we have to do it ourselves.
330     // This also automatically calls "update" _before_ it sets the keys.
331     // FIXME: This only works with single-column primary keys so far! Beware!
332     /**
333      * @param DB_DataObject &$orig  Must be "instanceof" $this
334      * @param string         $pid   Primary ID column (no escaping is done on column name!)
335      */
336     public function updateWithKeys(&$orig, $pid='id')
337     {
338         if (!$orig instanceof $this) {
339             throw new ServerException('Tried updating a DataObject with a different class than itself.');
340         }
341
342         // do it in a transaction
343         $this->query('BEGIN');
344
345         $parts = array();
346         foreach ($this->keys() as $k) {
347             if (strcmp($this->$k, $orig->$k) != 0) {
348                 $parts[] = $k . ' = ' . $this->_quote($this->$k);
349             }
350         }
351         if (count($parts) == 0) {
352             // No changes to keys, it's safe to run ->update(...)
353             if ($this->update($orig) === false) {
354                 common_log_db_error($this, 'UPDATE', __FILE__);
355                 // rollback as something bad occurred
356                 $this->query('ROLLBACK');
357                 throw new ServerException("Could not UPDATE non-keys for {$this->__table}");
358             }
359             $orig->decache();
360             $this->encache();
361
362             // commit our db transaction since we won't reach the COMMIT below
363             $this->query('COMMIT');
364             // @FIXME return true only if something changed (otherwise 0)
365             return true;
366         }
367
368         $qry = sprintf('UPDATE %1$s SET %2$s WHERE %3$s = %4$s',
369                             common_database_tablename($this->tableName()),
370                             implode(', ', $parts),
371                             $pid,
372                             $this->_quote($this->$pid));
373
374         $result = $this->query($qry);
375         if ($result === false) {
376             common_log_db_error($this, 'UPDATE', __FILE__);
377             // rollback as something bad occurred
378             $this->query('ROLLBACK');
379             throw new ServerException("Could not UPDATE key fields for {$this->__table}");
380         }
381
382         // Update non-keys too, if the previous endeavour worked.
383         // The ->update call uses "$this" values for keys, that's why we can't do this until
384         // the keys are updated (because they might differ from $orig and update the wrong entries).
385         if ($this->update($orig) === false) {
386             common_log_db_error($this, 'UPDATE', __FILE__);
387             // rollback as something bad occurred
388             $this->query('ROLLBACK');
389             throw new ServerException("Could not UPDATE non-keys for {$this->__table}");
390         }
391         $orig->decache();
392         $this->encache();
393
394         // commit our db transaction
395         $this->query('COMMIT');
396         // @FIXME return true only if something changed (otherwise 0)
397         return $result;
398     }
399
400     static public function beforeSchemaUpdate()
401     {
402         // NOOP
403     }
404 }