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

// prevent direct script access
if(!defined('IN_WEENCOMPANY'))
die('非法进入!');

// ########################### Check Directory Permissions ########################
if($sitedefaultlang == 'en') 
{
	$mplang='en';
}
else
{
	$mplang='cn';
}

$uploaddir  = dirname(__FILE__) . '/upload/';
$imagedir = dirname(__FILE__) . '/images_'.$mplang.'/'; 
$errors = array();

if (!is_writable($uploaddir))
{
        $errors[] = '上传文件夹 ('.$uploaddir.') 不可写 - 文件夹属性需改为: 0777';
}

if (!is_writable($imagedir))
{
        $errors[] = '产品图片文件夹 ('.$imagedir.') 不可写 - 文件夹属性需改为: 0777';
}

if (!is_dir($uploaddir))
{
        $errors[] ='上传文件夹 ('.$uploaddir.') 不存在';
}

if (!is_dir($imagedir))
{
        $errors[] ='产品图片文件夹 ('.$imagedir.') 不存在';
}

if (!empty($errors))
{
        PrintErrors($errors, '模块设置错误!');
}


// ############################## INSERT SECTION ###############################

function InsertSection()
{
        global $DB, $refreshpage;

        $activated = empty($_POST['activated']) ? 0 : $_POST['activated'];

        $parentid        = $_POST['parentid'];
        $name         = $_POST['name'];
        $description   = $_POST['description'];
        $sorting = $_POST['sorting'];

        if(strlen($name) == 0)
        {
                $errors[] = '必须输入产品类别名称!';
        }

        if(!isset($errors))
        {
                $DB->query("INSERT INTO " . TABLE_PREFIX . "m17_sections VALUES ('0', '$parentid', '$activated', '0', '$name', '$description', '$sorting', '0', '" . time() . "') ");

				$sectionid = $DB->insert_id();
				$DB->query("UPDATE " . TABLE_PREFIX . "m17_sections SET ordernum     = '$sectionid' WHERE sectionid = '$sectionid'");

                PrintRedirect($refreshpage, 1);
        }
        else
        {
                PrintErrors($errors);

                DisplaySectionForm(null);
        }
}



// ############################## UPDATE SECTION ###############################

