source: trunk/lib/Lock.inc.php

Last change on this file was 726, checked in by anonymous, 4 years ago
File size: 16.5 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 * Lock.inc.php
25 *
26 * The Lock class provides a system for locking abstract DB rows.
27 *
28 * @author  Quinn Comendant <quinn@strangecode.com>
29 * @version 2.1
30 */
31class Lock
32{
33    // A place to keep an object instance for the singleton pattern.
34    protected static $instance = null;
35
36    // Configuration of this object.
37    protected $_params = array(
38        // The time required to pass before a user can forcibly unlock a locked record.
39        'timeout' => 600,
40
41        // The time after which a record will automatically become unlocked.
42        'auto_timeout' => 1800,
43
44        // The URL to the lock script.
45        'error_url' => '/lock.php',
46
47        // The name of the database table to store locks.
48        'db_table' => 'lock_tbl',
49
50        // Automatically create table and verify columns. Better set to false after site launch.
51        // This value is overwritten by the $app->getParam('db_create_tables') setting if it is available.
52        'create_table' => true,
53    );
54
55    // Store lock data from DB.
56    protected $data = array();
57
58    // Auth_SQL object from which to access a current user_id.
59    protected $_auth = null;
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=null)
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 or Auth_FILE object.
81     */
82    public function __construct($auth_object=null)
83    {
84        $app =& App::getInstance();
85
86        if (!is_null($auth_object) || is_null($this->_auth)) {
87            if (!method_exists($auth_object, 'get') || !method_exists($auth_object, 'getUsername')) {
88                trigger_error('Constructor not provided a valid Auth_* object.', E_USER_ERROR);
89            }
90
91            $this->_auth = $auth_object;
92        }
93
94        // Get create tables config from global context.
95        if (!is_null($app->getParam('db_create_tables'))) {
96            $this->setParam(array('create_table' => $app->getParam('db_create_tables')));
97        }
98    }
99
100    /**
101     * Setup the database table for this class.
102     *
103     * @access  public
104     * @author  Quinn Comendant <quinn@strangecode.com>
105     * @since   26 Aug 2005 17:09:36
106     */
107    public function initDB($recreate_db=false)
108    {
109        $app =& App::getInstance();
110        $db =& DB::getInstance();
111
112        static $_db_tested = false;
113
114        if ($recreate_db || !$_db_tested && $this->getParam('create_table')) {
115            if ($recreate_db) {
116                $db->query("DROP TABLE IF EXISTS " . $this->getParam('db_table'));
117                $app->logMsg(sprintf('Dropping and recreating table %s.', $this->getParam('db_table')), LOG_INFO, __FILE__, __LINE__);
118            }
119            $db->query(sprintf("CREATE TABLE IF NOT EXISTS %s (
120                lock_id INT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
121                record_table varchar(255) NOT NULL default '',
122                record_key varchar(255) NOT NULL default '',
123                record_val varchar(255) NOT NULL default '',
124                title varchar(255) NOT NULL default '',
125                set_by_admin_id smallint(11) NOT NULL default '0',
126                lock_datetime datetime NOT NULL default '%s 00:00:00',
127                KEY record_table (record_table),
128                KEY record_key (record_key),
129                KEY record_val (record_val)
130            )", $db->escapeString($this->getParam('db_table')), $db->getParam('zero_date')));
131
132            if (!$db->columnExists($this->getParam('db_table'), array(
133                'lock_id',
134                'record_table',
135                'record_key',
136                'record_val',
137                'title',
138                'set_by_admin_id',
139                'lock_datetime',
140            ), false, false)) {
141                $app->logMsg(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_table')), LOG_ALERT, __FILE__, __LINE__);
142                trigger_error(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_table')), E_USER_ERROR);
143            }
144        }
145        $_db_tested = true;
146    }
147
148    /**
149     * Set the params of this object.
150     *
151     * @param  array $params   Array of param keys and values to set.
152     */
153    public function setParam($params=null)
154    {
155        if (isset($params) && is_array($params)) {
156            // Merge new parameters with old overriding only those passed.
157            $this->_params = array_merge($this->_params, $params);
158        }
159    }
160
161    /**
162     * Return the value of a parameter, if it exists.
163     *
164     * @access public
165     * @param string $param        Which parameter to return.
166     * @return mixed               Configured parameter value.
167     */
168    public function getParam($param)
169    {
170        $app =& App::getInstance();
171
172        if (array_key_exists($param, $this->_params)) {
173            return $this->_params[$param];
174        } else {
175            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
176            return null;
177        }
178    }
179
180    /**
181     * Select the lock to manipulate.
182     *
183     * @param mixed  $record_table_or_lock_id  The table containing the record to lock,
184     *                                         or a numeric lock_id.
185     * @param string $record_key  The key column for the record to lock.
186     * @param string $record_val  The value of the key column for the record to lock.
187     */
188    public function select($record_table_or_lock_id, $record_key=null, $record_val=null)
189    {
190        $app =& App::getInstance();
191        $db =& DB::getInstance();
192
193        $this->initDB();
194
195        // Expire old locks.
196        $this->_auto_timeout();
197
198        if (is_numeric($record_table_or_lock_id) && !isset($record_key) && !isset($record_val)) {
199            // Get lock data by lock_id.
200            $qid = $db->query("
201                SELECT * FROM " . $db->escapeString($this->getParam('db_table')) . "
202                WHERE lock_id = '" . $db->escapeString($record_table_or_lock_id) . "'
203            ");
204        } else {
205            // Get lock data by record specs
206            $qid = $db->query("
207                SELECT * FROM " . $db->escapeString($this->getParam('db_table')) . "
208                WHERE record_table = '" . $db->escapeString($record_table_or_lock_id) . "'
209                AND record_key = '" . $db->escapeString($record_key) . "'
210                AND record_val = '" . $db->escapeString($record_val) . "'
211            ");
212        }
213        if ($this->data = mysql_fetch_assoc($qid)) {
214            $app->logMsg(sprintf('Selecting %slocked record: %s %s %s', ($this->data['set_by_admin_id'] == $this->_auth->get('user_id') ? 'self-' : ''), $record_table_or_lock_id, $record_key, $record_val), LOG_DEBUG, __FILE__, __LINE__);
215            // FIXME: What if admin set lock, but public user is current lock user?
216            $this->data['editor'] = $this->_auth->getUsername($this->data['set_by_admin_id']);
217            return true;
218        } else {
219            return false;
220        }
221    }
222
223    /**
224     * Returns true if the record we instantiated with is locked.
225     *
226     * @return bool            True if locked.
227     */
228    public function isLocked()
229    {
230        return isset($this->data['lock_id']);
231    }
232
233    /**
234     * Returns the status of who set the lock. Use this to ignore locks set by
235     * the current user.
236     *
237     * @return bool            True if current user set the lock.
238     */
239    public function isMine()
240    {
241        $db =& DB::getInstance();
242
243        $this->initDB();
244
245        if ($this->isLocked()) {
246            $qid = $db->query("SELECT * FROM " . $db->escapeString($this->getParam('db_table')) . " WHERE lock_id = '" . $db->escapeString($this->data['lock_id']) . "'");
247            if ($lock = mysql_fetch_assoc($qid)) {
248                return ($lock['set_by_admin_id'] == $this->_auth->get('user_id'));
249            } else {
250                return false;
251            }
252        } else {
253            return false;
254        }
255    }
256
257    /**
258     * Create a new lock for the specified table/key/value.
259     *
260     * @param string $record_table  The table containing the record to lock.
261     * @param string $record_key  The key column for the record to lock.
262     * @param string $record_val  The value of the key column for the record to lock.
263     * @param string $title       A title to apply to the lock, for display purposes.
264     *
265     * @return int            The id for the lock (mysql last insert id).
266     */
267    public function set($record_table, $record_key, $record_val, $title='')
268    {
269        $app =& App::getInstance();
270        $db =& DB::getInstance();
271
272        $this->initDB();
273
274        if ($this->_auth->get('user_id') == '' || filter_var($this->_auth->get('user_id'), FILTER_VALIDATE_INT) === false) {
275            $app->logMsg(sprintf("auth->get('user_id') returns a non-integer: %s", $this->_auth->get('user_id')), LOG_ERR, __FILE__, __LINE__);
276            return false;
277        }
278
279        // Expire old locks.
280        $this->_auto_timeout();
281
282        // Remove previous locks if exist. Is this better than using a REPLACE INTO?
283        $db->query("
284            DELETE FROM " . $db->escapeString($this->getParam('db_table')) . "
285            WHERE record_table = '" . $db->escapeString($record_table) . "'
286            AND record_key = '" . $db->escapeString($record_key) . "'
287            AND record_val = '" . $db->escapeString($record_val) . "'
288        ");
289
290        // Set new lock.
291        $db->query("
292            INSERT INTO " . $db->escapeString($this->getParam('db_table')) . " (
293                record_table,
294                record_key,
295                record_val,
296                title,
297                set_by_admin_id,
298                lock_datetime
299            ) VALUES (
300                '" . $db->escapeString($record_table) . "',
301                '" . $db->escapeString($record_key) . "',
302                '" . $db->escapeString($record_val) . "',
303                '" . $db->escapeString($title) . "',
304                '" . $db->escapeString($this->_auth->get('user_id')) . "',
305                NOW()
306            )
307        ");
308        $lock_id = mysql_insert_id($db->getDBH());
309
310        // Must register this locked record as the current.
311        $this->select($lock_id);
312
313        return $lock_id;
314    }
315
316    /**
317     * Unlock the currently selected record.
318     */
319    public function remove()
320    {
321        $app =& App::getInstance();
322        $db =& DB::getInstance();
323
324        $this->initDB();
325
326        // Expire old locks.
327        $this->_auto_timeout();
328
329        if (!$this->isLocked()) {
330            // No lock selected.
331            return false;
332        }
333
334        // Delete a specific lock.
335        $db->query("
336            DELETE FROM " . $db->escapeString($this->getParam('db_table')) . "
337            WHERE lock_id = '" . $db->escapeString($this->data['lock_id']) . "'
338        ");
339
340        $app->logMsg(sprintf('Removing lock: %s', $this->data['lock_id']), LOG_DEBUG, __FILE__, __LINE__);
341        return true;
342    }
343
344    /**
345     * Unlock all records, or all records for a specified user.
346     */
347    public function removeAll($user_id=null)
348    {
349        $app =& App::getInstance();
350        $db =& DB::getInstance();
351
352        $this->initDB();
353
354        // Expire old locks.
355        $this->_auto_timeout();
356
357        if (isset($user_id)) {
358            // Delete specific user's locks.
359            $db->query("DELETE FROM " . $db->escapeString($this->getParam('db_table')) . " WHERE set_by_admin_id = '" . $db->escapeString($user_id) . "'");
360            $app->logMsg(sprintf('Record locks owned by user %s have been deleted', $this->_auth->getUsername($user_id)), LOG_DEBUG, __FILE__, __LINE__);
361        } else {
362            // Delete ALL locks.
363            $db->query("DELETE FROM " . $db->escapeString($this->getParam('db_table')) . "");
364            $app->logMsg(sprintf('All record locks deleted by user %s', $this->_auth->get('username')), LOG_DEBUG, __FILE__, __LINE__);
365        }
366    }
367
368    /**
369     * Deletes all locks that are older than auto_timeout.
370     */
371    public function _auto_timeout()
372    {
373        $db =& DB::getInstance();
374
375        static $_timeout_run = false;
376
377        $this->initDB();
378
379        if (!$_timeout_run) {
380            // Delete all old locks.
381            $db->query("
382                DELETE FROM " . $db->escapeString($this->getParam('db_table')) . "
383                WHERE DATE_ADD(lock_datetime, INTERVAL '" . $db->escapeString($this->getParam('auto_timeout')) . "' SECOND) < NOW()
384            ");
385            $_timeout_run = true;
386        }
387    }
388
389    /**
390     * Redirect to record lock error page.
391     */
392    public function dieErrorPage()
393    {
394        $app =& App::getInstance();
395
396        $app->dieURL($this->getParam('error_url'), array('lock_id' => $this->data['lock_id'], 'boomerang' => urlencode(getenv('REQUEST_URI'))));
397    }
398
399    /**
400     * Print error page. This method is probably not used anywhere; instead, we're including this via the template codebase/services/templates/lock.ihtml
401     */
402    public function printErrorHTML()
403    {
404        $app =& App::getInstance();
405        ?>
406        <form method="post" action="<?php echo oTxt($_SERVER['PHP_SELF']); ?>">
407            <?php $app->printHiddenSession() ?>
408            <input type="hidden" name="lock_id" value="<?php echo $this->getID(); ?>" />
409            <div id="sc-msg" class="sc-msg">
410                <div class="sc-msg-notice">
411                <?php printf(_("<em>%s</em> is currently being edited by %s (%d minutes elapsed). You cannot modify this database record while it is locked. Please try again later."),
412                    ucfirst($this->getTitle()),
413                    $this->getEditor(),
414                    date('i', $this->getSecondsElapsed() + 60)
415                ); ?>
416                </div>
417                <?php if ($this->getSecondsElapsed() >= $this->getParam('timeout')) { ?>
418                    <div class="sc-msg-notice"><?php printf(_("You can forcibly unlock the record if you believe the editing session has expired. You might want to confirm with %s before doing this."), $this->getEditor()) ?></div>
419                    <div class="sc-msg-notice">
420                        <input type="submit" name="unlock" value="<?php echo _("Unlock"); ?>" />
421                        <input type="submit" name="cancel" value="<?php echo _("Cancel"); ?>" />
422                    </div>
423                <?php } else { ?>
424                    <div class="sc-msg-notice">
425                        <input type="submit" name="cancel" value="<?php echo _("Cancel"); ?>" />
426                    </div>
427                <?php } ?>
428            </div>
429        </form>
430        <?php
431    }
432
433    /**
434     * Return lock_id of locked record.
435     */
436    public function getID()
437    {
438        return $this->data['lock_id'];
439    }
440
441    /**
442     * Return title of locked record.
443     */
444    public function getTitle()
445    {
446        return $this->data['title'];
447    }
448
449    /**
450     * Return administrator username for locked record.
451     */
452    public function getEditor()
453    {
454        return $this->data['editor'];
455    }
456
457    /**
458     * Return total seconds since the record was locked.
459     */
460    public function getSecondsElapsed()
461    {
462        if (isset($this->data['lock_datetime']) && false !== ($lock_timestamp = strtotime($this->data['lock_datetime'])) && $lock_timestamp < time()) {
463            return time() - $lock_timestamp;
464        } else {
465            return 0;
466        }
467    }
468
469
470} // End of class.
Note: See TracBrowser for help on using the repository browser.