<?php

define('MOD_ACCESS', true);
define('IN_ADMIN', true);
define('IN_WEENCOMPANY', true);
$rootpath = "../../../../";



// ################################ INCLUDE CORE ###############################

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

SetPageCharacterSet();

// ######################### GET ACTION AND FOLDERPATH #########################

$action = isset($_POST['action']) ? $_POST['action'] : (isset($_GET['action']) ? $_GET['action'] : 'displayimages');
$folderpath = isset($_POST['folderpath']) ? $_POST['folderpath'] : (isset($_GET['folderpath']) ? $_GET['folderpath'] : '../../../../images/');



// ########################### DISPLAY FILE DETAILS ############################

function DisplayFileDetails($file, $rowcolor = '')
{
  global $folderpath, $weenurl, $rootpath;

  // first create the full path to the file
  $filepath = $folderpath . $file;

  // array of valid image extensions
  $imageextensions = array('jpeg', '.gif', '.jpg', '.bmp', '.png');

  // first lets determine what kind of file we are dealing with
  $extension = strtolower(substr($file, -4));

  // either display an image or folder
  if(in_array($extension, $imageextensions))
  {
    // define the max thumbnail width and height
    $maxwidth  = 80;
    $maxheight = 80;

    // lets make sure we're dealing with a real image
    if($imagesize = @getimagesize($filepath))
    {
      // get the image information
      list($width, $height, $type, $attr) = $imagesize;

      // lets scale the image so it fits nicely into our window
      $scale = min($maxwidth/$width, $maxheight/$height);
      $newwidth  = ($scale < 1) ? floor($scale * $width)  : $width;
      $newheight = ($scale < 1) ? floor($scale * $height) : $height;

      // now display the image
      echo '<table width="100%" border="0" cellpadding="0" cellspacing="0">
            <tr>
              <td width="80" height="80" align="center" style="padding-right: 15px;">
                <a href=\'javascript:void(0);\' onmousedown=\'InsertweenCompanyImage("' . $weenurl . substr($filepath, 12) . '");\'><img border="0" src="' . $filepath . '" width="' . $newwidth . '" height="' . $newheight . '" /></a>
              </td>
              <td valign="top">
                <b>' . $file . '</b><br /><br />
                宽:  ' . $width . ' 像素<br />
                高: ' . $height . ' 像素<br /><br />
                <a href=\'javascript:void(0);\' onmousedown=\'InsertweenCompanyImage("' . $weenurl . substr($filepath, 12) . '");\'>插入此图片</a>
              </td>
            </tr>
            </table>';
    }
  }
  else // the file is not an image
  {
    // display 'go back (..)'?
    if($file == '..')
    {
      // only let the user go back if we aren't in root
      if(substr($folderpath, -7) == 'images/')
      {
        echo '<table width="100%" border="0" cellpadding="0" cellspacing="0">
              <tr>
                <td width="10" valign="top" style="padding-right: 15px;">
                  <img border="0" src="./images/folderforbidden' . iif($rowcolor == '#FFFFFF', '1' , '2') . '.gif" />
                </td>
                <td valign="top">
                  <b>上层文件夹</b><br /><br />
                  当前是图片根文件夹.
                </td>
              </tr>
              </table>';
      }
      else
      {
        $tmp_folderpath = explode('/', substr($folderpath, 0, -1));
        echo '<table width="100%" border="0" cellpadding="0" cellspacing="0">
              <tr>
                <td width="10" valign="top" style="padding-right: 15px;">
                  <a href="./imagemanager.php?folderpath=' . str_replace(end($tmp_folderpath), '', substr($folderpath, 0, -1))  . '"><img border="0" src="./images/folderup' . iif($rowcolor == '#FFFFFF', '1' , '2') . '.gif" /></a>
              </td>
              <td valign="top">
                <b>上层文件夹</b><br /><br />
                <a href="./imagemanager.php?folderpath=' . str_replace(end($tmp_folderpath), '', substr($folderpath, 0, -1))  . '">返回上层文件夹</a>
              </td>
              </tr>
              </table>';
      }
    }
    else if(is_dir($filepath))
    {
      echo '<table width="100%" border="0" cellpadding="0" cellspacing="0">
            <tr>
              <td width="10" valign="top" style="padding-right: 15px;">
                <a href="./imagemanager.php?folderpath=' . $filepath . '/"><img border="0" src="./images/folder' . iif($rowcolor == '#FFFFFF', '1' , '2') . '.gif" /></a>
              </td>
              <td valign="top">
                <b>' . $file . '</b><br /><br />
                <a href="./imagemanager.php?folderpath=' . $filepath . '/">打开文件夹</a>
              </td>
            </tr>
            </table>';
    }
  }

}



// ############################### 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
  {
    DisplayImages($image['name']);
  }
}



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

