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

define('IN_ADMIN', true);
define('IN_WEENCOMPANY', true);

$rootpath = "./../";

include($rootpath . 'includes/core.php');

PrintHeader('圖片管理');


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

// the folder to search through:
$folderpath = isset($_POST['folderpath']) ? $_POST['folderpath'] : (isset($_GET['folderpath']) ? $_GET['folderpath'] : '../images/');



// ############################# GET IMAGE FOLDERS #############################

function GetImageFolders($dirname)
{
  global $selectoption, $folderpath;

  $d = dir($dirname);

  while($entry = $d->read())
  {
    if($entry != '.' AND $entry != '..')
    {
      if(is_dir($dirname . '/' . $entry))
      {
        GetImageFolders($dirname . $entry . '/');

        if($entry != 'smilies' AND $entry != 'avatars')
        {
          echo '<option value="' . $dirname . $entry . '/"' . iif($folderpath == $dirname . $entry . '/', ' SELECTED', '') . '>' . substr($dirname, 3) . $entry . '</option>' . "\n";
        }
      }

    }
  }

  $d->close();
}



// ########################### DISPLAY IMAGE DETAILS ###########################

function DisplayImageDetails($imagename, $imagepath, $extratext = '')
{
  $maxwidth  = 80;
  $maxheight = 80;

  list($width, $height, $type, $attr) = getimagesize($imagepath);

  $scale = min($maxwidth/$width, $maxheight/$height);

  // If the image is larger than the max shrink it
  if($scale < 1)
  {
    $newwidth = floor($scale * $width);
    $newheight = floor($scale * $height);
  }
  else
  {
    $newwidth = $width;
    $newheight = $height;
  }

  echo '<table width="100%" border="0" cellpadding="0" cellspacing="0">
        <tr>
          <td width="10" valign="top" style="padding-right: 15px;">
            <a href="' . $imagepath . '" target="_blank"><img src="' . $imagepath . '" width="' . $newwidth . '" height="' . $newheight . '" /></a>
          </td>
          <td valign="top">
            <b>' . $imagename . '</b><br /><br />
            寬:  ' . $width . ' 像素<br />
            高: ' . $height . ' 像素' . iif(strlen($extratext), '<br /><br />' . $extratext, '') . '
          </td>
        </tr>
        </table>';
}



// ############################# CREATE THUMBNAIL ##############################

function DoCreateThumbnail()
{
  $imagepath     = $_POST['imagepath'];
  $folderpath    = $_POST['folderpath'];
  $thumbfilename = $_POST['thumbfilename'];
  $maxwidth      = $_POST['maxwidth'];
  $maxheight     = $_POST['maxheight'];
  
	if (file_exists($folderpath.$thumbfilename))
	{
		PrintErrors("目標文件夾內已存在同名的文件!");
		DisplayThumbnailForm();
	}
	elseif($errormsg = CreateThumbnail($imagepath, $folderpath . $thumbfilename, $maxwidth, $maxheight, false))
	{
		PrintErrors($errormsg);
		DisplayThumbnailForm();
	}
	else
	{
		PrintRedirect('imagemanager.php?action=displayimages&folderpath=' . $folderpath . '', 1);
	}
}



// ########################## DISPLAY THUMBNAIL FORM ###########################

