source: trunk/lib/PEdit.inc.php @ 93

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

Q - couple tweaks to PEdit

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