function DisplayImages($newimage = '')
{
  global $folderpath, $weenurl;

  PrintTableHeader('添加图片');

  if($newimage)
  {
    echo '<table width="100%" cellpadding="0" cellspacing="0" border="0">
          <tr>
            <td style="padding: 5px;">
              <font style="color:blue"><b>上传图片成功!</b></font><br /><br />';
    DisplayFileDetails($newimage);

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

    echo '<table width="100%" cellpadding="0" cellspacing="0" border="0">
          <tr>
            <td style="padding: 5px;"><b>上传一个新图片到当前文件夹:</b></td>
          </tr>
          <tr>
            <td style="padding: 5px;">
              <form enctype="multipart/form-data" method="post" action="./imagemanager.php" name="upload_form">
              <input type="hidden" name="action" value="uploadimage" />
              <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>';


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

  // This is the correct way to loop over the directory
  while(false !== ($file = readdir($handle)))
  {
    $extension = strtolower(substr($file, -4));

    if(($extension == '.gif') || ($extension == '.jpg') || ($extension == 'jpeg') || ($extension == '.png') || ($extension == '.bmp') )
    {
      $images[]  = $file;
    }
    else if($file != '.' AND is_dir($folderpath . $file))
    {
      $folders[] = $file;
    }
  }

  // now sort both images and folders
  @sort($images);
  @sort($folders);

  // combine the two
  $files = @array_merge($folders, $images);

  $columncount = 0;
  $rowcolor = '#FFFFFF';

  $currentpath = '<b>当前文件夹:</b> ' . $weenurl;

  echo '<br /><hr /><br />
        <table width="100%" cellpadding="0" cellspacing="0" border="0">
        <tr>
          <td style="padding: 5px;" colspan="3"> ' . $currentpath . substr($folderpath, 12) . '<br /><br /></td>
        </tr>';

  for($i = 0; $i < count($files); $i++)
  {
    $columncount++;

    // start a new row?
    if($columncount == 1)
    {
      echo '<tr>';
    }

    // open column
    switch($columncount)
    {
      case 1:
        echo '<td width="33%" align="center" valign="top" bgcolor="' . $rowcolor . '" style="padding: 5px;">';
      break;

      case 2:
        echo '<td width="33%" align="center" valign="top" bgcolor="' . $rowcolor . '" style="padding: 5px;">';
      break;

      case 3:
        echo '<td width="33%" align="center" valign="top" bgcolor="' . $rowcolor . '" style="padding: 5px;">';
      break;
    }

    // display the file's details
    DisplayFileDetails($files[$i], $rowcolor);

    // close column
    echo '</td>';

    // close the row?
    if($columncount == 3)
    {
      echo '</tr>';

      // start over
      $columncount = 0;

      // change the row color
      $rowcolor = $rowcolor == '#FFFFFF' ? '#F1F3F5' : '#FFFFFF';
    }
  }

  closedir($handle);

  // now close the table
  switch($columncount)
  {
    case '1':
      echo '<td colspan="2" bgcolor="' . $rowcolor . '" style="padding: 5px;">&nbsp;</td></tr></table>';
    break;

    case '2':
      echo '<td bgcolor="' . $rowcolor . '" style="padding: 5px;">&nbsp;</td></tr></table>';
    break;

    case '3':
      echo '</table>';
    break;
  }
  PrintTableFooter();
}



// ############################ PRINT TABLE HEADER #############################

function PrintTableHeader($tablename)
{
  echo '<table width="100%" cellpadding="0" cellspaing="0" border="0" bgcolor="#FFFFFF">
        <tr>
          <td align="center" style="padding: 1px; color: #FFFFFF; border: 1px solid #A5B5C5; background-image: url(../../../styles/advanced/images/menu_category_bg.gif);"><b>' . $tablename . '</b></td>
        </tr>
          <td bgcolor="#F1F3F5" style="padding: 1px; color: 819AAD; border: 1px solid #D1D3D4;">';
}



// ############################ PRINT TABLE FOOTER #############################

function PrintTableFooter()
{
  echo '  </td>
        </tr>
        </table>

        <br />';
}



// ############################## DISPLAY HEADER ###############################


echo '<html>
      <head>
        <script language="javascript" src="../../tiny_mce_popup.js"></script>

        <script language="javascript">
        function InsertweenCompanyImage(imagepath)
        {
			var ed = tinyMCEPopup.editor, dom = ed.dom;
	
			tinyMCEPopup.execCommand(\'mceInsertContent\', false, dom.createHTML(\'img\', {
				src : imagepath,
				border : 0
			}));
	
			tinyMCEPopup.close();
        }
        </script>
		
        <style type="text/css">
        a:link    { font: 11px verdana; color: #0000EE; text-decoration: underline; }
        a:active  { font: 11px verdana; color: #0000EE; text-decoration: underline; }
        a:visited { font: 11px verdana; color: #0000EE; text-decoration: underline; }
        a:hover   { font: 11px verdana; color: #0000EE; text-decoration: underline; }

        body
        {
          background-color: #778AAF;
          color: #000000;
          font-family: verdana, arial;
          font-size: 11px;

          margin-top:    10px;
          margin-bottom: 10px;
          margin-left:   10px;
          margin-right:  10px;
        }

        td, font
        {
          font: 11px verdana, arial;
          color: #000000;
        }

        hr
        {
          height: 1px;
          border: 0px;

          color: #778AAF;
          background-color: #778AAF;

          width: 98%;
        }
        </style>
      
		<title>上传/插入 图片</title>
	  </head>

      <body>';


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

switch($action)
{
  case 'uploadimage':
    UploadImage();
  break;

  case 'displayimages':
    DisplayImages();
  break;
}



// ############################## DISPLAY FOOTER ###############################

echo '</body>
      </html>';


?>