<?php
/**
 * Zend Framework Examples
 *
 * @category  ZfEx
 * @package   TryIt
 * @author    Michel Corne
 * @copyright 2009 Michel Corne
 * @license   http://www.opensource.org/licenses/bsd-license.php The BSD License
 * @see       http://zend-framework-examples.blogspot.com
 */

/*
In this example, we implement a log file.
*/

/*
Loads the autoloader
*/
set_include_path('../ZendFramework/1.9.5/library');
require_once 
'Zend/Loader/Autoloader.php';
$autoloader Zend_Loader_Autoloader::getInstance();

/*
Implementation of the log process
*/
class MyLog
{
    const 
FORMAT '%timestamp% %priorityName% (%priority%): %message%';

    
// We define the set of the available priorities.
    
private $_priorities = array(
        
'EMERG' => Zend_Log::EMERG,
        
'ALERT' => Zend_Log::ALERT,
        
'CRIT' => Zend_Log::CRIT,
        
'ERR' => Zend_Log::ERR,
        
'WARN' => Zend_Log::WARN,
        
'NOTICE' => Zend_Log::NOTICE,
        
'INFO' => Zend_Log::INFO,
        
'DEBUG' => Zend_Log::DEBUG,
    );

    
/* Logging the message */
    
public function process()
    {
        
// We get the message, the priority, the formatter, the custom format, the filter,
        // or the log removal request, from the GET request.
        
list($message$priority$formatter$format$filter$remove) =
            
$this->_getParameters();

        try {
            
// We get the file name.
            
$file $this->_getFile();

            if (
$remove) {
                
// If the user requested to remove the logs, we delete the file.
                
@unlink($file);
                
setcookie('log'''1'/');
                
$result 'The messages have been removed!';
            } else {
                
// Otherwise, we instantiate the log  object.
                
$logger = new Zend_Log;

                
// We add the writing adapter.
                
$writer $this->_setWriter($file$formatter$format);
                
$logger->addWriter($writer);

                if (isset(
$this->_priorities[$filter])) {
                    
// If the user requested a filter, we add the filter.
                    
$logFilter = new Zend_Log_Filter_Priority($this->_priorities[$filter]);
                    
$logger->addFilter($logFilter);
                }

                if (
$message) {
                    
// We write the message into the log file.
                    
$logger->log($message$this->_priorities[$priority]);
                    
$result 'The message is logged if not filtered!';
                } else {
                    
$result 'Please enter a message!';
                }
            }


        } catch (
Exception $e) {
            
// If we catch an exception, we return the error message.
            
$result $e->getMessage();
        }

        
$logs = @file_get_contents($file) or $logs 'There are no messages';

        return array(
$message$priority$formatter$format$filter$remove,
            
$result$logs);
    }

    
/* Extraction of the parameters from the GET request */
    
private function _getParameters()
    {
        
$message = isset($_GET['message'])? trim($_GET['message']) : null;
        
$formatter = isset($_GET['formatter'])? $_GET['formatter'] : null;
        
$format = empty($_GET['format'])? self::FORMAT $_GET['format'];

        
// We set the priority to the emergency level by default.
        
$priority = (isset($_GET['priority']) and isset($this->_priorities[$_GET['priority']]))?
            
$_GET['priority'] : 'EMERG';
        
// We ignore the filter if the filter is invalid.
        
$filter = (isset($_GET['filter']) and isset($this->_priorities[$_GET['filter']]))?
            
$_GET['filter'] : null;

        
$remove = !empty($_GET['remove']);

        return array(
$message$priority$formatter$format$filter$remove);
    }

    
/* Getting a log file name */
    
private function _getFile()
    {
        if (empty(
$_COOKIE['log'])) {
            
// If the cookie does not exist, we create the name of the file randomly.
            // And we store the name in the cookie.
            
$file dirname(__FILE__) . '/data/log/file-' rand() . '.txt';
            
setcookie('log'$filetime() + 3600'/');
        } else {
           
// If the cookie exists, we get the name of the file from the cookie.
           
$file $_COOKIE['log'];
        }

        return 
$file;
    }

    
/* Creation of the writing adapter */
    
private function _setWriter($file$formatter$format)
    {
        
$writer = new Zend_Log_Writer_Stream($file);

        
// We create an XML adapter or a simple adapter.
        // The simple adapter will use the custom format.
        
$logFormatter $formatter == 'XML'? new Zend_Log_Formatter_Xml():
            new 
Zend_Log_Formatter_Simple($format PHP_EOL);

        
$writer->setFormatter($logFormatter);

        return 
$writer;
    }
}

