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

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

First set of changes towards 2.2.0. Improved functinoality with integration in wordpress; bugs fixed.

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

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