function DisplayThumbnailForm()
{
  global $folderpath;

  $imagename = isset($_GET['imagename']) ? $_GET['imagename'] : $_POST['imagename'];
  $imageextension = substr($imagename, -4);

  $imagepath = isset($_POST['imagepath']) ? $_POST['imagepath'] : $folderpath . $imagename;

  $thumbname   = ($imageextension == 'jpeg') ? substr($imagename, 0, -5) . '_thumbnail.jpeg' : substr($imagename, 0, -4) . '_thumbnail' . $imageextension;
  $thumbname   = str_replace(' ', '_', $thumbname);
  $thumbwidth  = 80;
  $thumbheight = 80;
  
  $valid_image_extensions = array('jpg',
        						  'peg', // jpeg
        						  'png');
  if(!in_array(substr($imagename, -3), $valid_image_extensions))
  {
	  $invalidimage = true;
  }



  PrintSection('創建縮圖');
  echo '<form method="post" action="./imagemanager.php">
        <input type="hidden" name="action" value="DoCreateThumbnail" />
        <input type="hidden" name="imagepath" value="' . $imagepath . '" />
        <input type="hidden" name="imagename" value="' . $imagename . '" />
        <table width="100%" border="0" cellpadding="5" cellspacing="0">
        <tr>
          <td class="tdrow1" colspan="2">來源圖片</td>
        </tr>
        <tr>
          <td class="tdrow2" width="75%">由此圖片創建縮圖:<br/>注: 僅支持jpg, png格式的圖片文件創建縮圖.</td>
          <td class="tdrow3">';

  DisplayImageDetails($imagename, $imagepath);

  echo '  </td>
        </tr>
        <tr>
          <td class="tdrow1" colspan="2">目標文件夾</td>
        </tr>
        <tr>
          <td class="tdrow2">選擇存放縮圖的文件夾:</td>
          <td class="tdrow3">
            <select name="folderpath">
            <option value="../images/">images</option>';

  GetImageFolders('../images/');

  echo '    </select>
          </td>
        </tr>
        <tr>
          <td class="tdrow1" colspan="2">縮圖文件名</td>
        </tr>
        <tr>
          <td class="tdrow2">輸入縮圖文件名:</td>
          <td class="tdrow3"><input type="text" name="thumbfilename" value="' . $thumbname . '" size="35" /></td>
        </tr>
        <tr>
          <td class="tdrow1" colspan="2">縮圖寬</td>
        </tr>
        <tr>
          <td class="tdrow2">縮圖的最大寬度(像素):</td>
          <td class="tdrow3"><input type="text" name="maxwidth" value="' . $thumbwidth . '" size="4" /></td>
        </tr>
        <tr>
          <td class="tdrow1" colspan="2">縮圖高</td>
        </tr>
        <tr>
          <td class="tdrow2">縮圖的最大高度(像素):</td>
          <td class="tdrow3"><input type="text" name="maxheight" value="' . $thumbheight . '" size="4" /></td>
        </tr>
        <tr>
          <td class="tdrow1" bgcolor="#FCFCFC" colspan="2" align="center">
            <input type="submit" value=" 創建縮圖 "' . iif($invalidimage, 'disabled', 'enabled') . ' />
            <input type="submit" value=" 取消 " onclick="window.location=\'imagemanager.php?action=displayimages&folderpath=' . $folderpath . '\'; return false" />
          </td>
        </tr>
       </table>
       </form>';
  EndSection();
}



// ############################### UPLOAD IMAGE ################################

function UploadImage()
{
  global $folderpath;

  $image     = $_FILES['image'];
  $imagesdir = dirname(__FILE__) . '/' .  $folderpath;

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

  // check if image was uploaded
  if($image['size'] == 0)
  {
    $errors[] = '請選擇要上傳的文件!';
  }
  else if(!in_array($image['type'], $known_photo_types))
  {
    $errors[] = '無效的文件類型!';
  }
  // lets make sure the extension is correct
  else if(!in_array(strtolower(substr($image['name'], -3)), $valid_image_extensions))
  {
    $errors[] = '不允許的圖片類型!';
  }
  // final attempt to make sure it's a real image:
  else if(!getimagesize($image['tmp_name']))
  {
    $errors[] = '無效的圖片類型!';
  }
  elseif (file_exists($imagesdir . $image['name']))
	{
		$errors[] = '目標文件夾內已存在同名的文件!';
	}
  else
  {
    // Store the orignal file
    if(!@copy($image['tmp_name'], $imagesdir . $image['name']))
    {
      $errors[] = '圖片文件夾 "' . substr($folderpath, 1) . '" 不可寫!<br />
                   注: 將文件夾 "' . substr($folderpath, 1) . '" 的屬性改為: 777.';
    }
  }

  if(isset($errors))
  {
    PrintErrors($errors, '上傳錯誤');
    DisplayImages();
  }
  else
  {
    PrintRedirect('imagemanager.php?action=displayimages&folderpath=' . $folderpath . '', 1);
  }
}



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