function UpdateSection()
{
  global $DB, $refreshpage, $imagedir;

  $parentid = empty($_POST['parentid']) ? 0 : $_POST['parentid'];
	$activated = empty($_POST['activated']) ? 0 : $_POST['activated'];
	$imageid = empty($_POST['imageid']) ? 0 : $_POST['imageid'];
	$ordernum = is_numeric($_POST['ordernum']) ? $_POST['ordernum'] : 0;

	$sectionid        = $_POST['sectionid'];
	$name         = $_POST['name'];
	$description   = $_POST['description'];
	$sorting = $_POST['sorting'];

  // delete section and images
  if($_POST['deletesection'] == 1)
  {
	   $subsection = $DB->query_first("SELECT parentid FROM " . TABLE_PREFIX . "m17_sections WHERE parentid = '$sectionid'");
	   if (isset($subsection))
	   {
			$errors[] = '无法删除此产品类别! 您必须先删除此类别的子类别.';
			PrintErrors($errors);
			DisplaySectionForm($sectionid);
			exit();
	   }
  }
  
  if($_POST['deletesectionimages'] == 1 && $_POST['deletesection'] == 1)
{
		$images = $DB->query("SELECT imageid, filename,thumbname FROM " . TABLE_PREFIX . "m17_products WHERE sectionid = '$sectionid'");
		while($getfilename = $DB->fetch_array($images))
		{
			$imageid     = $getfilename['imageid'];
			$filename    = $getfilename['filename'];
			$thumbname    = $getfilename['thumbname'];
			$image     = $imagedir . $filename;
			$thumbnail = $imagedir . 'tb_' . $thumbname;
			$midsize   = $imagedir . 'md_' . $filename;
	
			// delete image's comments
			DeleteModuleComments(17, $imageid);
	
			@unlink($image);
			@unlink($thumbnail);
			@unlink($midsize);
        }
        
        $DB->query("DELETE FROM " . TABLE_PREFIX . "m17_products WHERE sectionid = '$sectionid'");
		$DB->query("DELETE FROM " . TABLE_PREFIX . "m17_sections WHERE sectionid = '$sectionid'");

		PrintRedirect($refreshpage, 1);
  }
  
  if ($_POST['deletesectionimages'] == 1 && $_POST['deletesection'] == 0)
  {
		$images = $DB->query("SELECT imageid, filename,thumbname FROM " . TABLE_PREFIX . "m17_products WHERE sectionid = '$sectionid'");
		while($getfilename = $DB->fetch_array($images))
		{
			$imageid     = $getfilename['imageid'];
			$filename    = $getfilename['filename'];
			$thumbname    = $getfilename['thumbname'];
			$image     = $imagedir . $filename;
			$thumbnail = $imagedir . 'tb_' . $thumbname;
			$midsize   = $imagedir . 'md_' . $filename;
	
			// delete image's comments
			DeleteModuleComments(17, $imageid);
	
			@unlink($image);
			@unlink($thumbnail);
			@unlink($midsize);
        }
		
		$DB->query("DELETE FROM " . TABLE_PREFIX . "m17_products WHERE sectionid = '$sectionid'");

		$imageid     = 0;

  }
  
  if ($_POST['deletesectionimages'] == 0 && $_POST['deletesection'] == 1)
  {
        $DB->query("DELETE FROM " . TABLE_PREFIX . "m17_sections WHERE sectionid = '$sectionid'");
        $DB->query("UPDATE " . TABLE_PREFIX . "m17_products SET sectionid = '$parentid' WHERE sectionid = '$sectionid'");

        PrintRedirect($refreshpage, 1);
  }

  if(strlen($name) == 0)
  {
    $errors[] = '必须输入产品类别名称!';
  }

  if(!isset($errors))
  {
    if($sectionid=='1'){$activated=1;}
	
    $DB->query("UPDATE " . TABLE_PREFIX . "m17_sections SET parentid    = '$parentid',
                                                            activated   = '$activated',
                                                            ordernum   = '$ordernum',
                                                            name        = '$name',
                                                            description = '$description',
                                                            sorting     = '$sorting',
                                                            imageid     = '$imageid'
                                                      WHERE sectionid   = '$sectionid'");

    PrintRedirect($refreshpage, 1);
  }
  else
  {
    PrintErrors($errors);
    DisplaySectionForm($sectionid);
  }
}



// ########################### DISPLAY SECTION FORM ############################

// view the section form to insert/edit a section
function DisplaySectionForm($sectionid)
{
        global $DB, $refreshpage, $sitedefaultlang, $loadwysiwyg, $enablewysiwyg;
		if($sitedefaultlang == 'en') 
		{
			$mplang='en';
		}
		else
		{
			$mplang='cn';
		}
        if(isset($sectionid))
        {
                // gather section information
                $section = $DB->query_first("SELECT * FROM " . TABLE_PREFIX . "m17_sections WHERE sectionid = '$sectionid'");

                PrintSection('编辑分类: '.$section['name']);
        }
        else
        {
                // create empty array
                $section = array("parentid"    => '1',
                "activated"   => 1,
                "name"        => '',
                "description" => '',
                "sorting"     => '时间(降序)',
                "imageid"           => 0);

                PrintSection('添加分类');
        }

        echo '<form method="post" action="'.$refreshpage.'">
        <input type="hidden" name="sectionid"  value="'.$sectionid.'" />

        <table width="100%" border="0" cellpadding="5" cellspacing="0">';

        if(isset($sectionid))
        {
                echo '<tr>
            <td class="tdrow2" width="15%" valign="top"><b>删除类别:</b></td>
            <td class="tdrow3" width="85%" valign="top">';

                if($sectionid == 1)
                {
                        echo '默认根类别不能删除.';
                }
                else
                {
                        echo '<input type="checkbox" name="deletesection" value="1"> 删除此类别? 注: 如仅删除产品类别, 而不删除所有此类产品, 则所有此类产品自动转入其父类.<br/>';
                }

                echo '  </td>
          </tr>';

                echo '<tr>
            <td class="tdrow2" width="15%" valign="top"><b>删除产品:</b></td>
            <td class="tdrow3" width="85%" valign="top">
              <input type="checkbox" name="deletesectionimages" value="1"> 删除此类别的所有产品?
            </td>
          </tr>
		  <tr>
            <td class="tdrow2" width="15%" valign="top"><b>类别编号:</b></td>
            <td class="tdrow3" width="85%" valign="top">
              <input type="text" name="ordernum" value="'.$section['ordernum'].'" size="4" />
            </td>
          </tr>';
        }

        echo '<tr>
          <td class="tdrow2" width="15%"><b>所属类别:</b></td>
          <td class="tdrow3" width="85%" valign="top">';

        if(isset($sectionid))
		{
			if($sectionid == 1)
			{
			  echo '根类别不能设置所属类别.';
			}
			else
			{
					PrintSectionSelectionEXX('parentid', $section['parentid'], $section['sectionid']);
			}
		}
		else
		{
				PrintSectionSelection('parentid', $section['parentid'], $section['sectionid']);
		}

        echo '  </td>
        </tr>
        <tr>
          <td class="tdrow2" width="15%" valign="top"><b>产品排序:</b></td>
          <td class="tdrow3" width="85%" valign="top">
                          <select name="sorting">
                          <option '.iif($section[sorting] == "时间(降序)",       "selected", "") .'>时间(降序)</option>
                          <option '.iif($section[sorting] == "时间(升序)",       "selected", "") .'>时间(升序)</option>
                          <option '.iif($section[sorting] == "编号(降序)", "selected", "") .'>编号(降序)</option>
                          <option '.iif($section[sorting] == "编号(升序)", "selected", "") .'>编号(升序)</option>
                        </select>
          </td>
        </tr>
        <tr>
          <td class="tdrow2" width="15%"><b>类别名称:</b></td>
          <td class="tdrow3" width="85%" valign="top">
            <input type="text" name="name" value="'.CleanFormValue($section['name']).'" />
          </td>
        </tr>';

        if($sectionid != 1)
        {
                echo '<tr>
            <td class="tdrow2" width="15%" valign="top"><b>类别描述:</b>';
		  
		  if($loadwysiwyg AND $enablewysiwyg){
			echo '&nbsp&nbsp<a href="javascript:;" onclick="javascript: ween_toggleEditor(\'catdescription\', \'tinytogglecat\', \'tinytoggleimgcat\');return false;" id="tinytogglecat" title="Hide TinyMCE"><img src="styles/advanced/images/disabletiny.gif" border="0" align="absmiddle" id="tinytoggleimgcat"></a>';
		  }
	      echo '</td>
             <td class="tdrow3" width="85%" valign="top">
              <textarea name="description" style="width: 100%;" rows="16" class="mceEditor" id="catdescription">' . $section['description'] . '</textarea>
            </td>
          </tr>
          <tr>
            <td class="tdrow2" width="15%" valign="top"><b>是否发布:</b></td>
            <td class="tdrow3" width="85%" valign="top">
              <input type="checkbox" name="activated" value="1" '.iif($section['activated'] == 1, "CHECKED", "").'><b>发布:</b> 网站显示此类别及其下属产品?
            </td>
          </tr>';

                if(isset($sectionid))
                {
                        // Display the images in the section so that the user can choose one to represent the section
                        echo '<tr>
            <td class="tdrow2" width="15%" valign="top"><b>类别缩图:</b><br/><br/>注: 从默认图片或最新的10个此类产品缩图中选择一个.</td>
            <td class="tdrow3" width="85%" valign="top">';

						$isload = 0;
						$getimages = $DB->query("SELECT imageid, thumbname FROM " . TABLE_PREFIX . "m17_products WHERE sectionid = " . $sectionid . " ORDER BY imageid DESC LIMIT 0, 10");
                        while($image = $DB->fetch_array($getimages))
                        {
						 $number=$number+1;
						 if($image['imageid'] == $section['imageid'])
						 {
							 echo '<input type="radio" name="imageid" value="' . $image['imageid'] . '" ' . iif($image['imageid'] == $section['imageid'], 'checked', '') . ' ><img src="../modules/m17_products/images_'.$mplang.'/tb_' . $image['thumbname'] .'" align="middle" />';
							 $isload=1;
							 }
							 else
							 {
							 echo '<input type="radio" name="imageid" value="' . $image['imageid'] . '"><img src="../modules/m17_products/images_'.$mplang.'/tb_' . $image['thumbname'] .'" align="middle" />';
						 }
						 		 
					     if(is_int($number/5)){echo '<br /><br />';}
                        }
						
						if($isload == 0 AND isset($section['imageid']))
						{
							$getimages = $DB->query("SELECT imageid, thumbname FROM " . TABLE_PREFIX . "m17_products WHERE imageid = " . $section['imageid']);
							while($image = $DB->fetch_array($getimages))
							{
							 echo '<input type="radio" name="imageid" value="' . $image['imageid'] . '", checked><img src="../modules/m17_products/images_'.$mplang.'/tb_' . $image['thumbname'] .'" align="middle" />';
							 }
						 }

                        echo '<input type="radio" name="imageid" value="0" ' . iif($section['imageid'] == "0", 'checked', '') . ' ><img src="../modules/m17_products/defaultfolder.gif" align="middle" />';

                        echo '  </td>
        </tr>';
                }
        }

        echo  '<tr>
          <td colspan="2" align="center" class="tdrow1">';

        if($sectionid)
        {
                echo '<input type="hidden" name="action" value="updatesection" />
          <input type="submit" value=" 保存更新 " />';  }
                else
                {
                        echo '<input type="hidden" name="action" value="insertsection" />
          <input type="submit" value=" 创建分类 " />';
                }

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



// ############################### DELETE IMAGE ################################

function DeleteImage($imageid)
{
        global $DB, $refreshpage, $imagedir;

        $getfilename = $DB->query_first("SELECT filename, thumbname FROM " . TABLE_PREFIX . "m17_products WHERE imageid = '$imageid'");
        $filename    = $getfilename['filename'];

        $image     = $imagedir . $filename;
        $thumbnail = $imagedir . 'tb_' . $getfilename['thumbname'];
        $midsize   = $imagedir . 'md_' . $filename;

        // delete image
        $DB->query("DELETE FROM " . TABLE_PREFIX . "m17_products WHERE imageid = '$imageid'");

        // delete image's comments
        DeleteModuleComments(17, $imageid);

        @unlink($image);
        @unlink($thumbnail);
        @unlink($midsize);

        PrintRedirect($refreshpage, 1);
}



// ############################### UPDATE IMAGE ################################

function UpdateImage()
{
        global $DB, $refreshpage, $imagedir;

        $image         = $_FILES['image'];
        $thumbnail     = $_FILES['thumbnail'];
        $imageid     = $_POST['imageid'];
        $sectionid     = $_POST['sectionid'];
        $deleteimage     = empty($_POST['deleteimage']) ? 0 : $_POST['deleteimage'];
		$ordernum = is_numeric($_POST['ordernum']) ? $_POST['ordernum'] : 0;
        $activated     = empty($_POST['activated']) ? 0 : $_POST['activated'];
        $allowsmilies  = empty($_POST['allowsmilies']) ? 0 : $_POST['allowsmilies'];
        $allowcomments = empty($_POST['allowcomments']) ? 0 : $_POST['allowcomments'];
        $showauthor    = empty($_POST['showauthor']) ? 0 : $_POST['showauthor'];
        $author        = $_POST['author'];
        $title         = $_POST['title'];
        $description   = $_POST['description'];
        $specification = $_POST['specification'];
        $priceship     = $_POST['priceship'];

        $valid_image_types = array('image/pjpeg',
        'image/jpeg',
        'image/gif',
        'image/bmp',
        'image/x-png',
        'image/png');

        // get module settings
        $getsettings = $DB->query("SELECT title, value FROM " . TABLE_PREFIX . "modulesettings WHERE moduleid = '17'");
        while($setting = $DB->fetch_array($getsettings))
        {
                $settings[$setting['title']] = $setting['value'];
        }

		// delete image?
        if($deleteimage == 1)
        {
                DeleteImage($imageid);
        }


        // check if image was uploaded
        if($image['size'] != 0)
        {
                if(!in_array($image['type'], $valid_image_types))
                {
                        $errors[] = '产品图片类型无效!';
                }

                if($settings['自动缩图'] == 1 && ($image['type'] == 'image/gif' OR $image['type'] == 'image/bmp'))
                {
                        $errors[] =  '<b>当php使用GD1或GD2函数库时, 无法自动生成gif和bmp图片缩图!<br />
          如果想添加gif和bmp图片缩图, 请打开<u><a href="mymodules.php?moduleid=17&action=displaysettings">产品模块设置</a></u>, 更改"缩图设置"中的"自动缩图"为"否".</b>';
                }
				
                if($settings['自动中图'] == 1 && ($image['type'] == 'image/gif' OR $image['type'] == 'image/bmp'))
                {
                        $errors[] =  '<b>当php使用GD1或GD2函数库时, 无法自动生成gif和bmp图片缩图!<br />
          请打开<u><a href="mymodules.php?moduleid=17&action=displaysettings">产品模块设置</a></u>, 更改"中图设置"中的"自动中图"为"否", 此时系统将无法创建中图.</b>';
                }
        }


        if($thumbnail['size'] != 0)
        {

                if(!in_array($thumbnail['type'], $valid_image_types))
                {
                        $errors[] = '产品缩图类型无效!';
                }
        }


        if(!isset($errors))
        {

				$DB->query("UPDATE " . TABLE_PREFIX . "m17_products SET sectionid     = '$sectionid',
                                    activated     = '$activated',
                                    ordernum     = '$ordernum',
                                    allowsmilies  = '$allowsmilies',
                                    allowcomments = '$allowcomments',
                                    showauthor    = '$showauthor',
                                    author        = '$author',
                                    title         = '$title',
                                    description   = '$description',
                                    specification   = '$specification',
                                    priceship   = '$priceship'
                              WHERE imageid       = '$imageid'");


				$known_photo_types = array(
				'image/pjpeg' => 'jpg',
				'image/jpeg'  => 'jpg',
				'image/gif'   => 'gif',
				'image/bmp'   => 'bmp',
				'image/x-png' => 'png',
				'image/png'   => 'png'
				);

				if($image['size'] != 0){
					$getfilename = $DB->query_first("SELECT filename, thumbname FROM " . TABLE_PREFIX . "m17_products WHERE imageid = '$imageid'");
					$filename_del    = $getfilename['filename'];

					$image_del     = $imagedir . $filename_del;
					$thumbnai_del = $imagedir . 'tb_' . $getfilename['thumbname'];
					$midsize_del   = $imagedir . 'md_' . $filename_del;

					@unlink($image_del);
					@unlink($midsize_del);


					$filetype  = $image['type'];
					$extention = $known_photo_types[$filetype];
					$filename  = $imageid . '.' . $extention;
					$tbname    = $filename;

					$DB->query("UPDATE " . TABLE_PREFIX . "m17_products SET filename  = '$filename' WHERE imageid = '$imageid' ");

					// Store the orignal file
					copy($image['tmp_name'], $imagedir.$filename);

					if($settings['自动缩图'])
					{
							@unlink($thumbnai_del);
							$DB->query("UPDATE " . TABLE_PREFIX . "m17_products SET thumbname  = '$filename' WHERE imageid = '$imageid' ");
							CreateThumbnail($imagedir.$filename, $imagedir."tb_".$filename, $settings['缩图最大宽度'], $settings['缩图最大高度'], $settings['方形缩图']);

					}else if($thumbnail['size'] != 0){
							@unlink($thumbnai_del);
							$thumbtype = $thumbnail['type'];
							$extention = $known_photo_types[$thumbtype];
							$thumbname = 'tb_' . $imageid . '.' . $extention;
							$tbname = $imageid . '.' . $extention;
							
							$DB->query("UPDATE " . TABLE_PREFIX . "m17_products SET thumbname  = '$tbname', isautothumb='0' WHERE imageid = '$imageid' ");

							copy($thumbnail['tmp_name'], $imagedir . $thumbname);
							
					}

					if($settings['自动中图'])
					{
							CreateThumbnail($imagedir.$filename, $imagedir."md_".$filename, $settings['中图最大宽度'], $settings['中图最大高度'], $settings['方型中图']);
					}

					if(!$settings['大图保持原始'] AND $settings['自动中图'])
					{
							@unlink($imagedir.$filename);
					}

				}else if($thumbnail['size'] != 0){

					$getfilename = $DB->query_first("SELECT thumbname FROM " . TABLE_PREFIX . "m17_products WHERE imageid = '$imageid'");
					$thumbnai_del = $imagedir . 'tb_' . $getfilename['thumbname'];

					@unlink($thumbnai_del);


					$thumbtype = $thumbnail['type'];
					$extention = $known_photo_types[$thumbtype];
					$thumbname = 'tb_' . $imageid . '.' . $extention;
					$tbname = $imageid . '.' . $extention;
					
					$DB->query("UPDATE " . TABLE_PREFIX . "m17_products SET thumbname  = '$tbname', isautothumb='0' WHERE imageid = '$imageid' ");

					copy($thumbnail['tmp_name'], $imagedir . $thumbname);
							
				}


                PrintRedirect($refreshpage, 1);
        }
        else
        {
                PrintErrors($errors);

                DisplayImageForm($imageid);
        }
}





// ############################### INSERT IMAGE ################################

function InsertImage()
{
        global $DB, $refreshpage, $imagedir;
        // get post variables
        $image         = $_FILES['image'];
        $thumbnail     = $_FILES['thumbnail'];
        $sectionid     = $_POST['sectionid'];
        $activated     = empty($_POST['activated']) ? 0 : $_POST['activated'];
        $allowsmilies  = empty($_POST['allowsmilies']) ? 0 : $_POST['allowsmilies'];
        $allowcomments = empty($_POST['allowcomments']) ? 0 : $_POST['allowcomments'];
        $showauthor    = empty($_POST['showauthor']) ? 0 : $_POST['showauthor'];
        $author        = $_POST['author'];
        $title         = $_POST['title'];
        $description   = $_POST['description'];
        $specification = $_POST['specification'];
        $priceship     = $_POST['priceship'];
		
        $valid_image_types = array('image/pjpeg',
        'image/jpeg',
        'image/gif',
        'image/bmp',
        'image/x-png',
        'image/png');

        // get module settings
        $getsettings = $DB->query("SELECT title, value FROM " . TABLE_PREFIX . "modulesettings WHERE moduleid = '17'");
        while($setting = $DB->fetch_array($getsettings))
        {
                $settings[$setting['title']] = $setting['value'];
        }

        if(strlen($author) == 0 && $showauthor == 1)
        {
                $errors[] = '请输入作者的姓名!';
        }

        // check if image was uploaded
        if($image['size'] == 0)
        {
                $errors[] = '产品图片太大(不能大于2M)或没有选择图片文件!';
        }
        else
        {
                if(!in_array($image['type'], $valid_image_types))
                {
                        $errors[] = '产品图片类型无效!';
                }

                if(isset($_FILES['thumbnail']) AND !in_array($thumbnail['type'], $valid_image_types))
                {
                        $errors[] = '请选择一个产品缩图或缩图类型无效!';
                }

                if($settings['自动缩图'] == 1 && ($image['type'] == 'image/gif' OR $image['type'] == 'image/bmp'))
                {
                        $errors[] =  '<b>当php使用GD1或GD2函数库时, 无法自动生成gif和bmp图片缩图!<br />
          如果想添加gif和bmp图片缩图, 请打开<u><a href="mymodules.php?moduleid=17&action=displaysettings">产品模块设置</a></u>, 更改"缩图设置"中的"自动缩图"为"否".</b>';
                }
				
                if($settings['自动中图'] == 1 && ($image['type'] == 'image/gif' OR $image['type'] == 'image/bmp'))
                {
                        $errors[] =  '<b>当php使用GD1或GD2函数库时, 无法自动生成gif和bmp图片缩图!<br />
          请打开<u><a href="mymodules.php?moduleid=17&action=displaysettings">产品模块设置</a></u>, 更改"中图设置"中的"自动中图"为"否", 此时系统将无法创建中图.</b>';
                }
        }

        if(!isset($errors))
        {
                // List of our known photo types
                $known_photo_types = array(
                'image/pjpeg' => 'jpg',
                'image/jpeg'  => 'jpg',
                'image/gif'   => 'gif',
                'image/bmp'   => 'bmp',
                'image/x-png' => 'png',
                'image/png'   => 'png'
                );

                $DB->query("INSERT INTO " . TABLE_PREFIX . "m17_products(sectionid, activated, ordernum, filename, thumbname, isautothumb, allowsmilies, allowcomments, showauthor, author, title, description, specification, priceship, datecreated)
                            VALUES('$sectionid', '$activated', '0', '0', '0', '1', '$allowsmilies', '$allowcomments', '$showauthor', '$author', '$title', '$description', '$specification', '$priceship', " . time() . ") ");

                $imageid   = $DB->insert_id();
                $filetype  = $image['type'];
                $extention = $known_photo_types[$filetype];
                $filename  = $imageid . '.' . $extention;
                $tbname    = $filename;

                $DB->query("UPDATE " . TABLE_PREFIX . "m17_products SET ordernum  = '$imageid', filename  = '$filename', thumbname  = '$filename' WHERE imageid = '$imageid' ");

                // Store the orignal file
                copy($image['tmp_name'], $imagedir.$filename);

                if(!isset($_FILES['thumbnail']))
                {
                        CreateThumbnail($imagedir.$filename, $imagedir."tb_".$filename, $settings['缩图最大宽度'], $settings['缩图最大高度'], $settings['方形缩图']);

                        if($settings['自动中图'])
                        {
                                CreateThumbnail($imagedir.$filename, $imagedir."md_".$filename, $settings['中图最大宽度'], $settings['中图最大高度'], $settings['方型中图']);
                        }

                        if(!$settings['大图保持原始'] AND $settings['自动中图'])
                        {
                                @unlink($imagedir.$filename);
                                // Here we would usually clear the 'filename' column in the DB but unfortunately
                                // the thumbnail/midsize code needs it so we'll use file_exists instead
                        }
                }
                else
                {
                        // user submitted thumbnail
                        
                        $thumbtype = $thumbnail['type'];
                        $extention = $known_photo_types[$thumbtype];
                        $thumbname = 'tb_' . $imageid . '.' . $extention;
						$tbname = $imageid . '.' . $extention;
						
						$DB->query("UPDATE " . TABLE_PREFIX . "m17_products SET thumbname  = '$tbname', isautothumb='0' WHERE imageid = '$imageid' ");

                        copy($thumbnail['tmp_name'], $imagedir . $thumbname);
						
                        if($settings['自动中图'])
                        {
                                CreateThumbnail($imagedir.$filename, $imagedir."md_".$filename, $settings['中图最大宽度'], $settings['中图最大高度'], $settings['方型中图']);
                        }

                        if(!$settings['大图保持原始'] AND $settings['自动中图'])
                        {
                                @unlink($imagedir.$filename);
                        }
                }
                				
                PrintRedirect($refreshpage, 1);
        }
        else
        {
                PrintErrors($errors);
                DisplayImageForm(NULL);
        }
}



// ############################ DISPLAY IMAGE FORM #############################

function DisplayImageForm($imageid)
{
        global $DB, $refreshpage, $userinfo, $sitedefaultlang;
		if($sitedefaultlang == 'en') 
		{
			$mplang='en';
		}
		else
		{
			$mplang='cn';
		}
        // get module settings
        $getsettings = $DB->query("SELECT title, value FROM " . TABLE_PREFIX . "modulesettings WHERE moduleid = '17'");
        while($setting = $DB->fetch_array($getsettings))
        {
                $settings[$setting['title']] = $setting['value'];
        }

        if(is_numeric($imageid))
        {
                // gather image information
                $image = $DB->query_first("SELECT * FROM " . TABLE_PREFIX . "m17_products WHERE imageid = '$imageid'");

                PrintSection('编辑产品');
        }
        else if(isset($_POST['SubmitImage']))
        {
                // create empty array
                $image = array("sectionid"     => $_POST['sectionid'],
                "author"        => $userinfo['username'],
                "title"         => $_POST['title'],
                "description"   => $_POST['description'],
                "specification"   => $_POST['specification'],
                "priceship"   => $_POST['priceship'],
                "activated"     => $_POST['activated'],
                "showauthor"    => $_POST['showauthor'],
                "allowsmilies"  => $_POST['allowsmilies'],
                "allowcomments" => $_POST['allowcomments'] );

                PrintSection('添加产品');
        }
        else
        {
                // create empty array
                $image = array("sectionid"     => '1',
                "author"        => $userinfo['username'],
                "title"         => "",
                "description"   => "",
                "specification"   => "",
                "priceship"   => "",
                "activated"     => 1,
                "showauthor"    => 0,
                "allowsmilies"  => 1,
                "allowcomments" => 1 );

                PrintSection('添加产品');
        }

        echo '<form enctype="multipart/form-data" action="'.$refreshpage.'" method="post" name="upload_form">
        <input type="hidden" name="imageid"  value="'.$imageid.'" />

        <table width="100%" border="0" cellpadding="5" cellspacing="0">';

        if(isset($imageid))
        {
                // delete image option
                echo '<tr>
                <td class="tdrow2" width="15%"><b>产品编号:</b></td>
                <td class="tdrow3" width="85%" valign="top">
                  <input type="text" name="ordernum" value="'.$image['ordernum'].'" size="4" />
                </td>
              </tr>
			  <tr>
                <td class="tdrow2" width="15%"><b>删除产品:</b></td>
                <td class="tdrow3" width="85%" valign="top">
                  <input type="checkbox" name="deleteimage" value="1"> 删除此产品? (注: 完全删除此产品信息及大中小图片)
                </td>
              </tr>';
			  
        }

        

        if(isset($imageid))
        {
                echo '<tr>
          <td class="tdrow2" width="15%"><b>产品缩图:</b></td>
          <td class="tdrow3" width="85%" valign="top">';
				
				if(file_exists('../modules/m17_products/images_'.$mplang.'/'.$image['filename']))
                {
                        echo '<a href="../modules/m17_products/images_'.$mplang.'/'.$image['filename'].'" target="_blank"><img src="../modules/m17_products/images_'.$mplang.'/tb_'.$image['thumbname'].'" /></a>';
                }
                else
                {
                        echo '<a href="../modules/m17_products/images_'.$mplang.'/md_'.$image['filename'].'" target="_blank"><img src="../modules/m17_products/images_'.$mplang.'/tb_'.$image['thumbname'].'" /></a>';
                }
        }

         echo '<tr>
          <td class="tdrow2" width="15%"><b>' . iif(isset($imageid), '重传大图', '上传大图') . ':</b></td>
          <td class="tdrow3" width="85%" valign="top"><input name="image" type="file" size="38" /></td>
        </tr>
		<tr>
            <td class="tdrow2" width="15%"><b>' . iif(isset($imageid), '重传缩图', '上传缩图') . ':</b></td>
            <td class="tdrow3" width="85%" valign="top">';

                if($settings['自动缩图'] == 1 && $settings['自动中图'] == 1)
                {
                        echo '根据上传的产品大图自动创建缩图和中图, 大图限jpg和png格式.';
                }
                elseif($settings['自动缩图'] == 1 && $settings['自动中图'] == 0)
                {
                        echo '根据上传的产品大图自动创建缩图, 大图限jpg和png格式; "自动中图"功能关闭, 系统将无法创建中图.';
                }else{
                        echo '<input name="thumbnail" type="file" size="38" />';
				}

         echo '</td></tr><tr>
          <td class="tdrow2" width="15%"><b>产品类别:</b></td>
          <td class="tdrow3" width="85%" valign="top">';

        PrintSectionSelection('sectionid', $image['sectionid']);

        echo '  </td>
        </tr>
        <tr>
          <td class="tdrow2" width="15%"><b>发布人:</b></td>
          <td class="tdrow3" width="85%" valign="top">
            <input type="text" name="author" value="'.CleanFormValue($image['author']).'" />
          </td>
        </tr>
        <tr>
          <td class="tdrow2" width="15%"><b>产品名称:</b></td>
          <td class="tdrow3" width="85%" valign="top">
            <input type="text" name="title" value="'.CleanFormValue($image['title']).'" />
          </td>
        </tr>
        <tr>
          <td class="tdrow2" width="15%" valign="top"><b>产品描述:</b></td>
          <td class="tdrow3" width="85%" valign="top">
            <textarea name="description" rows="16" style="width: 100%;" class="mceEditor">'.$image['description'].'</textarea>
          </td>
        </tr>
        <tr>
          <td class="tdrow2" width="15%" valign="top"><b>技术规格:</b></td>
          <td class="tdrow3" width="85%" valign="top">
            <textarea name="specification" rows="16" style="width: 100%;" class="mceEditor">'.$image['specification'].'</textarea>
          </td>
        </tr>
        <tr>
          <td class="tdrow2" width="15%" valign="top"><b>价格及运输:</b></td>
          <td class="tdrow3" width="85%" valign="top">
            <textarea name="priceship" rows="16" style="width: 100%;" class="mceEditor">'.$image['priceship'].'</textarea>
          </td>
        </tr>
        <tr>
          <td class="tdrow2" width="15%" valign="top"><b>发布选项:</b></td>
          <td class="tdrow3" width="85%" valign="top">
            <input type="checkbox" name="activated"      value="1" '.iif($image['activated']     == 1, "CHECKED", "").'> <b>发布:</b> 选择是否发布产品?<br />
            <input type="checkbox" name="showauthor"     value="1" '.iif($image['showauthor']    == 1, "CHECKED", "").'> <b>发布人:</b> 选择是否显示发布人?<br />
            <input type="checkbox" name="allowsmilies"   value="1" '.iif($image['allowsmilies']  == 1, "CHECKED", "").'> <b>表情符号:</b> 是否允许在产品描述中输入的表情代码字符组合转换成表情符号?<br />
            <input type="checkbox" name="allowcomments"  value="1" '.iif($image['allowcomments'] == 1, "CHECKED", "").'> <b>产品评论:</b> 是否允许对产品发表评论?<br />
          </td>
        </tr>
        <tr>
          <td class="tdrow1" colspan="2" align="center">';

        if($imageid)
        {
                echo '<input type="hidden" name="action" value="updateimage" />
          <input type="submit" value=" 保存更新 " />';  }
                else
                {
                        echo '<input type="hidden" name="action" value="insertimage" />
						<input name="loadwysiwyg" type="hidden" value="'.$settings['TinyMCE编辑器'].'" />
          <input type="submit" name="SubmitImage" value=" 提交保存 " />';
                }

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

        </form>';
                EndSection();
}



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

function DisplaySettings()
{
        global $DB, $moduleid, $refreshpage;

        PrintModuleSettings($moduleid, '基本设置', $refreshpage);
        PrintModuleSettings($moduleid, '类别设置', $refreshpage);
        PrintModuleSettings($moduleid, '缩图设置', $refreshpage);
        PrintModuleSettings($moduleid, '中图设置', $refreshpage);
        PrintModuleSettings($moduleid, '边框设置', $refreshpage);
}



// ############################## DELETE IMAGES ################################

function DeleteImages()
{
        global $DB, $refreshpage, $imagedir;

        // get post vars
        $imageids = $_POST['imageids'];
        $editimageids = $_POST['editimageids'];
		$onlinestatus  = $_POST['onlinestatus'];
		$sectionid  = $_POST['sectionid'];
		$ordernums = $_POST['ordernums'];

		for($i = 0; $i < count($editimageids); $i++)
		{
			$DB->query("UPDATE " . TABLE_PREFIX . "m17_products SET sectionid    = '$sectionid[$i]',
																ordernum = '".iif(is_numeric($ordernums[$i]), $ordernums[$i], 0)."',
																activated = '$onlinestatus[$i]'
															WHERE imageid = '$editimageids[$i]'");
		}

        for($i = 0; $i < count($imageids); $i++)
        {
                $getfilename = $DB->query_first("SELECT filename,thumbname FROM " . TABLE_PREFIX . "m17_products WHERE imageid = '".$imageids[$i]."'");
                $filename    = $getfilename['filename'];
                $thumbname    = $getfilename['thumbname'];
                $image     = $imagedir . $filename;
                $thumbnail = $imagedir . 'tb_' . $thumbname;
                $midsize   = $imagedir . 'md_' . $filename;

                // delete image
                $DB->query("DELETE FROM " . TABLE_PREFIX . "m17_products WHERE imageid = '".$imageids[$i]."'");

                // delete image's comments
                DeleteModuleComments(17, $imageids[$i]);

                @unlink($image);
                @unlink($thumbnail);
                @unlink($midsize);
        }

        PrintRedirect($refreshpage, 1);
}



// ############################## DISPLAY IMAGES ###############################

function DisplayImages($viewtype,$start)
{
        global $DB, $refreshpage, $sitedefaultlang, $issearchimages;
		if($sitedefaultlang == 'en') 
		{
			$mplang='en';
		}
		else
		{
			$mplang='cn';
		}
        $getsettings = $DB->query("SELECT title, value FROM " . TABLE_PREFIX . "modulesettings WHERE moduleid = '17'");
        while($setting = $DB->fetch_array($getsettings))
        {
                $settings[$setting['title']] = $setting['value'];
        }
		
		$thisaction ='displayimages';

		if($issearchimages == true){
             $searchtitle = $viewtype;
             $viewtype = 'search';
		}
        switch($viewtype)
        {
                case 'all':   
                $getimages = $DB->query("SELECT * FROM " . TABLE_PREFIX . "m17_products ORDER BY imageid DESC LIMIT $start,10");
				$maxrows = $DB->query_first("SELECT COUNT(*) AS value FROM " . TABLE_PREFIX . "m17_products");
				$viewtypename  = '全部产品列表';
				$thisaction ='';
                break;

                case 'search':   
                $getimages = $DB->query("SELECT * FROM " . TABLE_PREFIX . "m17_products WHERE author LIKE '%".$searchtitle."%' OR title LIKE '%".$searchtitle."%' OR description LIKE '%".$searchtitle."%' OR specification LIKE '%".$searchtitle."%' OR priceship LIKE '%".$searchtitle."%' ORDER BY imageid DESC LIMIT $start,10");
				$maxrows = $DB->query_first("SELECT COUNT(*) AS value FROM " . TABLE_PREFIX . "m17_products WHERE author LIKE '%".$searchtitle."%' OR title LIKE '%".$searchtitle."%' OR description LIKE '%".$searchtitle."%' OR specification LIKE '%".$searchtitle."%' OR priceship LIKE '%".$searchtitle."%'");
				$viewtypename  = '搜索产品列表';
				$viewtype = urlencode($searchtitle);
				$thisaction ='searchimages';
                break;

                case 'nonline':  // offline = (not activated, needs review)
                $getimages = $DB->query("SELECT * FROM " . TABLE_PREFIX . "m17_products WHERE activated = '0' ORDER BY imageid DESC LIMIT $start,10");
				$maxrows = $DB->query_first("SELECT COUNT(*) AS value FROM " . TABLE_PREFIX . "m17_products WHERE activated = '0'");
		        $viewtypename  = '未发布_产品列表';
				break;

                default:
                $sectionid = $viewtype;
                $getimages  = $DB->query("SELECT * FROM " . TABLE_PREFIX . "m17_products WHERE sectionid = '$sectionid' ORDER BY imageid DESC LIMIT $start,10");
				$maxrows = $DB->query_first("SELECT COUNT(*) AS value FROM " . TABLE_PREFIX . "m17_products WHERE sectionid = '$sectionid'");
				
				$sectionname  = $DB->query_first("SELECT name FROM " . TABLE_PREFIX . "m17_sections WHERE sectionid = '$sectionid'");
				$viewtypename = $sectionname[0] . '_产品列表';
        }

        PrintSection($viewtypename);

        echo '<form action="'.$refreshpage.'" method="POST" name="deleteimageform">
        <input type="hidden" name="action" value="deleteimages" />

        <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 (\'deleteimageform\', this, \'group\');">删除</td>
        </tr>';

        while($image = $DB->fetch_array($getimages))
        {

                echo '<tr><td class="tdrow3"><input type="text" name="ordernums[]" value="' . $image['ordernum'] . '" size="4" /></td>
            <td class="tdrow2">
			<a href="'.$refreshpage.'&action=displayimageform&imageid='.$image['imageid'].'&loadwysiwyg='.$settings['TinyMCE编辑器'].'"><img src="../modules/m17_products/images_'.$mplang.'/tb_' . $image['thumbname'] .'" /></a></td>
            <td class="tdrow3"><input type="hidden" name="editimageids[]" value="'.$image['imageid'].'" /><span style='.iif($image['activated']=="1","\"color:green;\"","\"color:red; font-weight:bold;\"").'>'.iif(strlen($image['title']), $image['title'], '&nbsp;').'</span></td>
			<td class="tdrow3"><select name="onlinestatus[]">
				<option value="1">发布</option>
				<option value="0" ' . iif(!$image['activated'], 'SELECTED', '') . '>隐藏</option>
			</select>
			</td>
            <td class="tdrow3">';
			PrintSectionSelection('sectionid[]', $image['sectionid']);
			echo '</td>
            <td class="tdrow2">' . iif(strlen($image['author']), $image['author'], '&nbsp;') . '</td>
            <td class="tdrow2">'.$image['viewcount'].'</td>
            <td class="tdrow2"><input type="checkbox" name="imageids[]" value="'.$image['imageid'].'" checkme="group" /></td>
          </tr>';
        }

        $limit = 10;
		$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;

      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.'&start='.($start - $limit).'&sectionid='.$viewtype.'&action='.$thisaction.'">&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.'&start=0&sectionid='.$viewtype.'&action='.$thisaction.'">1</a><a href="'.$refreshpage.'&start='.($start_page-2)*$limit.'&sectionid='.$viewtype.'&action='.$thisaction.'">&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.'&start='.($p-1)*$limit.'&sectionid='.$viewtype.'&action='.$thisaction.'">'.$p.'</a>';
				}
				if($p >= $page_num){
					break;
				}
			}

			if($page_num - $now_page_num >= 10){
				$direct_bar .= '<a href="'.$refreshpage.'&start='.($page_group + 7)*$limit.'&sectionid='.$viewtype.'&action='.$thisaction.'">...&rsaquo;&rsaquo;</a><a href="'.$refreshpage.'&start='.($page_num-1)*$limit.'&sectionid='.$viewtype.'&action='.$thisaction.'">'.$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.'&start='.$start.'&sectionid='.$viewtype.'&action='.$thisaction.'">下一页 &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();

}

function PrintSectionChildren($parentid, $selected, $exclude, $indent, $displaycounts = 0)
{
  global $DB;

  $getsections = $DB->query("SELECT sectionid, ordernum, name FROM " . TABLE_PREFIX . "m17_sections WHERE parentid = $parentid ORDER BY ordernum DESC");


  while($sections = $DB->fetch_array($getsections))
  {
        if($exclude != $sections['sectionid'])
    {
                $name = $indent . ' ' . $sections['name'] .iif($sections['sectionid'] == 1,"(默认)","(编号".$sections['ordernum'].")");

                if($displaycounts)
				{
                $getimagecount = $DB->query_first("SELECT COUNT(*) FROM " . TABLE_PREFIX . "m17_products WHERE sectionid = " . $sections['sectionid']);
            $name .= '('.$getimagecount[0].')';
                }

                echo "<option value=\"$sections[sectionid]\" ".iif($selected == $sections['sectionid'],"selected","").">$name</option>";
    }

    PrintSectionChildren($sections['sectionid'], $selected, $exclude, $indent . '-', $displaycounts);
  }
}

function PrintSectionChildrenEXX($parentid, $selected, $exclude, $indent, $displaycounts = 0)
{
  global $DB;

  $getsections = $DB->query("SELECT sectionid, parentid, ordernum, name FROM " . TABLE_PREFIX . "m17_sections WHERE parentid = $parentid ORDER BY ordernum DESC");


  while($sections = $DB->fetch_array($getsections))
  {
    if($exclude != $sections['sectionid'] && $exclude != $parentid)
    {
		$name = $indent . ' ' . $sections['name'] .iif($sections['sectionid'] == 1,"(默认)","(编号".$sections['ordernum'].")");

		if($displaycounts)
		{
		$getimagecount = $DB->query_first("SELECT COUNT(*) FROM " . TABLE_PREFIX . "m17_products WHERE sectionid = " . $sections['sectionid']);
	$name .= '('.$getimagecount[0].')';
		}

		echo "<option value=\"$sections[sectionid]\" ".iif($selected == $sections['sectionid'],"selected","").">$name</option>";
		PrintSectionChildrenEXX($sections['sectionid'], $selected, $exclude, $indent . '-', $displaycounts);
	}
  }
}


// ############################ PRINT SELECTION BOX ############################

// display sections in a selection box
function PrintSectionSelection($name, $selected = null, $exclude = null)
{
        echo '<select name="' . $name . '">';

        PrintSectionChildren(0, $selected, $exclude, '');

        echo '</select>';
}

function PrintSectionSelectionEXX($name, $selected = null, $exclude = null)
{
        echo '<select name="' . $name . '">';

        PrintSectionChildrenEXX(0, $selected, $exclude, '');

        echo '</select>';
}



// ######################## PRINT SECTION SELECTION EX #########################

function PrintSectionSelectionEx()
{
        global $DB;

        echo '<select name="sectionid">';

    PrintSectionChildren(0, null, null, '', 1);

        $getofflineimages = $DB->query_first("SELECT count(*) FROM " . TABLE_PREFIX . "m17_products WHERE activated = '0'");

        echo '<option value="nonline">未发布(' . $getofflineimages[0] . ')</option>
        </select>';
}



// ############################### BATCH UPLOAD ################################

function BatchUpload()
{
        global $DB, $refreshpage, $moduleid, $uploaddir, $imagedir;

        // get post variables
        $sectionid     = $_POST['sectionid'];
        $activated     = empty($_POST['activated']) ? 0 : $_POST['activated'];
        $allowsmilies  = empty($_POST['allowsmilies']) ? 0 : $_POST['allowsmilies'];
        $allowcomments = empty($_POST['allowcomments']) ? 0 : $_POST['allowcomments'];
        $showauthor    = empty($_POST['showauthor']) ? 0 : $_POST['showauthor'];
        $author        = $_POST['author'];
        $uploadlimit   = $_POST['uploadlimit'];

        // error checking
        if(!is_numeric($uploadlimit))
        {
                $uploadlimit = 10; // default
        }

        // init vars
        $imagesmoved = 0;
        $errors      = '';
        $datecreated = TIMENOW;

        // get module settings
        $getsettings = $DB->query("SELECT title, value FROM " . TABLE_PREFIX . "modulesettings WHERE moduleid = '17'");
        while($setting = $DB->fetch_array($getsettings))
        {
                $settings[$setting['title']] = $setting['value'];
        }

        // List of our known photo types
        $known_photo_types = array(
        'image/pjpeg' => 'jpg',
        'image/jpeg'  => 'jpg',
        'image/gif'   => 'gif',
        'image/bmp'   => 'bmp',
        'image/x-png' => 'png',
        'image/png'   => 'png'
        );

        $d = dir($uploaddir);

        for($i = 0; ($entry = $d->read()) && ($i < $uploadlimit); $i++)
        {
          // else time for all images is the same which screws up everything
          $datecreated++;

                // get image title
                if(substr($entry, -4) == 'jpeg')
                {
                        $title = substr($entry, 0, -5);
                }
                else // .jpg, .bmp, .png, etc...
                {
                        $title = substr($entry, 0, -4);
                }

                // is it an image? GIF not supported!
                if( (@$size = GetImageSize($uploaddir . $entry)) && (substr($entry, -3) != 'gif') && (substr($entry, -3) != 'bmp') )
                {
                        switch($size[2])
                        {
                                case '1':
                                $filetype = 'image/gif';
                                break;

                                case '2':
                                $filetype = 'image/jpeg';
                                break;

                                case '3':
                                $filetype = 'image/x-png';
                                break;

                                case '4':
                                $filetype = 'image/bmp';
                                break;
                        }

                        // addslashes needs to be added to title, title was not cleaned because it came from a $_FILE (not get or post)
                        // if its not cleaned, then a single apostrophe will break the sql
                        // this only needs to be done for bulk uploading, for single images the title is entered by the user
                        // and thus runs through the $_POST cleanup
                        $DB->query("INSERT INTO " . TABLE_PREFIX . "m17_products(sectionid, activated, ordernum, filename, thumbname, isautothumb, allowsmilies, allowcomments, showauthor, author, title, datecreated)
                                    VALUES('$sectionid', '$activated', '0', '0', '0', '1', '$allowsmilies', '$allowcomments', '$showauthor', '$author', '" . addslashes($title) . "', " . $datecreated . ") ");

                        $imageid   = $DB->insert_id();
                        $extention = $known_photo_types[$filetype];
                        $filename  = $imageid . '.' . $extention;

                        $DB->query("UPDATE " . TABLE_PREFIX . "m17_products SET ordernum  = '$imageid', filename  = '$filename', thumbname  = '$filename' WHERE imageid = '$imageid' ");

                        // move the file
                        if(rename($uploaddir . $entry, $imagedir . $filename))
                        {
                                CreateThumbnail($imagedir.$filename, $imagedir."/tb_".$filename, $settings['缩图最大宽度'], $settings['缩图最大高度'], $settings['方形缩图']);

                                if($settings['自动中图'])
                                CreateThumbnail($imagedir.$filename, $imagedir."/md_".$filename, $settings['中图最大宽度'], $settings['中图最大高度'], $settings['方型中图']);

                                if(!$settings['大图保持原始'] AND $settings['自动中图'])
                                {
                                        @unlink($imagedir.$filename);
                                        // Here we would usually clear the 'filename' column in the DB but unfortunately
                                        // the thumbnail/midsize code needs it so we'll use file_exists instead
                                }

                                $imagesmoved++;
                        }
                        else
                        {
                                // move file did NOT work
                                // delete db record and report error
                                $DB->query("DELETE FROM " . TABLE_PREFIX . "m17_products WHERE imageid = '$imageid'");
                                $errors .= $entry . ' 拷贝产品图片失败!<br />';
                        }
                }
                else
                {
                        $i--;  // could have been a gif or non image, so lets try the next image!
                }  // end if is image

        } // end the for loop

        PrintSection('批量添加产品结果');
        echo '<table width="100%" border="0" cellpadding="5" cellspacing="0">
        <tr>
          <td class="tdrow2" align="center"></br />
           批量添加产品成功! 共计添加: ' . $imagesmoved . ' 个产品.<br /><br />

            <b>'.$errors.'</b><br /><br />

            <a href="'.$refreshpage.'">返回 产品模块</a>
          </td>
        </tr>
        </table>';
        EndSection();

}



// ############################# BATCH UPLOAD FORM #############################

function BatchUploadForm()
{
        global $DB, $refreshpage, $moduleid, $userinfo;

        // get module settings
        $getsettings = $DB->query("SELECT title, value FROM " . TABLE_PREFIX . "modulesettings WHERE moduleid = '17'");
        while($setting = $DB->fetch_array($getsettings))
        {
                $settings[$setting['title']] = $setting['value'];
        }

        if($settings['自动缩图'] == 0)
        {
                PrintSection('请打开"自动缩图"功能!');
                echo '<table width="100%" border="0" cellpadding="5" cellspacing="0">
          <tr>
            <td class="tdrow2" align="center">
              <b>批量添加产品需要将产品模块设置中的"自动缩图"功能打开.</b>
            </td>
          </tr>
          </table>';
                EndSection();

                return(0);
        }

        PrintSection('批量添加产品');
        echo '<form action="'.$refreshpage.'" method="post">
        <input type="hidden" name="action" value="batchupload" />

        <table width="100%" border="0" cellpadding="5" cellspacing="0">
        <tr>
          <td class="tdrow2" width="15%" valign="top"><b>提示:</b></td>
          <td class="tdrow3" width="85%" valign="top">
            先用ftp工具上传产品图片到网站目录: <i>./modules/m17_products/upload/</i><br />
            <b>批量添加产品不支持GIF和BMP图片格式. 添加成功后, 上传的原始图片自动删除.</b>

          </td>
        </tr>
        <tr>
          <td class="tdrow2" width="15%"><b>添加数量:</b></td>
          <td class="tdrow3" width="85%" valign="top">
            <input type="text" name="uploadlimit" value="10" />
          </td>
        </tr>
        <tr>
          <td class="tdrow2" width="15%"><b>产品类别:</b></td>
          <td class="tdrow3" width="85%" valign="top">';

        PrintSectionSelection('sectionid');

        echo '  </td>
        </tr>
        <tr>
          <td class="tdrow2" width="15%"><b>发布人:</b></td>
          <td class="tdrow3" width="85%" valign="top">
            <input type="text" name="author" value="'.CleanFormValue($userinfo['username']).'" />
          </td>
        </tr>
        <tr>
          <td class="tdrow2" width="15%" valign="top"><b>发布选项:</b></td>
          <td class="tdrow3" width="85%" valign="top">
            <input type="checkbox" name="activated"      value="1" CHECKED><b>发布:</b> 选择是否发布产品?<br />
            <input type="checkbox" name="showauthor"     value="1"><b>发布人:</b> 选择是否显示发布人?<br />
            <input type="checkbox" name="allowsmilies"   value="1" CHECKED><b>表情符号:</b> 是否允许在产品描述中输入的表情代码字符组合转换成表情符号?<br />
            <input type="checkbox" name="allowcomments"  value="1" CHECKED><b>产品评论:</b> 是否允许对产品发表评论?<br />
          </td>
        </tr>
        <tr>
          <td colspan="2" align="center" class="tdrow1">
          <input type="submit" value=" 开始添加 " />
          </td>
        </tr>
        </table>
        </form>';
        EndSection();

}



// ############################## DISPLAY DEFAULT ##############################

function DisplayDefault($start)
{
        global $DB, $refreshpage, $moduleid;
        $getsettings = $DB->query("SELECT title, value FROM " . TABLE_PREFIX . "modulesettings WHERE moduleid = '17'");
        while($setting = $DB->fetch_array($getsettings))
        {
                $settings[$setting['title']] = $setting['value'];
        }
        // module settings
        PrintSection('模块设置');
        echo '<table width="100%" border="0" cellpadding="5" cellspacing="0">
        <tr><td class="tdrow1" colspan="2">详细选项</td></tr>
        <tr><td class="tdrow2" width="70%">显示设置模块详细属性:</td>
            <td class="tdrow3" style="padding-left: 40px;">
            <form method="post" action="'.$refreshpage.'">
            <input type="hidden" name="action" value="displaysettings" />
            <input type="submit" value=" 设置模块 " />
            </form>
            </td></tr>
        </table>';
        EndSection();

        // images - add/manage
        PrintSection('产品管理');
        echo '<table width="100%" border="0" cellpadding="5" cellspacing="0">
        <tr><td class="tdrow1" colspan="2">添加产品</td></tr>
        <tr><td class="tdrow2" width="70%">添加新产品到网站:</td>
            <td class="tdrow3" style="padding-left: 40px;">
            <form method="post" action="'.$refreshpage.'&action=displayimageform&loadwysiwyg='.$settings['TinyMCE编辑器'].'">
            <input type="submit" value=" 添加产品 " />
            </form>
            </td></tr>
        <tr><td class="tdrow1" colspan="2">批量添加</td></tr>
        <tr><td class="tdrow2" width="70%">上传产品图片, 并批量建立产品信息:</td>
            <td class="tdrow3" style="padding-left: 40px;">
            <form method="post" action="'.$refreshpage.'">
            <input type="hidden" name="action" value="batchuploadform" />
            <input type="submit" value=" 批量添加 " />
            </form>
            </td></tr>
        <tr><td class="tdrow1" colspan="2">编辑产品</td></tr>
        <tr><td class="tdrow2" width="70%">按分类查看, 编辑产品信息:</td>
            <td class="tdrow3" style="padding-left: 40px;">
            <form method="post" action="'.$refreshpage.'">';

        PrintSectionSelectionEx();

        echo '    <input type="hidden" name="action" value="displayimages" />
            <input type="submit" value=" 编辑产品 " />
            </form>
            </td></tr>
        <tr><td class="tdrow1" colspan="2">搜索产品</td></tr>
        <tr><form method="post" action="'.$refreshpage.'">
			<td class="tdrow2" width="70%"><input type="text" name="sectionid"  size="58" /></td>
            <td class="tdrow3" style="padding-left: 40px;">
            <input type="hidden" name="action" value="searchimages" />
            <input type="submit" value=" 搜索产品 " />
            </form>
            </td></tr>
        </table>';
        EndSection();


        // sections - add/manage
        PrintSection('类别管理');
        echo '<table width="100%" border="0" cellpadding="5" cellspacing="0">
        <tr><td class="tdrow1" colspan="2">添加分类</td></tr>
        <tr>
          <td class="tdrow2" width="70%">添加产品分类, 以便对产品进行分类管理和发布:<br />
          默认产品类别为"产品", 且不能删除.
          </td>
            <td class="tdrow3" style="padding-left: 40px;">
            <form method="post" action="'.$refreshpage.'">
            <input type="hidden" name="action" value="displaysectionform" />
			<input name="loadwysiwyg" type="hidden" value="1" />
            <input type="submit" value=" 添加分类 " />
            </form>
            </td></tr>
        <tr><td class="tdrow1" colspan="2">编辑分类</td></tr>
        <tr><td class="tdrow2" width="70%">选择一个产品分类, 然后进行编辑:</td>
            <td class="tdrow3" style="padding-left: 40px;">
            <form method="post" action="'.$refreshpage.'">';

        PrintSectionSelection('sectionid');

        echo '<input type="hidden" name="action" value="displaysectionform" />
			<input name="loadwysiwyg" type="hidden" value="1" />
            <input type="submit" value=" 编辑分类 " />
            </form>
            </td></tr>
        </table>';
        EndSection();


        DisplayImages('all', $start);
}



// ############################## SELECT FUNCTION ##############################
if(isset($_GET['start']))
  $start = $_GET['start'];
else
  $start = 0;

switch($action)
{
        case 'batchupload':
        BatchUpload();
        break;

        case 'batchuploadform':
        BatchUploadForm();
        break;

        case 'insertimage':
        InsertImage();
        break;

        case 'updateimage':
        UpdateImage();
        break;

        case 'deleteimages':
        DeleteImages();
        break;

        case 'insertsection':
        InsertSection();
        break;

        case 'updatesection':
        UpdateSection();
        break;

        case 'displayimageform':
        DisplayImageForm($imageid);
        break;

        case 'displaysectionform':
        DisplaySectionForm($sectionid);
        break;

        case 'displayimages':
        DisplayImages($sectionid, $start);
        break;

        case 'searchimages':
		$issearchimages = true;
        DisplayImages(urldecode($sectionid), $start);
        break;

        case 'displaysettings':
        DisplaySettings();
        break;

        default:
        DisplayDefault($start);
}

?>