<?php
// +---------------------------------------------+
// |     Copyright  2007 - 2009 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('模板编辑器');


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

echo '<script type="text/javascript">
function yiru(t, tw, th, e){    
    var ei = document.getElementById("big_image");
    ei.style.display = "block";
	var thisstyle = "";
	var thisw = null;
	var thish = null;
 if (tw > 380){
    thisstyle = "width=380px";
	thisw = 380;
	thish = parseInt(380 * th /tw);
 }else if (th > 380){
    thisstyle = "height=380px";
	thisw = parseInt(380 * tw /th);
	thish = 380;
 }else if (th < 160 && tw <= th){
    thisstyle = "height=160px";
	thisw = parseInt(160 * tw /th);
	thish = 160;
 }else if (tw < 160 && tw >= th){
    thisstyle = "width=160px";
	thisw = 160;
	thish = parseInt(160 * th /tw);
 }else{
    thisstyle = "width=" + tw + " height=" + th;
	thisw = tw;
	thish = th;
 }
 ei.innerHTML = \'<img src="\' + t.src + \'" \' + thisstyle + \' />\';

	if((e.clientY+thish+10)>document.body.clientHeight){
	 ei.style.top  =document.body.scrollTop+e.clientY-thish-10+"px";
	
	}else{
	 ei.style.top  =document.body.scrollTop+e.clientY+10+"px";
	}
	
	if((e.clientX+thisw+10) >document.body.clientWidth){
	 ei.style.left  =document.body.scrollLeft+e.clientX-thisw-10+"px";
	
	}else{
	 ei.style.left =document.body.scrollLeft+e.clientX+10+"px";
	}
 
 
}

function yichu(){
    var ei = document.getElementById("big_image");
    ei.innerHTML = "";
 ei.style.display = "none";
}

</script>
<div id="big_image" style="position: absolute; display: none; z-index: 80; border: 0px solid #996600;">
</div>

';
// ############################# GET TEMPLATES FOLDERS #############################

function DisplayFileDetails($file, $tdstyle = '')
{
  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');
  $fileextensions = array('html', '.css', '.htm', '.php', '.txt', '.asp', '.jsp', '.tpl', '.xml');
  
  // first lets determine what kind of file we are dealing with
  $extension = strtolower(substr($file, -4));
  $extension2 = strtolower(substr($file, -3));
  // 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="' . $filepath . '" target="_blank"><img border="0" src="' . $filepath . '" width="' . $newwidth . '" height="' . $newheight . '"  onMouseMove="yiru(this, '.$width.', '.$height.', event);" onMouseOut="yichu(this);" /></a>
              </td>
              <td valign="top">
                <b>' . $file . '</b> (' .filesize($filepath)/1000 . 'K)<br />
                宽:  ' . $width . ' px<br />
                高: ' . $height . ' px<br /><br />
                <a href="template_editor.php?action=deleteimage&folderpath=' . $folderpath . '&imagepath=' . $filepath . '">删除图片</a>
              </td>
            </tr>
            </table>';
    }
  }
  else if(in_array($extension, $fileextensions) || $extension2 == '.js')
  {
      echo '<table width="100%" border="0" cellpadding="0" cellspacing="0">
            <tr>
              <td width="10" valign="top" style="padding-right: 15px;">
                <a href="template_editor.php?action=edittemplatefile&folderpath=' . $folderpath . '&imagepath=' . $filepath . '"><img border="0" src="styles/advanced/images/editablefile' . iif($tdstyle == 'tdrow3', '1' , '2') . '.gif" /></a>
              </td>
              <td valign="top">
                <b>' . $file . '</b> (' .filesize($filepath)/1000 . 'K)<br /><br />
                <a href="template_editor.php?action=deleteimage&folderpath=' . $folderpath . '&imagepath=' . $filepath . '">删除文件</a><br /><br />
				<a href="template_editor.php?action=edittemplatefile&folderpath=' . $folderpath . '&imagepath=' . $filepath . '">编辑文件</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, -10) == 'templates/')
      {
        echo '<table width="100%" border="0" cellpadding="0" cellspacing="0">
              <tr>
                <td width="10" valign="top" style="padding-right: 15px;">
                  <img border="0" src="styles/advanced/images/folderforbidden' . iif($tdstyle == 'tdrow3', '1' , '2') . '.gif" />
                </td>
                <td valign="top">
                  <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="template_editor.php?folderpath=' . str_replace(end($tmp_folderpath), '', substr($folderpath, 0, -1))  . '"><img border="0" src="styles/advanced/images/folderup' . iif($tdstyle == 'tdrow3', '1' , '2') . '.gif" /></a>
              </td>
              <td valign="top">
                <b>上层文件夹</b><br /><br />
                <a href="template_editor.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="template_editor.php?folderpath=' . $filepath . '/"><img border="0" src="styles/advanced/images/folder' . iif($tdstyle == 'tdrow3', '1' , '2') . '.gif" /></a>
              </td>
              <td valign="top">
                <b>' . $file . '</b><br /><br />
                <a href="template_editor.php?folderpath=' . $filepath . '/">打开文件夹</a>
              </td>
            </tr>
            </table>';
    }
  }

}



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