function DeleteImage()
{
  global $folderpath;

  if(isset($_GET['imagepath']))
  {
    $imagepath = $_GET['imagepath'];
    $doconfirm = true;
  }
  else if(isset($_POST['imagepath']))
  {
    $imagepath = $_POST['imagepath'];
    $deleteimage = true;
  }

  $deleteimage = isset($_POST['deleteimage']) ? $_POST['deleteimage'] : 'Confirm Delete';


  if($deleteimage == ' 確定刪除 ')
  {
    // delete image
    if(@unlink($imagepath))
    {
      // delete worked, now redirect
      PrintRedirect('imagemanager.php?action=displayimages&folderpath=' . $folderpath, 1);
    }
    else
    {
      // print error, delete did not work
      $errors[] = '無法刪除圖片!';
      PrintErrors($errors, '刪除失敗');
      $deleteimage = 'Confirm Delete';
    }
  }
  else if($deleteimage == ' 取消 ')
  {
    // go back
    PrintRedirect('imagemanager.php?action=displayimages&folderpath=' . $folderpath, 1);
  }

  // confirm delete
  if($deleteimage == 'Confirm Delete')
  {
    // confirm delete
    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%" valign="top">';

    $extratext = '<b>確定刪除此圖片嗎?</b>';
    DisplayImageDetails(substr($imagepath, 1), $imagepath, $extratext);

    echo '  </td>
            <td class="tdrow3" valign="top">
              <form method="post" action="imagemanager.php">
              <input type="hidden" name="action" value="deleteimage" />
              <input type="hidden" name="folderpath" value="' . $folderpath . '" />
              <input type="hidden" name="imagepath" value="' . $imagepath . '" />
              <input type="submit" name="deleteimage" value=" 確定刪除 " />&nbsp;&nbsp;
              <input type="submit" value=" 取消 " onclick="window.location=\'imagemanager.php?action=displayimages&folderpath=' . $folderpath . '\'; return false" />
              </form>
            </td>
          </tr>
          </table>';
    EndSection();
  }

}



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

function DisplayImages()
{
  global $folderpath;

  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">
            <form method="post" action="imagemanager.php">
            <input type="hidden" name="action" value="displayimages" />
            <select name="folderpath">
            <option value="../images/">images</option>';

  GetImageFolders('../images/');

  echo '    </select>
            <input type="submit" value=" 打開 " />
            </form>
          </td>
        </tr>
        <tr>
          <td class="tdrow1" colspan="2">上傳圖片</td>
        </tr>
        <tr>
          <td class="tdrow2" width="70%">上傳一個圖片文件至當前文件夾(圖片格式: gif, jpg, png, bmp):</td>
          <td class="tdrow3">
            <form enctype="multipart/form-data" method="post" action="imagemanager.php" name="upload_form">
            <input type="hidden" name="action" value="upload_image" />
            <input type="hidden" name="folderpath" value="' . $folderpath . '" />
            <input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
            <input name="image" type="file" />
            <input type="submit" value=" 上傳圖片 " />
            </form>
          </td>
        </tr>
        </table>';
  EndSection();

  PrintSection('當前文件夾"' . substr($folderpath, 1) . '"內的圖片列表');
  echo '<table width="100%" border="0" cellpadding="5" cellspacing="0">';

  $display_no_images_message = true;

  $images = array();
  $handle = opendir($folderpath);

  $tdcount = 0;
  $tdstyle = 'tdrow3';

  while($file = readdir($handle))
  {
    $extension = strtolower(substr($file, -4));

    if(($extension == '.gif') || ($extension == '.jpg') || ($extension == '.jpeg') || ($extension == '.png') || ($extension == '.bmp') )
    {
      $display_no_images_message = false;

      $tdcount++;

      if($tdcount == 1)
      {
        echo '<tr>';
        $tdstyle = ($tdstyle == 'tdrow3') ? 'tdrow2' : 'tdrow3';
      }

      echo '<td class="' . $tdstyle . '" width="25%">';

      $extratext = '<a href="./imagemanager.php?action=displaythumbnailform&folderpath=' . $folderpath . '&imagename=' . $file . '">創建縮圖</a><br /><br />
                    <a href="./imagemanager.php?action=deleteimage&folderpath=' . $folderpath . '&imagepath=' . $folderpath . $file . '">刪除圖片</a><br /><br />';
      DisplayImageDetails($file, $folderpath . $file, $extratext);


      echo '</td>';

      if($tdcount == 4)
      {
        echo '</tr>';
        $tdcount = 0;
      }
    }
  }

  // close off remaining columns
  if($tdcount != 0 && $tdcount != 4)
  {
    while($tdcount < 4)
    {
      $tdcount++;
      echo '<td class="' . $tdstyle . '">&nbsp;</td>';
    }
    echo '</tr>';
  }

  if($display_no_images_message)
  {
    echo '<tr><td class="tdrow3" align="center"><b>當前文件夾內無任何圖片.</b></td></tr>';
  }

  echo '</table>';
  EndSection();
}



// ########################### CHANGE SMILIE SYSTEM ############################

function ChangeSmilieSystem()
{
  global $DB;

  $smiliesystem = $_POST['smiliesystem'];

  $DB->query("UPDATE " . TABLE_PREFIX . "mainsettings SET value = '$smiliesystem' WHERE varname = 'smiliesystem'");

  PrintRedirect('imagemanager.php?action=displaysmilies', 1);
}



