source: trunk/lib/Version.inc.php @ 468

Last change on this file since 468 was 468, checked in by anonymous, 10 years ago

Completed integrating /branches/eli_branch into /trunk. Changes include:

  • Removed closing ?> from end of files
  • Upgrade old-style contructor methods to use construct() instead.
  • Class properties and methods defined as public, private, static or protected
  • Ensure code runs under E_ALL with only mysql_* deprecated warnings
  • Search for the '@' symbol anywhere it might be used to supress runtime errors, then replace with proper error recovery.
  • Run the php cli -l option to check files for syntax errors.
  • Bring tests up-to-date with latest version and methods of PHPUnit
File size: 19.1 KB
Line 
1<?php
2/**
3 * The Strangecode Codebase - a general application development framework for PHP
4 * For details visit the project site: <http://trac.strangecode.com/codebase/>
5 * Copyright 2001-2012 Strangecode, LLC
6 *
7 * This file is part of The Strangecode Codebase.
8 *
9 * The Strangecode Codebase is free software: you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License as published by the
11 * Free Software Foundation, either version 3 of the License, or (at your option)
12 * any later version.
13 *
14 * The Strangecode Codebase is distributed in the hope that it will be useful, but
15 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * details.
18 *
19 * You should have received a copy of the GNU General Public License along with
20 * The Strangecode Codebase. If not, see <http://www.gnu.org/licenses/>.
21 */
22
23/**
24 * Version.inc.php
25 *
26 * The Version class provides a system for saving, reviewing, and
27 * restoring versions of a record of any DB table. All the data in the record is
28 * serialized, compressed, and saved in a blob in the version_tbl. Restoring a
29 * version simply does a REPLACE INTO of the data. It is very simple, and works
30 * with multiple database tables, but the drawback is that relationships for
31 * a record cannot be retained. For example, an article from an article_tbl can
32 * be saved, but not categories associated to the record in a category_article_tbl.
33 * The restored article will simple retain the relationships that the previous
34 * current article had.
35 *
36 * @author  Quinn Comendant <quinn@strangecode.com>
37 * @version 2.1
38 */
39class Version {
40
41    // A place to keep an object instance for the singleton pattern.
42    private static $instance = null;
43
44    // Configuration of this object.
45    private $_params = array(
46        'max_qty' => 100, // Never have more than this many versions of each record.
47        'min_qty' => 25, // Keep at least this many versions of each record.
48        'min_days' => 7, // Keep ALL versions within this many days, even if MORE than min_qty.
49        'db_table' => 'version_tbl',
50
51        // Automatically create table and verify columns. Better set to false after site launch.
52        // This value is overwritten by the $app->getParam('db_create_tables') setting if it is available.
53        'create_table' => true,
54        // If true, makes an exact comparison of saved vs. live table schemas. If false, just checks that the saved columns are available.
55        'db_schema_strict' => true,
56    );
57
58    // Auth_SQL object from which to access a current user_id.
59    private $_auth;
60
61    /**
62     * This method enforces the singleton pattern for this class.
63     *
64     * @return  object  Reference to the global Lock object.
65     * @access  public
66     * @static
67     */
68    public static function &getInstance($auth_object)
69    {
70        if (self::$instance === null) {
71            self::$instance = new self($auth_object);
72        }
73
74        return self::$instance;
75    }
76
77    /**
78     * Constructor. Pass an Auth object on which to perform user lookups.
79     *
80     * @param mixed  $auth_object  An Auth_SQL object.
81     */
82    public function __construct($auth_object)
83    {
84        $app =& App::getInstance();
85
86        if (!method_exists($auth_object, 'get') || !method_exists($auth_object, 'getUsername')) {
87            trigger_error('Constructor not provided a valid Auth_* object.', E_USER_ERROR);
88        }
89
90        $this->_auth = $auth_object;
91
92        // Get create tables config from global context.
93        if (!is_null($app->getParam('db_create_tables'))) {
94            $this->setParam(array('create_table' => $app->getParam('db_create_tables')));
95        }
96    }
97
98    /**
99     * Setup the database table for this class.
100     *
101     * @access  public
102     * @author  Quinn Comendant <quinn@strangecode.com>
103     * @since   26 Aug 2005 17:09:36
104     */
105    public function initDB($recreate_db=false)
106    {
107        $app =& App::getInstance();
108        $db =& DB::getInstance();
109
110        static $_db_tested = false;
111
112        if ($recreate_db || !$_db_tested && $this->getParam('create_table')) {
113            if ($recreate_db) {
114                $db->query("DROP TABLE IF EXISTS " . $this->getParam('db_table'));
115                $app->logMsg(sprintf('Dropping and recreating table %s.', $this->getParam('db_table')), LOG_INFO, __FILE__, __LINE__);
116            }
117            $db->query("CREATE TABLE IF NOT EXISTS " . $db->escapeString($this->getParam('db_table')) . " (
118                version_id INT NOT NULL AUTO_INCREMENT,
119                record_table VARCHAR(255) NOT NULL DEFAULT '',
120                record_key VARCHAR(255) NOT NULL DEFAULT '',
121                record_val VARCHAR(255) NOT NULL DEFAULT '',
122                version_data MEDIUMBLOB NOT NULL,
123                version_title VARCHAR(255) NOT NULL DEFAULT '',
124                version_number SMALLINT(11) UNSIGNED NOT NULL DEFAULT '0',
125                version_notes VARCHAR(255) NOT NULL DEFAULT '',
126                saved_by_user_id SMALLINT(11) NOT NULL DEFAULT '0',
127                version_datetime DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
128                PRIMARY KEY (version_id),
129                KEY record_table (record_table),
130                KEY record_key (record_key),
131                KEY record_val (record_val)
132            )");
133
134            if (!$db->columnExists($this->getParam('db_table'), array(
135                'version_id',
136                'record_table',
137                'record_key',
138                'record_val',
139                'version_data',
140                'version_title',
141                'version_number',
142                'version_notes',
143                'saved_by_user_id',
144                'version_datetime',
145            ), false, false)) {
146                $app->logMsg(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_table')), LOG_ALERT, __FILE__, __LINE__);
147                trigger_error(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_table')), E_USER_ERROR);
148            }
149        }
150        $_db_tested = true;
151    }
152
153    /**
154     * Set the params of this object.
155     *
156     * @param  array $params   Array of param keys and values to set.
157     */
158    public function setParam($params=null)
159    {
160        if (isset($params) && is_array($params)) {
161            // Merge new parameters with old overriding only those passed.
162            $this->_params = array_merge($this->_params, $params);
163        }
164    }
165
166    /**
167     * Return the value of a parameter, if it exists.
168     *
169     * @access public
170     * @param string $param        Which parameter to return.
171     * @return mixed               Configured parameter value.
172     */
173    public function getParam($param)
174    {
175        $app =& App::getInstance();
176
177        if (isset($this->_params[$param])) {
178            return $this->_params[$param];
179        } else {
180            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
181            return null;
182        }
183    }
184
185    /**
186     * Saves a version of the current record into the version table.
187     *
188     * @param string $record_table  The table containing the record.
189     * @param string $record_key    The key column for the record.
190     * @param string $record_val    The value of the key column for the record.
191     * @param string $title         The title of this record. Only used for human presentation.
192     *
193     * @return int                  The id for the version (mysql last insert id).
194     */
195    public function create($record_table, $record_key, $record_val, $title='', $notes='')
196    {
197        $app =& App::getInstance();
198        $db =& DB::getInstance();
199
200        $this->initDB();
201
202        // Get current record.
203        if (!$record = $this->getCurrent($record_table, $record_key, $record_val)) {
204            $app->logMsg(sprintf('Could not create %s version, record not found: %s, %s, %s.', $title, $record_table, $record_key, $record_val), LOG_ERR, __FILE__, __LINE__);
205            return false;
206        }
207
208        // Get previous version_number.
209        $qid = $db->query("
210            SELECT MAX(version_number) FROM " . $db->escapeString($this->getParam('db_table')) . "
211            WHERE record_table = '" . $db->escapeString($record_table) . "'
212            AND record_key = '" . $db->escapeString($record_key) . "'
213            AND record_val = '" . $db->escapeString($record_val) . "'
214        ");
215        list($last_version_number) = mysql_fetch_row($qid);
216
217        // Clean-up old versions.
218        $this->deleteOld($record_table, $record_key, $record_val);
219
220        // Save as new version.
221        // TODO: after MySQL 5.0.23 is released this query could benefit from INSERT DELAYED.
222        $db->query("
223            INSERT INTO " . $db->escapeString($this->getParam('db_table')) . " (
224                record_table,
225                record_key,
226                record_val,
227                version_data,
228                version_title,
229                version_number,
230                version_notes,
231                saved_by_user_id,
232                version_datetime
233            ) VALUES (
234                '" . $db->escapeString($record_table) . "',
235                '" . $db->escapeString($record_key) . "',
236                '" . $db->escapeString($record_val) . "',
237                '" . $db->escapeString(gzcompress(serialize($record), 9)) . "',
238                '" . $db->escapeString($title) . "',
239                '" . $db->escapeString($last_version_number + 1) . "',
240                '" . $db->escapeString($notes) . "',
241                '" . $db->escapeString($this->_auth->get('user_id')) . "',
242                NOW()
243            )
244        ");
245
246        return mysql_insert_id($db->getDBH());
247    }
248
249    /**
250     * Copy a version back into it's original table.
251     *
252     * @param string $version_id    The id of the version to restore.
253     *
254     * @return int                  The id for the version (mysql last insert id).
255     */
256    public function restore($version_id)
257    {
258        $app =& App::getInstance();
259        $db =& DB::getInstance();
260
261        $this->initDB();
262
263        // Get version data.
264        $qid = $db->query("
265            SELECT * FROM " . $db->escapeString($this->getParam('db_table')) . "
266            WHERE version_id = '" . $db->escapeString($version_id) . "'
267        ");
268        if (!$record = mysql_fetch_assoc($qid)) {
269            $app->raiseMsg(sprintf(_("Version ID %s%s not found."), $version_id, (empty($record['version_title']) ? '' : ' (' . $record['version_title'] . ')')), MSG_WARNING, __FILE__, __LINE__);
270            $app->logMsg(sprintf('Version ID %s%s not found.', $version_id, (empty($record['version_title']) ? '' : ' (' . $record['version_title'] . ')')), LOG_WARNING, __FILE__, __LINE__);
271            return false;
272        }
273        $data = unserialize(gzuncompress($record['version_data']));
274
275        // Ensure saved db columns match current table schema.
276        if (!$db->columnExists($record['record_table'], array_keys($data), $this->getParam('db_schema_strict'))) {
277            $app->raiseMsg(sprintf(_("Version ID %s%s is not compatible with the current database table."), $version_id, (empty($record['version_title']) ? '' : ' (' . $record['version_title'] . ')')), MSG_ERR, __FILE__, __LINE__);
278            $app->logMsg(sprintf('Version ID %s%s restoration failed, DB schema does not match for table %s.', $version_id, (empty($record['version_title']) ? '' : ' (' . $record['version_title'] . ')'), $record['record_table']), LOG_ALERT, __FILE__, __LINE__);
279            return false;
280        }
281
282        // SQLize the keys of the specified versioned record.
283        $replace_keys = join(",\n", array_map(array($db, 'escapeString'), array_keys($data)));
284
285        // SQLize the keys of the values of the specified versioned record. (These are more complex because we need to account for SQL null values.)
286        $replace_values = '';
287        $comma = '';
288        foreach ($data as $v) {
289            $replace_values .= is_null($v) ? "$comma\nNULL" : "$comma\n'" . $db->escapeString($v) . "'";
290            $comma = ',';
291        }
292
293        // Replace current record with specified versioned record.
294        $db->query("
295            REPLACE INTO " . $record['record_table'] . " (
296                $replace_keys
297            ) VALUES (
298                $replace_values
299            )
300        ");
301
302        return $record;
303    }
304
305    /**
306     * Version garbage collection. Deletes versions older than min_days
307     * when quantity of versions exceeds min_qty. If quantity
308     * exceeds 100 within min_days, the oldest are deleted to bring the
309     * quantity back down to min_qty.
310     *
311     * @param string $record_table  The table containing the record.
312     * @param string $record_key    The key column for the record.
313     * @param string $record_val    The value of the key column for the record.
314     *
315     * @return mixed                Array of versions, or false if none.
316     */
317    public function deleteOld($record_table, $record_key, $record_val)
318    {
319        $db =& DB::getInstance();
320
321        $this->initDB();
322
323        // Get total number of versions for this record.
324        $qid = $db->query("
325            SELECT COUNT(*) FROM " . $db->escapeString($this->getParam('db_table')) . "
326            WHERE record_table = '" . $db->escapeString($record_table) . "'
327            AND record_key = '" . $db->escapeString($record_key) . "'
328            AND record_val = '" . $db->escapeString($record_val) . "'
329        ");
330        list($v_count) = mysql_fetch_row($qid);
331
332        if ($v_count > $this->getParam('min_qty')) {
333            if ($v_count > $this->getParam('max_qty')) {
334                // To prevent a record bomb, limit max number of versions to max_qty.
335                // First query for oldest records, selecting enough to bring total number down to min_qty.
336                $qid = $db->query("
337                    SELECT version_id FROM " . $db->escapeString($this->getParam('db_table')) . "
338                    WHERE record_table = '" . $db->escapeString($record_table) . "'
339                    AND record_key = '" . $db->escapeString($record_key) . "'
340                    AND record_val = '" . $db->escapeString($record_val) . "'
341                    ORDER BY version_datetime ASC
342                    LIMIT " . ($v_count - $this->getParam('min_qty')) . "
343                ");
344                while (list($old_id) = mysql_fetch_row($qid)) {
345                    $old_versions[] = $old_id;
346                }
347                $db->query("
348                    DELETE FROM " . $db->escapeString($this->getParam('db_table')) . "
349                    WHERE version_id IN ('" . join("','", $old_versions) . "')
350                ");
351            } else {
352                // Delete versions older than min_days, while still keeping min_qty.
353                $qid = $db->query("
354                    SELECT version_id FROM " . $db->escapeString($this->getParam('db_table')) . "
355                    WHERE record_table = '" . $db->escapeString($record_table) . "'
356                    AND record_key = '" . $db->escapeString($record_key) . "'
357                    AND record_val = '" . $db->escapeString($record_val) . "'
358                    AND DATE_ADD(version_datetime, INTERVAL '" . $this->getParam('min_days') . "' DAY) < NOW()
359                    ORDER BY version_datetime ASC
360                    LIMIT " . ($v_count - $this->getParam('min_qty')) . "
361                ");
362                while (list($old_id) = mysql_fetch_row($qid)) {
363                    $old_versions[] = $old_id;
364                }
365                if (sizeof($old_versions) > 0) {
366                    $db->query("
367                        DELETE FROM " . $db->escapeString($this->getParam('db_table')) . "
368                        WHERE version_id IN ('" . join("','", $old_versions) . "')
369                    ");
370                }
371            }
372        }
373    }
374
375    /**
376     * Get a list of versions of specified record.
377     *
378     * @param string $record_table  The table containing the record.
379     * @param string $record_key    The key column for the record.
380     * @param string $record_val    The value of the key column for the record.
381     *
382     * @return mixed                Array of versions, or false if none.
383     */
384    public function getList($record_table, $record_key, $record_val)
385    {
386        $db =& DB::getInstance();
387
388        $this->initDB();
389
390        // Get versions of this record.
391        $qid = $db->query("
392            SELECT
393                version_id,
394                saved_by_user_id,
395                version_datetime,
396                version_title,
397                version_number,
398                version_notes
399            FROM " . $db->escapeString($this->getParam('db_table')) . "
400            WHERE record_table = '" . $db->escapeString($record_table) . "'
401            AND record_key = '" . $db->escapeString($record_key) . "'
402            AND record_val = '" . $db->escapeString($record_val) . "'
403            ORDER BY version_datetime DESC
404        ");
405        $versions = array();
406        while ($row = mysql_fetch_assoc($qid)) {
407            // Get admin usernames.
408            $row['editor'] = $this->_auth->getUsername($row['saved_by_user_id']);
409            $versions[] = $row;
410        }
411        return $versions;
412    }
413
414    /**
415     * Get the version record for a specified version id.
416     *
417     * @param string $version_id    The id of the version to restore.
418     *
419     * @return mixed                Array of data saved in version, or false if none.
420     */
421    public function getVerson($version_id)
422    {
423        $db =& DB::getInstance();
424
425        $this->initDB();
426
427        // Get version data.
428        $qid = $db->query("
429            SELECT * FROM " . $db->escapeString($this->getParam('db_table')) . "
430            WHERE version_id = '" . $db->escapeString($version_id) . "'
431        ");
432        return mysql_fetch_assoc($qid);
433    }
434
435    /**
436     * Get the data stored for a specified version id.
437     *
438     * @param string $version_id    The id of the version to restore.
439     *
440     * @return mixed                Array of data saved in version, or false if none.
441     */
442    public function getData($version_id)
443    {
444        $db =& DB::getInstance();
445
446        $this->initDB();
447
448        // Get version data.
449        $qid = $db->query("
450            SELECT * FROM " . $db->escapeString($this->getParam('db_table')) . "
451            WHERE version_id = '" . $db->escapeString($version_id) . "'
452        ");
453        $record = mysql_fetch_assoc($qid);
454        if (isset($record['version_data'])) {
455            return unserialize(gzuncompress($record['version_data']));
456        } else {
457            return false;
458        }
459    }
460
461    /**
462     * Get the current record data from the original table.
463     *
464     * @param string $version_id    The id of the version to restore.
465     *
466     * @return mixed                Array of data saved in version, or false if none.
467     */
468    public function getCurrent($record_table, $record_key, $record_val)
469    {
470        $db =& DB::getInstance();
471
472        $this->initDB();
473
474        $qid = $db->query("
475            SELECT * FROM " . $db->escapeString($record_table) . "
476            WHERE " . $db->escapeString($record_key) . " = '" . $db->escapeString($record_val) . "'
477        ");
478        if ($record = mysql_fetch_assoc($qid)) {
479            return $record;
480        } else {
481            return false;
482        }
483    }
484
485
486} // End of class.
Note: See TracBrowser for help on using the repository browser.