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

if(!defined('IN_WEENCOMPANY'))
  die('File not found');

$articlebitfield = array('useglobalsettings'       => 1,
                         'displayonline'           => 2,
                         'displaytitle'            => 4,
                         'displayauthor'           => 8,
                         'displaycreateddate'      => 16,
                         'displayupdateddate'      => 32,
                         'displayprintarticlelink' => 64,
                         'displayemailarticlelink' => 128,
                         'displaydescription'      => 256,
                         'displaysmilies'          => 512,
                         'displaycomments'         => 1024);


// get the value of $action
$action = isset($_POST['action']) ? $_POST['action'] : (isset($_GET['action']) ? $_GET['action'] : 'displayarticles');

echo '<SCRIPT LANGUAGE="JavaScript">
      <!--
      function DisableCheckboxes(disabledstatus)
      {
        if(document.articleform.useglobalsettings.checked || disabledstatus == 1)
        {
          document.articleform.displaytitle.disabled            = true;
          document.articleform.displayauthor.disabled           = true;
          document.articleform.displaycreateddate.disabled      = true;
          document.articleform.displayupdateddate.disabled      = true;
          document.articleform.displayprintarticlelink.disabled = true;
          document.articleform.displayemailarticlelink.disabled = true;
          document.articleform.displaydescription.disabled      = true;
          document.articleform.displaysmilies.disabled          = true;
          document.articleform.displaycomments.disabled         = true;
        }
        else
        {
          document.articleform.displaytitle.disabled            = false;
          document.articleform.displayauthor.disabled           = false;
          document.articleform.displaycreateddate.disabled      = false;
          document.articleform.displayupdateddate.disabled      = false;
          document.articleform.displayprintarticlelink.disabled = false;
          document.articleform.displayemailarticlelink.disabled = false;
          document.articleform.displaydescription.disabled      = false;
          document.articleform.displaysmilies.disabled          = false;
          document.articleform.displaycomments.disabled         = false;
        }
      }

      function SetStartFinishDatesStatus(status)
      {
        if(status == 1)
        {
          document.articleform.datestart.disabled = false;
          document.articleform.dateend.disabled   = false;
        }
        else
        {
          document.articleform.datestart.disabled = true;
          document.articleform.dateend.disabled   = true;
        }
      }
      //-->
      </SCRIPT>';


// ############################### DISPLAY MENU ################################

function DisplayMenu()
{
  global $refreshpage;
  global $action;

  PrintSection('');
  echo '<table width="100%" border="0" cellpadding="5" cellspacing="0">
        <tr>
          <td class="tdrow2" width="25%" align="center"><form method="post" action="' . $refreshpage . '&action=displayarticleform&loadwysiwyg=1"><input type="submit" value=" 添加文章 " ' . iif($action == 'displayarticleform', 'DISABLED') . ' /></form></td>
          <td class="tdrow2" width="25%" align="center"><form method="post" action="' . $refreshpage . '&action=displayarticles"><input type="submit" value="显示全部文章" /></form></td>
          <td class="tdrow2" width="25%" align="center"><form method="post" action="' . $refreshpage . '&action=displayarticlesettings"><input type="submit" value="模块设置" /></form></td>
          <td class="tdrow2" width="25%" align="center"><form method="post" action="' . $refreshpage . '&action=displaycategorysettings"><input type="submit" value=" 菜单设置 " /></form></td>
        </tr>
        </table>';
  EndSection();
}



// ########################## UPDATE CATEGORY OPTIONS ##########################

if($action == 'displayarticlesettings')
{
  DisplayMenu();
  PrintmoduleSettings($moduleid, '模块设置', $refreshpage);

  PrintmoduleSettings($moduleid, '显示设置', $refreshpage . '&action=displayarticlesettings');
}



// ########################## UPDATE CATEGORY OPTIONS ##########################

