<?php
/**
 * News module
 * 
 * Provides basics methods called from public templates
 * These methods can be overriden. Discover logic and examples on :
 * @url http://dev.linea21.com/projects/linea21/wiki/Override
 * @url http://dev.linea21.com/projects/linea21/wiki/Personnalisation_de_l%27interface_publique
 * 
 * @package linea21\modules\news
 * @author $Author$ - linea21 <info@linea21.com>
 * @version $Id$ 
 * @access public
 * @license http://opensource.org/licenses/gpl-3.0.html
 */

include_once(override('../news/' . SQL . '.inc.php'));



/**
 * get_latestnews_id()
 * return latestnews_id
 *
 * @return int or false
 */

function get_latestnews_id()
{
	global $sql_object;

	$r = $sql_object->DBSelect(SQL_getLatestNews());

	if(isset($r[0])) return $r[0]['news_id'];

	return false;
}

/**
 * DisplayListNews()
 * Affichage de la liste des news publique
 *
 * @param  $statut
 * @param  $filter
 * @param  $id_filter
 * @param  $debut
 * @return void echo content
 */
if(!function_exists('DisplayListNews')) {

  function DisplayListNews($statut, $filter, $id_filter, $debut)
  {
  	include_once('../lib/vendor/wideimage/lib/WideImage.php');
  	
    if ($statut == 'public') {
      $pas = SELECT_LIMIT;
      $suffix = '';
    } else $pas = SELECT_LIMIT;
    
    if(is_numeric(strpos(ActiveItemKey($GLOBALS['activeitem']), 'archives'))) {
    	$title = mb_ucfirst(_t('news','section') . ' - ' ._t('archives', 'name'));
    } else {
    	$title = mb_ucfirst(_t('news','section'));
    }
    
    // getting tags
    include_once('../class/class.tag.php');

    $sep = ' <span class="separator">/</span> ';

    if ($statut == 'archives_p') $suffix = ' "'.strtolower(_t('statut','PA')).'"';
    if($filter == 'LEVEL') {
    	$levels = getLevelChildren($GLOBALS['sql_object']->DBSelect(SQL_getLevelsList()), $id_filter);
    	$id_filter = array_extract($levels, 'level_id', true, 'children');
    }
    $data = $GLOBALS['sql_object']->DBSelect(SQL_getNewsList($debut, $pas, $statut, $filter, $id_filter));
    $datacount = $GLOBALS['sql_object']->DBSelect(SQL_getCountNewsList($statut, $filter, $id_filter));
    $bdd_nb_com = $datacount[0]['num_rows'];
    $bdd_nb_com_display = '<p>' . $bdd_nb_com . ' ' . _t('news','name2') . $suffix . '</p>' . PHP_EOL;
    $content = '<h1>' . $title . '</h1>' . PHP_EOL;
    $content .= '<div class="grid-3 has-gutter-xl">'.PHP_EOL;
    
    if ($data != 0) {
      // echo $bdd_nb_com_display;	// affichage du nombre d'enregistrements
      $current_link = array('rub' => $GLOBALS['links'][U_L][ActiveItemKey($GLOBALS['activeitem'])]['linkvalue']);
      $content .= get_linkin_page($current_link, $bdd_nb_com, $debut, $pas);
      
      for($i=0; $i<count($data); $i++) {
      
      	// get image with SIMPLEHTMLDOM
      
      	$html = new simple_html_dom();
      
      	$html->load($data[$i]['news_header']. $data[$i]['news_body']);
      
      	// we get the image with thumbnail class if provided
      	if($html->find('img.thumbnail', 0)) $imgsrc = $html->find('img.thumbnail', 0)->src;
      	else $imgsrc = false;
      
      	// if img.thumbnail does not exist we get the first image
      	if(!$imgsrc) {
      		// we get the first image if provided
      		if($html->find('img', 0)) $imgsrc = $html->find('img', 0)->src;
      	}
      	
      	// if there is still no image, we take default app image
      	if(!$imgsrc) {
      		$imgsrc = '../library/userfiles/no-image.png';
      	}
      
      	$thumbpath = '../library/userfiles/_thumbs/';
      	
				$path_parts = pathinfo ( $imgsrc );
				list($width, $height) = explode('x', THUMBNAIL_SIZE);
				
				$thumbname = $path_parts ['filename'] . '_' . $width . 'x' . $height . 'px.' . $path_parts ['extension'];
				
				$thumb_fullpath = $thumbpath . $thumbname;
				
				// if thumbnail does not exist
				if (! file_exists ( $thumb_fullpath )) {
					
					$image = WideImage::load ( $imgsrc );
					$resized = $image->resize ( $width, $height, 'outside' )->crop ( 'center', 'center', $width, $height );
					;
					$resized->saveToFile ( $thumb_fullpath );
					chmod ( $thumb_fullpath, 0755 );
					$imgsrc = $thumb_fullpath;
				} else {
					$imgsrc = $thumb_fullpath;
				}
      
      	$title=formatText($data[$i]['complete_news_title'],'2HTML');
      
      	// we remove all images contained in header
      	$html->load($data[$i]['news_header']);
      
      	foreach($html->find('img') as $element) {
      		$images = $element->outertext = '';
      	}
      
      
      
      	$link_table= array('rub'=> $GLOBALS['links'][U_L]['news']['linkvalue'],'id'=>$data[$i]['news_id'], 'name' => $data[$i]['news_title']);
      	$link_user = array('rub' => $GLOBALS['links'][U_L]['user-profile']['linkvalue'], 'id' => $data[$i]['news_posted_by'], 'name' => $data[$i]['user_login']);
      	$link_detail = array('rub' => $GLOBALS['links'][U_L]['news']['linkvalue'], 'id' => $data[$i]['news_id'], 'name' => $data[$i]['news_title']);
      
      	$news_posted_on = formatText($data[$i]['news_published_date_display'], '2HTML');
      	$news_posted_on_long = formatText($data[$i]['news_published_date_display_long'], '2ATT');
      	$news_posted_by = formatText($data[$i]['user_login'], '2HTML');
      
      	$content .= '<div class="onenews line mtm pas">'.PHP_EOL;
      	$content .= '<img src="' . str_replace('../', SITE_ROOT_URL, $imgsrc) . '" alt="' . $imgsrc . '" class="left nomouseover" />';
      	$content .= '<div class="mod">';
      	$content .= '<h2><a href="'.HrefMaker($link_table).'" title="'.formatText($GLOBALS['links'][U_L]['news']['desc'].' : '.$title, '2ATT').'">'.$title.'</a></h2>';
      	$content .= '<div>'.formatText($html, '2HTML').'</div>'.PHP_EOL;
      	$content .= '<a class="readmore" href="'.HrefMaker($link_detail).'">'._t('btn', 'read_more').'</a>';
      	$content .= '<p class="published_by">' . PHP_EOL;
      	$content .= '<span class="published-on">'._t('statut','published_on') . '</span> <span class="date" data-published-date="'.$news_posted_on_long.'">' . $news_posted_on . '</span> ';
      	$content .= _t('divers','by').' <a href="' . HrefMaker($link_user) . '" title="' . $GLOBALS['links'][U_L]['user-profile']['desc'] . ' (' . $news_posted_by . ')">' . $news_posted_by . '</a>';
      	$content .= '</p>' . PHP_EOL;
      	$content .= '</div>';
      	$content .= '</div>'.PHP_EOL;
      
      	// we clear SimpleHTMLDom to prevent memory leaks
      	$html->clear();
      	unset($html);
      }
      
    } else {
      $content .= '<p class="info">' . _t('divers','nodata') . '</p>';
    }
    
	$content .= '</div>' . PHP_EOL;
    echo $content;
  }
}