/* Displaying items */
class MyHtml
{
    
/* Displaying the title of the page based on the file name. */
    
public static function printTitle()
    {
        
$basename basename(__FILE__'.php');
        
$title ucwords(str_replace('-' ' '$basename));
        
$zfVersion Zend_Version::VERSION;
        
$phpVersion phpversion();
        echo 
"ZfEx $title (ZF/$zfVersion PHP/$phpVersion)";
    }

    
/* Displaying the selected option */
    
public static function printSelected($value$target)
    {
        
$value == $target and print 'selected="selected"';
    }

    
/* Displaying a string or an array */
    
public static function display($mixed)
    {
        
// If the data is an array, we convert the array into a set of lines.
        
is_array($mixed) and $mixed implode("\n"$mixed);
        
$mixed stripslashes($mixed);
        
// We converts special characters into HTML entities.
        
$mixed htmlspecialchars($mixedENT_QUOTES'UTF-8');
        
// We convert new-line characters into line breaks.
        
echo nl2br($mixed);
    }
}

/*
Logging the message
*/
// We log the message and we get all the parameters and the result of the request,
// to display in the form.
$log = new MyLog();
list(
$message$priority$formatter$format$filter$remove$result$logs) =
    
$log->process();
?>
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title><?php MyHtml::printTitle();?></title>
    <style type="text/css">
      body, td {
          font-family: arial, sans-serif;
          font-size: 0.9em;
      }
      input.message {
          width: 50em;
      }
      input.format {
          width: 30em;
      }
    </style>
  </head>

  <body>

    <p>EXAMPLE <?php MyHtml::printTitle();?></p>
    <hr />

    <form name="form">
      <table>

        <tr>
          <td>Message</td>
          <td><input class="message" type="text" name="message"
                     value="<?php MyHtml::display($message);?>"/>
          </td>
        </tr>

        <tr>
          <td>Priority</td>
          <td>
            <select name="priority">
              <option <?php MyHtml::printSelected($priority'EMERG');?>>EMERG</option>
              <option <?php MyHtml::printSelected($priority'ALERT');?>>ALERT</option>
              <option <?php MyHtml::printSelected($priority'CRIT');?>>CRIT</option>
              <option <?php MyHtml::printSelected($priority'ERR');?>>ERR</option>
              <option <?php MyHtml::printSelected($priority'WARN');?>>WARN</option>
              <option <?php MyHtml::printSelected($priority'NOTICE');?>>NOTICE</option>
              <option <?php MyHtml::printSelected($priority'INFO');?>>INFO</option>
              <option <?php MyHtml::printSelected($priority'DEBUG');?>>DEBUG</option>
            </select>
          </td>
        </tr>

        <tr>
          <td>Formatter</td>
          <td>
            <select name="formatter">
              <option <?php MyHtml::printSelected($formatter'Simple');?>>Simple</option>
              <option <?php MyHtml::printSelected($formatter'XML');?>>XML</option>
            </select>
          </td>
        </tr>

        <tr>
          <td>Format</td>
          <td><input class="format" type="text" name="format"
                     value="<?php MyHtml::display($format);?>"/>
              <a href="javascript: form.format.value = '<?php echo MyLog::FORMAT;?>'">Reset</a>
          </td>
        </tr>

        <tr>
          <td>Filter</td>
          <td>
            <select name="filter">
              <option></option>
              <option <?php MyHtml::printSelected($filter'EMERG');?>>EMERG</option>
              <option <?php MyHtml::printSelected($filter'ALERT');?>>ALERT</option>
              <option <?php MyHtml::printSelected($filter'CRIT');?>>CRIT</option>
              <option <?php MyHtml::printSelected($filter'ERR');?>>ERR</option>
              <option <?php MyHtml::printSelected($filter'WARN');?>>WARN</option>
              <option <?php MyHtml::printSelected($filter'NOTICE');?>>NOTICE</option>
              <option <?php MyHtml::printSelected($filter'INFO');?>>INFO</option>
              <option <?php MyHtml::printSelected($filter'DEBUG');?>>DEBUG</option>
            </select>
          </td>
        </tr>

        <tr><td>&nbsp;</td></tr>

        <tr>
          <td></td>
          <td>
            <input type="submit" value="Submit" />
            <br /> <br />
            <a href="?remove=1">Remove messages</a>
          </td>
        </tr>

      </table>
    </form>

    <hr />
    RESULT
    <br /> <br />
    <?php MyHtml::display($result);?>
    <br /> <br />

    <hr />
    MESSAGES
    <br /> <br />
    <?php MyHtml::display($logs);?>

  </body>
</html>