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

Last change on this file since 159 was 159, checked in by scdev, 18 years ago

${1}

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