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

// prevent direct script access
if(!defined('IN_WEENCOMPANY'))
die('File not found!');

// ########################### Check Directory Permissions ########################
$uploaddir  = dirname(__FILE__) . '/upload/';
$imagedir = dirname(__FILE__) . '/images/'; 
$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, $loadwysiwyg, $enablewysiwyg;

        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/tb_' . $image['thumbname'] .'" align="middle" />';
							 $isload=1;
							 }
							 else
							 {
							 echo '<input type="radio" name="imageid" value="' . $image['imageid'] . '"><img src="../modules/m17_products/images/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/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;

        // 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/'.$image['filename']))
                {
                        echo '<a href="../modules/m17_products/images/'.$image['filename'].'" target="_blank"><img src="../modules/m17_products/images/tb_'.$image['thumbname'].'" /></a>';
                }
                else
                {
                        echo '<a href="../modules/m17_products/images/md_'.$image['filename'].'" target="_blank"><img src="../modules/m17_products/images/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, $issearchimages;
        $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/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 activated = '1' AND 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);
}

?>
