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

Last change on this file since 532 was 532, checked in by anonymous, 9 years ago

Added common config for codebase cli scripts. Changed behavior of db_auth.json loading. validSignature() now fails on empty string.

File size: 19.9 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
42    // A place to keep an object instance for the singleton pattern.
43    protected static $instance = null;
44
45    // Configuration of this object.
46    protected $_params = array(
47        'max_qty' => 100, // Never have more than this many versions of each record.
48        'min_qty' => 25, // Keep at least this many versions of each record.
49        'min_days' => 7, // Keep ALL versions within this many days, even if MORE than min_qty.
50        'db_table' => 'version_tbl',
51
52        // Automatically create table and verify columns. Better set to false after site launch.
53        // This value is overwritten by the $app->getParam('db_create_tables') setting if it is available.
54        'create_table' => true,
55
56        // If true, makes an exact comparison of saved vs. live table schemas. If false, just checks that the saved columns are available.
57        'db_schema_strict' => true,
58    );
59
60    // Auth_SQL object from which to access a current user_id.
61    protected $_auth;
62
63    /**
64     * This method enforces the singleton pattern for this class.
65     *
66     * @return  object  Reference to the global Lock object.
67     * @access  public
68     * @static
69     */
70    public static function &getInstance($auth_object=null)
71    {
72        if (self::$instance === null) {
73            self::$instance = new self($auth_object);
74        }
75
76        return self::$instance;
77    }
78
79    /**
80     * Constructor. Pass an Auth object on which to perform user lookups.
81     *
82     * @param mixed  $auth_object  An Auth_SQL object.
83     */
84    public function __construct($auth_object=null)
85    {
86        $app =& App::getInstance();
87
88        if (!is_null($auth_object) || is_null($this->_auth)) {
89            if (!method_exists($auth_object, 'get') || !method_exists($auth_object, 'getUsername')) {
90                trigger_error('Constructor not provided a valid Auth_* object.', E_USER_ERROR);
91            }
92
93            $this->_auth = $auth_object;
94        }
95
96        // Get create tables config from global context.
97        if (!is_null($app->getParam('db_create_tables'))) {
98            $this->setParam(array('create_table' => $app->getParam('db_create_tables')));
99        }
100    }
101
102    /**
103     * Setup the database table for this class.
104     *
105     * @access  public
106     * @author  Quinn Comendant <quinn@strangecode.com>
107     * @since   26 Aug 2005 17:09:36
108     */
109    public function initDB($recreate_db=false)
110    {
111        $app =& App::getInstance();
112        $db =& DB::getInstance();
113
114        static $_db_tested = false;
115
116        if ($recreate_db || !$_db_tested && $this->getParam('create_table')) {
117            if ($recreate_db) {
118                $db->query("DROP TABLE IF EXISTS " . $this->getParam('db_table'));
119                $app->logMsg(sprintf('Dropping and recreating table %s.', $this->getParam('db_table')), LOG_INFO, __FILE__, __LINE__);
120            }
121            $db->query("CREATE TABLE IF NOT EXISTS " . $db->escapeString($this->getParam('db_table')) . " (
122                version_id INT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
123                record_table VARCHAR(255) NOT NULL DEFAULT '',
124                record_key VARCHAR(255) NOT NULL DEFAULT '',
125                record_val VARCHAR(255) NOT NULL DEFAULT '',
126                version_data MEDIUMBLOB NOT NULL,
127                version_title VARCHAR(255) NOT NULL DEFAULT '',
128                version_number SMALLINT(11) UNSIGNED NOT NULL DEFAULT '0',
129                version_notes VARCHAR(255) NOT NULL DEFAULT '',
130                saved_by_user_id SMALLINT(11) NOT NULL DEFAULT '0',
131                version_datetime DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
132                KEY record_table (record_table),
133                KEY record_key (record_key),
134                KEY record_val (record_val)
135            )");
136
137            if (!$db->columnExists($this->getParam('db_table'), array(
138                'version_id',
139                'record_table',
140                'record_key',
141                'record_val',
142                'version_data',
143                'version_title',
144                'version_number',
145                'version_notes',
146                'saved_by_user_id',
147                'version_datetime',
148            ), false, false)) {
149                $app->logMsg(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_table')), LOG_ALERT, __FILE__, __LINE__);
150                trigger_error(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_table')), E_USER_ERROR);
151            }
152        }
153        $_db_tested = true;
154    }
155
156    /**
157     * Set the params of this object.
158     *
159     * @param  array $params   Array of param keys and values to set.
160     */
161    public function setParam($params=null)
162    {
163        if (isset($params) && is_array($params)) {
164            // Merge new parameters with old overriding only those passed.
165            $this->_params = array_merge($this->_params, $params);
166        }
167    }
168
169    /**
170     * Return the value of a parameter, if it exists.
171     *
172     * @access public
173     * @param string $param        Which parameter to return.
174     * @return mixed               Configured parameter value.
175     */
176    public function getParam($param)
177    {
178        $app =& App::getInstance();
179
180        if (array_key_exists($param, $this->_params)) {
181            return $this->_params[$param];
182        } else {
183            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
184            return null;
185        }
186    }
187
188    /**
189     * Saves a version of the current record into the version table.
190     *
191     * @param string $record_table  The table containing the record.
192     * @param string $record_key    The key column for the record.
193     * @param string $record_val    The value of the key column for the record.
194     * @param string $title         The title of this record. Only used for human presentation.
195     *
196     * @return int                  The id for the version (mysql last insert id).
197     */
198    public function create($record_table, $record_key, $record_val, $title='', $notes='')
199    {
200        $app =& App::getInstance();
201        $db =& DB::getInstance();
202
203        $this->initDB();
204
205        // Get current record.
206        if (!$record = $this->getCurrent($record_table, $record_key, $record_val)) {
207            $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__);
208            return false;
209        }
210
211        // Get previous version_number.
212        $qid = $db->query("
213            SELECT MAX(version_number) FROM " . $db->escapeString($this->getParam('db_table')) . "
214            WHERE record_table = '" . $db->escapeString($record_table) . "'
215            AND record_key = '" . $db->escapeString($record_key) . "'
216            AND record_val = '" . $db->escapeString($record_val) . "'
217        ");
218        list($last_version_number) = mysql_fetch_row($qid);
219
220        // Clean-up old versions.
221        $this->deleteOld($record_table, $record_key, $record_val);
222
223        // Save as new version.
224        // TODO: after MySQL 5.0.23 is released this query could benefit from INSERT DELAYED.
225        $db->query("
226            INSERT INTO " . $db->escapeString($this->getParam('db_table')) . " (
227                record_table,
228                record_key,
229                record_val,
230                version_data,
231                version_title,
232                version_number,
233                version_notes,
234                saved_by_user_id,
235                version_datetime
236            ) VALUES (
237                '" . $db->escapeString($record_table) . "',
238                '" . $db->escapeString($record_key) . "',
239                '" . $db->escapeString($record_val) . "',
240                '" . $db->escapeString(gzcompress(serialize($record), 9)) . "',
241                '" . $db->escapeString($title) . "',
242                '" . $db->escapeString($last_version_number + 1) . "',
243                '" . $db->escapeString($notes) . "',
244                '" . $db->escapeString($this->_auth->get('user_id')) . "',
245                NOW()
246            )
247        ");
248
249        return mysql_insert_id($db->getDBH());
250    }
251
252    /**
253     * Copy a version back into it's original table.
254     *
255     * @param string $version_id    The id of the version to restore.
256     *
257     * @return int                  The id for the version (mysql last insert id).
258     */
259    public function restore($version_id)
260    {
261        $app =& App::getInstance();
262        $db =& DB::getInstance();
263
264        $this->initDB();
265
266        // Get version data.
267        $qid = $db->query("
268            SELECT * FROM " . $db->escapeString($this->getParam('db_table')) . "
269            WHERE version_id = '" . $db->escapeString($version_id) . "'
270        ");
271        if (!$record = mysql_fetch_assoc($qid)) {
272            $app->raiseMsg(sprintf(_("Version %s%s not found."), $version_id, (empty($record['version_title']) ? '' : ' (' . $record['version_title'] . ')')), MSG_WARNING, __FILE__, __LINE__);
273            $app->logMsg(sprintf('Version %s%s not found.', $version_id, (empty($record['version_title']) ? '' : ' (' . $record['version_title'] . ')')), LOG_WARNING, __FILE__, __LINE__);
274            return false;
275        }
276        $data = unserialize(gzuncompress($record['version_data']));
277
278        // Ensure saved db columns match current table schema.
279        if (!$db->columnExists($record['record_table'], array_keys($data), $this->getParam('db_schema_strict'))) {
280            $app->raiseMsg(sprintf(_("Version %s%s is not compatible with the current database table."), $version_id, (empty($record['version_title']) ? '' : ' (' . $record['version_title'] . ')')), MSG_ERR, __FILE__, __LINE__);
281            $app->logMsg(sprintf('Version %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__);
282            return false;
283        }
284
285        // SQLize the keys of the specified versioned record.
286        $replace_keys = join(",\n", array_map(array($db, 'escapeString'), array_keys($data)));
287
288        // SQLize the keys of the values of the specified versioned record. (These are more complex because we need to account for SQL null values.)
289        $replace_values = '';
290        $comma = '';
291        foreach ($data as $v) {
292            $replace_values .= is_null($v) ? "$comma\nNULL" : "$comma\n'" . $db->escapeString($v) . "'";
293            $comma = ',';
294        }
295
296        // Disable foreign_key_checks to prevent ON DELETE triggers or restrictions.
297        $db->query("SET SESSION foreign_key_checks = 0");
298        // Replace current record with specified versioned record. Consider converting this SQL to use INSERT 
 ON DUPLICATE KEY UPDATE 

299        $db->query("
300        REPLACE INTO " . $record['record_table'] . " (
301                $replace_keys
302            ) VALUES (
303                $replace_values
304            );
305        ");
306        // Re-enable foreign_key_checks.
307        $db->query("SET SESSION foreign_key_checks = 1");
308
309        return $record;
310    }
311
312    /**
313     * Version garbage collection. Deletes versions older than min_days
314     * when quantity of versions exceeds min_qty. If quantity
315     * exceeds 100 within min_days, the oldest are deleted to bring the
316     * quantity back down to min_qty.
317     *
318     * @param string $record_table  The table containing the record.
319     * @param string $record_key    The key column for the record.
320     * @param string $record_val    The value of the key column for the record.
321     *
322     * @return mixed                Array of versions, or false if none.
323     */
324    public function deleteOld($record_table, $record_key, $record_val)
325    {
326        $db =& DB::getInstance();
327
328        $this->initDB();
329
330        // Get total number of versions for this record.
331        $qid = $db->query("
332            SELECT COUNT(*) FROM " . $db->escapeString($this->getParam('db_table')) . "
333            WHERE record_table = '" . $db->escapeString($record_table) . "'
334            AND record_key = '" . $db->escapeString($record_key) . "'
335            AND record_val = '" . $db->escapeString($record_val) . "'
336        ");
337        list($v_count) = mysql_fetch_row($qid);
338
339        if ($v_count > $this->getParam('min_qty')) {
340            if ($v_count > $this->getParam('max_qty')) {
341                // To prevent a record bomb, limit max number of versions to max_qty.
342                // First query for oldest records, selecting enough to bring total number down to min_qty.
343                $qid = $db->query("
344                    SELECT version_id FROM " . $db->escapeString($this->getParam('db_table')) . "
345                    WHERE record_table = '" . $db->escapeString($record_table) . "'
346                    AND record_key = '" . $db->escapeString($record_key) . "'
347                    AND record_val = '" . $db->escapeString($record_val) . "'
348                    ORDER BY version_datetime ASC
349                    LIMIT " . ($v_count - $this->getParam('min_qty')) . "
350                ");
351                while (list($old_id) = mysql_fetch_row($qid)) {
352                    $old_versions[] = $old_id;
353                }
354                $db->query("
355                    DELETE FROM " . $db->escapeString($this->getParam('db_table')) . "
356                    WHERE version_id IN ('" . join("','", $old_versions) . "')
357                ");
358            } else {
359                // Delete versions older than min_days, while still keeping min_qty.
360                $qid = $db->query("
361                    SELECT version_id FROM " . $db->escapeString($this->getParam('db_table')) . "
362                    WHERE record_table = '" . $db->escapeString($record_table) . "'
363                    AND record_key = '" . $db->escapeString($record_key) . "'
364                    AND record_val = '" . $db->escapeString($record_val) . "'
365                    AND DATE_ADD(version_datetime, INTERVAL '" . $this->getParam('min_days') . "' DAY) < NOW()
366                    ORDER BY version_datetime ASC
367                    LIMIT " . ($v_count - $this->getParam('min_qty')) . "
368                ");
369                while (list($old_id) = mysql_fetch_row($qid)) {
370                    $old_versions[] = $old_id;
371                }
372                if (sizeof($old_versions) > 0) {
373                    $db->query("
374                        DELETE FROM " . $db->escapeString($this->getParam('db_table')) . "
375                        WHERE version_id IN ('" . join("','", $old_versions) . "')
376                    ");
377                }
378            }
379        }
380    }
381
382    /**
383     * Get a list of versions of specified record.
384     *
385     * @param string $record_table  The table containing the record.
386     * @param string $record_key    The key column for the record.
387     * @param string $record_val    The value of the key column for the record.
388     *
389     * @return mixed                Array of versions, or false if none.
390     */
391    public function getList($record_table, $record_key, $record_val)
392    {
393        $db =& DB::getInstance();
394
395        $this->initDB();
396
397        // Get versions of this record.
398        $qid = $db->query("
399            SELECT
400                version_id,
401                saved_by_user_id,
402                version_datetime,
403                version_title,
404                version_number,
405                version_notes
406            FROM " . $db->escapeString($this->getParam('db_table')) . "
407            WHERE record_table = '" . $db->escapeString($record_table) . "'
408            AND record_key = '" . $db->escapeString($record_key) . "'
409            AND record_val = '" . $db->escapeString($record_val) . "'
410            ORDER BY version_datetime DESC
411        ");
412        $versions = array();
413        while ($row = mysql_fetch_assoc($qid)) {
414            // Get admin usernames.
415            $row['editor'] = $this->_auth->getUsername($row['saved_by_user_id']);
416            $versions[] = $row;
417        }
418        return $versions;
419    }
420
421    /**
422     * Get the version record for a specified version id.
423     *
424     * @param string $version_id    The id of the version to restore.
425     *
426     * @return mixed                Array of data saved in version, or false if none.
427     */
428    public function getVerson($version_id)
429    {
430        $db =& DB::getInstance();
431
432        $this->initDB();
433
434        // Get version data.
435        $qid = $db->query("
436            SELECT * FROM " . $db->escapeString($this->getParam('db_table')) . "
437            WHERE version_id = '" . $db->escapeString($version_id) . "'
438        ");
439        return mysql_fetch_assoc($qid);
440    }
441
442    /**
443     * Get the data stored for a specified version id.
444     *
445     * @param string $version_id    The id of the version to restore.
446     *
447     * @return mixed                Array of data saved in version, or false if none.
448     */
449    public function getData($version_id)
450    {
451        $db =& DB::getInstance();
452
453        $this->initDB();
454
455        // Get version data.
456        $qid = $db->query("
457            SELECT * FROM " . $db->escapeString($this->getParam('db_table')) . "
458            WHERE version_id = '" . $db->escapeString($version_id) . "'
459        ");
460        $record = mysql_fetch_assoc($qid);
461        if (isset($record['version_data'])) {
462            return unserialize(gzuncompress($record['version_data']));
463        } else {
464            return false;
465        }
466    }
467
468    /**
469     * Get the current record data from the original table.
470     *
471     * @param string $version_id    The id of the version to restore.
472     *
473     * @return mixed                Array of data saved in version, or false if none.
474     */
475    public function getCurrent($record_table, $record_key, $record_val)
476    {
477        $db =& DB::getInstance();
478        $app =& App::getInstance();
479
480        $this->initDB();
481
482        if (!$record_table || !$record_key || !$record_val) {
483            $app->logMsg(sprintf('Invalid current version args: %s, %s, %s.', $record_table, $record_key, $record_val), LOG_ERR, __FILE__, __LINE__);
484            return false;
485        }
486
487        $qid = $db->query("
488            SELECT * FROM " . $db->escapeString($record_table) . "
489            WHERE " . $db->escapeString($record_key) . " = '" . $db->escapeString($record_val) . "'
490        ");
491        if ($record = mysql_fetch_assoc($qid)) {
492            return $record;
493        } else {
494            return false;
495        }
496    }
497
498
499} // End of class.
Note: See TracBrowser for help on using the repository browser.