<?php

    /**
     *  Main JSON Rest api for LGCCC Conferences
     */

    //Enable error reporting for dev only
        error_reporting(E_ERROR | E_PARSE);

    //Enable compression/output buffering
        if(substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start("ob_gzhandler"); else ob_start();

    //Set required response 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']}");
    }

    //Set JSON response format for header
        header("Content-Type: application/json; charset=UTF-8");
    
    //Include required files
        include_once( '../inc/db.php' );
        include_once( '../inc/conferencia.php' );
        include_once( '../inc/helpers.php' );

    //Set incoming variables, parse and validate
    if($_REQUEST){
        $func = ($_REQUEST['f']!=''?$_REQUEST['f']:'list');
        $h = ($_REQUEST['h']!=''?$_REQUEST['h']:false);
        $p = ($_REQUEST['p']!=''?$_REQUEST['p']:false);
        $file = ($_REQUEST['file']!=''?$_REQUEST['file']:false);
        $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']:'');
        $month = ($_REQUEST['month']!=''?$_REQUEST['month']:'');
        $cache = ($_REQUEST['cache']!=''?$_REQUEST['cache']:false);
        $algolia = false;
        $limit = ($_REQUEST['limit']!=''?$_REQUEST['limit']:16);
        define('RELEVANT', ($_REQUEST['relevant']!=''?$_REQUEST['relevant']:false));
        define('EXPORT', ($_REQUEST['export']!=''?$_REQUEST['export']:false));
        if($_REQUEST['locale']!=''){
            if($_REQUEST['locale']=='es'){
                define('LOCALE', 'es_ES');
            } else {
                define('LOCALE', $_REQUEST['locale']);
            }
        } else {
            define('LOCALE', 'es_ES');
        }
    }

    /*if(LOCALE == 'es'){
        LOCALE = 'es_ES';
    }*/

    switch ( $func ){
        case "homepage":
            conferences_list(null,null,null,false,false,false,4);
            break;
        case "algolia":
            $algolia = true;
            conferences_list($year,$month,$last_update,false,$cache,true);
            break;
        case "lgccctv":
            conference_list_lgccctv();
            break;
        case "years":
            conference_years();
            break;
        case "download":
            conference_download($h,$p,$file);
            break;
        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 "summary":
            conference_detail($id,false);
	    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,false,$limit);
            break;
    }

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

        $conference = new Conferencia($db);

        $stmt = $conference->lgccctv_list( LOCALE );

        $num = $stmt->rowCount();

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

                $date = '';
                $no_activity = '';
                $city = '';
                $state = '';
                $country = '';
            
                $response_item=array(
                    "title" => $title
                );

                $translations = unserialize($translationmeta);
                $translations[LOCALE] = (int)$ID;
                                    
                if(LOCALE=='es_ES'){
                    $original_id = $ID;
                } else {
                    $original_id = $translations['es_ES'];
                }

                $confmeta = $conference->conference_meta( $original_id );

                extract($confmeta);

                $response_item['date'] = $date;
                $response_item['activity'] = $no_activity;

                $dt = new DateTime($date);
                $formatter = new IntlDateFormatter(LOCALE, IntlDateFormatter::SHORT, IntlDateFormatter::SHORT);
                $formatter->setPattern( datePattern( $date ) );
                $response_item['nicedate'] = ucfirst($formatter->format($dt));
                $response_item['location'] = implode(', ',array_filter(array($city,$state,Locale::getDisplayRegion('-'.strtoupper($country), LOCALE ))));

                array_push($conferences_arr, $response_item);
            }
        }

        //Add activities data as well
        $activities_json = json_decode(file_get_contents('https://www.carpa.com/wp-admin/admin-ajax.php?action=processQueue'), JSON_UNESCAPED_UNICODE | JSON_NUMERIC_CHECK );

        $all_data = array_merge($conferences_arr,$activities_json);

        $data = array(
            'count' => count($all_data),
            'result' => array (
                'conferencias' => $all_data
            )
        );

        send_response( $data );
    }

    /**
     *  Create conference list with cache option
     */
    function conferences_list( $year, $month, $last_update, $text, $cache, $algolia=false, $limit=16 ){
        
        if( $cache==false ){
        	
		//Cache directory
            $dir = '/var/www/html/v3/cache';
            //Define filename
            $filen = 'conferencias_' . LOCALE;
            //Set filename for relevant conferences
            if( RELEVANT ){
                $filen .= '_relevant';
            } else {
                //If year
                if($year != ''){
                    $filen .= '_' . $year;
                    if($month != ''){
                        $filen .= '_' . $month;
                    }
                }
            }
            if($text){
                $filen .= '_texts';
            }
            $file = $dir . '/' . $filen . '.json';
            if(!file_exists( $file ) || $_REQUEST['forceupdate']==true ){
                $data = build_conferences_list( $year, $month, $last_update, $text, $algolia, $limit );
                $data['cache'] = time();
                $data['filename'] = $filen;
		$res = file_put_contents( $file , json_encode($data) );
                $data['res'] = $res;
            } else {
                readfile( $file );
                die();
            }    
        
	} else {

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

        }
        
        send_response( $data );
    }

    /**
     *  Generate conference list
     */
    function build_conferences_list( $year, $month, $last_update, $text, $algolia=false, $limit=16 ){

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

        $conference = new Conferencia($db);

        $data = [];

        if( EXPORT ){
            $gettext = true;
        } else if($algolia){
            $gettext = $text;
        } else {
            $gettext = false;
        }

        if( RELEVANT ){
            $stmt = $conference->translation_list( $year, $month, $last_update, $gettext, LOCALE, 'relevantes', $limit );
        } else {
            $stmt = $conference->translation_list( $year, $month, $last_update, $gettext, LOCALE, 'ultimas', $limit );
        }
        
        $num = $stmt->rowCount();

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

                $date = '';
                $no_activity = '';
                $city = '';
                $state = '';
                $country = '';
                $thumbnail = '';
        
                if(!$text){
                    $response_item=array(
                        "_id" => $ID,
                        "title" => $title,
                        "slug" => $slug
                    );

                    if(!$algolia){
                        $response_item["hasText"] = ($bodylength>0?true:false);
                    }

                    $translations = unserialize($translationmeta);
                    $translations[LOCALE] = (int)$ID;
                                        
                    if(LOCALE=='es_ES'){
                        $original_id = $ID;
                    } else {
                        $original_id = $translations['es_ES'];
                    }

                    foreach($translations as $translation_locale=>$translation_id){
                        $the_slug = $conference->translation_slug( $translation_locale, $translation_id);
                        $row = $the_slug->fetch(PDO::FETCH_ASSOC);
                        $translations[$translation_locale.'_slug'] = $row['slug'];
                    }

                    $confmeta = $conference->conference_meta( $original_id );

                    extract($confmeta);

                    $response_item['date'] = (new DateTime($date, new DateTimeZone('America/Bogota')))->format('Y-m-d');
                    $response_item['timestamp'] = (new DateTime($date, new DateTimeZone('America/Bogota')))->getTimestamp();
                    $response_item['activity'] = $no_activity;
                    $response_item['city'] = $city;
                    $response_item['state'] = $state;
                    $response_item['country'] = $country;
                    if(!$algolia){
                        $response_item['private'] = $private;
                    }
                    $response_item['thumbnail'] = $thumbnail;

                    if(!$algolia){
                        $dt = new DateTime($date);
                        $formatter = new IntlDateFormatter(LOCALE, IntlDateFormatter::SHORT, IntlDateFormatter::SHORT);
                        $formatter->setPattern( datePattern( $date ) );
                        $response_item['nicedate'] = ucfirst($formatter->format($dt));
                        $response_item['location'] = implode(', ',array_filter(array($city,$state,Locale::getDisplayRegion('-'.strtoupper($country), LOCALE ))));
                    }
                    $response_item['duration'] = gmdate("H:i:s", (int)$duration);

                    if( !EXPORT && !$algolia ){
                        $fileData = $conference->get_post_files( $ID, LOCALE );
                        $files = $fileData->fetch(PDO::FETCH_ASSOC);

                        $response_item['files'] = [];
                        
                        $response_item['files']['youtube'] = str_replace( 'http://', 'https://', $files['youtube']);
                        
                        if($files['videofile'] != ''){
                            $response_item['files']['video'] = $conference->get_post_file($files['videofile'], LOCALE)->fetch(PDO::FETCH_ASSOC)['url']; 
                            if( $response_item['files']['video'] == ''){
                                $response_item['files']['video'] = str_replace( 'http://', 'https://',$files['video']);    
                            }
                        } else {
                            $response_item['files']['video'] = str_replace( 'http://', 'https://',$files['video']);
                        }

                        if($files['audiofile'] != ''){
                            $response_item['files']['audio'] = $conference->get_post_file($files['audiofile'], LOCALE)->fetch(PDO::FETCH_ASSOC)['url'];
                            if( $response_item['files']['audio'] == ''){
                                $response_item['files']['audio'] = str_replace( 'http://', 'https://',$files['audio']);    
                            }
                        } else {
                            $response_item['files']['audio'] = str_replace( 'http://', 'https://',$files['audio']);
                        }

                        if($files['pdffile'] != ''){
                            $response_item['files']['pdf'] = $conference->get_post_file($files['pdffile'], LOCALE)->fetch(PDO::FETCH_ASSOC)['url'];
                            if( $response_item['files']['pdf'] == ''){
                                $response_item['files']['pdf'] = str_replace( 'http://', 'https://',$files['pdf']);    
                            }
                        } else {
                            $response_item['files']['pdf'] = str_replace( 'http://', 'https://',$files['pdf']);
                        }

                        if($files['pdfsimplefile'] != ''){
                            $response_item['files']['pdf_simple'] = $conference->get_post_file($files['pdfsimplefile'], LOCALE)->fetch(PDO::FETCH_ASSOC)['url'];
                            if( $response_item['files']['pdf_simple'] == ''){
                                $response_item['files']['pdf_simple'] = str_replace( 'http://', 'https://',$files['pdf_simple']);    
                            }
                        } else {
                            $response_item['files']['pdf_simple'] = str_replace( 'http://', 'https://',$files['pdf_simple']);
                        }

                        //Image metadata for thumbnail use. TODO: Optimize this return array
                        if(!$algolia){
                            $response_item['meta'] = unserialize($meta);
                        }

                        $imeta = unserialize($meta);
                        $images = [];
                        $images['small']    = explode('.',$imeta['file'])[0].'-'.$imeta['sizes']['medium']['width'].'x'.$imeta['sizes']['medium']['height'].'.'.explode('.',$imeta['file'])[1];
                        $images['medium']   = explode('.',$imeta['file'])[0].'-'.$imeta['sizes']['medium_large']['width'].'x'.$imeta['sizes']['medium_large']['height'].'.'.explode('.',$imeta['file'])[1];
                        $images['large']    = explode('.',$imeta['file'])[0].'-'.$imeta['sizes']['large']['width'].'x'.$imeta['sizes']['large']['height'].'.'.explode('.',$imeta['file'])[1];
                        $images['original'] = $imeta['file'];
                        if(!$algolia){
                            $response_item['images'] = $images;
                        }
                    } else {
                        $response_item['body'] = wpautop( $content );
                    }

                    $response_item['translations'] = $translations;

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

                if($algolia){
                    $response_item['body'] = wpautop( $content );
                    if( $response_item['body'] != '' ){
                        array_push($data, $response_item);
                    }
                } else {
                    array_push($conferences_arr, $response_item);
                }
            }
        }
        
        if(!$algolia){
            $data = array(
                'count' => $num,
                'result' => array (
                    'conferencias' => $conferences_arr
                )
            );
    
            $data['year'] = $year;
            $data['month'] = $month;
        }

        return $data;
    }

    function datePattern( $date ){
        $format = '';
        switch( LOCALE ){
            case "en_US":
                $format = "EEEE, MMMM d, yyyy";
                break;
            case "fr":
            case "pt_BR":
            case "es_ES":
            default:
                $format = "EEEE, d 'de' MMMM 'de' yyyy";
                break;
        }
        return $format;
    }

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

        $conference = new Conferencia($db);

        if(is_numeric($id)){
            $stmt = $conference->detail($id,LOCALE);
        } else {
            $stmt = $conference->detailBySlug($id,LOCALE);
        }
        
        $num = $stmt->rowCount();
        
        if($num>0){
            $conferences_arr=array();
        
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){

                $date = '';
                $no_activity = '';
                $city = '';
                $state = '';
                $country = '';
                $thumbnail = '';

                extract($row);
                
                $response_item=array(
                    "_id" => $ID,
                    "title" => $title,
                    "slug" => $slug,
                    "hasText" => ($bodylength>0?true:false)
                );

		if($showBody){
			$response_item['body'] = wpautop($content);
		}

                $translations = unserialize($translationmeta);
                $translations[LOCALE] = (int)$ID;
                                    
                if(LOCALE=='es_ES'){
                    $original_id = $ID;
                } else {
                    $original_id = $translations['es_ES'];
                }

                foreach($translations as $translation_locale=>$translation_id){
                    $the_slug = $conference->translation_slug( $translation_locale, $translation_id);
                    $row = $the_slug->fetch(PDO::FETCH_ASSOC);
                    $translations[$translation_locale.'_slug'] = $row['slug'];
                }

                $confmeta = $conference->conference_meta( $original_id );

                extract($confmeta);

                $response_item['date'] = $date;
                $response_item['activity'] = $no_activity;
                $response_item['city'] = $city;
                $response_item['state'] = $state;
                $response_item['country'] = $country;
                $response_item['thumbnail'] = $thumbnail;

                $dt = new DateTime($date);
                $formatter = new IntlDateFormatter(LOCALE, IntlDateFormatter::SHORT, IntlDateFormatter::SHORT);
                $formatter->setPattern( datePattern( $date ) );
                $response_item['nicedate'] = ucfirst($formatter->format($dt));
                $response_item['location'] = implode(', ',array_filter(array($city,$state,Locale::getDisplayRegion('-'.strtoupper($country), LOCALE ))));
                $response_item['duration'] = gmdate("H:i:s", (int)$duration);

                $fileData = $conference->get_post_files( $ID, LOCALE );
                $files = $fileData->fetch(PDO::FETCH_ASSOC);

                $response_item['files'] = [];
                
                $response_item['files']['youtube'] = str_replace( 'http://', 'https://', $files['youtube']);
                
                if($files['videofile'] != ''){
                    $response_item['files']['video'] = $conference->get_post_file($files['videofile'], LOCALE)->fetch(PDO::FETCH_ASSOC)['url']; 
                } else {
                    $response_item['files']['video'] = str_replace( 'http://', 'https://',$files['video']);
                }

                if($files['audiofile'] != ''){
                    $response_item['files']['audio'] = $conference->get_post_file($files['audiofile'], LOCALE)->fetch(PDO::FETCH_ASSOC)['url'];
                } else {
                    $response_item['files']['audio'] = str_replace( 'http://', 'https://',$files['audio']);
                }

                if($files['pdffile'] != ''){
                    $response_item['files']['pdf'] = $conference->get_post_file($files['pdffile'], LOCALE)->fetch(PDO::FETCH_ASSOC)['url'];
                } else {
                    $response_item['files']['pdf'] = str_replace( 'http://', 'https://',$files['pdf']);
                }

                if($files['pdfsimplefile'] != ''){
                    $response_item['files']['pdf_simple'] = $conference->get_post_file($files['pdfsimplefile'], LOCALE)->fetch(PDO::FETCH_ASSOC)['url'];
                } else {
                    $response_item['files']['pdf_simple'] = str_replace( 'http://', 'https://',$files['pdf_simple']);
                }
                
                $response_item['translations'] = $translations;

                //Image metadata for thumbnail use. TODO: Optimize this return array
                $response_item['meta'] = unserialize($meta);

                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
	header('Content-Type: application/json; charset=utf-8');
	
        http_response_code(200);
       
        echo json_encode(
            $data, JSON_UNESCAPED_UNICODE
        );
    }

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

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

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

                $date = '';
                $no_activity = '';
                $city = '';
                $state = '';
                $country = '';
                $thumbnail = '';

                $response_item=array(
                    "_id" => $ID,
                    "title" => $title,
                    "body" => wpautop($content),
                    "slug" => $slug,
                    "hasText" => ($bodylength>0?true:false)
                );

                $translations = unserialize($translationmeta);
                $translations[LOCALE] = (int)$ID;
                                    
                if(LOCALE=='es_ES'){
                    $original_id = $ID;
                } else {
                    $original_id = $translations['es_ES'];
                }

                $confmeta = $conference->conference_meta( $original_id );

                extract($confmeta);

                $response_item['date'] = $date;
                $response_item['activity'] = $no_activity;
                $response_item['city'] = $city;
                $response_item['state'] = $state;
                $response_item['country'] = $country;
                $response_item['thumbnail'] = $thumbnail;

                $dt = new DateTime($date);
                $formatter = new IntlDateFormatter(LOCALE, IntlDateFormatter::SHORT, IntlDateFormatter::SHORT);
                $formatter->setPattern( datePattern( $date ) );
                $response_item['nicedate'] = ucfirst($formatter->format($dt));
                $response_item['location'] = implode(', ',array_filter(array($city,$state,Locale::getDisplayRegion('-'.strtoupper($country), LOCALE ))));
                $response_item['duration'] = gmdate("H:i:s", (int)$duration);

                $fileData = $conference->get_post_files( $ID, LOCALE );
                $files = $fileData->fetch(PDO::FETCH_ASSOC);

                $response_item['files'] = [];
                
                $response_item['files']['youtube'] = str_replace( 'http://', 'https://', $files['youtube']);
                $response_item['files']['video'] = str_replace( 'http://', 'https://',$files['video']);
                $response_item['files']['audio'] = str_replace( 'http://', 'https://',$files['audio']);
                $response_item['files']['pdf'] = str_replace( 'http://', 'https://',$files['pdf']);
                $response_item['files']['pdf_simple'] = str_replace( 'http://', 'https://',$files['pdf_simple']);
                
                $response_item['translations'] = $translations;

                //Image metadata for thumbnail use. TODO: Optimize this return array
                $response_item['meta'] = unserialize($meta);
                
                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://conferenciaswp.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,LOCALE);

        $num = $stmt->rowCount();

        if($num>0){
            $conferences_arr=array();
        
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
                extract($row);
        
                $date = '';
                $no_activity = '';
                $city = '';
                $state = '';
                $country = '';
                $thumbnail = '';
        
                $response_item=array(
                    "_id" => $ID,
                    "title" => $title,
                    "slug" => $slug,
                    "hasText" => ($bodylength>0?true:false)
                );

                $translations = unserialize($translationmeta);
                $translations[LOCALE] = (int)$ID;
                                    
                if(LOCALE=='es_ES'){
                    $original_id = $ID;
                } else {
                    $original_id = $translations['es_ES'];
                }

                $confmeta = $conference->conference_meta( $original_id );

                extract($confmeta);

                $response_item['date'] = $date;
                $response_item['activity'] = $no_activity;
                $response_item['city'] = $city;
                $response_item['state'] = $state;
                $response_item['country'] = $country;
                $response_item['thumbnail'] = $thumbnail;

                $dt = new DateTime($date);
                $formatter = new IntlDateFormatter(LOCALE, IntlDateFormatter::SHORT, IntlDateFormatter::SHORT);
                $formatter->setPattern( datePattern( $date ) );
                $response_item['nicedate'] = ucfirst($formatter->format($dt));
                $response_item['location'] = implode(', ',array_filter(array($city,$state,Locale::getDisplayRegion('-'.strtoupper($country), LOCALE ))));
                $response_item['duration'] = gmdate("H:i:s", (int)$duration);

                $fileData = $conference->get_post_files( $ID, LOCALE );
                $files = $fileData->fetch(PDO::FETCH_ASSOC);

                $response_item['files'] = [];
                
                $response_item['files']['youtube'] = str_replace( 'http://', 'https://', $files['youtube']);
                $response_item['files']['video'] = str_replace( 'http://', 'https://',$files['video']);
                $response_item['files']['audio'] = str_replace( 'http://', 'https://',$files['audio']);
                $response_item['files']['pdf'] = str_replace( 'http://', 'https://',$files['pdf']);
                $response_item['files']['pdf_simple'] = str_replace( 'http://', 'https://',$files['pdf_simple']);
                
                //Image metadata for thumbnail use. TODO: Optimize this return array
                $response_item['meta'] = unserialize($meta);
                $response_item['translations'] = $translations;

                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 getFilePrefix(){
          switch (LOCALE){
            case "pt_BR":
	    case "pt":
                $prefix = "POR";
                break;
            case "en_US":
	    case "en":
                $prefix = "ENG";
                break;
            case "fr_FR":
	    case "fr":
                $prefix = "FRA";
                break;
            case "es_ES":
	    case "es":
            default:
                $prefix = "SPA";
                break;
          }
          return $prefix;
      }

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

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

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

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

                $date = '';
                $no_activity = '';
                $city = '';
                $state = '';
                $country = '';
                $thumbnail = '';

                $response_item=array(
                    "_id" => $ID,
                    "title" => $title,
                    "body" => wpautop($content),
                    "slug" => $slug,
                    "hasText" => ($bodylength>0?true:false)
                );

                $translations = unserialize($translationmeta);
                $translations[LOCALE] = (int)$ID;
                                    
                if(LOCALE=='es_ES'){
                    $original_id = $ID;
                } else {
                    $original_id = $translations['es_ES'];
                }

                $confmeta = $conference->conference_meta( $original_id );

                extract($confmeta);

                $response_item['date'] = $date;
                $response_item['activity'] = $no_activity;
                $response_item['city'] = $city;
                $response_item['state'] = $state;
                $response_item['country'] = $country;
                $response_item['thumbnail'] = $thumbnail;

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

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

                //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( LOCALE ); // 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";

                    $svgData = '<?xml version="1.0" encoding="utf-8"?><svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" x="0" y="0" version="1.1" viewBox="0 0 710.33 134.1"><path d="M276.83 79.5c-27.61-9.75-78.41-6.39-91.89-.06C242.35 41.14 315.81 8.7 402.17 1.07c17.45-1.38 40.95-1.52 63.71.18C572.97 9.26 658.85 65.5 710.33 134.1 663.2 90.76 585.31 31.86 461.15 31.86c-95.72 0-167.71 38.13-184.32 47.64z" fill="#ed1c24" fill-rule="evenodd" clip-rule="evenodd"/><path d="M91.41 79.44C64.55 68.85 12.87 73.78.52 79.27 70.43 29.73 170.34-3.72 316.7 1.6 178.46 11.28 102.53 72.2 91.41 79.44z" fill="#2d4ea2" fill-rule="evenodd" clip-rule="evenodd"/><path d="M184.94 79.64c-26.86-10.59-81.18-5.69-93.53-.2C161.32 29.9 249.94-6.39 403.56 1.48 294.93 9.2 216.06 60.24 184.94 79.64z" fill="#fff" fill-rule="evenodd" clip-rule="evenodd"/><path d="M0 86.68h7.56v22.68c0 1.66.25 3.03.76 4.13.5 1.1 1.2 1.98 2.08 2.65.88.67 1.92 1.14 3.1 1.43 1.19.29 2.45.43 3.78.43H27v6.48h-9.72c-2.38 0-4.61-.25-6.7-.76-2.09-.5-3.92-1.35-5.48-2.54-1.57-1.19-2.81-2.75-3.73-4.67S0 112.2 0 109.36V86.68z"/><path d="M37.97 97.53h5.81l12.01 26.95h-6.01l-2.27-5.39H34.24l-2.27 5.39h-6.01l12.01-26.95zm7.59 16.94-4.7-11.01-4.66 11.01h9.36zm162.21 8.81c-1.96-.67-3.68-1.74-5.16-3.21-1.48-1.48-2.64-3.42-3.48-5.83-.85-2.41-1.27-5.36-1.27-8.86 0-3.49.42-6.44 1.27-8.86.85-2.41 2.01-4.36 3.48-5.83 1.48-1.48 3.19-2.55 5.16-3.21 1.96-.67 4.06-1 6.29-1h14.04v6.48h-12.96c-1.33 0-2.59.2-3.78.59s-2.22 1.07-3.1 2.02c-.88.95-1.58 2.22-2.08 3.81-.5 1.58-.76 3.58-.76 5.99s.25 4.41.76 5.99c.5 1.58 1.2 2.85 2.08 3.81.88.95 1.92 1.63 3.1 2.02 1.19.4 2.45.59 3.78.59h12.96v6.48h-14.04c-2.23.02-4.33-.31-6.29-.98zm33.88-28.23h6.31l13.03 29.23h-6.51l-2.46-5.85H237.6l-2.46 5.85h-6.52l13.03-29.23zm8.23 18.37-5.09-11.94-5.05 11.94h10.14zm11.73-18.37h17.33c1.28 0 2.49.15 3.63.46 1.14.31 2.14.8 3.01 1.48.86.68 1.54 1.59 2.03 2.71.49 1.13.73 2.5.73 4.11 0 1.42-.17 2.65-.5 3.7s-.8 1.93-1.4 2.65c-.6.72-1.31 1.29-2.13 1.71-.82.42-1.71.72-2.65.92l6.64 11.48h-6.77L275.35 113h-7.89v11.28h-5.85V95.05zm17.33 12.94c.97 0 1.81-.3 2.51-.9.7-.6 1.04-1.69 1.04-3.28 0-1.39-.35-2.37-1.04-2.92-.7-.56-1.53-.83-2.51-.83h-11.48V108h11.48zm12.74-12.94h16.91c1.34 0 2.6.17 3.8.5 1.2.33 2.24.88 3.13 1.63.89.75 1.59 1.74 2.11 2.97.51 1.23.77 2.73.77 4.51 0 1.92-.26 3.52-.77 4.8-.52 1.28-1.22 2.31-2.11 3.09-.89.78-1.94 1.33-3.13 1.65-1.2.32-2.46.48-3.8.48h-11.07v9.61h-5.85V95.05zm16.91 14.61c.53 0 1.04-.08 1.52-.25.49-.17.91-.44 1.27-.81.36-.38.65-.88.86-1.52.21-.64.31-1.45.31-2.42 0-1.67-.39-2.85-1.17-3.55-.78-.7-1.71-1.04-2.8-1.04h-11.07v9.61h11.08zm19.38-14.61h6.31l13.03 29.23h-6.51l-2.46-5.85h-14.41l-2.46 5.85h-6.52l13.02-29.23zm8.23 18.37-5.09-11.94-5.05 11.94h10.14zm29.09 10.19c-1.96-.67-3.68-1.74-5.16-3.21-1.48-1.48-2.64-3.42-3.48-5.83-.85-2.41-1.27-5.36-1.27-8.86 0-3.49.42-6.44 1.27-8.86.85-2.41 2.01-4.36 3.48-5.83 1.48-1.48 3.19-2.55 5.16-3.21 1.96-.67 4.06-1 6.29-1h14.04v6.48h-12.96c-1.33 0-2.59.2-3.78.59-1.19.4-2.22 1.07-3.11 2.02-.88.95-1.58 2.22-2.08 3.81-.5 1.58-.76 3.58-.76 5.99s.25 4.41.76 5.99c.5 1.58 1.2 2.85 2.08 3.81.88.95 1.92 1.63 3.11 2.02 1.19.4 2.45.59 3.78.59h12.96v6.48h-14.04c-2.24.02-4.33-.31-6.29-.98zm33.87-28.23h6.31l13.03 29.23h-6.52l-2.46-5.85h-14.41l-2.46 5.85h-6.51l13.02-29.23zm8.23 18.37-5.09-11.94-5.05 11.94h10.14zm15.99-13.36h-10.44v-5.01h26.73v5.01h-10.44v24.22h-5.85v-24.22zm23.99 23.45c-1.52-.51-2.85-1.34-3.99-2.49-1.14-1.14-2.04-2.64-2.69-4.51-.65-1.87-.98-4.15-.98-6.85 0-2.7.33-4.98.98-6.85.65-1.87 1.55-3.37 2.69-4.51 1.14-1.14 2.47-1.97 3.99-2.48 1.52-.52 3.14-.77 4.87-.77h10.86v5.01h-10.02c-.92 0-1.78.12-2.59.36-.81.24-1.54.63-2.19 1.17-.65.54-1.21 1.27-1.67 2.17-.46.91-.77 2.04-.94 3.4h17.42v5.01h-17.42c.17 1.36.48 2.5.94 3.4.46.91 1.02 1.63 1.67 2.17.65.54 1.38.93 2.19 1.17.81.24 1.67.35 2.59.35h10.02v5.01h-10.86c-1.73.01-3.35-.25-4.87-.76zm19.7-28.46h14.2c1.73 0 3.35.26 4.87.77s2.85 1.34 3.99 2.48c1.14 1.14 2.04 2.65 2.69 4.51.65 1.87.98 4.15.98 6.85 0 2.7-.33 4.98-.98 6.85-.66 1.87-1.55 3.37-2.69 4.51a10.276 10.276 0 0 1-3.99 2.49c-1.52.52-3.14.77-4.87.77h-14.2V95.38zm13.36 24.22c1.03 0 2-.15 2.92-.46.92-.31 1.72-.83 2.4-1.57.68-.74 1.22-1.72 1.61-2.94.39-1.22.58-2.77.58-4.64 0-1.87-.2-3.41-.58-4.64-.39-1.22-.93-2.21-1.61-2.94a5.673 5.673 0 0 0-2.4-1.57c-.92-.31-1.89-.46-2.92-.46h-7.52v19.21h7.52zm16.08-24.22h17.33c1.28 0 2.49.15 3.63.46 1.14.31 2.14.8 3.01 1.48.86.68 1.54 1.59 2.03 2.71.49 1.13.73 2.5.73 4.11 0 1.42-.17 2.65-.5 3.7-.33 1.04-.8 1.93-1.4 2.65-.6.72-1.31 1.29-2.13 1.71-.82.42-1.71.72-2.65.92l6.64 11.48h-6.77l-6.18-11.28h-7.89v11.28h-5.85V95.38zm17.33 12.94c.97 0 1.81-.3 2.51-.9.7-.6 1.04-1.69 1.04-3.28 0-1.39-.35-2.37-1.04-2.92-.7-.56-1.53-.83-2.51-.83h-11.48v7.94h11.48zm22.43-12.94h6.31l13.03 29.23h-6.52l-2.46-5.85h-14.41l-2.46 5.85h-6.51l13.02-29.23zm8.22 18.37-5.09-11.94-5.05 11.94h10.14zm11.32-18.37h5.85v17.54c0 1.28.2 2.35.59 3.19.39.85.93 1.53 1.61 2.05.68.52 1.48.88 2.4 1.11.92.22 1.89.33 2.92.33h7.52v5.01h-7.52c-1.84 0-3.56-.19-5.18-.58-1.62-.39-3.03-1.04-4.24-1.96-1.21-.92-2.17-2.12-2.88-3.61-.71-1.49-1.07-3.33-1.07-5.53V95.38zm42.7 25.72c-.92-.31-1.72-.81-2.4-1.5-.69-.69-1.23-1.59-1.62-2.72-.39-1.12-.59-2.5-.59-4.13s.2-3 .59-4.13c.39-1.12.93-2.03 1.62-2.72.69-.69 1.49-1.19 2.4-1.5.91-.31 1.89-.47 2.93-.47h6.54v3.02h-6.04c-.62 0-1.21.09-1.76.28-.55.18-1.04.5-1.45.94-.41.44-.73 1.04-.97 1.77-.24.74-.35 1.67-.35 2.79s.12 2.05.35 2.79c.23.74.56 1.33.97 1.77.41.44.89.76 1.45.94.55.18 1.14.28 1.76.28h6.04v3.02h-6.54c-1.04.04-2.01-.12-2.93-.43zm11.49-8.34c0-1.69.22-3.13.67-4.3.44-1.17 1.05-2.12 1.82-2.84.77-.72 1.68-1.24 2.72-1.56 1.04-.32 2.16-.48 3.35-.48 1.16 0 2.26.16 3.3.48 1.04.32 1.95.84 2.73 1.56.78.72 1.4 1.67 1.85 2.84.45 1.17.68 2.61.68 4.3s-.23 3.13-.68 4.3c-.45 1.17-1.07 2.12-1.85 2.84-.78.72-1.69 1.24-2.73 1.56-1.04.32-2.14.48-3.3.48-1.19 0-2.31-.16-3.35-.48s-1.95-.84-2.72-1.56c-.77-.72-1.38-1.67-1.82-2.84-.45-1.17-.67-2.61-.67-4.3zm8.56 6.16c.69 0 1.34-.1 1.95-.29.61-.19 1.14-.52 1.6-.99s.81-1.1 1.08-1.9c.27-.8.4-1.79.4-2.98s-.13-2.19-.4-2.98-.63-1.43-1.08-1.9c-.45-.47-.99-.8-1.6-.99-.61-.19-1.26-.29-1.95-.29-.71 0-1.36.1-1.98.29-.61.19-1.15.52-1.6.99-.45.47-.81 1.1-1.07 1.9s-.39 1.79-.39 2.98.13 2.19.39 2.98c.26.8.62 1.43 1.07 1.9.45.47.99.8 1.6.99.61.2 1.27.29 1.98.29zm10.82-14.97h10.44c.77 0 1.5.09 2.19.28.69.18 1.29.48 1.81.89.52.41.93.96 1.22 1.64.29.68.44 1.51.44 2.48 0 .86-.1 1.6-.3 2.23-.2.63-.48 1.16-.84 1.6-.36.44-.79.78-1.28 1.03-.5.25-1.03.44-1.6.55l4 6.92h-4.08l-3.72-6.79h-4.76v6.79h-3.52v-17.62zm10.44 7.8c.59 0 1.09-.18 1.51-.54.42-.36.63-1.02.63-1.98 0-.84-.21-1.43-.63-1.76-.42-.33-.92-.5-1.51-.5h-6.92v4.78h6.92zm8.31-7.8h10.19c.8 0 1.57.1 2.29.3.72.2 1.35.53 1.89.98.54.45.96 1.05 1.27 1.79s.47 1.64.47 2.72c0 1.16-.16 2.12-.47 2.89s-.73 1.39-1.27 1.86c-.54.47-1.17.8-1.89.99-.72.19-1.49.29-2.29.29h-6.67v5.79h-3.52v-17.61zm10.19 8.81c.32 0 .63-.05.92-.15.29-.1.55-.26.77-.49.22-.23.39-.53.52-.92s.19-.87.19-1.46c0-1.01-.24-1.72-.71-2.14-.47-.42-1.03-.63-1.69-.63h-6.67v5.79h6.67zm.66 6.1h4.01v4.01h-4.01v-4.01zm-585.61 4.68c-1.96-.67-3.68-1.74-5.16-3.21-1.48-1.48-2.64-3.42-3.48-5.83-.85-2.41-1.27-5.36-1.27-8.86 0-3.49.42-6.44 1.27-8.86.85-2.41 2.01-4.36 3.48-5.83 1.48-1.48 3.19-2.55 5.16-3.21 1.96-.67 4.06-1 6.29-1h18.36v6.48H80.75c-1.33 0-2.59.2-3.78.59s-2.22 1.07-3.1 2.02c-.88.95-1.58 2.22-2.08 3.81-.5 1.58-.76 3.58-.76 5.99s.25 4.41.76 5.99c.5 1.58 1.2 2.85 2.08 3.81.88.95 1.92 1.63 3.1 2.02 1.19.4 2.45.59 3.78.59h9.72v-9.18h-7.56v-6.48h15.12v22.14H79.67c-2.24.02-4.33-.32-6.3-.98zm28.98-27.42h16.85c1.24 0 2.42.15 3.53.45 1.11.3 2.08.78 2.92 1.44.84.66 1.5 1.54 1.97 2.64s.71 2.43.71 4c0 1.38-.16 2.58-.49 3.59-.32 1.01-.78 1.87-1.36 2.58-.58.7-1.27 1.26-2.07 1.66-.8.41-1.66.7-2.58.89l6.46 11.17h-6.58l-6.01-10.96h-7.67v10.96h-5.68V96.12zm16.85 12.58c.95 0 1.76-.29 2.44-.87.68-.58 1.01-1.64 1.01-3.19 0-1.35-.34-2.3-1.01-2.84-.68-.54-1.49-.81-2.44-.81h-11.17v7.71h11.17zM141 96.12h6.13l12.67 28.42h-6.33l-2.4-5.68h-14.01l-2.4 5.68h-6.33L141 96.12zm8 17.86-4.95-11.61-4.91 11.61H149zm11.41-17.86h7.31l11.37 20.67V96.12h5.68v28.42h-7.31l-11.37-20.67v20.67h-5.68V96.12zm421.96 34.28v-3.77h-2.24v-5h4.8v3.63c0 1.09-.21 2.05-.62 2.86s-1.05 1.58-1.94 2.28z"/></svg>';

                    $book->addFile("logo_lgccc_epub.svg", "logo_svg", $svgData, "image/svg+xml");
    
                    $cover = $content_start . "<h6>".$code."</h6><h1>".$title."</h1>\n<h2>Dr. William Soto Santiago<br/>".$nicedate."<br/>" . $lo . "</h2><br/><div style=\"text-align:center;width:60%;margin:0 auto;margin-top:100px;\"><img alt=\"La Gran Carpa Catedral Corp.\" src=\"logo_lgccc_epub.svg\" style=\"width:60%;\"/></div>\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;
          }

          function conference_download($h,$p,$file){
            header_remove();
            header("X-Accel-Redirect: /downloadfile/" . $h . $p .'?' . $file);
        }

    function last_updated(){
        
    }
    
function conference_years(){

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

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

        $num = $stmt->rowCount();

        if($num>0){
            $conferences_arr=array();
        
            $years = [];
            $formattedYears = [];

            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
                extract($row);
                
                if ($currentYear != $year){
                    $currentYear = $year;
                    $years[$currentYear] = [];
                }

                $format = new IntlDateFormatter(LOCALE, IntlDateFormatter::NONE, IntlDateFormatter::NONE, NULL, NULL, "MMMM");
                $monthName = datefmt_format($format, mktime(0, 0, 0, $month));

                array_push( $years[$currentYear], array('name'=>$monthName,'month'=>str_pad($month,2,'0',STR_PAD_LEFT),'count' => $total));

            }
        }

        $newYears = [];

        foreach($years as $year=>$months){
            $totalyear = 0;
            foreach($months as $month=>$count){
                $totalyear += $count['count'];
            }
            array_push($newYears, array('year'=>$year, 'count'=>$totalyear, 'months' => $months));
        }
                
        $data = array(
            'result' => array (
                'years' => $newYears
            )
        );


        send_response( $data );   
    }