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

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

moving pEdit styles into codebase

File size: 23.7 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        <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" id="sc-pedit-form">
215        <input type="hidden" name="filename" value="<?php echo $_SERVER['PHP_SELF']; ?>" />
216        <input type="hidden" name="file_hash" value="<?php echo $this->_fileHash(); ?>" />
217        <?php
218        App::printHiddenSession();
219        switch ($this->op) {
220        case 'Edit' :
221            ?>
222            <div class="sc-pedit-buttons">
223                <input type="submit" name="op" value="<?php echo _("Save"); ?>" />
224                <input type="submit" name="op" value="<?php echo _("Cancel"); ?>" />
225            </div>
226            <?php
227            break;
228        case 'View' :
229            ?>
230            <input type="hidden" name="version" value="<?php echo getFormData('version'); ?>" />
231            <?php
232            break;
233        }
234    }
235
236    /**
237     * Loops through the PEdit data array and prints all the HTML forms corresponding
238     * to all pedit variables, in the order in which they were 'set'.
239     *
240     * @access public
241     */
242    function printAllForms()
243    {
244        if ($this->_authorized && $this->op == 'Edit' && is_array($this->_data) && $this->_data_loaded) {
245            foreach ($this->_data as $name=>$d) {
246                $this->printForm($name);
247            }
248        }
249    }
250
251    /**
252     * Prints the HTML forms corresponding to pedit variables. Each variable
253     * must first be 'set'.
254     *
255     * @access public
256     * @param string $name      The name of the variable.
257     * @param string $type      Type of form to print. Currently only 'text' and 'textarea' supported.
258     */
259    function printForm($name, $type='text')
260    {
261        if ($this->_authorized && $this->op == 'Edit' && $this->_data_loaded) {
262            $type = (isset($this->_data[$name]['type'])) ? $this->_data[$name]['type'] : $type;
263            // Print edit form.
264            switch ($type) {
265            case 'text' :
266            default :
267                ?><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
268                break;
269            case 'textarea' :
270                ?><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
271                break;
272            }
273        }
274    }
275
276    /**
277     * Prints the endig </form> HTML tag, as well as buttons used during
278     * different operations.
279     *
280     * @return bool  False if unauthorized or current page is a version.
281     */
282    function formEnd()
283    {
284        if (!$this->_authorized || empty($this->_data)) {
285            // Don't show form elements for versioned documents.
286            return false;
287        }
288        switch ($this->op) {
289        case 'Edit' :
290            ?>
291            <div class="sc-pedit-buttons">
292                <input type="submit" name="op" value="<?php echo _("Save"); ?>" />
293                <input type="submit" name="op" value="<?php echo _("Cancel"); ?>" />
294            </div>
295            </form>
296            <?php
297            break;
298        case 'Versions' :
299            ?>
300            <div class="sc-pedit-buttons">
301                <input type="submit" name="op" value="<?php echo _("Cancel"); ?>" />
302            </div>
303            </form>
304            <?php
305            break;
306        case 'View' :
307            ?>
308            <div class="sc-pedit-buttons">
309                <input type="submit" name="op" value="<?php echo _("Restore"); ?>" />
310                <input type="submit" name="op" value="<?php echo _("Cancel"); ?>" />
311            </div>
312            <?php
313            break;
314        default :
315            ?>
316            <div class="sc-pedit-buttons">
317                <input type="submit" name="op" value="<?php echo _("Edit"); ?>" />
318                <input type="submit" name="op" value="<?php echo _("Versions"); ?>" />
319            </div>
320            </form>
321            <?php
322        }
323    }
324
325    /**
326     * Prints an HTML list of versions of current file, with the filesize
327     * and links to view and restore the file.
328     *
329     * @access public
330     */
331    function printVersions()
332    {
333        if ($this->_authorized && $this->op == 'Versions') {
334            // Print versions and commands to view/restore.
335            $version_files = $this->_getVersions();
336            ?><h1><?php printf(_("%s saved versions of %s"), sizeof($version_files), basename($_SERVER['PHP_SELF'])); ?></h1><?php
337            if (is_array($version_files) && !empty($version_files)) {
338                ?><table id="sc-pedit-versions"><?php
339                foreach ($version_files as $v) {
340                    ?>
341                    <tr>
342                        <td><?php echo date('r', $v['unixtime']); ?></td>
343                        <td><?php printf(_("%s bytes"), $v['filesize']); ?></td>
344                        <td><a href="<?php echo App::oHREF($_SERVER['PHP_SELF'] . '?op=View&version=' . $v['unixtime'] . '&file_hash=' . $this->_fileHash()); ?>"><?php echo _("View"); ?></a></td>
345                        <td><a href="<?php echo App::oHREF($_SERVER['PHP_SELF'] . '?op=Restore&version=' . $v['unixtime'] . '&file_hash=' . $this->_fileHash()); ?>"><?php echo _("Restore"); ?></a></td>
346                    </tr>
347                    <?php
348                }
349                ?></table><?php
350            ?><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
351            }
352        }
353    }
354
355    /*
356    * Returns a secreat hash for the current file.
357    *
358    * @access   public
359    * @author   Quinn Comendant <quinn@strangecode.com>
360    * @since    12 Apr 2006 10:52:35
361    */
362    function _fileHash()
363    {
364        return md5(App::getParam('signing_key') . $_SERVER['PHP_SELF']);
365    }
366
367    /*
368    * Load the XML data file into $this->_data.
369    *
370    * @access   public
371    * @return   bool    false on error
372    * @author   Quinn Comendant <quinn@strangecode.com>
373    * @since    11 Apr 2006 20:36:26
374    */
375    function _loadDataFile()
376    {
377        if (!file_exists($this->_data_file)) {
378            if (!$this->_initializeDataFile()) {
379                App::logMsg(sprintf('Initializing content file failed: %s', $this->_data_file), LOG_WARNING, __FILE__, __LINE__);
380                return false;
381            }
382        }
383        $xml_file_contents = file_get_contents($this->_data_file);
384        $status = $this->xml_unserializer->unserialize($xml_file_contents, false);   
385        if (PEAR::isError($status)) {
386            App::logMsg(sprintf('XML_Unserialize error: %s', $status->getMessage()), LOG_WARNING, __FILE__, __LINE__);
387            return false;
388        }
389        $xml_file_data = $this->xml_unserializer->getUnserializedData();
390
391        // Only load data specified with set(), even though there may be more in the xml file.
392        foreach ($this->_data as $name => $initial_data) {
393            if (isset($xml_file_data[$name])) {
394                $this->_data[$name] = array_merge($initial_data, $xml_file_data[$name]);
395            } else {
396                $this->_data[$name] = $initial_data;
397            }
398        }
399
400        $this->_data_loaded = true;
401        return true;
402    }
403   
404    /*
405    * Start a new data file.
406    *
407    * @access   public
408    * @return   The success value of both xml_serializer->serialize() and _filePutContents()
409    * @author   Quinn Comendant <quinn@strangecode.com>
410    * @since    11 Apr 2006 20:53:42
411    */
412    function _initializeDataFile()
413    {
414        App::logMsg(sprintf('Initializing data file: %s', $this->_data_file), LOG_INFO, __FILE__, __LINE__);
415        $xml_file_contents = $this->xml_serializer->serialize($this->_data);
416        return $this->_filePutContents($this->_data_file, $xml_file_contents);
417    }
418
419    /**
420     * Saves the POSTed data by overwriting the pedit variables in the
421     * current file.
422     *
423     * @access private
424     * @return bool  False if unauthorized or on failure. True on success.
425     */
426    function _writeData()
427    {
428        if (!$this->_authorized) {
429            return false;
430        }
431        if ($this->_fileHash() != getFormData('file_hash')) {
432            // Posted data is NOT for this file!
433            App::logMsg(sprintf('File_hash does not match current file.', null), LOG_WARNING, __FILE__, __LINE__);
434            return false;
435        }
436
437        // Scrub incoming data. Escape tags?
438        $new_data = getFormData('_pedit_data');
439
440        if (is_array($new_data) && !empty($new_data)) {
441            // Make certain a version is created.
442            $this->_deleteOldVersions();
443            if (!$this->_createVersion()) {
444                App::logMsg(sprintf('Failed creating new version of file.', null), LOG_NOTICE, __FILE__, __LINE__);
445                return false;
446            }
447           
448            // Collect posted data that is already specified in _data (by set()).
449            foreach ($new_data as $name => $content) {
450                if (isset($this->_data[$name])) {
451                    $this->_data[$name]['content'] = $content;
452                }
453            }
454           
455            if (is_array($this->_data) && !empty($this->_data)) {
456                $xml_file_contents = $this->xml_serializer->serialize($this->_data);
457                return $this->_filePutContents($this->_data_file, $xml_file_contents);
458            }
459        }
460    }
461   
462    /*
463    * Writes content to the specified file.
464    *
465    * @access   public
466    * @param    string  $filename   Path to file.
467    * @param    string  $content    Data to write into file.
468    * @return   bool                Success or failure.
469    * @author   Quinn Comendant <quinn@strangecode.com>
470    * @since    11 Apr 2006 22:48:30
471    */
472    function _filePutContents($filename, $content)
473    {
474        // Ensure requested filename is within the pedit data dir.
475        if (strpos($filename, $this->getParam('data_dir')) === false) {
476            App::logMsg(sprintf('Failed writing file outside pedit _data_dir: %s', $filename), LOG_ERR, __FILE__, __LINE__);
477            return false;
478        }
479
480        // Recursively create directories.
481        $subdirs = preg_split('!/!', str_replace($this->getParam('data_dir'), '', dirname($filename)), -1, PREG_SPLIT_NO_EMPTY);
482        // Start with the pedit _data_dir base.
483        $curr_path = $this->getParam('data_dir');
484        while (!empty($subdirs)) {
485            $curr_path .= '/' . array_shift($subdirs);
486            if (!is_dir($curr_path)) {
487                if (!mkdir($curr_path)) {
488                    App::logMsg(sprintf('Failed mkdir: %s', $curr_path), LOG_ERR, __FILE__, __LINE__);
489                    return false;
490                }
491            }
492        }
493
494        // Open file for writing and truncate to zero length.
495        if ($fp = fopen($filename, 'w')) {
496            if (flock($fp, LOCK_EX)) {
497                fwrite($fp, $content, strlen($content));
498                flock($fp, LOCK_UN);
499            } else {
500                App::logMsg(sprintf('Could not lock file for writing: %s', $filename), LOG_ERR, __FILE__, __LINE__);
501                return false;
502            }
503            fclose($fp);
504            // Success!
505            App::logMsg(sprintf('Wrote to file: %s', $filename), LOG_DEBUG, __FILE__, __LINE__);
506            return true;
507        } else {
508            App::logMsg(sprintf('Could not open file for writing: %s', $filename), LOG_ERR, __FILE__, __LINE__);
509            return false;
510        }
511    }
512
513    /**
514     * Makes a copy of the current file with the unix timestamp appended to the
515     * filename.
516     *
517     * @access private
518     * @return bool  False on failure. True on success.
519     */
520    function _createVersion()
521    {
522        if (!$this->_authorized) {
523            return false;
524        }
525        if ($this->_fileHash() != getFormData('file_hash')) {
526            // Posted data is NOT for this file!
527            App::logMsg(sprintf('File_hash does not match current file.', null), LOG_ERR, __FILE__, __LINE__);
528            return false;
529        }
530
531        // Ensure current data file exists.
532        if (!file_exists($this->_data_file)) {
533            App::logMsg(sprintf('Data file does not yet exist: %s', $this->_data_file), LOG_NOTICE, __FILE__, __LINE__);
534            return false;
535        }
536
537        // Do the actual copy. File naming scheme must be consistent!
538        // filename.php.xml becomes filename.php__1124124128.xml
539        $version_file = sprintf('%s__%s.xml', preg_replace('/\.xml$/', '', $this->_data_file), time());
540        if (!copy($this->_data_file, $version_file)) {
541            App::logMsg(sprintf('Failed copying new version: %s -> %s', $this->_data_file, $version_file), LOG_ERR, __FILE__, __LINE__);
542            return false;
543        }
544
545        return true;
546    }
547   
548    /*
549    * Delete all versions older than versions_min_days if there are more than versions_min_qty or 100.
550    *
551    * @access   public
552    * @return bool  False on failure. True on success.
553    * @author   Quinn Comendant <quinn@strangecode.com>
554    * @since    12 Apr 2006 11:08:11
555    */
556    function _deleteOldVersions()
557    {
558        $version_files = $this->_getVersions();
559        if (is_array($version_files) && sizeof($version_files) > $this->getParam('versions_min_qty')) {
560            // Pop oldest ones off bottom of array.
561            $oldest = array_pop($version_files);
562            // Loop while minimum X qty && minimum X days worth but never more than 100 qty.
563            while ((sizeof($version_files) > $this->getParam('versions_min_qty')
564            && $oldest['unixtime'] < mktime(date('H'), date('i'), date('s'), date('m'), date('d') - $this->getParam('versions_min_days'), date('Y')))
565            || sizeof($version_files) > 100) {
566                $del_file = dirname($this->_data_file) . '/' . $oldest['filename'];
567                if (!unlink($del_file)) {
568                    App::logMsg(sprintf('Failed deleting version: %s', $del_file), LOG_ERR, __FILE__, __LINE__);
569                }
570                $oldest = array_pop($version_files);
571            }
572        }
573    }
574
575    /**
576     * Returns an array of all archived versions of the current file,
577     * sorted with newest versions at the top of the array.
578     *
579     * @access private
580     * @return array  Array of versions.
581     */
582    function _getVersions()
583    {
584        $version_files = array();
585        $dir_handle = opendir(dirname($this->_data_file));
586        $curr_file_preg_pattern = sprintf('/^%s__(\d+).xml$/', preg_quote(basename($_SERVER['PHP_SELF'])));
587        while ($dir_handle && ($version_file = readdir($dir_handle)) !== false) {
588            if (!preg_match('/^\./', $version_file) && !is_dir($version_file) && preg_match($curr_file_preg_pattern, $version_file, $time)) {
589                $version_files[] = array(
590                    'filename' => $version_file,
591                    'unixtime' => $time[1],
592                    'filesize' => filesize(dirname($this->_data_file) . '/' . $version_file)
593                );
594            }
595        }
596
597        if (is_array($version_files) && !empty($version_files)) {
598            array_multisort($version_files, SORT_DESC);
599            return $version_files;
600        } else {
601            return array();
602        }
603    }
604
605    /**
606     * Makes a version backup of the current file, then copies the specified
607     * archived version over the current file.
608     *
609     * @access private
610     * @param string $version    Unix timestamp of archived version to restore.
611     * @return bool  False on failure. True on success.
612     */
613    function _restoreVersion($version)
614    {
615        if (!$this->_authorized) {
616            return false;
617        }
618       
619        // The file to restore.
620        $version_file = sprintf('%s__%s.xml', preg_replace('/\.xml$/', '', $this->_data_file), $version);
621       
622        // Ensure specified version exists.
623        if (!file_exists($version_file)) {
624            App::logMsg(sprintf('Cannot restore non-existant file: %s', $version_file), LOG_NOTICE, __FILE__, __LINE__);
625            return false;
626        }
627
628        // Make certain a version is created.
629        if (!$this->_createVersion()) {
630            App::logMsg(sprintf('Failed creating new version of file.', null), LOG_ERR, __FILE__, __LINE__);
631            return false;
632        }
633
634        // Do the actual copy.
635        if (!copy($version_file, $this->_data_file)) {
636            App::logMsg(sprintf('Failed copying old version: %s -> %s', $version_file, $this->_data_file), LOG_ERR, __FILE__, __LINE__);
637            return false;
638        }
639
640        // Success!
641        App::raiseMsg(sprintf(_("Page has been restored to version %s."), $version), MSG_SUCCESS, __FILE__, __LINE__);
642        return true;
643    }
644
645} // End class.
646
647?>
Note: See TracBrowser for help on using the repository browser.