// ############################## UPDATE SMILIES ###############################

function UpdateSmilies()
{
  global $DB;

  $smilieids       = $_POST['smilieids'];
  $smilietitles    = $_POST['smilietitles'];
  $smilietexts     = $_POST['smilietexts'];
  $smilieimages    = $_POST['smilieimages'];
  $deletesmilieids = $_POST['deletesmilieids'];

  // first update smilies
  for($i = 0; $i < count($smilietitles); $i++)
  {
    $DB->query("UPDATE " . TABLE_PREFIX . "smilies SET title    = '$smilietitles[$i]',
                                                       text     = '$smilietexts[$i]',
                                                       image    = '$smilieimages[$i]'
                                                 WHERE smilieid = '$smilieids[$i]'");
  }

  // now delete smilies (if user selected to delete any)
  for($i = 0; $i < count($deletesmilieids); $i++)
  {
    $DB->query("DELETE FROM " . TABLE_PREFIX . "smilies WHERE smilieid = '" . $deletesmilieids[$i] . "'");
	
	@unlink('./../images/smilies/'.$smilieimages[$i]);
  }

  PrintRedirect('imagemanager.php?action=displaysmilies', 1);
}



// ############################### UPLOAD SMILIE ###############################

function UploadSmilie()
{
  global $DB;

  $smilietitle = $_POST['smilietitle'];
  $smiliecode  = $_POST['smiliecode'];
  $smilieimage = $_FILES['smilieimage'];

  $smiliedir = dirname(__FILE__) . '/../images/smilies/';

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

  // check if image was uploaded
  if($smilieimage['size'] == 0)
  {
    $errors[] = '請選擇要上傳的文件!';
  }
  else if(!in_array($smilieimage['type'], $known_photo_types))
  {
    $errors[] = '無效的文件類型!';
  }
  else
  {
	if (file_exists($smiliedir . $smilieimage['name']))
	{
		$errors[] = '目標文件夾內已存在同名的文件!';
	}
    else
    {
      // Store the orignal file
      if(@copy($smilieimage['tmp_name'], $smiliedir . $smilieimage['name']))
      {
      // image has been uploaded, now save smilie in database
        $DB->query("INSERT INTO " . TABLE_PREFIX . "smilies (title, text, image)
                    VALUES ('$smilietitle', '$smiliecode', '" . $smilieimage['name'] . "')");
      }
      else
      {
        $errors[] = '圖標文件夾 "images/smilies" 不可寫!<br />
                     注: 將文件夾 "images/smilies" 的屬性改為: 777.';
      }
    }
  }

  if(isset($errors))
  {
    PrintErrors($errors, '上傳錯誤');
    DisplaySmilies();
  }
  else
  {
    PrintRedirect('imagemanager.php?action=displaysmilies', 1);
  }
}



// ############################## DISPLAY SMILIES ##############################

function DisplaySmilies()
{
  global $DB;

  // check which smilie system is being used
  $smiliesystem = $DB->query_first("SELECT value FROM " . TABLE_PREFIX . "mainsettings WHERE varname = 'smiliesystem'");

  // check if we are integrating with a forum
  // if so then display the option to use the forum's smilies
  if($forum = $DB->query_first("SELECT name FROM " . TABLE_PREFIX . "usersystems WHERE name != 'weenCompany' AND activated = '1'"))
  {
    PrintSection('切換圖標系統');
    echo '<form method="post" action="imagemanager.php">
          <input type="hidden" name="action" value="changesmiliesystem" />
          <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">
              <select name="smiliesystem">
              <option value="weenCompany" ' . iif($smiliesystem['value'] == 'weenCompany', 'SELECTED', '') . '>weenCompany圖標系統</option>
              <option value="Forum" ' . iif($smiliesystem['value'] == 'Forum', 'SELECTED', '') . '>' . $forum['name'] . '圖標系統</option>
              </select>
            </td>
          </tr>
          <tr>
            <td class="tdrow1" bgcolor="#FCFCFC" colspan="2" align="center"><input type="submit" value="切換圖標系統" /></td>
          </tr>
          </table>
          </form>';
    EndSection();
  }

  // display smilie functions if we are using the weenCompany Smilie System
  if($smiliesystem['value'] == 'weenCompany')
  {
    PrintSection('添加表情圖標');
    echo '<form enctype="multipart/form-data" method="post" action="imagemanager.php">
          <input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
          <input type="hidden" name="action" value="uploadsmilie" />
          <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"><input type="text" name="smilietitle" /></td>
          </tr>
          <tr>
            <td class="tdrow1" colspan="2">表情符號</td>
          </tr>
            <td class="tdrow2" width="70%">按表情符號將內容中對應的字符轉換成表情圖標:<br />如: \':)\', \':(\', \':|\'等.</td>
            <td class="tdrow3"><input type="text" name="smiliecode" /></td>
          </tr>
          <tr>
            <td class="tdrow1" colspan="2">表情圖標</td>
          </tr>
          <tr>
            <td class="tdrow2" width="70%">選擇並上傳圖標(圖片格式: gif, jpg, png, bmp):</td>
            <td class="tdrow3"><input name="smilieimage" type="file" /></td>
          </tr>
          <tr>
            <td class="tdrow1" bgcolor="#FCFCFC" colspan="5" align="center"><input type="submit" value=" 上傳圖標 " /></td>
          </tr>
          </table>
          </form>';
    EndSection();

    // get all smilie filenames
    $handle = opendir('../images/smilies/');

    while($file = readdir($handle))
    {
      $extension = substr($file, -4);

      if(($extension == '.gif') || ($extension == '.jpg') || ($extension == 'jpeg') || ($extension == '.png') )
      {
        $smiliefiles[] = $file;
      }
    }

    // get all smilies in the database
    $smilies = $DB->query("SELECT * FROM " . TABLE_PREFIX . "smilies ORDER BY smilieid DESC");

    PrintSection('圖標列表');
    echo '<form method="post" action="imagemanager.php" name="deletesmilies">
          <input type="hidden" name="action" value="updatesmilies" />
          <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" width="75"><input type="checkbox" checkall="group" onclick="javascript: return select_deselectAll (\'deletesmilies\', this, \'group\');"> 刪除</td>
          </tr>';

    for($x = 0; $smilie = $DB->fetch_array($smilies); $x++)
    {
      echo '<tr>
              <td class="tdrow2"><input type="hidden" name="smilieids[]" value="' . $smilie['smilieid'] . '" /><img src="./../images/smilies/' . $smilie['image'] . '" /></td>
              <td class="tdrow3"><input type="text" name="smilietitles[]" value="' . htmlentities($smilie['title'], ENT_QUOTES,'UTF-8') . '" /></td>
              <td class="tdrow2"><input type="text" name="smilietexts[]"  value="' . htmlentities($smilie['text'], ENT_QUOTES,'UTF-8')  . '" /></td>
              <td class="tdrow3">
                <select name="smilieimages[]">';

      for($i = 0; $i < count($smiliefiles); $i++)
      {
        echo '<option value="' . $smiliefiles[$i] . '" ' . iif($smilie['image'] == $smiliefiles[$i], 'SELECTED', '') . '>' . $smiliefiles[$i] . '</option>';
      }

      echo '    </select>
              </td>
              <td class="tdrow2"><input type="checkbox" name="deletesmilieids[]" value="' . $smilie['smilieid']   . '" checkme="group" /></td>
            </tr>';
    }

    echo '<tr>
            <td class="tdrow1" bgcolor="#FCFCFC" colspan="5" align="center"><input type="submit" value=" 保存更新 " /></td>
          </tr>
          </table>
          </form>';
    EndSection();
  }
  else  // using forum smilies
  {
    PrintSection('論壇表情圖標列表');
    echo '<table width="100%" border="0" cellpadding="5" cellspacing="0">
          <tr>
            <td class="tdrow2" align="center">當前正在使用論壇表情圖標系統, 請在論壇管理中進行圖標管理.</td>
          </tr>
          </table>
          </form>';
    EndSection();
  }

}


// ############################## SELECT FUNCTION ##############################

switch($action)
{
  case 'uploadsmilie':
    UploadSmilie();
  break;

  case 'updatesmilies':
    UpdateSmilies();
  break;

  case 'displaysmilies':
    DisplaySmilies();
  break;

  case 'changesmiliesystem':
    ChangeSmilieSystem();
  break;

  case 'displaythumbnailform':
    DisplayThumbnailForm();
  break;

  case 'DoCreateThumbnail':
	DoCreateThumbnail();
  break;

  case 'upload_image':
    UploadImage();
  break;

  case 'deleteimage':
    DeleteImage();
  break;

  case 'displayimages':
    DisplayImages();
  break;

  case 'displayavatars':
    DisplayAvatars();
  break;
}



PrintFooter();

?>