if($action == 'updatecategorysettings')
{
  // following $_POST variables are all arrays
  $categoryids   = $_POST['categoryids'];
  $maxarticles   = $_POST['maxarticles'];
  $sorting       = $_POST['sorting'];
  $multiplepages = $_POST['multiplepages'];

  for($i = 0; $i < count($categoryids); $i++)
  {
    $categoryid = $categoryids[$i];

    // update or insert? (I could just delete all settings and then just insert, but for some reason I'm doing updating instead)
    if($categorysettings = $DB->query_first("SELECT categoryid FROM " . TABLE_PREFIX . "m2_settings WHERE categoryid = '$categoryid'"))
    {
      $DB->query("UPDATE " . TABLE_PREFIX . "m2_settings SET maxarticles   = '$maxarticles[$i]',
                                                             sorting       = '$sorting[$i]',
                                                             multiplepages = '$multiplepages[$categoryid]'
                                                       WHERE categoryid    = '$categoryids[$i]'");
    }
    else
    {
      // only insert, update if the selected data is not the default data
      if($maxarticles[$i] != 10 || $sorting[$i] != 'IF ( dateupdated = 0, datecreated, dateupdated ) DESC' || $multiplepages[$categoryid] != 1)
      {
        $DB->query("INSERT INTO " . TABLE_PREFIX . "m2_settings (categoryid, maxarticles, sorting, multiplepages)
                    VALUES ('$categoryids[$i]', '$maxarticles[$i]', '$sorting[$i]', '$multiplepages[$categoryid]')");
      }
    }
  }

  PrintRedirect($refreshpage . '&action=displaycategorysettings', 1);
}



// ############################### ARTICLE TIME ################################

function CreateUnixTimestamp($stringtime)
{
  global $DB;

  // $stringtime = 0000-00-00 00:00:00
  // Year-Month-Day Hour:Minute:Second

  // get time from YEAR-MONTH-DAY H:M:S (all have leading zeros: 0000-00-00 00:00:00)
  // use regular expressions to see if the sentence is valid.
  // if its valid, then change it into the timestampe and subtract the users timezonesettings and dst settings
  // the finally add it into the database
  // if anything is not valid then change it back to 0

  if(preg_match("/^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})[[:space:]]{1}([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})$/i", $stringtime, $eregidata))
  {
    // date is formatted correctly
    $year   = $eregidata[1];
    $month  = $eregidata[2];
    $day    = $eregidata[3];
    $hour   = $eregidata[4];
    $minute = $eregidata[5];
    $second = $eregidata[6];

    if($month > 12 || $day > 31 || $hour > 23 || $minute > 59 || $second > 59)
    {
      return 0;
    }

    if($month < 1 || $day < 1) // hour, minute, secound can not be less than zero (becuase -1 wouldn't get through the regular expression)
    {
      return 0;
    }

    $timezoneoffset = $DB->query_first("SELECT value FROM " . TABLE_PREFIX . "mainsettings WHERE varname = 'timezoneoffset'");
    $daylightsavings = $DB->query_first("SELECT value FROM " . TABLE_PREFIX . "mainsettings WHERE varname = 'daylightsavings'");

    $dst = $daylightsavings['value'] == 1 ? 1 : 0;

    return (gmmktime($hour, $minute, $second, $month, $day, $year) - (3600 * ($timezoneoffset['value'] + $dst)));
  }
  else
  {
    return 0;
  }
}



// ######################### INSERT OR UPDATE ARTICLE ##########################

if($action == 'insertarticle' OR $action == 'updatearticle')
{
  // basic article post data
  $categoryid      = $_POST['categoryid'];
  $views           = $_POST['views'];
  $datecreated     = isset($_POST['datecreated']) ? CreateUnixTimestamp($_POST['datecreated']) : 0;
  $dateupdated     = isset($_POST['dateupdated']) ? CreateUnixTimestamp($_POST['dateupdated']) : 0;
  $datestart       = isset($_POST['datestart'])   ? CreateUnixTimestamp($_POST['datestart'])   : 0;
  $dateend         = isset($_POST['dateend'])     ? CreateUnixTimestamp($_POST['dateend'])     : 0;
  $author          = $_POST['author'];
  $title           = $_POST['title'];
  $metadescription = $_POST['metadescription'];
  $metakeywords    = $_POST['metakeywords'];
  $description     = $_POST['description'] == '&nbsp;' ? '' : $_POST['description']; // sometimes fckeditor adds a &nsbp;
  $article         = $_POST['article'];

  // create settings
  $settings = 0;
  $settings += isset($_POST['useglobalsettings'])       ? 1    : 0;
  $settings += $_POST['displayonline'] == 1             ? 2    : 0;
  $settings += isset($_POST['displaytitle'])            ? 4    : 0;
  $settings += isset($_POST['displayauthor'])           ? 8    : 0;
  $settings += isset($_POST['displaycreateddate'])      ? 16   : 0;
  $settings += isset($_POST['displayupdateddate'])      ? 32   : 0;
  $settings += isset($_POST['displayprintarticlelink']) ? 64   : 0;
  $settings += isset($_POST['displayemailarticlelink']) ? 128  : 0;
  $settings += isset($_POST['displaydescription'])      ? 256  : 0;
  $settings += isset($_POST['displaysmilies'])          ? 512  : 0;
  $settings += isset($_POST['displaycomments'])         ? 1024 : 0;

  // insert or update the article
  if($action == 'insertarticle')
  {
    // get displayorder
    $articlecount = $DB->query_first("SELECT COUNT(*) AS value FROM " . TABLE_PREFIX . "m2_news");
    $displayorder = ($articlecount['value'] + 1);

    $DB->query("INSERT INTO " . TABLE_PREFIX . "m2_news (categoryid, settings, views, displayorder, datecreated, dateupdated, datestart, dateend, author, title, metadescription, metakeywords, description, article)
                VALUES ('$categoryid', '$settings', '$views', '$displayorder', '" . time() . "', '$dateupdated', '$datestart', '$dateend', '$author', '$title', '$metadescription', '$metakeywords', '$description', '$article')");
  }
  else
  {
    $articleid = $_POST['articleid'];

    $DB->query("UPDATE " . TABLE_PREFIX . "m2_news SET categoryid        = '$categoryid',
                                                       settings          = '$settings',
                                                       views             = '$views',
                                                       datecreated       = '$datecreated',
                                                       dateupdated       = '$dateupdated',
                                                       datestart         = '$datestart',
                                                       dateend           = '$dateend',
                                                       author            = '$author',
                                                       title             = '$title',
                                                       metadescription   = '$metadescription',
                                                       metakeywords      = '$metakeywords',
                                                       description       = '$description',
                                                       article           = '$article'
                                                 WHERE articleid         = '$articleid'");
  }

  PrintRedirect($refreshpage, 1);
}



// ######################### DISPLAY CATEGORY SETTINGS #########################

function DisplayCategorySettings($parentid = 0, $sublevelmarker = '')
{
  global $DB;
  global $refreshpage;

  // start table
  if($parentid == 0)
  {
    PrintSection('菜单设置');
    echo '<form method="post" action="' . $refreshpage . '">
          <input type="hidden" name="action" value="updatecategorysettings" />
          <table width="100%" border="0" cellpadding="5" cellspacing="0">
          <tr>
            <td class="tdrow2" height="50" colspan="4">
              <b>提示: </b>
              <br/>菜单设置是指设置当前文章模块中的文章在所属菜单中的排序方式, 是否进行分页显示, 以及每页显示的文章数量.<br/>如果"是否允许分页?"设置为"否", 则此菜单下只显示 \'N\' 篇文章, 且没有分页.
            </td>
          </tr>
          <tr>
            <td class="tdrow1">菜单名称</td>
            <td class="tdrow1">排序方式</td>
            <td class="tdrow1">每页数量</td>
            <td class="tdrow1">是否允许分页?</td>
          </tr>';
  }
  else
  {
    $sublevelmarker .= '- - ';
  }

  $getcategories = $DB->query("SELECT categoryid, parentid, name FROM " . TABLE_PREFIX . "categories WHERE parentid = $parentid ORDER BY displayorder");

  while($category = $DB->fetch_array($getcategories))
  {
    if(!$categorysettings = $DB->query_first("SELECT * FROM " . TABLE_PREFIX . "m2_settings WHERE categoryid = '" . $category['categoryid'] . "'"))
    {
      // settings have not been defined, show default
      $categorysettings = array('maxarticles'   => 10,
                                'sorting'       => 'Display Order',
                                'multiplepages' => 1);
    }

    echo '<input type="hidden" name="categoryids[]"   value="' . $category['categoryid'] . '">

          <tr>
            <td class="tdrow2">' . $sublevelmarker . $category['name'] . '</td>
            <td class="tdrow3">
              <select name="sorting[]">
              <option value="IF ( dateupdated = 0, datecreated, dateupdated ) DESC"  ' . iif($categorysettings['sorting'] == 'IF ( dateupdated = 0, datecreated, dateupdated ) DESC',    'SELECTED') .'>时间(降序)</option>
              <option value="IF ( dateupdated = 0, datecreated, dateupdated ) ASC"   ' . iif($categorysettings['sorting'] == 'IF ( dateupdated = 0, datecreated, dateupdated ) ASC',   'SELECTED') .'>时间(升序)</option>
              <option value="displayorder ASC"  ' . iif($categorysettings['sorting'] == 'displayorder ASC',  'SELECTED') .'>编号(升序)</option>
              <option value="displayorder DESC" ' . iif($categorysettings['sorting'] == 'displayorder DESC', 'SELECTED') .'>编号(降序)</option>
              <option value="title ASC"         ' . iif($categorysettings['sorting'] == 'title ASC',         'SELECTED') .'>标题(A-Z)</option>
              <option value="title DESC"        ' . iif($categorysettings['sorting'] == 'title DESC',        'SELECTED') .'>标题(Z-A)</option>
              <option value="author ASC"        ' . iif($categorysettings['sorting'] == 'author ASC',        'SELECTED') .'>作者(A-Z)</option>
              <option value="author DESC"       ' . iif($categorysettings['sorting'] == 'author DESC',       'SELECTED') .'>作者(Z-A)</option>
              </select>
            </td>
            <td class="tdrow3"><input type="text" name="maxarticles[]" value="' . $categorysettings['maxarticles'] . '" size="4" maxlength="4"></td>
            <td class="tdrow2">
              是<input type="radio" name="multiplepages[' . $category['categoryid'] . ']" value="1" ' . iif($categorysettings['multiplepages'] == 1, 'checked') . '>&nbsp;&nbsp;&nbsp;否<input type="radio" name="multiplepages[' . $category['categoryid'] . ']" value="0" ' . iif($categorysettings['multiplepages'] == 0, 'checked') . '>
            </td>
          </tr>';

    DisplayCategorySettings($category['categoryid'], $sublevelmarker);
  }

  // end table
  if($parentid == 0)
  {
    echo '<tr>
            <td class="tdrow1" bgcolor="#FCFCFC" colspan="4" align="center">
             <input type="submit" value=" 保存设置 " />
            </td>
          </tr>
          </table>

          </form>';

    EndSection();
  }
}

if($action == 'displaycategorysettings')
{
  DisplayMenu();
  DisplayCategorySettings();
}



// ########################### DISPLAY ARTICLE FORM ############################

if($action == 'displayarticleform')
{
  DisplayMenu();

  if(is_numeric($_GET['articleid']))
  {
    $article = $DB->query_first("SELECT * FROM " . TABLE_PREFIX . "m2_news WHERE articleid = '" . $_GET['articleid'] . "'");
  }
  else
  {
    $article = array('categoryid'      => 0,
                     'settings'        => 3, // 1 + 2 use global settings, display online
                     'views'           => 0,
                     'displayorder'    => 0,
                     'datecreated'     => '',
                     'dateupdated'     => '',
                     'datestart'       => time(),
                     'dateend'         => 0,
                     'author'          => $userinfo['username'],
                     'title'           => '',
                     'metadescription' => '',
                     'metakeywords'    => '',
                     'description'     => '',
                     'article'         => '');
  }

  if($article['dateend'] == 0)
  {
    $article['dateend'] = '从不';
  }

  echo '<form method="post" action="' . $refreshpage . '" name="articleform">

        <table width="100%" cellpadding="0" cellspacing="0" border="0">
        <tr>
          <td valign="top">';

  PrintSection(iif(is_numeric($_GET['articleid']), '编辑文章', '添加文章'));

  echo '<table width="100%" border="0" cellpadding="5" cellspacing="0">
        <tr>
          <td class="tdrow3" width="85%" valign="top">
            <table border="0" cellpadding="0" cellspacing="0">
            <tr>
              <td width="75"><b>标题:</b></td>
              <td><input type="text" name="title" size="60" maxlength="128" value="' .CleanFormValue($article['title']) . '"></td>
            </tr>
            </table>
          </td>
        </tr>
        <tr>
          <td class="tdrow3" width="85%" valign="top">
            <table border="0" cellpadding="0" cellspacing="0">
            <tr>
              <td width="75"><b>所属菜单:</b></td>
              <td>';

  //$categoryid = 0, $showzerovalue = 0, $parentid = 0, $sublevelmarker = '', $selectname = 'parentid'
  DisplayCategorySelection($article['categoryid'], 0, 0, '', 'categoryid');

  echo '      </td>
            </tr>
            </table>
          </td>
        </tr>
        <tr>
          <td class="tdrow3" width="85%" valign="top">
            <table border="0" cellpadding="0" cellspacing="0">
            <tr>
              <td width="75"><b>作者:</b></td>
              <td><input type="text" name="author" value="'.CleanFormValue($article['author']).'" /></td>
            </tr>
            </table>
          </td>
        </tr>
        <tr>
          <td class="tdrow3" width="85%" valign="top">
            <table border="0" cellpadding="0" cellspacing="0">
            <tr>
              <td width="75"><b>状态:</b></td>
              <td>
                <select name="displayonline" onchange="SetStartFinishDatesStatus(this.options[selectedIndex].value);">
                  <option value="1">发布</option>
                  <option value="0" ' . iif(!($article['settings'] & $articlebitfield['displayonline']), 'SELECTED') . '>隐藏</option>
                </select>
              </td>
            </tr>
            </table>
          </td>
        </tr>
        <tr>
          <td class="tdrow3" width="85%" valign="top">
            <b>简要描述:</b> 如果填写了简要描述，那么完整的文章内容需要在一个新网页中打开.<br /><br />
            <textarea name="description" style="width: 100%;" rows="15" class="mceEditor">' . $article['description'] . '</textarea>
          </td>
        </tr>
        <tr>
          <td class="tdrow3" width="85%" valign="top">
            <b>详细内容:</b> 可加入"{pagebreak}"进行分页.<br /><br />
            <textarea name="article" style="width: 100%;" rows="30" class="mceEditor">' . $article['article'] . '</textarea>
          </td>
        </tr>
        <tr>
          <td class="tdrow1" bgcolor="#FCFCFC" colspan="2" align="center">';

  if(is_numeric($_GET['articleid']))
  {
    echo '<input type="hidden" name="action"  value="updatearticle" />
          <input type="hidden" name="articleid"  value="' . $article['articleid'] . '" />
          <input type="submit" value=" 保存更新 " />';
  }
  else
  {
    echo '<input type="hidden" name="action"  value="insertarticle" />
          <input type="submit" value=" 保存 " />';
  }

  echo '  </td>
        </tr>
        </table>';
  EndSection();

  echo '  </td>
          <td width="265px" valign="top">';

  PrintSection('设置');
  echo '<table width="100%" border="0" cellpadding="5" cellspacing="0">
        <tr>
          <td class="tdrow3" width="85%" valign="top">

            <table width="100%" border="0" cellpadding="5" cellspacing="0">
            <tr><td colspan="2"><b>显示设置</b></td></tr>
            <tr><td width="10"><input type="checkbox" name="useglobalsettings"       ' . iif($article['settings'] & $articlebitfield['useglobalsettings'],       'CHECKED') . ' onclick="DisableCheckboxes()"  /></td><td >使用全局设置</td></tr>
            <tr><td width="10"><input type="checkbox" name="displaytitle"            ' . iif($article['settings'] & $articlebitfield['displaytitle'],            'CHECKED') . ' /></td><td>显示标题</td></tr>
            <tr><td width="10"><input type="checkbox" name="displayauthor"           ' . iif($article['settings'] & $articlebitfield['displayauthor'],           'CHECKED') . ' /></td><td>显示作者</td></tr>
            <tr><td width="10"><input type="checkbox" name="displaycreateddate"      ' . iif($article['settings'] & $articlebitfield['displaycreateddate'],      'CHECKED') . ' /></td><td>显示发布日期</td></tr>
            <tr><td width="10"><input type="checkbox" name="displayupdateddate"      ' . iif($article['settings'] & $articlebitfield['displayupdateddate'],      'CHECKED') . ' /></td><td>显示更新日期</td></tr>
            <tr><td width="10"><input type="checkbox" name="displayprintarticlelink" ' . iif($article['settings'] & $articlebitfield['displayprintarticlelink'], 'CHECKED') . ' /></td><td>显示打印</td></tr>
            <tr><td width="10"><input type="checkbox" name="displayemailarticlelink" ' . iif($article['settings'] & $articlebitfield['displayemailarticlelink'], 'CHECKED') . ' /></td><td>显示发送邮件</td></tr>
            <tr><td width="10"><input type="checkbox" name="displaydescription"      ' . iif($article['settings'] & $articlebitfield['displaydescription'],      'CHECKED') . ' /></td><td>简要描述显示在详细内容中</td></tr>
            <tr><td width="10"><input type="checkbox" name="displaysmilies"          ' . iif($article['settings'] & $articlebitfield['displaysmilies'],          'CHECKED') . ' /></td><td>显示表情符号</td></tr>
            <tr><td width="10"><input type="checkbox" name="displaycomments"         ' . iif($article['settings'] & $articlebitfield['displaycomments'],         'CHECKED') . ' /></td><td>显示用户评论</td></tr>
            </table>

          </td>
        </tr>
        <tr>
          <td class="tdrow3">

            <table width="100%" border="0" cellpadding="5" cellspacing="0">
            <tr><td colspan="2"><b>日期设置</b></td></tr>
            <tr><td width="100">&nbsp;</td><td>年-月-日 时:分:秒</td></tr>';

  if(is_numeric($_GET['articleid']))
  {
    echo '<tr><td width="100">创建时间:</td><td><input type="text" name="datecreated" value="' . DisplayDate($article['datecreated'], 'Y-m-d H:i:s') . '" size="17" /></td></tr>
          <tr><td width="100">更新时间:</td><td><input type="text" name="dateupdated" value="' . DisplayDate($article['dateupdated'], 'Y-m-d H:i:s') . '" size="17" /></td></tr>';
  }

  echo '    <tr><td width="100">发布时间:</td><td><input type="text" name="datestart" value="' . DisplayDate($article['datestart'], 'Y-m-d H:i:s') . '" size="17" /></td></tr>
            <tr><td width="100">过期时间:</td><td><input type="text" name="dateend" value="' . iif($article['dateend'] == '从不', '从不', DisplayDate($article['dateend'], 'Y-m-d H:i:s')) . '" size="17" /></td></tr>
            <tr><td colspan="2">文章状态只有设置为"发布", 才能设置发布与过期时间.</td></tr>
            </table>

          </td>
        </tr>';


  if($article['settings'] & $articlebitfield['useglobalsettings'])
  {
    echo '<SCRIPT LANGUAGE="JavaScript">
          <!--
          DisableCheckboxes(1);
          //-->
          </SCRIPT>';
  }

  if(!($article['settings'] & $articlebitfield['displayonline']))
  {
    // article is offline, disable the start and finish publishing dates
    echo '<SCRIPT LANGUAGE="JavaScript">
          <!--
          SetStartFinishDatesStatus(0);
          //-->
          </SCRIPT>';
  }

  echo '<tr>
          <td class="tdrow3">

            <table width="100%" border="0" cellpadding="5" cellspacing="0">
            <tr><td colspan="2"><b>点击次数</b></td></tr>
            <tr><td width="100">文章点击次数:</td><td><input type="text" name="views" value="' . $article['views'] . '" size="5" /></td></tr>
            </table>

          </td>
        </tr>
        <tr>
          <td class="tdrow3">

            <table width="100%" border="0" cellpadding="5" cellspacing="0">
            <tr><td><b>Meta设置</b></td></tr>
            <tr><td>描述:<br /><textarea rows="3" cols="25" name="metadescription">' . $article['metadescription'] . '</textarea></td></tr>
            <tr><td>关键字:<br /><textarea rows="3" cols="25" name="metakeywords">' . $article['metakeywords'] . '</textarea></td></tr>
            </table>

          </td>
        </tr>';

 echo '  </td>
        </tr>
        </table>';
  EndSection();

  echo '  </td>
        </tr>
        </table>

        </form>';
}




// ############################## DELETE ARTICLES ##############################

if($action == 'deletearticles')
{
  $articleids       = $_POST['articleids'];
  $displayorder     = $_POST['displayorder'];
  $onlinestatus     = $_POST['onlinestatus'];
  $categoryids      = $_POST['categoryids'];
  $deletearticleids = $_POST['deletearticleids'];

  // first update the articles
  for($i = 0; $i < count($articleids); $i++)
  {
    if(!is_numeric($displayorder[$i]))
    {
      $displayorder[$i] = 0;
    }

    // 2 = bitfield value for article settings onlinestatus
    if($onlinestatus[$i] == 1)
    {
      $DB->query("UPDATE " . TABLE_PREFIX . "m2_news SET settings = settings + 2 WHERE NOT(settings & 2) AND articleid = $articleids[$i]");
    }
    else
    {
      $DB->query("UPDATE " . TABLE_PREFIX . "m2_news SET settings = settings - 2 WHERE settings & 2 AND articleid = $articleids[$i]");
    }

    $DB->query("UPDATE " . TABLE_PREFIX . "m2_news SET categoryid   = $categoryids[$i],
                                                       displayorder = $displayorder[$i]
                                                 WHERE articleid    = $articleids[$i]");
  }
  
  
    for($i = 0; $i < count($deletearticleids); $i++)
    {
      // delete article
      $DB->query("DELETE FROM " . TABLE_PREFIX . "m2_news WHERE articleid = '" . $deletearticleids[$i] . "'");

      // delete article comments
      DeletemoduleComments(2, $deletearticleids[$i]);
    }

    PrintRedirect($refreshpage, 1);

}




// ############################# DISPLAY ARTICLES ##############################

if($action == 'displayarticles')
{
	if(isset($_GET['start'])){
		$start = $_GET['start'];
	}else{
		$start = 0;
	} 
  
    DisplayMenu();

	$title = isset($_POST['title']) ? $_POST['title'] : (isset($_GET['title']) ? urldecode($_GET['title']) : '');
	$author = isset($_POST['author']) ? $_POST['author'] : (isset($_GET['author']) ? urldecode($_GET['author']) : '');
	$categoryid = isset($_POST['categoryid']) ? $_POST['categoryid'] : (isset($_GET['categoryid']) ? $_GET['categoryid'] : 0);
	$online = isset($_POST['online']) ? $_POST['online'] : (isset($_GET['online']) ? $_GET['online'] : 'onlineoffline');
	$sorting = isset($_POST['sorting']) ? $_POST['sorting'] : (isset($_GET['sorting']) ? urldecode($_GET['sorting']) : 'IF ( dateupdated = 0, datecreated, dateupdated ) DESC');
	$limit = isset($_POST['limit']) ? $_POST['limit'] : (isset($_GET['limit']) ? $_GET['limit'] : 10);

  $articlequery = 'WHERE';

  // search for title?
  if(strlen($title))
  {
    $articlequery .= iif($articlequery != 'WHERE', ' AND') . " title LIKE '%" . $title . "%'";
  }

  // search for author?
  if(strlen($author))
  {
    $articlequery .= iif($articlequery != 'WHERE', ' AND') . " author LIKE '%" . $author . "%'";
  }

  // search for author?
  if($categoryid != 0)
  {
    $articlequery .= iif($articlequery != 'WHERE', ' AND') . " categoryid = " . $categoryid;
  }

  // search by online, offline, both?
  if($online != 'onlineoffline')
  {
    if($online == 'online')
    {
      $articlequery .= iif($articlequery != 'WHERE', ' AND') . " (settings & " . $articlebitfield['displayonline'] . ")";
    }
    else
    {
      $articlequery .= iif($articlequery != 'WHERE', ' AND') . " !(settings & " . $articlebitfield['displayonline'] . ")";
    }
  }

  $articles = $DB->query("SELECT articleid, categoryid, settings, views, displayorder, datecreated, datestart, dateend, author, title
                          FROM " . TABLE_PREFIX . "m2_news " . iif($articlequery != 'WHERE', $articlequery) . " ORDER BY $sorting LIMIT $start, $limit");

  $maxrows = $DB->query_first("SELECT COUNT(*) AS value FROM " . TABLE_PREFIX . "m2_news " . iif($articlequery != 'WHERE', $articlequery) . "");

  PrintSection('搜索文章');
  echo '<form method="post" action="' . $refreshpage . '" name="displayarticles">
        <input type="hidden" name="action" value="displayarticles" />
        <table width="100%" border="0" cellpadding="5" cellspacing="0">
        <tr>
          <td class="tdrow1">标题</td>
          <td class="tdrow1">作者</td>
          <td class="tdrow1">所属菜单</td>
          <td class="tdrow1">状态</td>
          <td class="tdrow1">排序</td>
          <td class="tdrow1">条/页</td>
        </tr>
        <tr>
          <td class="tdrow2"><input type="text" name="title"   value="' . $title . '" /></td>
          <td class="tdrow2"><input type="text" name="author" value="' . $author . '"" /></td>
          <td class="tdrow2">';

  // Default Function Values:
  // $categoryid = 0, $showzerovalue = 0, $parentid = 0, $sublevelmarker = '', $selectname = 'parentid'
  DisplayCategorySelection($categoryid, 1, 0, '', 'categoryid');

  echo '  </td>
          <td class="tdrow2">
            <select name="online">
              <option value="onlineoffline" ' . iif($online == 'onlineoffline', 'SELECTED') .'>发布/隐藏</option>
              <option value="online"        ' . iif($online == 'online',        'SELECTED') .'>发布</option>
              <option value="offline"       ' . iif($online == 'offline',       'SELECTED') .'>隐藏</option>
            </select>
          </td>
          <td class="tdrow2">
            <select name="sorting">
              <option value="IF ( dateupdated = 0, datecreated, dateupdated ) DESC"    ' . iif($sorting == 'IF ( dateupdated = 0, datecreated, dateupdated ) DESC', 'SELECTED') .'>时间(降序)</option>
              <option value="IF ( dateupdated = 0, datecreated, dateupdated ) ASC"     ' . iif($sorting == 'IF ( dateupdated = 0, datecreated, dateupdated ) ASC',    'SELECTED') .'>时间(升序)</option>
              <option value="displayorder ASC"  ' . iif($sorting == 'displayorder ASC',  'SELECTED') .'>编号(升序)</option>
              <option value="displayorder DESC" ' . iif($sorting == 'displayorder DESC', 'SELECTED') .'>编号(降序)</option>
              <option value="title ASC"         ' . iif($sorting == 'title ASC',         'SELECTED') .'>标题(A-Z)</option>
              <option value="title DESC"        ' . iif($sorting == 'title DESC',        'SELECTED') .'>标题(Z-A)</option>
              <option value="author ASC"        ' . iif($sorting == 'author ASC',        'SELECTED') .'>作者(A-Z)</option>
              <option value="author DESC"       ' . iif($sorting == 'author DESC',       'SELECTED') .'>作者(Z-A)</option>
            </select>
          </td>
          <td class="tdrow2"><input type="text" name="limit" value="' . $limit . '" size="4" /></td>
        </tr>
        <tr>
          <td class="tdrow1" colspan="6" align="center"><input type="submit" value=" 搜索 " /></td>
        </tr>
        </table></form>';
  EndSection();

  PrintSection('文章条目');

  echo '<form method="post" action="' . $refreshpage . '" name="deletearticles">
        <input type="hidden" name="action" value="deletearticles" />
		<table width="100%" border="0" cellpadding="5" cellspacing="0">
        <tr>
          <td class="tdrow1">编号</td>
          <td class="tdrow1">标题</td>
          <td class="tdrow1">状态</td>
          <td class="tdrow1">所属菜单</td>
          <td class="tdrow1">作者</td>
          <td class="tdrow1">发布日期</td>
          <td class="tdrow1">过期</td>
          <td class="tdrow1" width="75"><input type="checkbox" checkall="group" onclick="javascript: return select_deselectAll (\'deletearticles\', this, \'group\');"> 删除</td>
        </tr>';

  while($article = $DB->fetch_array($articles))
  {
    echo '<input type="hidden" name="articleids[]" value="' . $article['articleid'] . '" />

          <tr>
            <td class="tdrow2" align="center"><input type="text" name="displayorder[]" value="' . $article['displayorder'] . '" size="4" /></td>
            <td class="tdrow3"><a ' . iif(!($article['settings'] & $articlebitfield['displayonline']) || $article['dateend'], 'style="color: #FF0000; font-weight:bold;"') . ' href="' . $refreshpage . '&action=displayarticleform&articleid=' . $article['articleid'] . '&loadwysiwyg=1"><u>' . iif(strlen($article['title']), ShortTitle($article['title'],50), '未知标题') . '</u></a></td>
            <td class="tdrow2">
              <select name="onlinestatus[]">
                <option value="1">发布</option>
                <option value="0" ' . iif(!($article['settings'] & $articlebitfield['displayonline']), 'SELECTED', '') . '>隐藏</option>
              </select>
            </td>
            <td class="tdrow3">';

    //$categoryid = 0, $showzerovalue = 0, $parentid = 0, $sublevelmarker = '', $selectname = 'parentid'
    DisplayCategorySelection($article['categoryid'], 1, 0, '', 'categoryids[]');

    echo '  </td>
            <td class="tdrow2">' . iif(strlen($article['author']), $article['author'], '&nbsp;') . '</td>
            <td class="tdrow3">' . iif($article['datestart'] != 0, DisplayDate($article['datestart']), DisplayDate($article['datecreated'])) . '</td>
            <td class="tdrow2">' . iif($article['dateend']   != 0, '<font class=ohred>'.DisplayDate($article['dateend']).'</font>',   '从不') . '</td>
            <td class="tdrow3"><input type="checkbox" name="deletearticleids[]" value="' . $article['articleid'] . '" checkme="group" /></td>
          </tr>';
  }

	$sectionimagesnum = $maxrows['value'];
	$rows = $maxrows['value'] - $start;
	$page_num = ceil($sectionimagesnum / $limit);
	$page_group = floor($start/$limit/8)*8+1;
	$now_page_num = $start/$limit+1;

    $title = urlencode ($title);
    $author = urlencode ($author);
    $sorting = urlencode ($sorting);

  if(($start > 0) || ($rows > $limit))
  {

		echo '<tr><td class="tdrow3" colspan="8" align="center" height="48" valign="middle"><table width="100%" cellpadding="0" cellspacing="0" border="0">
		  <tr>';

		if($start > 0)
		{
		  echo '<td style="padding-left: 3px; vertical-align:middle;" width="10%" nowrap="nowrap"><a href="'.$refreshpage.'&action=displayarticles&title='.$title.'&author='.$author.'&categoryid=' . $categoryid.'&online=' . $online.'&sorting=' . $sorting.'&limit=' . $limit.'&start='.($start - $limit).'">&lsaquo;&lsaquo; 上一页</a></td>';
		}else{
		  echo '<td style="padding-left: 3px; vertical-align:middle;" width="10%" nowrap="nowrap">&nbsp;</td>';
		}

		if($page_num - $now_page_num < 10){
			$start_page = $page_num - 9;
			if($start_page<1){
				$start_page = 1;
			}
			$end_page = $page_num + 1;
		}else{
			$start_page = $page_group;
			$end_page = $start_page + 8;
		}

		if($start_page > 1){
			$direct_bar = '<a href="'.$refreshpage.'&action=displayarticles&title='.$title.'&author='.$author.'&categoryid=' . $categoryid.'&online=' . $online.'&sorting=' . $sorting.'&limit=' . $limit.'&start=0">1</a><a href="'.$refreshpage.'&action=displayarticles&title='.$title.'&author='.$author.'&categoryid=' . $categoryid.'&online=' . $online.'&sorting=' . $sorting.'&limit=' . $limit.'&start='.($start_page-2)*$limit.'">&lsaquo;&lsaquo;...</a>';
		}

		for ($p=$start_page; $p < $end_page; $p++ ) 
		{	
			if (($start/$limit+1) == $p){
				$direct_bar .= '<STRONG>'.$p.'</STRONG>';
			}else{
				$direct_bar .= '<a href="'.$refreshpage.'&action=displayarticles&title='.$title.'&author='.$author.'&categoryid=' . $categoryid.'&online=' . $online.'&sorting=' . $sorting.'&limit=' . $limit.'&start='.($p-1)*$limit.'">'.$p.'</a>';
			}
			if($p >= $page_num){
				break;
			}
		}

		if($page_num - $now_page_num >= 10){
			$direct_bar .= '<a href="'.$refreshpage.'&action=displayarticles&title='.$title.'&author='.$author.'&categoryid=' . $categoryid.'&online=' . $online.'&sorting=' . $sorting.'&limit=' . $limit.'&start='.($page_group + 7)*$limit.'">...&rsaquo;&rsaquo;</a><a href="'.$refreshpage.'&action=displayarticles&title='.$title.'&author='.$author.'&categoryid=' . $categoryid.'&online=' . $online.'&sorting=' . $sorting.'&limit=' . $limit.'&start='.($page_num-1)*$limit.'">'.$page_num.'</a>';
		}

		echo '<td width="80%" style="text-align:center; vertical-align:middle;" class="pages_nav">'.$direct_bar.'</td>';

		if($rows > $limit)
		{
		  $start += $limit;
		  echo '<td style="padding-right: 3px; vertical-align:middle;" width="10%" nowrap="nowrap"><div align="right"><a href="'.$refreshpage.'&action=displayarticles&title='.$title.'&author='.$author.'&categoryid=' . $categoryid.'&online=' . $online.'&sorting=' . $sorting.'&limit=' . $limit.'&start='.$start.'">下一页 &rsaquo;&rsaquo;</a></div></td>';
		}else{
		  echo '<td style="padding-right: 3px; vertical-align:middle;" width="10%" nowrap="nowrap">&nbsp;</td>';
		}

		echo '</tr></table>';

   }


	echo '<tr><td class="tdrow1" colspan="8" align="center"><input type="submit" onclick="return confirm(\'确定保存更新, 并删除选中的文章吗?\');" value=" 保存更新 " /></td></tr></table></form>';

	EndSection();
}

?>