source: trunk/lib/PEdit.inc.php

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

Many minor fixes during pulso development

File size: 28.1 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 * PEdit.inc.php
25 *
26 * PEdit provides a mechanism to store text in php variables
27 * which will be printed to the client browser under normal
28 * circumstances, but an authenticated user can 'edit' the document--
29 * data stored in vars will be shown in html form elements to be edited
30 * and saved. Posted data is stored in XML format in a specified data dir.
31 * A copy of the previous version is saved with the unix
32 * timestamp as part of the filename. This allows reverting to previous versions.
33 *
34 * To use, include this file, initialize variables,
35 * and call printing/editing functions where you want data and forms to
36 * show up.
37 *
38 * @author  Quinn Comendant <quinn@strangecode.com>
39 * @concept Beau Smith <beau@beausmith.com>
40 * @version 2.0
41 *
42 * Example of use:
43
44 // Initialize PEdit object.
45 require_once 'codebase/lib/PEdit.inc.php';
46 $pedit = new PEdit(array(
47     'data_dir' => COMMON_BASE . '/html/_pedit_data',
48     'authorized' => true,
49 ));
50
51 // Setup content data types.
52 $pedit->set('title');
53 $pedit->set('content', array('type' => 'textarea'));
54
55 // After setting all parameters and data, load the data.
56 $pedit->start();
57
58 // Print content.
59 echo $pedit->get('title');
60 echo $pedit->get('content');
61
62 // Print additional PEdit functionality.
63 $pedit->formBegin();
64 $pedit->printAllForms();
65 $pedit->printVersions();
66 $pedit->formEnd();
67
68 */
69class PEdit
70{
71
72    // PEdit object parameters.
73    protected $_params = array(
74        'data_dir' => '',
75        'character_set' => 'utf-8',
76        'versions_min_qty' => 20,
77        'versions_min_days' => 10,
78    );
79
80    protected $_data = array(); // Array to store loaded data.
81    protected $_data_file = ''; // Full file path to the pedit data file.
82    protected $_authorized = false; // User is authenticated to see extended functions.
83    protected $_data_loaded = false;
84    public $op = '';
85
86    /**
87     * Constructs a new PEdit object. Initializes what file is being operated with
88     * (PHP_SELF) and what that operation is. The two
89     * operations that actually modify data (save, restore) are treated differently
90     * than view operations (versions, view, default). They die redirect so you see
91     * the page you just modified.
92     *
93     * @access public
94     * @param optional array $params  A hash containing connection parameters.
95     */
96    public function __construct($params)
97    {
98        $this->setParam($params);
99
100        if ($this->getParam('authorized') === true) {
101            $this->_authorized = true;
102        }
103
104        // Setup PEAR XML libraries.
105        require_once 'XML/Serializer.php';
106        $this->xml_serializer = new XML_Serializer(array(
107            XML_SERIALIZER_OPTION_INDENT => '',
108            XML_SERIALIZER_OPTION_LINEBREAKS => '',
109            XML_SERIALIZER_OPTION_RETURN_RESULT => true,
110            XML_SERIALIZER_OPTION_TYPEHINTS => true,
111        ));
112        require_once 'XML/Unserializer.php';
113        $this->xml_unserializer = new XML_Unserializer(array(
114            XML_UNSERIALIZER_OPTION_COMPLEXTYPE => 'array',
115        ));
116    }
117
118    /**
119     * Set (or overwrite existing) parameters by passing an array of new parameters.
120     *
121     * @access public
122     * @param  array    $params     Array of parameters (key => val pairs).
123     */
124    public function setParam($params)
125    {
126        $app =& App::getInstance();
127
128        if (isset($params) && is_array($params)) {
129            // Merge new parameters with old overriding only those passed.
130            $this->_params = array_merge($this->_params, $params);
131        } else {
132            $app->logMsg(sprintf('Parameters are not an array: %s', $params), LOG_WARNING, __FILE__, __LINE__);
133        }
134    }
135
136    /**
137     * Return the value of a parameter, if it exists.
138     *
139     * @access public
140     * @param string $param        Which parameter to return.
141     * @return mixed               Configured parameter value.
142     */
143    public function getParam($param)
144    {
145        $app =& App::getInstance();
146
147        if (array_key_exists($param, $this->_params)) {
148            return $this->_params[$param];
149        } else {
150            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
151            return null;
152        }
153    }
154
155    /*
156    * Load the pedit data and run automatic functions.
157    *
158    * @access   public
159    * @author   Quinn Comendant <quinn@strangecode.com>
160    * @since    12 Apr 2006 12:43:47
161    */
162    public function start($initialize_data_file=false)
163    {
164        $app =& App::getInstance();
165
166        if (!is_dir($this->getParam('data_dir'))) {
167            trigger_error(sprintf('PEdit data directory not found: %s', $this->getParam('data_dir')), E_USER_WARNING);
168        }
169
170        // The location of the data file. (i.e.: "COMMON_DIR/html/_pedit_data/news/index.xml")
171        $this->_data_file = sprintf('%s%s.xml', $this->getParam('data_dir'), $_SERVER['SCRIPT_NAME']);
172
173        // Make certain the evaluated path matches the assumed path (realpath will expand /../../);
174        // if realpath returns FALSE we're not concerned because it means the file doesn't exist (_initializeDataFile() will create it).
175        if (false !== realpath($this->_data_file) && $this->_data_file !== realpath($this->_data_file)) {
176            $app->logMsg(sprintf('PEdit data file not a real path: %s', $this->_data_file), LOG_CRIT, __FILE__, __LINE__);
177            trigger_error(sprintf('PEdit data file not a real path: %s', $this->_data_file), E_USER_ERROR);
178        }
179
180        // op is used throughout the script to determine state.
181        $this->op = getFormData('op');
182
183        // Automatic functions based on state.
184        switch ($this->op) {
185        case 'Save' :
186            if ($this->_writeData()) {
187                $app->dieURL($_SERVER['PHP_SELF']);
188            }
189            break;
190
191        case 'Restore' :
192            if ($this->_restoreVersion(getFormData('version'))) {
193                $app->dieURL($_SERVER['PHP_SELF']);
194            }
195            break;
196
197        case 'View' :
198            $this->_data_file = sprintf('%s%s__%s.xml', $this->getParam('data_dir'), $_SERVER['PHP_SELF'], getFormData('version'));
199            $app->raiseMsg(sprintf(_("This is <em><strong>only a preview</strong></em> of version %s."), getFormData('version')), MSG_NOTICE, __FILE__, __LINE__);
200            break;
201        }
202
203        // Load data.
204        $this->_loadDataFile();
205
206        if ($initialize_data_file === true) {
207            $this->_createVersion();
208            $this->_initializeDataFile();
209        }
210    }
211
212    /**
213     * Stores a variable in the pedit data array with the content name, and type of form.
214     *
215     * @access public
216     *
217     * @param string    $content         The variable containing the text to store.
218     * @param array     $options         Additional options to store with this data.
219     */
220    public function set($name, $options=array())
221    {
222        $app =& App::getInstance();
223
224        $name = preg_replace('/\s/', '_', $name);
225        if (!isset($this->_data[$name])) {
226            $this->_data[$name] = array_merge(array('content' => ''), $options);
227        } else {
228            $app->logMsg(sprintf('Duplicate set data: %s', $name), LOG_NOTICE, __FILE__, __LINE__);
229        }
230    }
231
232    /**
233     * Returns the contents of a data variable. The variable must first be 'set'.
234     *
235     * @access public
236     * @param string $name   The name of the variable to return.
237     * @return string        The trimmed content of the named data.
238     */
239    public function get($name)
240    {
241        $name = preg_replace('/\s/', '_', $name);
242        if ($this->op != 'Edit' && $this->op != 'Versions' && isset($this->_data[$name]['content'])) {
243            return $this->_data[$name]['content'];
244        } else {
245            return '';
246        }
247    }
248
249    /**
250     * Prints the beginning <form> HTML tag, as well as hidden input forms.
251     *
252     * @return bool  False if unauthorized or current page is a version.
253     */
254    public function formBegin()
255    {
256        $app =& App::getInstance();
257
258        if (!$this->_authorized || empty($this->_data)) {
259            return false;
260        }
261        ?>
262        <form action="<?php echo oTxt($_SERVER['PHP_SELF']); ?>" method="post" id="sc-pedit-form">
263        <input type="hidden" name="filename" value="<?php echo oTxt($_SERVER['PHP_SELF']); ?>" />
264        <input type="hidden" name="file_hash" value="<?php echo $this->_fileHash(); ?>" />
265        <?php
266        $app->printHiddenSession();
267        switch ($this->op) {
268        case 'Edit' :
269            ?>
270            <div class="sc-pedit-buttons">
271                <input type="submit" name="op" value="<?php echo _("Save"); ?>" title="<?php echo preg_replace('/^(\w)/i', '($1)', _("Save"))?>" accesskey="<?php echo mb_substr(_("Save"), 0, 1) ?>" />
272                <input type="submit" name="op" value="<?php echo _("Cancel"); ?>" title="<?php echo preg_replace('/^(\w)/i', '($1)', _("Cancel"))?>" accesskey="<?php echo mb_substr(_("Cancel"), 0, 1) ?>" />
273            </div>
274            <?php
275            break;
276
277        case 'View' :
278            ?>
279            <input type="hidden" name="version" value="<?php echo getFormData('version'); ?>" />
280            <?php
281            break;
282        }
283    }
284
285    /**
286     * Loops through the PEdit data array and prints all the HTML forms corresponding
287     * to all pedit variables, in the order in which they were 'set'.
288     *
289     * @access public
290     */
291    public function printAllForms()
292    {
293        if ($this->_authorized && $this->op == 'Edit' && is_array($this->_data) && $this->_data_loaded) {
294            foreach ($this->_data as $name=>$d) {
295                $this->printForm($name);
296            }
297        }
298    }
299
300    /**
301     * Prints the HTML forms corresponding to pedit variables. Each variable
302     * must first be 'set'.
303     *
304     * @access public
305     * @param string $name      The name of the variable.
306     * @param string $type      Type of form to print. Currently only 'text' and 'textarea' supported.
307     */
308    public function printForm($name, $type='text')
309    {
310        if ($this->_authorized && $this->op == 'Edit' && $this->_data_loaded) {
311            ?>
312            <div class="sc-pedit-item">
313            <?php
314            $type = (isset($this->_data[$name]['type'])) ? $this->_data[$name]['type'] : $type;
315            // Print edit form.
316            switch ($type) {
317            case 'text' :
318            default :
319                ?>
320                <label>
321                <?php echo ucfirst(str_replace('_', ' ', $name)); ?>
322                <input type="text" name="_pedit_data[<?php echo $name; ?>]" id="sc-pedit-field-<?php echo $name; ?>" value="<?php echo oTxt($this->_data[$name]['content']); ?>" class="sc-full" />
323                </label>
324                <?php
325                break;
326
327            case 'textarea' :
328                ?>
329                <label>
330                <?php echo ucfirst(str_replace('_', ' ', $name)); ?>
331                <textarea name="_pedit_data[<?php echo $name; ?>]" id="sc-pedit-field-<?php echo $name; ?>" rows="" cols="" class="sc-full sc-tall"><?php echo oTxt($this->_data[$name]['content']); ?></textarea>
332                </label>
333                <?php
334                break;
335            }
336            ?>
337            </div>
338            <?php
339        }
340    }
341
342    /**
343     * Prints the ending </form> HTML tag, as well as buttons used during
344     * different operations.
345     *
346     * @return bool  False if unauthorized or current page is a version.
347     */
348    public function formEnd()
349    {
350        if (!$this->_authorized || empty($this->_data)) {
351            // Don't show form elements for versioned documents.
352            return false;
353        }
354        switch ($this->op) {
355        case 'Edit' :
356            ?>
357            <div class="sc-pedit-buttons">
358                <input type="submit" name="op" value="<?php echo _("Save"); ?>" title="<?php echo preg_replace('/^(\w)/i', '($1)', _("Save"))?>" accesskey="<?php echo mb_substr(_("Save"), 0, 1) ?>" />
359                <input type="submit" name="op" value="<?php echo _("Cancel"); ?>" title="<?php echo preg_replace('/^(\w)/i', '($1)', _("Cancel"))?>" accesskey="<?php echo mb_substr(_("Cancel"), 0, 1) ?>" />
360            </div>
361            </form>
362            <?php
363            break;
364
365        case 'Versions' :
366            ?>
367            <div class="sc-pedit-buttons">
368                <input type="submit" name="op" value="<?php echo _("Cancel"); ?>" title="<?php echo preg_replace('/^(\w)/i', '($1)', _("Cancel"))?>" accesskey="<?php echo mb_substr(_("Cancel"), 0, 1) ?>" />
369            </div>
370            </form>
371            <?php
372            break;
373
374        case 'View' :
375            ?>
376            <div class="sc-pedit-buttons">
377                <input type="submit" name="op" value="<?php echo _("Restore"); ?>" title="<?php echo preg_replace('/^(\w)/i', '($1)', _("Restore"))?>" accesskey="<?php echo mb_substr(_("Restore"), 0, 1) ?>" />
378                <input type="submit" name="op" value="<?php echo _("Versions"); ?>" title="<?php echo preg_replace('/^(\w)/i', '($1)', _("Versions"))?>" accesskey="<?php echo mb_substr(_("Versions"), 0, 1) ?>" />
379                <input type="submit" name="op" value="<?php echo _("Cancel"); ?>" title="<?php echo preg_replace('/^(\w)/i', '($1)', _("Cancel"))?>" accesskey="<?php echo mb_substr(_("Cancel"), 0, 1) ?>" />
380            </div>
381            </form>
382            <?php
383            break;
384
385        default :
386            ?>
387            <div class="sc-pedit-buttons">
388                <input type="submit" name="op" value="<?php echo _("Edit"); ?>" title="<?php echo preg_replace('/^(\w)/i', '($1)', _("Edit"))?>" accesskey="<?php echo mb_substr(_("Edit"), 0, 1) ?>" />
389                <input type="submit" name="op" value="<?php echo _("Versions"); ?>" title="<?php echo preg_replace('/^(\w)/i', '($1)', _("Versions"))?>" accesskey="<?php echo mb_substr(_("Versions"), 0, 1) ?>" />
390            </div>
391            </form>
392            <?php
393        }
394    }
395
396    /**
397     * Prints an HTML list of versions of current file, with the filesize
398     * and links to view and restore the file.
399     *
400     * @access public
401     */
402    public function printVersions()
403    {
404        $app =& App::getInstance();
405
406        if ($this->_authorized && $this->op == 'Versions') {
407            // Print versions and commands to view/restore.
408            $version_files = $this->_getVersions();
409            ?><h1><?php printf(_("%s saved versions of %s"), sizeof($version_files), basename($_SERVER['PHP_SELF'])); ?></h1><?php
410            if (is_array($version_files) && !empty($version_files)) {
411                ?>
412                <table id="sc-pedit-versions-table">
413                <tr>
414                    <th><?php echo _("Date"); ?></th>
415                    <th><?php echo _("Time"); ?></th>
416                    <th><?php echo _("File size"); ?></th>
417                    <th><?php echo _("Version options"); ?></th>
418                </tr>
419                <?php
420                foreach ($version_files as $v) {
421                    ?>
422                    <tr>
423                        <td><?php echo date($app->getParam('date_format'), $v['unixtime']); ?></td>
424                        <td><?php echo date($app->getParam('time_format'), $v['unixtime']); ?></td>
425                        <td><?php echo humanFileSize($v['filesize']); ?></td>
426                        <td class="sc-nowrap"><a href="<?php echo $app->oHREF($_SERVER['PHP_SELF'] . '?op=View&version=' . $v['unixtime'] . '&file_hash=' . $this->_fileHash()); ?>"><?php echo _("View"); ?></a> <?php echo _("or"); ?> <a href="<?php echo $app->oHREF($_SERVER['PHP_SELF'] . '?op=Restore&version=' . $v['unixtime'] . '&file_hash=' . $this->_fileHash()); ?>"><?php echo _("Restore"); ?></a></td>
427                    </tr>
428                    <?php
429                }
430                ?>
431                </table>
432                <div class="sc-help"><?php printf(_("When there are more than %s versions, those over %s days old are deleted."), $this->getParam('versions_min_qty'), $this->getParam('versions_min_days')); ?></div>
433                <?php
434            }
435        }
436    }
437
438    /*
439    * Returns a secret hash for the current file.
440    *
441    * @access   public
442    * @author   Quinn Comendant <quinn@strangecode.com>
443    * @since    12 Apr 2006 10:52:35
444    */
445    protected function _fileHash()
446    {
447        $app =& App::getInstance();
448
449        return md5($app->getParam('signing_key') . $_SERVER['PHP_SELF']);
450    }
451
452    /*
453    * Load the XML data file into $this->_data.
454    *
455    * @access   public
456    * @return   bool    false on error
457    * @author   Quinn Comendant <quinn@strangecode.com>
458    * @since    11 Apr 2006 20:36:26
459    */
460    protected function _loadDataFile()
461    {
462        $app =& App::getInstance();
463
464        if (!file_exists($this->_data_file)) {
465            if (!$this->_initializeDataFile()) {
466                $app->logMsg(sprintf('Initializing content file failed: %s', $this->_data_file), LOG_WARNING, __FILE__, __LINE__);
467                return false;
468            }
469        }
470        $xml_file_contents = file_get_contents($this->_data_file);
471        $status = $this->xml_unserializer->unserialize($xml_file_contents, false);
472        if (PEAR::isError($status)) {
473            $app->logMsg(sprintf('XML_Unserialize error: %s', $status->getMessage()), LOG_WARNING, __FILE__, __LINE__);
474            return false;
475        }
476        $xml_file_data = $this->xml_unserializer->getUnserializedData();
477
478        // Only load data specified with set(), even though there may be more in the xml file.
479        foreach ($this->_data as $name => $initial_data) {
480            if (isset($xml_file_data[$name])) {
481                $this->_data[$name] = array_merge($initial_data, $xml_file_data[$name]);
482            } else {
483                $this->_data[$name] = $initial_data;
484            }
485        }
486
487        $this->_data_loaded = true;
488        return true;
489    }
490
491    /*
492    * Start a new data file.
493    *
494    * @access   public
495    * @return   The success value of both xml_serializer->serialize() and _filePutContents()
496    * @author   Quinn Comendant <quinn@strangecode.com>
497    * @since    11 Apr 2006 20:53:42
498    */
499    protected function _initializeDataFile()
500    {
501        $app =& App::getInstance();
502
503        $app->logMsg(sprintf('Initializing data file: %s', $this->_data_file), LOG_INFO, __FILE__, __LINE__);
504        $xml_file_contents = $this->xml_serializer->serialize($this->_data);
505        return $this->_filePutContents($this->_data_file, $xml_file_contents);
506    }
507
508    /**
509     * Saves the POSTed data by overwriting the pedit variables in the
510     * current file.
511     *
512     * @access private
513     * @return bool  False if unauthorized or on failure. True on success.
514     */
515    protected function _writeData()
516    {
517        $app =& App::getInstance();
518
519        if (!$this->_authorized) {
520            return false;
521        }
522        if ($this->_fileHash() != getFormData('file_hash')) {
523            // Posted data is NOT for this file!
524            $app->logMsg(sprintf('File_hash does not match current file.', null), LOG_WARNING, __FILE__, __LINE__);
525            return false;
526        }
527
528        // Scrub incoming data. Escape tags?
529        $new_data = getFormData('_pedit_data');
530
531        if (is_array($new_data) && !empty($new_data)) {
532            // Make certain a version is created.
533            $this->_deleteOldVersions();
534            if (!$this->_createVersion()) {
535                $app->logMsg(sprintf('Failed creating new version of file.', null), LOG_NOTICE, __FILE__, __LINE__);
536                return false;
537            }
538
539            // Collect posted data that is already specified in _data (by set()).
540            foreach ($new_data as $name => $content) {
541                if (isset($this->_data[$name])) {
542                    $this->_data[$name]['content'] = $content;
543                }
544            }
545
546            if (is_array($this->_data) && !empty($this->_data)) {
547                $xml_file_contents = $this->xml_serializer->serialize($this->_data);
548                return $this->_filePutContents($this->_data_file, $xml_file_contents);
549            }
550        }
551    }
552
553    /*
554    * Writes content to the specified file.
555    *
556    * @access   public
557    * @param    string  $filename   Path to file.
558    * @param    string  $content    Data to write into file.
559    * @return   bool                Success or failure.
560    * @author   Quinn Comendant <quinn@strangecode.com>
561    * @since    11 Apr 2006 22:48:30
562    */
563    protected function _filePutContents($filename, $content)
564    {
565        $app =& App::getInstance();
566
567        // Ensure requested filename is within the pedit data dir.
568        if (mb_strpos($filename, $this->getParam('data_dir')) === false) {
569            $app->logMsg(sprintf('Failed writing file outside pedit data_dir: %s', $filename), LOG_ERR, __FILE__, __LINE__);
570            return false;
571        }
572
573        // Recursively create directories.
574        $subdirs = preg_split('!/!', str_replace($this->getParam('data_dir'), '', dirname($filename)), -1, PREG_SPLIT_NO_EMPTY);
575        // Start with the pedit data_dir base.
576        $curr_path = $this->getParam('data_dir');
577        while (!empty($subdirs)) {
578            $curr_path .= '/' . array_shift($subdirs);
579            if (!is_dir($curr_path)) {
580                if (!mkdir($curr_path)) {
581                    $app->logMsg(sprintf('Failed mkdir: %s', $curr_path), LOG_ERR, __FILE__, __LINE__);
582                    return false;
583                }
584            }
585        }
586
587        // Open file for writing and truncate to zero length.
588        if ($fp = fopen($filename, 'w')) {
589            if (flock($fp, LOCK_EX)) {
590                fwrite($fp, $content);
591                flock($fp, LOCK_UN);
592            } else {
593                $app->logMsg(sprintf('Could not lock file for writing: %s', $filename), LOG_ERR, __FILE__, __LINE__);
594                return false;
595            }
596            fclose($fp);
597            // Success!
598            $app->logMsg(sprintf('Wrote to file: %s', $filename), LOG_DEBUG, __FILE__, __LINE__);
599            return true;
600        } else {
601            $app->logMsg(sprintf('Could not open file for writing: %s', $filename), LOG_ERR, __FILE__, __LINE__);
602            return false;
603        }
604    }
605
606    /**
607     * Makes a copy of the current file with the unix timestamp appended to the
608     * filename.
609     *
610     * @access private
611     * @return bool  False on failure. True on success.
612     */
613    protected function _createVersion()
614    {
615        $app =& App::getInstance();
616
617        if (!$this->_authorized) {
618            return false;
619        }
620        if ($this->_fileHash() != getFormData('file_hash')) {
621            // Posted data is NOT for this file!
622            $app->logMsg(sprintf('File_hash does not match current file.', null), LOG_ERR, __FILE__, __LINE__);
623            return false;
624        }
625
626        // Ensure current data file exists.
627        if (!file_exists($this->_data_file)) {
628            $app->logMsg(sprintf('Data file does not yet exist: %s', $this->_data_file), LOG_NOTICE, __FILE__, __LINE__);
629            return false;
630        }
631
632        // Do the actual copy. File naming scheme must be consistent!
633        // filename.php.xml becomes filename.php__1124124128.xml
634        $version_file = sprintf('%s__%s.xml', preg_replace('/\.xml$/', '', $this->_data_file), time());
635        if (!copy($this->_data_file, $version_file)) {
636            $app->logMsg(sprintf('Failed copying new version: %s -> %s', $this->_data_file, $version_file), LOG_ERR, __FILE__, __LINE__);
637            return false;
638        }
639
640        return true;
641    }
642
643    /*
644    * Delete all versions older than versions_min_days if there are more than versions_min_qty or 100.
645    *
646    * @access   public
647    * @return bool  False on failure. True on success.
648    * @author   Quinn Comendant <quinn@strangecode.com>
649    * @since    12 Apr 2006 11:08:11
650    */
651    protected function _deleteOldVersions()
652    {
653        $app =& App::getInstance();
654
655        $version_files = $this->_getVersions();
656        if (is_array($version_files) && sizeof($version_files) > $this->getParam('versions_min_qty')) {
657            // Pop oldest ones off bottom of array.
658            $oldest = array_pop($version_files);
659            // Loop while minimum X qty && minimum X days worth but never more than 100 qty.
660            while ((sizeof($version_files) > $this->getParam('versions_min_qty')
661            && $oldest['unixtime'] < mktime(date('H'), date('i'), date('s'), date('m'), date('d') - $this->getParam('versions_min_days'), date('Y')))
662            || sizeof($version_files) > 100) {
663                $del_file = dirname($this->_data_file) . '/' . $oldest['filename'];
664                if (!unlink($del_file)) {
665                    $app->logMsg(sprintf('Failed deleting version: %s', $del_file), LOG_ERR, __FILE__, __LINE__);
666                }
667                $oldest = array_pop($version_files);
668            }
669        }
670    }
671
672    /**
673     * Returns an array of all archived versions of the current file,
674     * sorted with newest versions at the top of the array.
675     *
676     * @access private
677     * @return array  Array of versions.
678     */
679    protected function _getVersions()
680    {
681        $version_files = array();
682        $dir_handle = opendir(dirname($this->_data_file));
683        $curr_file_preg_pattern = sprintf('/^%s__(\d+).xml$/', preg_quote(basename($_SERVER['PHP_SELF'])));
684        while ($dir_handle && ($version_file = readdir($dir_handle)) !== false) {
685            if (!preg_match('/^\./', $version_file) && !is_dir($version_file) && preg_match($curr_file_preg_pattern, $version_file, $time)) {
686                $version_files[] = array(
687                    'filename' => $version_file,
688                    'unixtime' => $time[1],
689                    'filesize' => filesize(dirname($this->_data_file) . '/' . $version_file)
690                );
691            }
692        }
693
694        if (is_array($version_files) && !empty($version_files)) {
695            array_multisort($version_files, SORT_DESC);
696            return $version_files;
697        } else {
698            return array();
699        }
700    }
701
702    /**
703     * Makes a version backup of the current file, then copies the specified
704     * archived version over the current file.
705     *
706     * @access private
707     * @param string $version    Unix timestamp of archived version to restore.
708     * @return bool  False on failure. True on success.
709     */
710    protected function _restoreVersion($version)
711    {
712        $app =& App::getInstance();
713
714        if (!$this->_authorized) {
715            return false;
716        }
717
718        // The file to restore.
719        $version_file = sprintf('%s__%s.xml', preg_replace('/\.xml$/', '', $this->_data_file), $version);
720
721        // Ensure specified version exists.
722        if (!file_exists($version_file)) {
723            $app->logMsg(sprintf('Cannot restore non-existent file: %s', $version_file), LOG_NOTICE, __FILE__, __LINE__);
724            return false;
725        }
726
727        // Make certain a version is created.
728        if (!$this->_createVersion()) {
729            $app->logMsg(sprintf('Failed creating new version of file.', null), LOG_ERR, __FILE__, __LINE__);
730            return false;
731        }
732
733        // Do the actual copy.
734        if (!copy($version_file, $this->_data_file)) {
735            $app->logMsg(sprintf('Failed copying old version: %s -> %s', $version_file, $this->_data_file), LOG_ERR, __FILE__, __LINE__);
736            return false;
737        }
738
739        // Success!
740        $app->raiseMsg(sprintf(_("Page has been restored to version %s."), $version), MSG_SUCCESS, __FILE__, __LINE__);
741        return true;
742    }
743
744} // End class.
Note: See TracBrowser for help on using the repository browser.