/**
 * DisplayOneNews()
 * Affichage d'une actualté en détail
 *
 * @param  $news_id
 * @return $stat Nom du statut + echo content
 */
if(!function_exists('DisplayOneNews')) {

  function DisplayOneNews($news_id, $display_comments = true)
  {
    $data = $GLOBALS['sql_object']->DBSelect(SQL_getoneCompleteNews($news_id, array('P', 'PA')));
    $content = '';
    
    $levels = $GLOBALS['sql_object']->DBSelect(SQL_getLevelsList());
    $level = getLevelParent($levels, $data[0]['news_level'], 0);
    
    $sep = ' <span class="separator">/</span> ';
    
    // getting tags
    include_once('../class/class.tag.php');
    $otag = new tag();
    $tags = $otag->getTags('news', $news_id, false);

    if($data == 0) error_redirect();

    if (count($data) != 1) exit;
    else {
    	if(is_array($level)) {
      	$link_level = array('rub' => $GLOBALS['links'][U_L][ActiveItemKey($GLOBALS['activeitem'])]['linkvalue'], 'filter' => $GLOBALS['filters'][U_L]['level']['linkvalue'], 'id' => $level['id'], 'name' => $level['name']);
    	}
      $link_tag = array('rub' => $GLOBALS['links'][U_L][ActiveItemKey($GLOBALS['activeitem'])]['linkvalue'], 'filter' => 'tag');
      $link_scale = array('rub' => $GLOBALS['links'][U_L][ActiveItemKey($GLOBALS['activeitem'])]['linkvalue'], 'filter' => $GLOBALS['filters'][U_L]['scale']['linkvalue'], 'id' => $data[0]['news_scale'], 'name' => $data[0]['scale_denomination']);
      $link_user = array('rub' => $GLOBALS['links'][U_L]['user-profile']['linkvalue'], 'id' => $data[0]['news_posted_by'], 'name' => $data[0]['user_login']);
      $link_self = array('rub' => $GLOBALS['links'][U_L]['news']['linkvalue'], 'id' => $news_id);
      $news_title = formatText($data[0]['news_title'], '2HTML');
      $news_header = formatText($data[0]['news_header'], '2HTML');
      $news_body = formatText($data[0]['news_body'], '2HTML');
      $news_level = formatText($data[0]['level_name'], '2HTML');
      $news_scale_denomination = formatText($data[0]['scale_denomination'], '2HTML');
      $news_posted_on = formatText($data[0]['news_published_date_display'], '2HTML');
      $news_posted_on_long = formatText($data[0]['news_published_date_display_long'], '2ATT');
      $news_modify_on = formatText($data[0]['news_last_modify_display'], '2HTML');
      $news_posted_by = formatText($data[0]['user_login'], '2HTML');
      $news_statut = $data[0]['news_statut'];

      if(commentEnabled('news') && $display_comments == true) {
        postCommentAction(array('module'=> ActiveItemKey($GLOBALS['activeitem']), 'module_id'=> $news_id));
        $content .= '<div id="anchor-comments">'.PHP_EOL;
        $content .= getCommentsAnchor(array('module'=> ActiveItemKey($GLOBALS['activeitem']), 'module_id'=> $news_id));
        if($news_statut == 'P') $content .= getPostCommentAnchor();
        $content .= '</div>'.PHP_EOL;
      }
      $content .= '<h1>' . $news_title . '</h1>' . PHP_EOL;

      $content .= '<p class="published_by">' . PHP_EOL;
      $content .= '<span class="published-on">'._t('statut','published_on') . '</span> <span class="date" data-published-date="'.$news_posted_on_long.'">' . $news_posted_on . '</span> ';
      $content .= _t('divers','by').' <a href="' . HrefMaker($link_user) . '" title="' . $GLOBALS['links'][U_L]['user-profile']['desc'] . ' (' . $news_posted_by . ')">' . $news_posted_by . '</a>';
      if ($news_statut == 'PA') {
        $content .= ' (' . _t('statut','archived_on') . ' ' . $news_modify_on . ')';
      }
      $content .= formatted_permalink($link_self, ' - ');
      $content .= '</p>' . PHP_EOL;

      $content .= '<div class="chapo clear">' . $news_header . '</div>' . PHP_EOL;
      $content .= '<div class="body">' . $news_body . '</div>' . PHP_EOL;

      $content .= '<div class="filter_info">' . PHP_EOL;
      if(is_array($level)) $content .=  ' ' . $level['label'] . ' : <a href="' . HrefMaker($link_level) . '" title="' . $GLOBALS['filters'][U_L]['level']['desc'] . ' : ' . formatText($level['name'], '2ATT') . '" class="filter_info_theme">' . $level['name'] . '</a>'. $sep . PHP_EOL;
      //$content .= ' '._t('divers','sousthemeref') . ' : ' .$news_theme . PHP_EOL;
      if(!empty($news_scale_denomination)) $content .=  _t('divers','scale') . ' : <a href="' . HrefMaker($link_scale) . '" title="' . $GLOBALS['filters'][U_L]['scale']['desc'] . ' : ' . formatText($news_scale_denomination, '2ATT') . '" class="filter_info_scale">' . $news_scale_denomination . '</a>'. PHP_EOL; 
      if(!empty($tags)) {
	      $content .= '<div class="tags">' . PHP_EOL;
	      $content .= ' ' . mb_ucfirst(_t('tag','name')) . ' : ' . $otag->linkTags($tags, $link_tag). PHP_EOL;
	      $content .= '</div>' . PHP_EOL;
      }
      $content .= '</div>' . PHP_EOL;
    }
    echo $content;
    return GetStatutName($news_statut);
  }
}

