<?php

    error_reporting(E_ERROR | E_PARSE);

    if(substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start("ob_gzhandler"); else ob_start();

    // required headers
    header("Access-Control-Allow-Origin: *");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');    // cache for 1 day
    // Access-Control headers are received during OPTIONS requests
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");         
    
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
    
    }

    header("Content-Type: application/json; charset=UTF-8");
    
    include_once( '../inc/db.php' );
    include_once( '../inc/conferencia.php' );
    include_once( '../inc/helpers.php' );

    if($_REQUEST){
        $func = ($_REQUEST['f']!=''?$_REQUEST['f']:'list');
        $q = $_REQUEST['query'];
        $return = ($_REQUEST['return']!=''?$_REQUEST['return']:true);
        $overwrite = ($_REQUEST['overwrite']!=''?$_REQUEST['overwrite']:false);
        $id = $_REQUEST['id'];
        $co = $_REQUEST['country_code'];
        $last_update = ($_REQUEST['last_update']!=''?$_REQUEST['last_update']:'');
    	$text = $_REQUEST['t'];
        $year = ($_REQUEST['year']!=''?$_REQUEST['year']:2018);
        $month = ($_REQUEST['month']!=''?$_REQUEST['month']:'');
        $cache = ($_REQUEST['cache']!=''?$_REQUEST['cache']:false);
        //$locale = ($_REQUEST['locale']!=''?$_REQUEST['locale']:'es');
        define('LOCALE', ($_REQUEST['locale']!=''?$_REQUEST['locale']:'es_ES'));
    }

    switch ( $func ){
        case "epub":
            conference_epub($id,$return,$overwrite);
            break;
        case "country_conferences":
            country_conferences($co);
            break;
        case "countries":
            countries_list();
            break;
        case "content_search":
            conference_content_search($q);
            break;
        case "search":
            conference_search($q);
            break;
        case "detail":
            conference_detail($id);
            break;
        case "last_update":
            conference_last_update( $id );
            break;
        case "texts":
            conferences_list($year,$month,$last_update,true,$cache);
            break;
        case "list":
        default:
            conferences_list($year,$month,$last_update,false,$cache);
            break;
    }

    function conferences_list( $year, $month, $last_update, $text, $cache ){

        if( $cache==false ){
            
            $dir = '/var/www/html/v2/cache';
            $filen = 'conferencias_es_' . $year;
            if($text){
                $filen .= '_texts';
            }
            $file = $dir . '/' . $filen . '.json';
            if(!file_exists( $file ) || $_REQUEST['forceupdate']==true ){
                $data = build_conferences_list( $year, $month, $last_update, $text );
                $data['cache'] = time();
                file_put_contents( $file , json_encode($data) );
            } else {
                readfile( $file );
                die();
            }

        } else {

            $data = build_conferences_list( $year, $month, $last_update, $text );
            $data['cache'] = $cache;

        }
        
        send_response( $data );
    }

    function build_conferences_list( $year, $month, $last_update, $text ){

        $database = new Database();
        $db = $database->getConnection();

        $conference = new Conferencia($db);

        $stmt = $conference->list( $year, $month, $last_update, $text );
        
        $num = $stmt->rowCount();

        if($num>0){
            $conferences_arr=array();
        
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
                extract($row);
        
                if(!$text){
                    $response_item=array(
                        "_id" => $ID,
                        "ty" => 'conferencia',
                        "d" => date("Y-m-d", strtotime( $creation_date ) ),
                        "t" => $title,
                        "a" => $no_activity,
                        "c" => $city,
                        "st" => $state,
                        "co" => $country,
                        "s" => $duration,
                        "sl" => $slug,
                        "th" => $thumbnail,
                        "meta" => unserialize($meta),
                        "hasText" => ($bodylength>0?true:false)
                    );
                    $dt = new DateTime($date);
                    $formatter = new IntlDateFormatter(LOCALE, IntlDateFormatter::SHORT, IntlDateFormatter::SHORT);
                    $formatter->setPattern("EEEE, d 'de' MMMM 'de' yyyy");
                    $response_item['date'] = ucfirst($formatter->format($dt));
                    $response_item['lo'] = implode(', ',array_filter(array($city,$state,Locale::getDisplayRegion('-'.strtoupper($country), LOCALE ))));
                    $response_item['dur'] = gmdate("H:i:s", (int)$duration);
                    $response_item['slug'] = 'https://conferencias.carpa.com/conferencias/'.$slug;

                    $fileData = $conference->get_post_files( $ID );
                    $files = $fileData->fetch(PDO::FETCH_ASSOC);
                    
                    $response_item['yt'] = str_replace( 'http://', 'https://', $files['youtube']);
                    $response_item['v'] = str_replace( 'http://', 'https://',$files['video']);
                    $response_item['au'] = str_replace( 'http://', 'https://',$files['audio']);
                    $response_item['p'] = str_replace( 'http://', 'https://',$files['pdf']);
                    $response_item['ps'] = str_replace( 'http://', 'https://',$files['pdf_simple']);

                } else {
                    $response_item=array(
                        "_id" => $ID,
                        "b" => wpautop( $content )
                    );
                }

                array_push($conferences_arr, $response_item);
            }
        }
                
        $data = array(
            'count' => $num,
            'result' => array (
                'conferencias' => $conferences_arr
            )
        );

        $data['year'] = $year;
        $data['month'] = $month;

        return $data;
    }

    function conference_detail( $id ){
        $database = new Database();
        $db = $database->getConnection();

        $conference = new Conferencia($db);
        
        $stmt = $conference->detail($id);
        $num = $stmt->rowCount();
        
        if($num>0){
            $conferences_arr=array();
        
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
                extract($row);
        
                $response_item = array(
                    '_id' => $ID,
                    'ty' => 'conference',
                    'd' => date("Y/m/d", strtotime($date)),
                    't' => $title,
                    'b' => wpautop($content),
                    'lu' => time($last_updated),
                    'a' => $no_activity,
                    'c' => $city,
                    'st' => $state,
                    'co' => $country,
                    's' => $duration,
                    'th' => $thumbnail,
                );

                $url = str_replace( 'http://', 'https://', $guid );

                $response_item['u'] = $url;

                $fileData = $conference->get_post_files( $ID );
                $files = $fileData->fetch(PDO::FETCH_ASSOC);
                
                $response_item['yt'] = $files['youtube'];
                $response_item['v'] = $files['video'];
                $response_item['au'] = $files['audio'];
                $response_item['af'] = $files['audio_flac'];
                $response_item['p'] = $files['pdf'];
                $response_item['ps'] = $files['pdf_simple'];

                $dt = new DateTime($date);
                $formatter = new IntlDateFormatter(LOCALE, IntlDateFormatter::SHORT, IntlDateFormatter::SHORT);
                $formatter->setPattern("EEEE, d 'de' MMMM 'de' yyyy");
                $response_item['date'] = ucfirst($formatter->format($dt));
                $response_item['lo'] = implode(', ',array_filter(array($city,$state,Locale::getDisplayRegion('-'.strtoupper($country), LOCALE ))));
                $response_item['dur'] = gmdate("H:i:s", (int)$duration);
                $response_item['slug'] = 'https://conferencias.carpa.com/conferencias/'.$slug;

                array_push($conferences_arr, $response_item);
            }
        }

        $data = array(
            'count' => $num,
            'result' => array (
                'conferences' => $conferences_arr
            )
        );

        send_response( $data );
    }

    function send_response( $data ){
        // set response code - 200 OK
        http_response_code(200);
        
        echo json_encode(
            $data
        );
    }

    function conference_search( $q ){
        $database = new Database();
        $db = $database->getConnection();

        $conference = new Conferencia($db);
        $stmt = $conference->title_search($q);

        $num = $stmt->rowCount();
        
        if($num>0){
            $conferences_arr=array();
        
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
                extract($row);

                $response_item=array(
                    "_id" => $ID,
                    "ty" => 'conferencia',
                    "d" => date("Y-m-d", strtotime( $creation_date ) ),
                    "t" => $title,
                    "a" => $no_activity,
                    "c" => $city,
                    "st" => $state,
                    "co" => $country,
                    "s" => $duration,
                    "sl" => $slug,
                    "th" => $thumbnail
                );

                $dt = new DateTime($date);
                $formatter = new IntlDateFormatter(LOCALE, IntlDateFormatter::SHORT, IntlDateFormatter::SHORT);
                $formatter->setPattern("EEEE, d 'de' MMMM 'de' yyyy");
                $response_item['date'] = ucfirst($formatter->format($dt));
                $response_item['lo'] = implode(', ',array_filter(array($city,$state,Locale::getDisplayRegion('-'.strtoupper($country), LOCALE ))));
                $response_item['dur'] = gmdate("H:i:s", (int)$duration);
                $response_item['slug'] = 'https://conferencias.carpa.com/conferencias/'.$slug;

                $fileData = $conference->get_post_files( $ID );
                $files = $fileData->fetch(PDO::FETCH_ASSOC);
                
                $response_item['yt'] = str_replace( 'http://', 'https://', $files['youtube']);
                $response_item['v'] = str_replace( 'http://', 'https://',$files['video']);
                $response_item['au'] = str_replace( 'http://', 'https://',$files['audio']);
                $response_item['p'] = str_replace( 'http://', 'https://',$files['pdf']);
                $response_item['ps'] = str_replace( 'http://', 'https://',$files['pdf_simple']);
                
                array_push($conferences_arr, $response_item);
            }
        }

        $data = array(
            'count' => $num,
            'query' => $q,
            'result' => array (
                'conferencias' => $conferences_arr
            )
        );

        send_response( $data );
    }

    function conference_content_search( $q ){
        $database = new Database();
        $db = $database->getConnection();

        $conference = new Conferencia($db);
        $stmt = $conference->content_search($q);

        $num = $stmt->rowCount();

        if($num>0){
            $conferences_arr=array();
        
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
                extract($row);

                $response_item=array(
                    "_id" => $ID,
                    "ty" => 'conferencia',
                    "d" => date("Y-m-d", strtotime( $creation_date ) ),
                    "t" => $title,
                    "a" => $no_activity,
                    "c" => $city,
                    "st" => $state,
                    "co" => $country,
                    "s" => $duration,
                    "sl" => $slug,
                    "th" => $thumbnail,
                    "ex" => "..." . preg_replace("/\w*?$q\w*/i", '<span class="relevanssi-query-term">$0</span>', better_strip_tags($excerpt)) . "..."
                );

                $dt = new DateTime($date);
                $formatter = new IntlDateFormatter(LOCALE, IntlDateFormatter::SHORT, IntlDateFormatter::SHORT);
                $formatter->setPattern("EEEE, d 'de' MMMM 'de' yyyy");
                $response_item['date'] = ucfirst($formatter->format($dt));
                $response_item['lo'] = implode(', ',array_filter(array($city,$state,Locale::getDisplayRegion('-'.strtoupper($country), LOCALE ))));
                $response_item['dur'] = gmdate("H:i:s", (int)$duration);
                $response_item['slug'] = 'https://conferencias.carpa.com/conferencias/'.$slug;

                $fileData = $conference->get_post_files( $ID );
                $files = $fileData->fetch(PDO::FETCH_ASSOC);
                
                $response_item['yt'] = str_replace( 'http://', 'https://', $files['youtube']);
                $response_item['v'] = str_replace( 'http://', 'https://',$files['video']);
                $response_item['au'] = str_replace( 'http://', 'https://',$files['audio']);
                $response_item['p'] = str_replace( 'http://', 'https://',$files['pdf']);
                $response_item['ps'] = str_replace( 'http://', 'https://',$files['pdf_simple']);
                
                array_push($conferences_arr, $response_item);
            }
        }

        $data = array(
            'count' => $num,
            'query' => $q,
            'result' => array (
                'conferencias' => $conferences_arr
            )
        );

        send_response( $data );
    }

    function countries_list(){

        $database = new Database();
        $db = $database->getConnection();

        $conference = new Conferencia($db);
        $stmt = $conference->country_summary();

        $num = $stmt->rowCount();

        if($num>0){
            $conferences_arr=array();
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
                extract($row);

                $response_item=array(
                    'code' => $row['country_code'],
                    'country' => $row['country'],
                    'total' => $row['total']
                );

                array_push($conferences_arr, $response_item);
            }
        }

        $data = array(
            'count' => $num,
            'countries' => $conferences_arr
        );

        send_response( $data );
    }

    function country_conferences($co){
        $database = new Database();
        $db = $database->getConnection();

        $conference = new Conferencia($db);
        $stmt = $conference->country_list($co);

        $num = $stmt->rowCount();

        if($num>0){
            $conferences_arr=array();
        
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
                extract($row);
        
                $response_item=array(
                    "_id" => $ID,
                    "ty" => 'conferencia',
                    "d" => date("Y-m-d", strtotime( $creation_date ) ),
                    "t" => $title,
                    "a" => $no_activity,
                    "c" => $city,
                    "st" => $state,
                    "co" => $country,
                    "s" => $duration,
                    "sl" => $slug,
                    "th" => $thumbnail
                );
                $dt = new DateTime($date);
                $formatter = new IntlDateFormatter(LOCALE, IntlDateFormatter::SHORT, IntlDateFormatter::SHORT);
                $formatter->setPattern("EEEE, d 'de' MMMM 'de' yyyy");
                $response_item['date'] = ucfirst($formatter->format($dt));
                $response_item['lo'] = implode(', ',array_filter(array($city,$state,Locale::getDisplayRegion('-'.strtoupper($country), LOCALE ))));
                $response_item['dur'] = gmdate("H:i:s", (int)$duration);
                $response_item['slug'] = 'https://conferencias.carpa.com/conferencias/'.$slug;

                $fileData = $conference->get_post_files( $ID );
                $files = $fileData->fetch(PDO::FETCH_ASSOC);
                
                $response_item['yt'] = str_replace( 'http://', 'https://', $files['youtube']);
                $response_item['v'] = str_replace( 'http://', 'https://',$files['video']);
                $response_item['au'] = str_replace( 'http://', 'https://',$files['audio']);
                $response_item['p'] = str_replace( 'http://', 'https://',$files['pdf']);
                $response_item['ps'] = str_replace( 'http://', 'https://',$files['pdf_simple']);

                array_push($conferences_arr, $response_item);
            }
        }
                
        $data = array(
            'count' => $num,
            'result' => array (
                'conferencias' => $conferences_arr
            )
        );

        $data['country'] = Locale::getDisplayRegion('-'.strtoupper($country), LOCALE );

        send_response( $data );
    }

    function better_strip_tags( $str, $allowable_tags = '', $strip_attrs = false, $preserve_comments = false, callable $callback = null ) {
        $allowable_tags = array_map( 'strtolower', array_filter( // lowercase
            preg_split( '/(?:>|^)\\s*(?:<|$)/', $allowable_tags, -1, PREG_SPLIT_NO_EMPTY ), // get tag names
            function( $tag ) { return preg_match( '/^[a-z][a-z0-9_]*$/i', $tag ); } // filter broken
        ) );
        $comments_and_stuff = preg_split( '/(<!--.*?(?:-->|$))/', $str, -1, PREG_SPLIT_DELIM_CAPTURE );
        foreach ( $comments_and_stuff as $i => $comment_or_stuff ) {
          if ( $i % 2 ) { // html comment
            if ( !( $preserve_comments && preg_match( '/<!--.*?-->/', $comment_or_stuff ) ) ) {
              $comments_and_stuff[$i] = '';
            }
          } else { // stuff between comments
            $tags_and_text = preg_split( "/(<(?:[^>\"']++|\"[^\"]*+(?:\"|$)|'[^']*+(?:'|$))*(?:>|$))/", $comment_or_stuff, -1, PREG_SPLIT_DELIM_CAPTURE );
            foreach ( $tags_and_text as $j => $tag_or_text ) {
              $is_broken = false;
              $is_allowable = true;
              $result = $tag_or_text;
              if ( $j % 2 ) { // tag
                if ( preg_match( "%^(</?)([a-z][a-z0-9_]*)\\b(?:[^>\"'/]++|/+?|\"[^\"]*\"|'[^']*')*?(/?>)%i", $tag_or_text, $matches ) ) {
                  $tag = strtolower( $matches[2] );
                  if ( in_array( $tag, $allowable_tags ) ) {
                    if ( $strip_attrs ) {
                      $opening = $matches[1];
                      $closing = ( $opening === '</' ) ? '>' : $closing;
                      $result = $opening . $tag . $closing;
                    }
                  } else {
                    $is_allowable = false;
                    $result = '';
                  }
                } else {
                  $is_broken = true;
                  $result = '';
                }
              } else { // text
                $tag = false;
              }
              if ( !$is_broken && isset( $callback ) ) {
                // allow result modification
                call_user_func_array( $callback, array( &$result, $tag_or_text, $tag, $is_allowable ) );
              }
              $tags_and_text[$j] = $result;
            }
            $comments_and_stuff[$i] = implode( '', $tags_and_text );
          }
        }
        $str = implode( '', $comments_and_stuff );
        return $str;
      }

      function conference_epub($id,$return,$overwrite){
        
        require_once( '/var/www/html/v2/inc/epub/EPub.php');
        require_once( '/var/www/html/v2/inc/epub/EPubChapterSplitter.class.php');
        require_once( '/var/www/html/v2/inc/epub/Zip.class.php');

        $database = new Database();
        $db = $database->getConnection();

        $conference = new Conferencia($db);
        
        $stmt = $conference->detail($id);
        $num = $stmt->rowCount();
        
        if($num>0){

            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
                extract($row);

                $code = "SPA" . '-' . date("Y-m-d", strtotime( $date ) ) . '-' . $no_activity; 

                $dt = new DateTime($date);
                $formatter = new IntlDateFormatter(LOCALE, IntlDateFormatter::SHORT, IntlDateFormatter::SHORT);
                $formatter->setPattern("EEEE, d 'de' MMMM 'de' yyyy");
                $nicedate = ucfirst($formatter->format($dt));
                $lo = implode(', ',array_filter(array($city,$state,Locale::getDisplayRegion('-'.strtoupper($country), LOCALE ))));

                //Title
                $newTitle = sanitize_title( $title );
                $fixedNewTitle = str_replace( '-','_',$newTitle );

                $newFilename = $code . "-" . $fixedNewTitle . "-" . strtoupper( substr( $city , 0 , 3 ) ) . strtoupper( $country ) . ".epub";
                
                $file = $newFilename;
                
                $generate = 'true';

                if(file_exists( $file )){
                    $generate = 'false';
                }

                if($generate == 'true' || $overwrite == 'true'){
                    $book = new EPub();

                    // Title and Identifier are mandatory!
                    $book->setTitle( $title );
                    $book->setIdentifier( $code , EPub::IDENTIFIER_URI); // Could also be the ISBN number, prefered for published books, or a UUID.
                    $book->setLanguage( 'es' ); // Not needed, but included for the example, Language is mandatory, but EPub defaults to "en". Use RFC3066 Language codes, such as "en", "da", "fr" etc.
                    $book->setDescription( $t . ', predicado el ' . $nicedate . ', en ' . $lo );
                    $book->setAuthor("Dr. William Soto Santiago","Dr. William Soto Santiago"); 
                    $book->setPublisher("La Gran Carpa Catedral, Corp.", "https://www.carpa.com/"); // I hope this is a non existant address :) 
                    $book->setDate(time()); // Strictly not needed as the book date defaults to time().
                    $book->setRights("Copyright and licence information specific for the book.");
                    $book->setSourceURL( $u );
    
                    $cssData = "
                    h1 {\n text-transform : uppercase;\n text-align : center;\n}\n
                    h2 {\n text-align : center;\n text-transform : capitalize;\n}";
    
                    $book->addCSSFile("styles.css", "css1", $cssData);
    
                    // ePub uses XHTML 1.1, preferably strict.
                    $content_start =
                        "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                        . "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\"\n"
                        . "    \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n"
                        . "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
                        . "<head>"
                        . "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n"
                        . "<link rel=\"stylesheet\" type=\"text/css\" href=\"styles.css\" />\n"
                        . "<title>". $title ."</title>\n"
                        . "</head>\n"
                        . "<body>\n";
    
                    $cover = $content_start . "<h6>".$code."</h6><h1>".$title."</h1>\n<h2>Dr. William Soto Santiago<br/>".$nicedate."<br/>" . $lo . "</h2>\n"
                        . "</body>\n</html>\n";
                    $book->addChapter("Cover", "Cover.html", $cover);
    
                    $content = autop($content);
    
                    $content = preg_replace('/[\x00-\x1F\x7F]/u', '', $content);
    
                    $contenido = $content_start . "<h1>".$title."</h1>\n<h2>Dr. William Soto Santiago<br/>".$nicedate."<br/>" . $lo . "</h2>\n" . $content
                        . "</body>\n</html>\n";;
    
                    $book->addChapter("Contenido: " . $title, "Chapter001.html", $contenido);
    
                    $book->finalize(); // Finalize the book, and build the archive.
    
                    //save file
                    $fp = fopen( $file , 'w');
                    fwrite( $fp , $book->getBook() );
                    fclose( $fp );
                    
                    if($return=='true'){
                        $zipData = $book->sendBook( $newFilename );
                    }
    
                    //die();
                } else {

                    if($return=='true'){
                        $newTitle = sanitize_title( $title );
                        $fixedNewTitle = str_replace( '-','_',$newTitle );
        
                        $newFilename = $code . "-" . $fixedNewTitle . "-" . strtoupper( substr( $city , 0 , 3 ) ) . strtoupper( $country ) . ".epub";
        
                        //Send current file
                        header($_SERVER["SERVER_PROTOCOL"] . " 200 OK");
                        header("Cache-Control: public"); // needed for internet explorer
                        header("Content-Type: application/epub+zip");
                        header("Content-Transfer-Encoding: Binary");
                        header("Content-Length:".filesize($file));
                        header("Content-Disposition: attachment; filename=".$newFilename);
                        readfile($file);
                    }
                    
                }
            
            }
        }
      }

      function sanitize_title($text, string $divider = '-') {
        // replace non letter or digits by divider
        $text = preg_replace('~[^\pL\d]+~u', $divider, $text);

        // transliterate
        $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);

        // remove unwanted characters
        $text = preg_replace('~[^-\w]+~', '', $text);

        // trim
        $text = trim($text, $divider);

        // remove duplicate divider
        $text = preg_replace('~-+~', $divider, $text);

        // lowercase
        $text = strtolower($text);

        if (empty($text)) {
            return 'n-a';
        }

        return $text;
    }

    function nl2p($string, $line_breaks = false, $xml = true) {

        $string = str_replace(array('<p>', '</p>', '<br>', '<br />'), '', $string);
        
        // It is conceivable that people might still want single line-breaks
        // without breaking into a new paragraph.
        if ($line_breaks == true)
            return '<p>'.preg_replace(array("/([\n]{2,})/i", "/([^>])\n([^<])/i"), array("</p>\n<p>", '$1<br'.($xml == true ? ' /' : '').'>$2'), trim($string)).'</p>';
        else 
            return '<p>'.preg_replace(
            array("/([\n]{2,})/i", "/([\r\n]{3,})/i","/([^>])\n([^<])/i"),
            array("</p>\n<p>", "</p>\n<p>", '$1<br'.($xml == true ? ' /' : '').'>$2'),
        
            trim($string)).'</p>'; 
        }

        function autop($pee, $br = false) {
            $pre_tags = array();
          
              if ( trim($pee) === '' )
                  return '';
          
              $pee = $pee . "\n"; // just to make things a little easier, pad the end
          
              if ( strpos($pee, '<pre') !== false ) {
                  $pee_parts = explode( '</pre>', $pee );
                  $last_pee = array_pop($pee_parts);
                  $pee = '';
                  $i = 0;
          
                  foreach ( $pee_parts as $pee_part ) {
                      $start = strpos($pee_part, '<pre');
          
                      // Malformed html?
                      if ( $start === false ) {
                          $pee .= $pee_part;
                          continue;
                      }
          
                      $name = "<pre wp-pre-tag-$i></pre>";
                      $pre_tags[$name] = substr( $pee_part, $start ) . '</pre>';
          
                      $pee .= substr( $pee_part, 0, $start ) . $name;
                      $i++;
                  }
          
                  $pee .= $last_pee;
              }
          
              $pee = preg_replace('|<br />\s*<br />|', "\n\n", $pee);
              // Space things out a little
              $allblocks = '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|option|form|map|area|blockquote|address|math|style|p|h[1-6]|hr|fieldset|noscript|samp|legend|section|article|aside|hgroup|header|footer|nav|figure|figcaption|details|menu|summary)';
              $pee = preg_replace('!(<' . $allblocks . '[^>]*>)!', "\n$1", $pee);
              $pee = preg_replace('!(</' . $allblocks . '>)!', "$1\n\n", $pee);
              $pee = str_replace(array("\r\n", "\r"), "\n", $pee); // cross-platform newlines
              if ( strpos($pee, '<object') !== false ) {
                  $pee = preg_replace('|\s*<param([^>]*)>\s*|', "<param$1>", $pee); // no pee inside object/embed
                  $pee = preg_replace('|\s*</embed>\s*|', '</embed>', $pee);
              }
              $pee = preg_replace("/\n\n+/", "\n\n", $pee); // take care of duplicates
              // make paragraphs, including one at the end
              $pees = preg_split('/\n\s*\n/', $pee, -1, PREG_SPLIT_NO_EMPTY);
              $pee = '';
              foreach ( $pees as $tinkle )
                  $pee .= '<p>' . trim($tinkle, "\n") . "</p>\n";
              $pee = preg_replace('|<p>\s*</p>|', '', $pee); // under certain strange conditions it could create a P of entirely whitespace
              $pee = preg_replace('!<p>([^<]+)</(div|address|form)>!', "<p>$1</p></$2>", $pee);
              $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee); // don't pee all over a tag
              $pee = preg_replace("|<p>(<li.+?)</p>|", "$1", $pee); // problem with nested lists
              $pee = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $pee);
              $pee = str_replace('</blockquote></p>', '</p></blockquote>', $pee);
              $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)!', "$1", $pee);
              $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee);
              if ( $br ) {
                  $pee = preg_replace_callback('/<(script|style).*?<\/\\1>/s', create_function('$matches', 'return str_replace("\n", "<PreserveNewline />", $matches[0]);'), $pee);
                  $pee = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $pee); // optionally make line breaks
                  $pee = str_replace('<PreserveNewline />', "\n", $pee);
              }
              $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*<br />!', "$1", $pee);
              $pee = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $pee);
              $pee = preg_replace( "|\n</p>$|", '</p>', $pee );
          
              if ( !empty($pre_tags) )
                  $pee = str_replace(array_keys($pre_tags), array_values($pre_tags), $pee);
          
              return $pee;
          }