<?php
// +---------------------------------------------+
// |     Copyright 2006 -2009 weenCompany        |
// |     http://www.weentech.com                 |
// |     This file may not be redistributed.     |
// +---------------------------------------------+

if(!defined('IN_WEENCOMPANY'))
  die('非法进入 !');

// ################################ LATEST NEWS ################################

function m3_LatestNews()
{
  global $DB, $categoryid, $mainsettings, $weenurl;

  $language = GetLanguage(2);
  
  // get latest news settings
  $getsettings = $DB->query("SELECT title, value FROM " . TABLE_PREFIX . "modulesettings WHERE moduleid = 3");
  while($setting = $DB->fetch_array($getsettings))
  {
	$settings[$setting['title']] = $setting['value'];
  }
  
  $targetID              = $settings['目标模块'];                        // which module to display (default 2)

  $checktargetID = $DB->query_first("SELECT moduleid FROM " . TABLE_PREFIX . "modules WHERE moduleid = '$targetID' AND modulepath LIKE '%news/news.php%'");
  if (!isset($checktargetID))
  {
	  echo '目标模块不存在或目标模块不为文章模块类型!';
	  return;
  }
  
  $limit                 = $settings['条目数'];                        // how many news articles to display (default 10)
  $targeting             = $settings['目标菜单'];           // only display news from the current category (default no)?
  $includeids            = $settings['关联菜单'];           // the ID of the categories you want to include (only works if targeting is set to off)
  $matchingids           = $settings['匹配菜单'];          // combined with $includeids if this field has values.
																	  // if the value in $includeids is '1 3' and the matchingids is '2 6', then in category 1 (homepage) the latest news from category 2 will be displayed.
																	  // and if the module is placed in category 3, then latest news from category 6 will be displayed.
  $sorting               = $settings['排序方式'];                      // sort by author, title, newest first, oldest first etc (see the news module)
  $showcategoryname      = $settings['显示菜单名称'];        // display categoryname to the right of each news article (default no)?
  $showdescription       = $settings['显示简要描述'];          // display description (default no)?
  //$descriptionlimit      = $settings['Description Limit'];            // decide how many characters to display from description (0 = disabled)
  $showauthor            = $settings['显示作者'];               // display authorname (default no)?
  $showdate              = $settings['显示发布日期'];        // display creation date (default no)?
  $showprintlink         = $settings['显示打印']; // display print link for each news article in the list (uses language settings from news, default no)?
  $showemaillink         = $settings['显示发送邮件']; // display email link for each news article in the list (uses language settings from news, default no)?
  $showreadmore          = $settings['显示查看详情'];                    // display read more link (uses language settings from news, default no)
  $boldtitle             = $settings['粗体标题'];                   // convert news title to link (default yes)?
  $titletolink           = $settings['标题链接'];                   // convert news title to link (default yes)?
  $grouping              = $settings['分组显示'];                     // group the news article list by category, date, author or nothing  (default nothing)?
  $categorytolink        = $settings['菜单链接'];                // convert category name to link (default yes)?
  $groupseparator        = $settings['群组分隔符'];              // separator between each group, will not work if grouping is set to "nothing"
  $grouparticleseparator = $settings['组与文章分隔符'];      // separator between the group header and the news articles, will only work if grouping is used
  $articleseparator      = $settings['文章分隔符'];       // separator between each news article

  $includeidsarray  = explode(',', $includeids);
  $matchingidsarray = explode(',', $matchingids);

  $extraquery = '';
  
  if(strlen($matchingids) > 0) // match $includeids and $matchingids to create an associative array
  {
	if(count($includeidsarray) != count($matchingidsarray)) //don't do matching if not the same number of values in both fields
	{
	  if(strlen($includeids) > 0) // select news only from the $includeids
	  {
		$extraquery =  "AND m".$targetID."_news.categoryid IN ($includeids)";
	  }
	}
	else // do matching
	{
	  for($i = 0; $i < count($includeidsarray); $i++)
	  {
		$includeidsarray[$i]  = intval($includeidsarray[$i]);
		$matchingidsarray[$i] = intval($matchingidsarray[$i]);
		$matching[$includeidsarray[$i]] =  $matchingidsarray[$i];
	  }

	  $extraquery = strlen($matching[$categoryid]) ? "AND m".$targetID."_news.categoryid = $matching[$categoryid]" : '';
	}
  }

  // select news from the $includeids if no extraquery was made earlier
  if(strlen($includeids) AND $extraquery == '')
  {
	$extraquery = "AND m".$targetID."_news.categoryid IN ($includeids)";
  }

  if($targeting)
  {
	$extraquery = "AND m".$targetID."_news.categoryid = '$categoryid'";
  }

  // sorting articles
  switch($sorting)
  {
	case 'alphaAZ':
	  $sort = 'm'.$targetID.'_news.title ASC';
	break;

	case 'alphaZA':
	  $sort = 'm'.$targetID.'_news.title DESC';
	break;

	case 'authornameAZ':
	  $sort = 'm'.$targetID.'_news.author ASC';
	break;

	case 'authornameZA':
	  $sort = 'm'.$targetID.'_news.author DESC';
	break;

	case 'oldest':
	  $sort = 'IF ( m'.$targetID.'_news.dateupdated = 0, m'.$targetID.'_news.datecreated, m'.$targetID.'_news.dateupdated ) ASC';
	break;

	default:
	  $sort = 'IF ( m'.$targetID.'_news.dateupdated = 0, m'.$targetID.'_news.datecreated, m'.$targetID.'_news.dateupdated ) DESC';
  }

  // grouping articles
  switch($grouping)
  {
	case 'category':
	  $group = 'm'.$targetID.'_news.name ASC, ';
	break;

	case 'author':
	  $group = 'm'.$targetID.'_news.author ASC, ';
	break;

	case 'date':
	  $group = 'IF ( m'.$targetID.'_news.dateupdated = 0, m'.$targetID.'_news.datecreated, m'.$targetID.'_news.dateupdated ) DESC, ';
	break;

	default:
	  $group = '';
  }


  // bold title?
  $boldtitlestart = $boldtitle ? '<b>'  : '';
  $boldtitleend   = $boldtitle ? '</b>' : '';

  $articleflag    = 0;
  $groupflag      = 0;
  $articlecounter = 0;

  if(($grouping != 'nothing') OR ($sorting !='newest')) // create temporary table for grouping/sorting of selected articles
  {
	$DB->query("CREATE TEMPORARY TABLE " . TABLE_PREFIX . "m3_news_temp AS SELECT m".$targetID."_news.*, categories.name FROM " .
				TABLE_PREFIX . "m".$targetID."_news m".$targetID."_news, " . TABLE_PREFIX . "categories categories
				WHERE (m".$targetID."_news.settings & 2) AND (datestart = 0 OR datestart < '" . time() . "')
				AND (dateend = 0 OR dateend   > '" . time() . "') AND m".$targetID."_news.categoryid = categories.categoryid $extraquery
				ORDER BY IF (m".$targetID."_news.dateupdated = 0, m".$targetID."_news.datecreated, m".$targetID."_news.dateupdated) DESC LIMIT 0, $limit");

	$getarticles = $DB->query("SELECT articleid, categoryid, title, description, datecreated, author FROM " . TABLE_PREFIX . "m3_news_temp m".$targetID."_news
							   ORDER BY $group $sort");

	$numberofarticles = mysql_num_rows($getarticles);
  }
  else // no grouping ('nothing') and default sorting ('newest'), not necessary to create temporary table
  {
	$getarticles = $DB->query("SELECT * FROM " . TABLE_PREFIX . "m".$targetID."_news m".$targetID."_news
							   WHERE (settings & 2) AND (datestart = 0 OR datestart < '" . time() . "')
							   AND (dateend = 0 OR dateend   > '" . time() . "') $extraquery
							   ORDER BY IF (dateupdated = 0, datecreated, dateupdated) DESC LIMIT 0, $limit");

	$numberofarticles = mysql_num_rows($getarticles);
  }

  $previousarticle = '';
  
  while($article = $DB->fetch_array($getarticles))
  {
	$subtitle = '';
	$printlink = '';
	$emaillink = '';
	
	if($previousarticle != $article['title'])
	{
	  // does category exist?
	  if($category = $DB->query_first("SELECT name FROM " . TABLE_PREFIX . "categories WHERE categoryid = ".$article['categoryid']) )
	  {
		// does the news module exist in that category?
		if($newsmodule = $DB->query_first("SELECT displayorder FROM " . TABLE_PREFIX . "pagesort WHERE categoryid = '".$article['categoryid']."' AND moduleid = '".$targetID."'") )
		{
		  $articlecounter++;

		  // display category name to the right of each news article
		  if($showcategoryname)
		  {
			$categoryname = $categorytolink ? ' (<a href="' . RewriteLink('index.php?categoryid='. $article['categoryid']) . '">' . $category['name'] . '</a>)' :' (' . $category['name'] . ')';
		  }
		  else
		  {
			$categoryname = '';
		  }

		  // group news by category, author or creation date?
		  if($grouping != 'nothing' )
		  {
			if($grouping == 'category' AND ($category['name'] != $tempgroup)) // group by category
			{
			  if($groupflag)
			  {
				echo $groupseparator;
			  }

			  $groupflag = 1;

			  if($categorytolink) // convert category to link?
			  {
				echo '<a href="' . RewriteLink('index.php?categoryid=' . $article['categoryid']) . '"><b>' . $category['name'] . '</b></a>';
			  }
			  else
			  {
				echo '<b>' . $category['name'] . '</b>';
			  }

			  echo $grouparticleseparator;
			}

			if($grouping == 'author' AND ($article['author'] != $tempgroup)) // group by author
			{
			  if($groupflag)
			  {
				echo $groupseparator;
			  }

			  $groupflag = 1;

			  echo '<b>' . $article['author'] . '</b>' . $grouparticleseparator;
			}

			if( ($grouping == 'date') AND (iif($article['datestart'] != 0, DisplayDate($article['datestart']), DisplayDate($article['datecreated'])) != $tempgroup) ) // group by date
			{
			  if($groupflag)
			  {
				echo  $groupseparator;
			  }

			  $groupflag = 1;

			  echo '<b>' . iif($article['datestart'] != 0, DisplayDate($article['datestart']), DisplayDate($article['datecreated'])) . '</b>' . $grouparticleseparator;
			}

		  }
		  else // no grouping, print articleseparator, but not before the first article
		  {
			if($articleflag)
			{
			  echo $articleseparator;
			}

			$articleflag = 1;
		  }

		  if($showauthor)
		  {
			$subtitle = '<br />' . $language['by'] . ' ' . $article['author'];
		  }

		  if($showdate)
		  {
			if($showauthor)
			{
			  $subtitle .= ' - ' . iif($article['datestart'] != 0, DisplayDate($article['datestart']), DisplayDate($article['datecreated']));
			}
			else
			{
			  $subtitle = '<br />' . iif($article['datestart'] != 0, DisplayDate($article['datestart']), DisplayDate($article['datecreated']));
			}
		  }

		  if($showprintlink)
			$printlink = '<br /><a href="' . $weenurl . 'modules/m'.$targetID.'_news/printarticle.php?m'.$targetID.'_articleid=' . $article['articleid'] . '" target="_blank"><img alt="' . $language['print'] . '" src="' . $weenurl . 'modules/m'.$targetID.'_news/print.gif" /> ' . $language['print'] . '</a>&nbsp;&nbsp;&nbsp;';

		  if($showemaillink)
		  {
			$emaillink = '<a href="' . RewriteLink('index.php?categoryid=' . $article['categoryid'] . '&m'.$targetID.'_articleid=' . $article['articleid'] . '&m'.$targetID.'_action=emailarticle&moduleid='.$targetID) . '"><img alt="' . $language['email'] . '" src="' . $weenurl . 'modules/m'.$targetID.'_news/email.gif" /> ' . $language['email'] . '</a>';
		  }
		  
		  if(!$showprintlink AND $showemaillink)
		  {
			$emaillink = '<br />' . $emaillink;
		  }

		  // convert title to link?
		  $titlelinkstart = $titletolink ? '<a href="' . RewriteLink('index.php?categoryid=' . $article['categoryid'] . '&m'.$targetID.'_articleid=' . $article['articleid']) . '&moduleid='.$targetID.'">' : '';
		  $titlelinkend   = $titletolink ? '</a>' : '';

		  // start printing the articles

		  $articledescription = $showdescription ? '<br />' . $article['description'] : '';

		  if(strlen($article['description']) AND $showdescription)
		  {
			echo $titlelinkstart . $boldtitlestart . $article['title'] . $boldtitleend . $titlelinkend . $categoryname . $subtitle . $printlink . $emaillink . $articledescription;

			if($showreadmore)
			{
			  echo '&nbsp;&nbsp;&nbsp;<a href="' . RewriteLink('index.php?categoryid=' . $article['categoryid'] . '&m'.$targetID.'_articleid=' . $article['articleid']. '&moduleid='.$targetID) . '">' . $language['read_more'] . '</a>';
			}
		  }
		  else
		  {
			echo '<a href="' . RewriteLink('index.php?categoryid=' . $article['categoryid'] . '&m'.$targetID.'_articleid=' . $article['articleid'].'&moduleid='.$targetID) . '">' . $boldtitlestart . ShortTitle($article['title'],$settings['标题字节数']) . $boldtitleend . '</a>' . $categoryname . $subtitle . $printlink . $emaillink;
		  }

		  if($articlecounter < $numberofarticles AND $showdescription)
		  {
			echo iif($grouping == 'nothing', '<br /><hr size="1" noshade="noshade" />', '<br /><hr size="1" noshade="noshade" /><br />');
		  }

		  // used for checking group by category
		  if($grouping == 'category')
			$tempgroup = $category['name'];

		  // used for checking group by author
		  if($grouping == 'author')
			$tempgroup = $article['author'];

		  // used for checking group by date
		  if($grouping == 'date')
			$tempgroup = iif($article['datestart'] != 0, DisplayDate($article['datestart']), DisplayDate($article['datecreated']));
		}
	  }
	}

	$previousarticle =  $article['title'];
  }
	  
}


m3_LatestNews();

?>