/**
 * GetStatutName()
 *
 * @param  $statut
 * @return $stat Nom du statut
 */
if(!function_exists('GetStatutName')) {

  function GetStatutName($statut)
  {
    switch ($statut) {
      case 'P':
        $stat = 'public';
        break;
      case 'PA':
        $stat = 'archives_p';
        break;
      case 'AA':
        $stat = 'archives_a';
        break;
      default:
        $stat = 'public';
    }
    return $stat;
  }
}

/**
 * DisplayLinkNews()
 * Affiche ou non 1 lien vers les news a venir ou qui précéde.
 *
 * @param  $current_news
 * @param  $direction
 * @param  $statut
 * @return echo content
 */
if(!function_exists('DisplayLinkNews')) {

  function DisplayLinkNews($current_news, $direction, $statut)
  {
    $q = SQL_getNewsRangeAndDate($current_news);
    $r = $GLOBALS['sql_object']->DBSelect($q);

    $range = $r[0]['news_range'];
    $published_date = $r[0]['news_published_date'];

    if ($direction == 'NEXT') {
      if($range != 0) {
        $q = SQL_getNextNewsByRange($current_news, $range, $statut);
      } else {
        $q = SQL_getNextNewsByDate($current_news, $published_date, $statut);
      }
      $class = 'next';
      $prefix = ' | ';
      $suffix = ' →';
      $title = _t('news','next_news');
    }
    if ($direction == 'PREVIOUS') {
      if($range != 0) {
        $q = SQL_getPreviousNewsByRange($current_news, $range, $statut);
      } else {
        $q = SQL_getPreviousNewsByDate($current_news, $published_date, $statut);
      }
      $class = 'previous';
      $prefix = '← ';
      $suffix = '';
      $title = _t('news','prev_news');
    }
    $data = $GLOBALS['sql_object']->DBSelect($q);

    if ($data == false || count($data) != 1) $content = '';
    else {
      $link_news = array('rub' => $GLOBALS['links'][U_L]['news']['linkvalue'], 'id' => $data[0]['news_id'], 'name' => $data[0]['news_title']);
      $news_complete_title = formatText($data[0]['news_title'], '2HTML');
      $news_title = formatText(cutText($data[0]['news_title'], 45), '2HTML');

      $content = '<div class="' . $class . '">' . PHP_EOL;
      $content .= $prefix . PHP_EOL;
      $content .= '<a href="' . HrefMaker($link_news) . '" title="' . $title .' : '.formatText($news_complete_title, '2ATT'). '">' . $news_title .'</a>';
      $content .= $suffix . PHP_EOL;
      $content .= '</div>' . PHP_EOL;
    }
    echo $content;
  }
}

?>