function UploadImage()
{
  global $folderpath;

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

                            
  $valid_image_extensions = array('gif',
        						  'jpg',
        						  'peg', // jpeg
        						  'bmp',
        						  'tml',
        						  'htm',
        						  'php',
        						  'css',
        						  'txt',
        						  'asp',
        						  'jsp',
        						  '.js',
        						  'xml',
        						  'tpl',
        						  'png');

  // check if image was uploaded
  if($image['size'] == 0)
  {
    $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:
  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 IMAGE DETAILS ###########################

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

   if($imagesize = @getimagesize($imagepath))
    {
 
	  list($width, $height, $type, $attr) = $imagesize;
	
	  $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 . '"  onMouseMove="yiru(this, '.$width.', '.$height.', event);" onMouseOut="yichu(this);" /></a>
			  </td>
			  <td valign="top">
				<b>' . $imagename . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' .filesize($imagepath)/1000 . 'K</b><br /><br />
				宽:  ' . $width . ' 像素<br />
				高: ' . $height . ' 像素' . iif(strlen($extratext), '<br /><br />' . $extratext, '') . '
			  </td>
			</tr>
			</table>';
  
  }else{
  
	  echo '<table width="100%" border="0" cellpadding="0" cellspacing="0">
			<tr>
			  <td valign="middle" style="padding-right: 15px;">
				<b>' . $imagename . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' .filesize($imagepath)/1000 . 'K</b><br /><br />
				非图片文件, 大小: ' .filesize($imagepath)/1000 . ' K字节.</b>' . iif(strlen($extratext), '<br /><br />' . $extratext, '') . '
			  </td>
			</tr>
			</table>';
  }
}



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

function DeleteImage()
{
  global $folderpath;

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

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


  if($deleteimage == ' 确定删除 ')
  {
    // delete image
    if(@unlink($imagepath))
    {
      // delete worked, now redirect
      PrintRedirect('template_editor.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('template_editor.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="template_editor.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=\'template_editor.php?action=displayimages&folderpath=' . $folderpath . '\'; return false" />
              </form>
            </td>
          </tr>
          </table>';
    EndSection();
  }

}


// ############################### EDIT FILE ################################

function EditTemplateFile()
{
  global $folderpath;

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

  $savefile = isset($_POST['savefile']) ? $_POST['savefile'] : 'Confirm Edit';


  if($savefile == ' 保存更新 ')
  {
 
	$filecontent = stripslashes(trim($_POST['filecontent']));
	$fd = fopen("$imagepath",w);
	fputs($fd,$filecontent);
  
    PrintRedirect('template_editor.php?action=displayimages&folderpath=' . $folderpath, 1);

  }
  else if($savefile == ' 取消 ')
  {
    // go back
    PrintRedirect('template_editor.php?action=displayimages&folderpath=' . $folderpath, 1);
  }

  // confirm delete
  if($savefile == 'Confirm Edit')
  {
	 if ($imagepath){ $oldfilecontent = implode("",file($imagepath));}
	 
	 $oldfilecontent = htmlspecialchars($oldfilecontent);
	 
   // confirm delete
    PrintSection('编辑文件');
    echo '<form method="post" action="template_editor.php">
	       <table width="100%" border="0" cellpadding="5" cellspacing="0">
          <tr>
            <td class="tdrow1">
			<input type="hidden" name="action" value="edittemplatefile" />
              <input type="hidden" name="folderpath" value="' . $folderpath . '" />
              <input type="hidden" name="imagepath" value="' . $imagepath . '" />
              <input type="submit" name="savefile" value=" 保存更新 " onclick="return confirm(\'确定更新文件吗?\');" />&nbsp;&nbsp;
              <input type="submit" value=" 取消 " onclick="window.location=\'template_editor.php?action=displayimages&folderpath=' . $folderpath . '\'; return false" /></td>
          </tr>
          <tr>
            <td class="tdrow2" width="100%" valign="top">
			<textarea rows="40" style="width: 100%;" name="filecontent" >' . $oldfilecontent . '</textarea>';


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

}


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

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


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

  PrintSection('上传文件');
  echo '<table width="100%" border="0" cellpadding="5" cellspacing="0">

        <tr>
          <td class="tdrow1"> ' . $currentpath . substr($folderpath, 3) . '</td>
        </tr>
        <tr>
          <td class="tdrow2">';
		  
		  if($newimage)
		  {
			echo '<font class=ohblue>上传文件成功!</font><br /><br />';
		  }

			echo '上传文件到当前文件夹:<br />
					  <form enctype="multipart/form-data" method="post" action="template_editor.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="2000000" />
					  <input name="image" type="file" size="38" />
					  <input type="submit" value="上传文件" />
					  </form>';

		  
		  
        echo '<br />(注: 可上传jpg, png, gif, bmp, htm, html, php, css, txt, asp, jsp, js, tpl, xml文件)</td>
        </tr>
        </table>';
  EndSection();

  PrintSection('模板文件列表');
  
  $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));
    $extension2 = strtolower(substr($file, -3));

    $fileextensions = array('jpeg', '.gif', '.jpg', '.bmp', '.png', 'html', '.css', '.htm', '.php', '.txt', '.asp', '.jsp', '.tpl', '.xml');

    if(in_array($extension, $fileextensions) || $extension2 == '.js')
    {
      $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;
  $tdstyle = 'tdrow3';


  echo '<table width="100%" border="0" cellpadding="5" cellspacing="0"><tr>
          <td class="tdrow1" colspan="3"> ' . $currentpath . substr($folderpath, 3) . '</td>
        </tr>';



  for($i = 0; $i < count($files); $i++)
  {
    $columncount++;
    
    // start a new row?
    if($columncount == 1)
    {
      echo '<tr>';
	  $tdstyle = ($tdstyle == 'tdrow3') ? 'tdrow2' : 'tdrow3';
    }

    // open column
	echo '<td width="33%" class="' . $tdstyle . '">';

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

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

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

      // start over
      $columncount = 0;

    }
  }

  closedir($handle);

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

  echo '</table>';

  EndSection();

  
}



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


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

  case 'deleteimage':
    DeleteImage();
  break;
  
  case 'edittemplatefile':
    EditTemplateFile();
  break;

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


PrintFooter();

?>