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

Last change on this file since 726 was 637, checked in by anonymous, 6 years ago

Add version remove methods

File size: 23.1 KB
RevLine 
[1]1<?php
2/**
[362]3 * The Strangecode Codebase - a general application development framework for PHP
4 * For details visit the project site: <http://trac.strangecode.com/codebase/>
[396]5 * Copyright 2001-2012 Strangecode, LLC
[468]6 *
[362]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.
[468]13 *
[362]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.
[468]18 *
[362]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/**
[137]24 * Version.inc.php
[136]25 *
[137]26 * The Version class provides a system for saving, reviewing, and
[1]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
[42]31 * a record cannot be retained. For example, an article from an article_tbl can
[1]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 */
[502]39class Version
40{
[1]41
[468]42    // A place to keep an object instance for the singleton pattern.
[484]43    protected static $instance = null;
[468]44
[1]45    // Configuration of this object.
[484]46    protected $_params = array(
[1]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',
[468]51
[146]52        // Automatically create table and verify columns. Better set to false after site launch.
[396]53        // This value is overwritten by the $app->getParam('db_create_tables') setting if it is available.
[146]54        'create_table' => true,
[532]55
[396]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,
[550]58
59        // Serialization method.
60        // Legacy installations will have been using 'phpserialize' but these should migrate to use 'json' to avoid PHP object injection https://www.owasp.org/index.php/PHP_Object_Injection
61        'serialization_method' => 'phpserialize', // Or 'json'
[1]62    );
63
64    // Auth_SQL object from which to access a current user_id.
[484]65    protected $_auth;
[1]66
67    /**
68     * This method enforces the singleton pattern for this class.
69     *
[139]70     * @return  object  Reference to the global Lock object.
[1]71     * @access  public
72     * @static
73     */
[523]74    public static function &getInstance($auth_object=null)
[1]75    {
[468]76        if (self::$instance === null) {
77            self::$instance = new self($auth_object);
[1]78        }
79
[468]80        return self::$instance;
[1]81    }
82
83    /**
84     * Constructor. Pass an Auth object on which to perform user lookups.
85     *
86     * @param mixed  $auth_object  An Auth_SQL object.
87     */
[523]88    public function __construct($auth_object=null)
[1]89    {
[479]90        $app =& App::getInstance();
[136]91
[523]92        if (!is_null($auth_object) || is_null($this->_auth)) {
93            if (!method_exists($auth_object, 'get') || !method_exists($auth_object, 'getUsername')) {
94                trigger_error('Constructor not provided a valid Auth_* object.', E_USER_ERROR);
95            }
96
97            $this->_auth = $auth_object;
[19]98        }
[42]99
[1]100        // Get create tables config from global context.
[136]101        if (!is_null($app->getParam('db_create_tables'))) {
102            $this->setParam(array('create_table' => $app->getParam('db_create_tables')));
[1]103        }
104    }
[42]105
[1]106    /**
107     * Setup the database table for this class.
108     *
109     * @access  public
110     * @author  Quinn Comendant <quinn@strangecode.com>
111     * @since   26 Aug 2005 17:09:36
112     */
[468]113    public function initDB($recreate_db=false)
[1]114    {
[479]115        $app =& App::getInstance();
116        $db =& DB::getInstance();
[136]117
[1]118        static $_db_tested = false;
[42]119
[1]120        if ($recreate_db || !$_db_tested && $this->getParam('create_table')) {
121            if ($recreate_db) {
[136]122                $db->query("DROP TABLE IF EXISTS " . $this->getParam('db_table'));
[201]123                $app->logMsg(sprintf('Dropping and recreating table %s.', $this->getParam('db_table')), LOG_INFO, __FILE__, __LINE__);
[1]124            }
[601]125            $db->query(sprintf("CREATE TABLE IF NOT EXISTS %s (
[484]126                version_id INT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
[169]127                record_table VARCHAR(255) NOT NULL DEFAULT '',
128                record_key VARCHAR(255) NOT NULL DEFAULT '',
129                record_val VARCHAR(255) NOT NULL DEFAULT '',
130                version_data MEDIUMBLOB NOT NULL,
131                version_title VARCHAR(255) NOT NULL DEFAULT '',
132                version_number SMALLINT(11) UNSIGNED NOT NULL DEFAULT '0',
133                version_notes VARCHAR(255) NOT NULL DEFAULT '',
134                saved_by_user_id SMALLINT(11) NOT NULL DEFAULT '0',
[601]135                version_datetime DATETIME NOT NULL DEFAULT '%s 00:00:00',
[1]136                KEY record_table (record_table),
137                KEY record_key (record_key),
138                KEY record_val (record_val)
[601]139            )", $db->escapeString($this->getParam('db_table')), $db->getParam('zero_date')));
[42]140
[136]141            if (!$db->columnExists($this->getParam('db_table'), array(
[1]142                'version_id',
143                'record_table',
144                'record_key',
145                'record_val',
146                'version_data',
147                'version_title',
[169]148                'version_number',
[1]149                'version_notes',
[144]150                'saved_by_user_id',
[1]151                'version_datetime',
152            ), false, false)) {
[136]153                $app->logMsg(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_table')), LOG_ALERT, __FILE__, __LINE__);
[1]154                trigger_error(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_table')), E_USER_ERROR);
155            }
[42]156        }
[1]157        $_db_tested = true;
158    }
159
160    /**
161     * Set the params of this object.
162     *
163     * @param  array $params   Array of param keys and values to set.
164     */
[468]165    public function setParam($params=null)
[1]166    {
[550]167        $app =& App::getInstance();
168
169        if (isset($params['serialization_method']) && !in_array($params['serialization_method'], ['phpserialize', 'json'])) {
170            trigger_error(sprintf('Invalid serialization_method: %s', $params['serialization_method']), E_USER_ERROR);
171        }
[1]172        if (isset($params) && is_array($params)) {
173            // Merge new parameters with old overriding only those passed.
174            $this->_params = array_merge($this->_params, $params);
175        }
176    }
177
178    /**
[136]179     * Return the value of a parameter, if it exists.
[1]180     *
[136]181     * @access public
182     * @param string $param        Which parameter to return.
183     * @return mixed               Configured parameter value.
[1]184     */
[468]185    public function getParam($param)
[1]186    {
[479]187        $app =& App::getInstance();
[468]188
[478]189        if (array_key_exists($param, $this->_params)) {
[1]190            return $this->_params[$param];
191        } else {
[146]192            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
[1]193            return null;
194        }
195    }
196
197    /**
198     * Saves a version of the current record into the version table.
199     *
200     * @param string $record_table  The table containing the record.
201     * @param string $record_key    The key column for the record.
202     * @param string $record_val    The value of the key column for the record.
203     * @param string $title         The title of this record. Only used for human presentation.
204     *
205     * @return int                  The id for the version (mysql last insert id).
206     */
[468]207    public function create($record_table, $record_key, $record_val, $title='', $notes='')
[1]208    {
[479]209        $app =& App::getInstance();
210        $db =& DB::getInstance();
[136]211
[1]212        $this->initDB();
[42]213
[1]214        // Get current record.
215        if (!$record = $this->getCurrent($record_table, $record_key, $record_val)) {
[136]216            $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]217            return false;
218        }
[468]219
[169]220        // Get previous version_number.
221        $qid = $db->query("
222            SELECT MAX(version_number) FROM " . $db->escapeString($this->getParam('db_table')) . "
223            WHERE record_table = '" . $db->escapeString($record_table) . "'
224            AND record_key = '" . $db->escapeString($record_key) . "'
225            AND record_val = '" . $db->escapeString($record_val) . "'
226        ");
227        list($last_version_number) = mysql_fetch_row($qid);
[42]228
[1]229        // Clean-up old versions.
230        $this->deleteOld($record_table, $record_key, $record_val);
[42]231
[550]232        // Serialize the DB record.
233        switch ($this->getParam('serialization_method')) {
234        case 'phpserialize':
235            $data = gzcompress(serialize($record), 9);
236            break;
237
238        case 'json':
239            $data = gzcompress(json_encode($record), 9);
240            break;
241        }
242
[1]243        // Save as new version.
[159]244        // TODO: after MySQL 5.0.23 is released this query could benefit from INSERT DELAYED.
[136]245        $db->query("
[146]246            INSERT INTO " . $db->escapeString($this->getParam('db_table')) . " (
[1]247                record_table,
248                record_key,
249                record_val,
250                version_data,
251                version_title,
[169]252                version_number,
[1]253                version_notes,
[144]254                saved_by_user_id,
[1]255                version_datetime
256            ) VALUES (
[136]257                '" . $db->escapeString($record_table) . "',
258                '" . $db->escapeString($record_key) . "',
259                '" . $db->escapeString($record_val) . "',
[550]260                '" . $db->escapeString($data) . "',
[136]261                '" . $db->escapeString($title) . "',
[169]262                '" . $db->escapeString($last_version_number + 1) . "',
[136]263                '" . $db->escapeString($notes) . "',
[149]264                '" . $db->escapeString($this->_auth->get('user_id')) . "',
[1]265                NOW()
266            )
267        ");
268
[136]269        return mysql_insert_id($db->getDBH());
[1]270    }
271
272    /**
273     * Copy a version back into it's original table.
274     *
275     * @param string $version_id    The id of the version to restore.
276     *
277     * @return int                  The id for the version (mysql last insert id).
278     */
[468]279    public function restore($version_id)
[1]280    {
[479]281        $app =& App::getInstance();
282        $db =& DB::getInstance();
[136]283
[1]284        $this->initDB();
[42]285
[1]286        // Get version data.
[136]287        $qid = $db->query("
[550]288            SELECT *
289            FROM " . $db->escapeString($this->getParam('db_table')) . "
[136]290            WHERE version_id = '" . $db->escapeString($version_id) . "'
[1]291        ");
292        if (!$record = mysql_fetch_assoc($qid)) {
[497]293            $app->raiseMsg(sprintf(_("Version %s%s not found."), $version_id, (empty($record['version_title']) ? '' : ' (' . $record['version_title'] . ')')), MSG_WARNING, __FILE__, __LINE__);
294            $app->logMsg(sprintf('Version %s%s not found.', $version_id, (empty($record['version_title']) ? '' : ' (' . $record['version_title'] . ')')), LOG_WARNING, __FILE__, __LINE__);
[1]295            return false;
296        }
297
[550]298        // Unserialize the DB record.
299        switch ($this->getParam('serialization_method')) {
300        case 'phpserialize':
301            $data = unserialize(gzuncompress($record['version_data']));
302            break;
303
304        case 'json':
305            $data = json_decode(gzuncompress($record['version_data']), true);
306            break;
307        }
308
[1]309        // Ensure saved db columns match current table schema.
[136]310        if (!$db->columnExists($record['record_table'], array_keys($data), $this->getParam('db_schema_strict'))) {
[497]311            $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__);
312            $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__);
[1]313            return false;
314        }
315
316        // SQLize the keys of the specified versioned record.
[136]317        $replace_keys = join(",\n", array_map(array($db, 'escapeString'), array_keys($data)));
[42]318
[1]319        // SQLize the keys of the values of the specified versioned record. (These are more complex because we need to account for SQL null values.)
320        $replace_values = '';
321        $comma = '';
322        foreach ($data as $v) {
[136]323            $replace_values .= is_null($v) ? "$comma\nNULL" : "$comma\n'" . $db->escapeString($v) . "'";
[1]324            $comma = ',';
325        }
[42]326
[502]327        // Disable foreign_key_checks to prevent ON DELETE triggers or restrictions.
328        $db->query("SET SESSION foreign_key_checks = 0");
329        // Replace current record with specified versioned record. Consider converting this SQL to use INSERT 
 ON DUPLICATE KEY UPDATE 

[136]330        $db->query("
[502]331        REPLACE INTO " . $record['record_table'] . " (
[1]332                $replace_keys
333            ) VALUES (
334                $replace_values
[502]335            );
[1]336        ");
[502]337        // Re-enable foreign_key_checks.
338        $db->query("SET SESSION foreign_key_checks = 1");
[42]339
[1]340        return $record;
341    }
342
343    /**
344     * Version garbage collection. Deletes versions older than min_days
345     * when quantity of versions exceeds min_qty. If quantity
[42]346     * exceeds 100 within min_days, the oldest are deleted to bring the
[1]347     * quantity back down to min_qty.
348     *
349     * @param string $record_table  The table containing the record.
350     * @param string $record_key    The key column for the record.
351     * @param string $record_val    The value of the key column for the record.
352     *
353     * @return mixed                Array of versions, or false if none.
354     */
[468]355    public function deleteOld($record_table, $record_key, $record_val)
[1]356    {
[479]357        $db =& DB::getInstance();
[468]358
[1]359        $this->initDB();
[42]360
[1]361        // Get total number of versions for this record.
[136]362        $qid = $db->query("
[146]363            SELECT COUNT(*) FROM " . $db->escapeString($this->getParam('db_table')) . "
[136]364            WHERE record_table = '" . $db->escapeString($record_table) . "'
365            AND record_key = '" . $db->escapeString($record_key) . "'
366            AND record_val = '" . $db->escapeString($record_val) . "'
[1]367        ");
368        list($v_count) = mysql_fetch_row($qid);
[42]369
[1]370        if ($v_count > $this->getParam('min_qty')) {
371            if ($v_count > $this->getParam('max_qty')) {
372                // To prevent a record bomb, limit max number of versions to max_qty.
373                // First query for oldest records, selecting enough to bring total number down to min_qty.
[136]374                $qid = $db->query("
[550]375                    SELECT version_id
376                    FROM " . $db->escapeString($this->getParam('db_table')) . "
[136]377                    WHERE record_table = '" . $db->escapeString($record_table) . "'
378                    AND record_key = '" . $db->escapeString($record_key) . "'
379                    AND record_val = '" . $db->escapeString($record_val) . "'
[1]380                    ORDER BY version_datetime ASC
[550]381                    LIMIT " . $db->escapeString($v_count - $this->getParam('min_qty')) . "
[1]382                ");
[550]383                $old_versions = array();
[1]384                while (list($old_id) = mysql_fetch_row($qid)) {
385                    $old_versions[] = $old_id;
386                }
[136]387                $db->query("
[146]388                    DELETE FROM " . $db->escapeString($this->getParam('db_table')) . "
[1]389                    WHERE version_id IN ('" . join("','", $old_versions) . "')
390                ");
391            } else {
[49]392                // Delete versions older than min_days, while still keeping min_qty.
[136]393                $qid = $db->query("
[550]394                    SELECT version_id
395                    FROM " . $db->escapeString($this->getParam('db_table')) . "
[136]396                    WHERE record_table = '" . $db->escapeString($record_table) . "'
397                    AND record_key = '" . $db->escapeString($record_key) . "'
398                    AND record_val = '" . $db->escapeString($record_val) . "'
[1]399                    AND DATE_ADD(version_datetime, INTERVAL '" . $this->getParam('min_days') . "' DAY) < NOW()
400                    ORDER BY version_datetime ASC
401                    LIMIT " . ($v_count - $this->getParam('min_qty')) . "
402                ");
[550]403                $old_versions = array();
[1]404                while (list($old_id) = mysql_fetch_row($qid)) {
405                    $old_versions[] = $old_id;
406                }
407                if (sizeof($old_versions) > 0) {
[136]408                    $db->query("
[146]409                        DELETE FROM " . $db->escapeString($this->getParam('db_table')) . "
[1]410                        WHERE version_id IN ('" . join("','", $old_versions) . "')
411                    ");
412                }
413            }
414        }
415    }
416
417    /**
[637]418     * Delete all versioned history of a DB record.
419     *
420     * @param string $record_table  The table containing the record.
421     * @param string $record_key    The key column for the record.
422     * @param string $record_val    The value of the key column for the record.
423     *
424     * @return void
425     */
426    public function deleteAll($record_table, $record_key, $record_val)
427    {
428        $app =& App::getInstance();
429        $db =& DB::getInstance();
430
431        $this->initDB();
432
433        // Delete all versions for this record.
434        $qid = $db->query("
435            DELETE FROM " . $db->escapeString($this->getParam('db_table')) . "
436            WHERE record_table = '" . $db->escapeString($record_table) . "'
437            AND record_key = '" . $db->escapeString($record_key) . "'
438            AND record_val = '" . $db->escapeString($record_val) . "'
439        ");
440        $app->logMsg(sprintf('Deleted all %s rows for %s.%s=%s', mysql_affected_rows($db->getDBH()), $record_table, $record_key, $record_val), LOG_INFO, __FILE__, __LINE__);
441    }
442
443    /**
444     * Delete one version of a DB record.
445     *
446     * @param string $version_id    The ID of the version to delete.
447     *
448     * @return void
449     */
450    public function delete($version_id)
451    {
452        $app =& App::getInstance();
453        $db =& DB::getInstance();
454
455        $this->initDB();
456
457        // Delete one version.
458        $qid = $db->query("
459            DELETE FROM " . $db->escapeString($this->getParam('db_table')) . "
460            WHERE version_id = '" . $db->escapeString($version_id) . "'
461        ");
462        $app->logMsg(sprintf('Deleted version_id=%s', $version_id), LOG_INFO, __FILE__, __LINE__);
463    }
464
465    /**
[1]466     * Get a list of versions of specified record.
467     *
468     * @param string $record_table  The table containing the record.
469     * @param string $record_key    The key column for the record.
470     * @param string $record_val    The value of the key column for the record.
471     *
472     * @return mixed                Array of versions, or false if none.
473     */
[468]474    public function getList($record_table, $record_key, $record_val)
[1]475    {
[479]476        $db =& DB::getInstance();
[468]477
[1]478        $this->initDB();
[42]479
[1]480        // Get versions of this record.
[136]481        $qid = $db->query("
[468]482            SELECT
[169]483                version_id,
484                saved_by_user_id,
485                version_datetime,
486                version_title,
487                version_number,
488                version_notes
[146]489            FROM " . $db->escapeString($this->getParam('db_table')) . "
[136]490            WHERE record_table = '" . $db->escapeString($record_table) . "'
491            AND record_key = '" . $db->escapeString($record_key) . "'
492            AND record_val = '" . $db->escapeString($record_val) . "'
[1]493            ORDER BY version_datetime DESC
[15]494        ");
[1]495        $versions = array();
496        while ($row = mysql_fetch_assoc($qid)) {
497            // Get admin usernames.
[161]498            $row['editor'] = $this->_auth->getUsername($row['saved_by_user_id']);
[1]499            $versions[] = $row;
500        }
501        return $versions;
502    }
503
504    /**
505     * Get the version record for a specified version id.
506     *
507     * @param string $version_id    The id of the version to restore.
508     *
509     * @return mixed                Array of data saved in version, or false if none.
510     */
[468]511    public function getVerson($version_id)
[1]512    {
[479]513        $db =& DB::getInstance();
[468]514
[1]515        $this->initDB();
[42]516
[1]517        // Get version data.
[136]518        $qid = $db->query("
[146]519            SELECT * FROM " . $db->escapeString($this->getParam('db_table')) . "
[136]520            WHERE version_id = '" . $db->escapeString($version_id) . "'
[1]521        ");
522        return mysql_fetch_assoc($qid);
523    }
524
525    /**
526     * Get the data stored for a specified version id.
527     *
528     * @param string $version_id    The id of the version to restore.
529     *
530     * @return mixed                Array of data saved in version, or false if none.
531     */
[468]532    public function getData($version_id)
[1]533    {
[479]534        $db =& DB::getInstance();
[468]535
[1]536        $this->initDB();
[42]537
[1]538        // Get version data.
[136]539        $qid = $db->query("
[550]540            SELECT *
541            FROM " . $db->escapeString($this->getParam('db_table')) . "
[136]542            WHERE version_id = '" . $db->escapeString($version_id) . "'
[1]543        ");
544        $record = mysql_fetch_assoc($qid);
545        if (isset($record['version_data'])) {
[550]546            // Unserialize the DB record.
547            switch ($this->getParam('serialization_method')) {
548            case 'phpserialize':
549                return unserialize(gzuncompress($record['version_data']));
550
551            case 'json':
552                return json_decode(gzuncompress($record['version_data']));
553            }
[1]554        } else {
555            return false;
556        }
557    }
558
559    /**
560     * Get the current record data from the original table.
561     *
562     * @param string $version_id    The id of the version to restore.
563     *
564     * @return mixed                Array of data saved in version, or false if none.
565     */
[468]566    public function getCurrent($record_table, $record_key, $record_val)
[1]567    {
[479]568        $db =& DB::getInstance();
[502]569        $app =& App::getInstance();
[468]570
[1]571        $this->initDB();
[42]572
[502]573        if (!$record_table || !$record_key || !$record_val) {
574            $app->logMsg(sprintf('Invalid current version args: %s, %s, %s.', $record_table, $record_key, $record_val), LOG_ERR, __FILE__, __LINE__);
575            return false;
576        }
577
[136]578        $qid = $db->query("
579            SELECT * FROM " . $db->escapeString($record_table) . "
580            WHERE " . $db->escapeString($record_key) . " = '" . $db->escapeString($record_val) . "'
[1]581        ");
582        if ($record = mysql_fetch_assoc($qid)) {
583            return $record;
584        } else {
585            return false;
586        }
587    }
588
589
590} // End of class.
Note: See TracBrowser for help on using the repository browser.