<?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,'gb2312') . '" /></td>
              <td class="tdrow2"><input type="text" name="smilietexts[]"  value="' . htmlentities($smilie['text'], ENT_QUOTES,'gb2312')  . '" /></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();

?>