<?php
// +---------------------------------------------+
// |     Copyright 2006-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('模块管理');

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


// module bitfield data
$modulebitfield = array('canview'     => 1,
                        'cansubmit'   => 2,
                        'candownload' => 4,
                        'cancomment'  => 8,
                        'canadmin'    => 16);


// ############################### CLONE MODULE ################################

function CloneModule($modulefolderpath, $modulefolder, $moduleid, $clonemoduleid)
{
  // make sure the modulefolderpath has a slash at the end
  $modulefolderpath = substr($modulefolderpath, -1) != '/' ? $modulefolderpath . '/' : $modulefolderpath;

  $d = dir($modulefolderpath);

  while($entry = $d->read())
  {
    if($entry != "." && $entry != "..")
    {
      if(is_dir($modulefolderpath . $entry))
      {
        // copy the folder

        $cutoff = strlen($modulefolder) + 12;

        $clonefolder = '../modules/' . str_replace($moduleid, $clonemoduleid, $modulefolder) . '/' . substr($modulefolderpath . $entry, $cutoff);

        if(!is_dir($clonefolder))
        {
          mkdir($clonefolder, 0777);
        }

        // if file is a directory then do a recursive call
		if($entry != "images_cn" && $entry != "images_en" && $entry != "upload")
		{
             CloneModule($modulefolderpath . $entry, $modulefolder, $moduleid, $clonemoduleid);
	    }
      }
      else
      {
        $clone_filepath = '../modules/' . str_replace($moduleid, $clonemoduleid, $modulefolder) . '/' . substr($modulefolderpath, (strlen($modulefolder) + 12)) . str_replace($moduleid, $clonemoduleid, $entry);

        $module = implode('', file($modulefolderpath . $entry));

        // search and replace all the module's function names
        $module = str_replace('function m' . $moduleid . '_', 'function m' . $clonemoduleid . '_', $module);

        // search and replace all the moduleids with the prefix m and $m
        $module = str_replace('m' . $moduleid . '_', 'm' . $clonemoduleid . '_', $module);
        $module = str_replace('$m' . $moduleid . '_', '$m' . $clonemoduleid . '_', $module);

        // search and replace all urls
        $module = str_replace('?moduleid=' . $moduleid, '?moduleid=' . $clonemoduleid, $module);
        $module = str_replace('&moduleid=' . $moduleid, '&moduleid=' . $clonemoduleid, $module);

        // search and replace weencompany function calls
        $module = str_replace('GetLanguage(' . $moduleid, 'GetLanguage(' . $clonemoduleid, $module);
        $module = str_replace('Comments(' . $moduleid, 'Comments(' . $clonemoduleid, $module);
        $module = str_replace('DeleteModuleComments(' . $moduleid, 'DeleteModuleComments(' . $clonemoduleid, $module);

        // search and replace database calls
        $module = str_replace('moduleid = ' . $moduleid, 'moduleid = ' . $clonemoduleid, $module);
        $module = str_replace('moduleid=' . $moduleid, 'moduleid=' . $clonemoduleid, $module);
        $module = str_replace("moduleid = '" . $moduleid . "'", "moduleid = '" . $clonemoduleid . "'", $module);
        $module = str_replace("moduleid='" . $moduleid . "'", "moduleid='" . $clonemoduleid . "'", $module);

        // search and replace usergroup code
        $module = str_replace("in_array(" . $moduleid, "in_array(" . $clonemoduleid, $module);

        if($entry == 'install.php')
        {
          // modulesettings and languages in the install file
          $module = str_replace("VALUES ('', " . $moduleid,  "VALUES ('', " . $clonemoduleid, $module);
          $module = str_replace("VALUES (''," . $moduleid,   "VALUES (''," . $clonemoduleid, $module);
          $module = str_replace("VALUES ('', '" . $moduleid, "VALUES ('', '" . $clonemoduleid, $module);
          $module = str_replace("VALUES ('','" . $moduleid,  "VALUES ('','" . $clonemoduleid, $module);

          // modulesettings and languages in the install file (new style)
          $module = str_replace("VALUES ('0', " . $moduleid,  "VALUES ('0', " . $clonemoduleid, $module);
          $module = str_replace("VALUES ('0'," . $moduleid,   "VALUES ('0'," . $clonemoduleid, $module);
          $module = str_replace("VALUES ('0', '" . $moduleid, "VALUES ('0', '" . $clonemoduleid, $module);
          $module = str_replace("VALUES ('0','" . $moduleid,  "VALUES ('0','" . $clonemoduleid, $module);

          // the following might cause trouble if users are installing modules with hardcoded settingids
          // this replacement code assumes the user doesn't insert an empty '' for settingid
          $module = str_replace("VALUES ('" . $moduleid,  "VALUES ('" . $clonemoduleid, $module);
          $module = str_replace("VALUES (" . $moduleid,   "VALUES (" . $clonemoduleid, $module);
          $module = str_replace("VALUES ( '" . $moduleid, "VALUES ( '" . $clonemoduleid, $module);
          $module = str_replace("VALUES ( " . $moduleid,  "VALUES ( " . $clonemoduleid, $module);

          // search and replace the unique id in the install file
          $module = str_replace('= ' . $moduleid, '= ' . $clonemoduleid, $module);
        }

        if(!is_file($clone_filepath))
        {
          // open the file
          if(!$handle = fopen($clone_filepath, "w"))
          {
            echo '无法打开文件:' . $clone_filepath;
            exit;
          }

          if(fwrite($handle, $module) === FALSE)
          {
            echo '文件不可写:' . $clone_filepath;
            exit;
          }
        }

        // close file
        fclose($handle);
      }
    }
  }

}



// ############################ DISPLAY NEW MODULES ############################
// display modules that need to be installed or upgraded

function DisplayNewModules($dirname)
{
  global $DB;
  static $availablemodules;

  // initialize some variables
  $installtype = '';
  $currentversion = '';

  $d = dir($dirname);

  while($entry = $d->read())
  {
    if($entry != "." && $entry != "..")
    {
      if(is_dir($dirname."/".$entry))
      {
        DisplayNewModules($dirname."/".$entry);
      }
      else if(($entry == 'install.php') AND ($dirname != '../modules') AND (substr_count($dirname, '/') == 2)) // its a file, and it's in the correct folder
      {
        $installpath = $dirname . '/install.php';

        include($installpath);

        // check to see if module has already been installed

        // do not install or upgrade cloned modules
        if($uniqueid > 1999)
        {
          $installtype = '';
        }
        else if($module = $DB->query_first("SELECT version FROM " . TABLE_PREFIX . "modules WHERE moduleid = '$uniqueid'"))
        {
          // module is an update
          if($module['version'] < $version)
          {
            $installtype    = 'upgrade';
            $currentversion = $module['version'];
          }
        }
        else
        {
          $installtype = 'install';
        }

        if($installtype == 'install' || $installtype == 'upgrade')
        {
          $availablemodules++;

          echo '<tr>
                  <td class="tdrow1" colspan="2">'.$modulename.'</td>
                </tr>
                <tr>
                  <td class="tdrow2" width="70%">

                    <table border="0" cellpadding="5" cellspacing="0">
                    <tr><td width="150">模块名称:</td><td>'.$modulename.'</td></tr>
                    <tr><td>版本:</td><td>'.$version.'</td></tr>
                    <tr><td>作者:</td>';

          if(isset($authorlink))
          {
            echo '<td>'.$authorname.'</td></tr>';
          }

          echo '</table>

                  </td>
                  <td class="tdrow3" align="center">
                    <form  method="post" action="./modules.php">
                    <input type="hidden" name="action" value="' . $installtype . 'module" />
                    <input type="hidden" name="installtype" value="'.$installtype.'" />
                    <input type="hidden" name="installpath" value="'.$installpath.'" />';

          if($installtype == 'install')
          {
            echo '<input type="submit" value="安装此模块" />';
          }
          else
          {
            echo '<input type="hidden" name="currentversion" value="'.$currentversion.'" />
                  <input type="submit" value="升级 '.$modulename.'" />';
          }

          echo '  </form>
                  </td>
                </tr>';

          // reset vars
          unset($installtype);

        }
      }
      else if($entry == 'install.php' AND ( $dirname != '../modules' AND (substr_count($dirname, '/') > 2) ))
      {
        // the install folder was uploaded to the wrong spot,
        // lets give some information on this error

        $availablemodules++;

        // find the real module folder name
        $folders = explode('/', $dirname);
        $module_folder_name = $folders[(count($folders) - 1)];

        echo '<tr>
                <td class="tdrow1" colspan="2">模块上传错误</td>
              </tr>
              <tr>
                <td class="tdrow2" colspan="2">
                  模块上传错误.<br /><br />
                  此模块上传目录: ' . substr($dirname, 2) . '/<br /><br />
                  模块文件夹应上传到目录: /modules/' . $module_folder_name . '/<br /><br />
                </td>
              </tr>';
      }
    }
  }

  return $availablemodules;
}



// ########################### UPDATE MODULE VERSION ###########################
// this function is used when a module is upgrading from it's install.php file

function UpdateModuleVersion($moduleid, $version)
{
  global $DB;
  $DB->query("UPDATE " . TABLE_PREFIX . "modules SET version = '$version' WHERE moduleid = '$moduleid'");
}



// ############################### CLONE MODULE ################################

if($action == 'clonemodule')
{
  // $_POST vars
  $moduleid = $_POST['moduleid'];

  // find module folder path
  $module = $DB->query_first("SELECT modulepath FROM " . TABLE_PREFIX . "modules WHERE moduleid = '$moduleid'");
  $getmodulefolder = explode('/', $module['modulepath']);
  $modulefolder = $getmodulefolder[0];
  $modulefolderpath = '../modules/' . $modulefolder . '/';

  // get a clonemoduleid
  // Chinese clone moduleids range from 2000 -> 2999 (there can only be 999 cloned modules)
  // English clone moduleids range from 4000 -> 5999 (there can only be 999 cloned modules)
  if($sitedefaultlang == 'en') //Insert Chinese phrase.
  {
	$moduleidfrom = 3999;
  }
  else
  {
	$moduleidfrom = 1999;
  } 
  
  if($getcloneid = $DB->query_first("SELECT moduleid FROM " . TABLE_PREFIX . "modules WHERE moduleid > $moduleidfrom ORDER BY moduleid DESC"))
  {
    $clonemoduleid = ++$getcloneid['moduleid'];
  }
  else
  {
    $clonemoduleid = $moduleidfrom + 1;
  }

  $clonefolder = str_replace($moduleid, $clonemoduleid, $modulefolder);

  // first create the clone folder
  if(!is_dir('../modules/' . $clonefolder))
  {
    // the mode (chmod) of a directory is affected by the users current umask
    // default value of umask is 18 (22 octal, or 0022). Meaning when using mkdir()
    // to CHMOD the created folder to 0777, PHP takes 0777 and substracts the current
    // value of umask, in our case 0022, so the result is 0755 - so lets fix it by switching it to 0
    $oldumask = umask(0);

    if(@mkdir('../modules/' . $clonefolder, 0777))
    {
      // clone the module
      CloneModule($modulefolderpath, $modulefolder, $moduleid, $clonemoduleid);

      // return umask to its previous value
      umask($oldumask);

      // now install the module
      $installtype = 'install';
      if(@include('../modules/' . $clonefolder . '/install.php'))
      {
        $modulename .= ' 复制 ';
        if($nextclonenumber = $DB->query_first("SELECT name FROM " . TABLE_PREFIX . "modules WHERE name LIKE '" . $modulename . "%' ORDER BY moduleid DESC"))
        {
          $nextclonenumber = substr($nextclonenumber['name'], strlen($modulename));
          $modulename .= intval($nextclonenumber) + 1;
        }
        else
        {
          $modulename .= 1;
        }

        if(!isset($modulesettings))
        {
          // viewing, and admin bitfield value
          $modulesettings = 17;
        }

        $DB->query("INSERT INTO " . TABLE_PREFIX . "modules (moduleid, name, displayname, version, modulepath, settingspath, authorname, authorlink, settings)
                    VALUES ($uniqueid, '$modulename', '$modulename', '$version', '$modulepath', '$settingspath', 'weencompany_cloner', 1, $modulesettings)");

        // install default usergroup settings
        $usergroups = $DB->query("SELECT usergroupid, moduleviewids, modulesubmitids, moduledownloadids,
                                  modulecommentids, moduleadminids FROM " . TABLE_PREFIX . "usergroups");

        while($usergroup = $DB->fetch_array($usergroups))
        {
          if($usergroup['usergroupid'] == 1)
          {
            // ADMINISTRATOR USERS
            $moduleviewids     = ($modulesettings & $modulebitfield['canview'])?  (strlen($usergroup['moduleviewids'])? $usergroup['moduleviewids'] . ',' . $uniqueid : $uniqueid) : $usergroup['moduleviewids'];

            $modulesubmitids   = ($modulesettings & $modulebitfield['cansubmit'])? (strlen($usergroup['modulesubmitids'])? $usergroup['modulesubmitids']    . ',' . $uniqueid : $uniqueid) : $usergroup['modulesubmitids'] ;

            $moduledownloadids = ($modulesettings & $modulebitfield['candownload'])? (strlen($usergroup['moduledownloadids'])? $usergroup['moduledownloadids']  . ',' . $uniqueid : $uniqueid) : $usergroup['moduledownloadids'];

            $modulecommentids  = ($modulesettings & $modulebitfield['cancomment'])? (strlen($usergroup['modulecommentids'])? $usergroup['modulecommentids']   . ',' . $uniqueid : $uniqueid) : $usergroup['modulecommentids'];

            $moduleadminids    = ($modulesettings & $modulebitfield['canadmin'])? (strlen($usergroup['moduleadminids'])? $usergroup['moduleadminids']     . ',' . $uniqueid : $uniqueid) : $usergroup['moduleadminids'];
          }
          else if($usergroup['usergroupid'] == 2 OR $usergroup['usergroupid'] == 3)
          {
            // MODERATORS AND REGISTERED USERS
            $moduleviewids     = ($modulesettings & $modulebitfield['canview'])?  (strlen($usergroup['moduleviewids'])? $usergroup['moduleviewids'] . ',' . $uniqueid : $uniqueid) : $usergroup['moduleviewids'];

            $modulesubmitids   = ($modulesettings & $modulebitfield['cansubmit'])? (strlen($usergroup['modulesubmitids'])? $usergroup['modulesubmitids']    . ',' . $uniqueid : $uniqueid) : $usergroup['modulesubmitids'] ;

            $moduledownloadids = ($modulesettings & $modulebitfield['candownload'])? (strlen($usergroup['moduledownloadids'])? $usergroup['moduledownloadids']  . ',' . $uniqueid : $uniqueid) : $usergroup['moduledownloadids'];

            $modulecommentids  = ($modulesettings & $modulebitfield['cancomment'])? (strlen($usergroup['modulecommentids'])? $usergroup['modulecommentids']   . ',' . $uniqueid : $uniqueid) : $usergroup['modulecommentids'];

            $moduleadminids    = $usergroup['moduleadminids'];
          }
          else
          {
            // GUESTS, and other created usergroup users
            $moduleviewids     = ($modulesettings & $modulebitfield['canview'])?  (strlen($usergroup['moduleviewids'])? $usergroup['moduleviewids'] . ',' . $uniqueid : $uniqueid) : $usergroup['moduleviewids'];

			$modulesubmitids   = $usergroup['modulesubmitids'];
            $moduledownloadids = $usergroup['moduledownloadids'];
            $modulecommentids  = $usergroup['modulecommentids'];
            $moduleadminids    = $usergroup['moduleadminids'];
          }

          // update usergroup row
          $DB->query("UPDATE " . TABLE_PREFIX . "usergroups SET moduleviewids     = '$moduleviewids',
                                                                modulesubmitids   = '$modulesubmitids',
                                                                moduledownloadids = '$moduledownloadids',
                                                                modulecommentids  = '$modulecommentids',
                                                                moduleadminids    = '$moduleadminids'
                                                          WHERE usergroupid       = '" . $usergroup['usergroupid'] . "'");
        }

        echo '<BODY onLoad="parent.leftFrame.location.reload(true)">';
        PrintRedirect('modules.php?action=displaymodules', 1);
      }
      else
      {
        $errors = '复制模块失败.<br />无法打开目录: ' . $installpath;
        PrintErrors($errors, '无法打开目录');
        $action = 'displaymodules';
      }
    }
    else
    {
      $errors = '添加复制模块文件夹失败: ./modules/' . $clonefolder . '<br /><br />
                 请将模块目录: modules/ 的属性设置为可写(777).';
      PrintErrors($errors, '复制模块错误');
      $action = 'displaymodules';
    }
  }
  else
  {
    $errors = '试图创建已存在的文件夹: ./modules/' . $clonefolder . '<br /><br />
               请用ftp工具手动删除此文件夹后再创建.';
    PrintErrors($errors, '复制模块错误');
    $action = 'displaymodules';
  }

}



// ############################## INSTALL MODULE ###############################

if($action == 'installmodule')
{
  $installpath = $_POST['installpath'];

  $installtype = 'install';

  if(@include($installpath))
  {
    if(!isset($modulesettings))
    {
      // viewing, and admin bitfield value
      $modulesettings = 17;
    }

    $DB->query("INSERT INTO " . TABLE_PREFIX . "modules (moduleid,  name,        displayname,  version,  modulepath , settingspath,  authorname,  authorlink, settings)
                VALUES ('$uniqueid', '$modulename', '$modulename', '$version', '$modulepath', '$settingspath', '$authorname', '$authorlink', $modulesettings)");

    // install default usergroup settings
    $usergroups = $DB->query("SELECT usergroupid, moduleviewids, modulesubmitids, moduledownloadids,
                              modulecommentids, moduleadminids FROM " . TABLE_PREFIX . "usergroups");

    while($usergroup = $DB->fetch_array($usergroups))
    {
      if($usergroup['usergroupid'] == 1)
	  {
		// ADMINISTRATOR USERS
		$moduleviewids     = ($modulesettings & $modulebitfield['canview'])?  (strlen($usergroup['moduleviewids'])? $usergroup['moduleviewids'] . ',' . $uniqueid : $uniqueid) : $usergroup['moduleviewids'];

		$modulesubmitids   = ($modulesettings & $modulebitfield['cansubmit'])? (strlen($usergroup['modulesubmitids'])? $usergroup['modulesubmitids']    . ',' . $uniqueid : $uniqueid) : $usergroup['modulesubmitids'] ;

		$moduledownloadids = ($modulesettings & $modulebitfield['candownload'])? (strlen($usergroup['moduledownloadids'])? $usergroup['moduledownloadids']  . ',' . $uniqueid : $uniqueid) : $usergroup['moduledownloadids'];

		$modulecommentids  = ($modulesettings & $modulebitfield['cancomment'])? (strlen($usergroup['modulecommentids'])? $usergroup['modulecommentids']   . ',' . $uniqueid : $uniqueid) : $usergroup['modulecommentids'];

		$moduleadminids    = ($modulesettings & $modulebitfield['canadmin'])? (strlen($usergroup['moduleadminids'])? $usergroup['moduleadminids']     . ',' . $uniqueid : $uniqueid) : $usergroup['moduleadminids'];
	  }
	  else if($usergroup['usergroupid'] == 2 OR $usergroup['usergroupid'] == 3)
	  {
		// MODERATORS AND REGISTERED USERS
		$moduleviewids     = ($modulesettings & $modulebitfield['canview'])?  (strlen($usergroup['moduleviewids'])? $usergroup['moduleviewids'] . ',' . $uniqueid : $uniqueid) : $usergroup['moduleviewids'];

		$modulesubmitids   = ($modulesettings & $modulebitfield['cansubmit'])? (strlen($usergroup['modulesubmitids'])? $usergroup['modulesubmitids']    . ',' . $uniqueid : $uniqueid) : $usergroup['modulesubmitids'] ;

		$moduledownloadids = ($modulesettings & $modulebitfield['candownload'])? (strlen($usergroup['moduledownloadids'])? $usergroup['moduledownloadids']  . ',' . $uniqueid : $uniqueid) : $usergroup['moduledownloadids'];

		$modulecommentids  = ($modulesettings & $modulebitfield['cancomment'])? (strlen($usergroup['modulecommentids'])? $usergroup['modulecommentids']   . ',' . $uniqueid : $uniqueid) : $usergroup['modulecommentids'];

		$moduleadminids    = $usergroup['moduleadminids'];
	  }
	  else
	  {
		// GUESTS, and other created usergroup users
		$moduleviewids     = ($modulesettings & $modulebitfield['canview'])?  (strlen($usergroup['moduleviewids'])? $usergroup['moduleviewids'] . ',' . $uniqueid : $uniqueid) : $usergroup['moduleviewids'];

		$modulesubmitids   = $usergroup['modulesubmitids'];
		$moduledownloadids = $usergroup['moduledownloadids'];
		$modulecommentids  = $usergroup['modulecommentids'];
		$moduleadminids    = $usergroup['moduleadminids'];
	  }

      // update usergroup row
      $DB->query("UPDATE " . TABLE_PREFIX . "usergroups SET moduleviewids     = '$moduleviewids',
                                                            modulesubmitids   = '$modulesubmitids',
                                                            moduledownloadids = '$moduledownloadids',
                                                            modulecommentids  = '$modulecommentids',
                                                            moduleadminids    = '$moduleadminids'
                                                      WHERE usergroupid       = '" . $usergroup['usergroupid'] . "'");
    }

    echo '<BODY onLoad="parent.leftFrame.location.reload(true)">';
    PrintRedirect('modules.php?action=displaymodules', 1);
  }
  else
  {
    $errors = '安装模块失败.<br />
               无法打开文件夹: ' . $installpath;

    PrintErrors($errors, '安装错误');
    $action = 'displaymodules';
  }
}



// ############################# UNINSTALL MODULE ##############################

if($action == 'uninstallmodule')
{
  $moduleid = $_GET['moduleid'];
  
  // Check the user has permission to do this
  if(!@in_array($moduleid, $userinfo['moduleadminids']))
  {
    PrintErrors("您无权删除此模块.", '无权限操作');
    $action = 'displaymodules';
    return;
  }

  $installtype = 'uninstall';

  // find install file (to uninstall)
  $module = $DB->query_first("SELECT name, modulepath, authorname FROM " . TABLE_PREFIX . "modules WHERE moduleid = '$moduleid'");
  $getmodulefolder = explode('/', $module['modulepath']);
  $uninstallfile = '../modules/' . $getmodulefolder[0] . '/install.php';

  if(@include($uninstallfile))
  {
    $DB->query("DELETE FROM " . TABLE_PREFIX . "phrases        WHERE moduleid = '$uniqueid'");
    $DB->query("DELETE FROM " . TABLE_PREFIX . "modulesettings WHERE moduleid = '$uniqueid'");
    $DB->query("DELETE FROM " . TABLE_PREFIX . "modules        WHERE moduleid = '$uniqueid'");
    $DB->query("DELETE FROM " . TABLE_PREFIX . "comments       WHERE moduleid = '$uniqueid'");

    $DB->query("UPDATE " . TABLE_PREFIX . "pagesort SET moduleid = '1' WHERE moduleid = '$uniqueid'");

    // remove this moduleid from the usergroup rows
    $usergroups = $DB->query("SELECT usergroupid, moduleviewids, modulesubmitids, moduledownloadids,
                              modulecommentids, moduleadminids FROM " . TABLE_PREFIX . "usergroups");

    while($usergroup = $DB->fetch_array($usergroups))
    {
      // first get the arrays
      $moduleviewids     = @explode(',', $usergroup['moduleviewids']);
      $modulesubmitids   = @explode(',', $usergroup['modulesubmitids']);
      $moduledownloadids = @explode(',', $usergroup['moduledownloadids']);
      $modulecommentids  = @explode(',', $usergroup['modulecommentids']);
      $moduleadminids    = @explode(',', $usergroup['moduleadminids']);

      // erase the $moduleid from the arrays
      if(in_array($moduleid, $moduleviewids))
      {
        unset($moduleviewids[array_search($moduleid, $moduleviewids)]);
      }

      if(in_array($moduleid, $modulesubmitids))
      {
        unset($modulesubmitids[array_search($moduleid, $modulesubmitids)]);
      }

      if(in_array($moduleid, $moduledownloadids))
      {
        unset($moduledownloadids[array_search($moduleid, $moduledownloadids)]);
      }

      if(in_array($moduleid, $modulecommentids))
      {
        unset($modulecommentids[array_search($moduleid, $modulecommentids)]);
      }

      if(in_array($moduleid, $moduleadminids))
      {
        unset($moduleadminids[array_search($moduleid, $moduleadminids)]);
      }

      // put them back into strings
      $newmoduleviewids     = @implode(',', $moduleviewids);
      $newmodulesubmitids   = @implode(',', $modulesubmitids);
      $newmoduledownloadids = @implode(',', $moduledownloadids);
      $newmodulecommentids  = @implode(',', $modulecommentids);
      $newmoduleadminids    = @implode(',', $moduleadminids);

      // now update the usergroup with the updated category values
      $DB->query("UPDATE " . TABLE_PREFIX . "usergroups SET moduleviewids     = '$newmoduleviewids',
                                                            modulesubmitids   = '$newmodulesubmitids',
                                                            moduledownloadids = '$newmoduledownloadids',
                                                            modulecommentids  = '$newmodulecommentids',
                                                            moduleadminids    = '$newmoduleadminids'
                                                      WHERE usergroupid       = '" . $usergroup['usergroupid'] . "'");
    }

        // If this is a cloned module, delete the directory
        if($module['authorname'] == 'weencompany_cloner')
        {
          rmdirr('../modules/' . $getmodulefolder[0]);
        }

    echo '<BODY onLoad="parent.leftFrame.location.reload(true)">';
    PrintRedirect('modules.php?action=displaymodules', 1);
  }
  else
  {
    $errors = '删除模块失败 "' . $module['name'] . '" module.<br /><br />
               无法打开文件: ' . $uninstallfile;

    PrintErrors($errors, '删除出错');
    $action = 'displaymodules';
  }
}
// ######################### DELETE FOLDER AND CONTENTS ############################

function rmdirr($dir)
{
//新程序:
if ($handle = opendir($dir)) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
			is_dir($dir."/".$file)? rmdirr($dir."/".$file) : unlink($dir."/".$file);
        }
    }
    closedir($handle);
}

rmdir($dir);
}

// ############################## UPGRADE MODULE ###############################

if($action == 'upgrademodule')
{
  $installpath    = $_POST['installpath'];
  $currentversion = $_POST['currentversion'];

  $installtype = 'upgrade';

  if(@include($installpath))
  {
    // the upgrade takes place in the install.php file

    echo '<BODY onLoad="parent.leftFrame.location.reload(true)">';
    PrintRedirect('modules.php?action=displaymodules', 1);
  }
  else
  {
    $errors = '模块升级失败.<br />
               无法打开文件夹: ' . $installpath;

    PrintErrors($errors, '升级失败');
    $action = 'displaymodules';
  }
}



// ########################### DELETE CUSTOM MODULE ############################

if($action == 'deletecustommodule')
{
  $custommoduleid = $_GET['custommoduleid'];
  
  // Check the user has permission to do this
  if(!@in_array($custommoduleid, $userinfo['custommoduleadminids']))
  {
    PrintErrors("您无权删除此模块.", '无权限操作');
    $action = 'displaymodules';
    return;
  }

  $DB->query("DELETE FROM " . TABLE_PREFIX . "custommodules WHERE custommoduleid = $custommoduleid");

  $pagesortid = 'c' . $custommoduleid;
  $DB->query("UPDATE " . TABLE_PREFIX . "pagesort SET moduleid = '1' WHERE moduleid = '$pagesortid'");

  // remove this custommoduleid from the usergroup rows
  $usergroups = $DB->query("SELECT usergroupid, custommoduleviewids, custommoduleadminids FROM " . TABLE_PREFIX . "usergroups");

  while($usergroup = $DB->fetch_array($usergroups))
  {
    // get the custom module view and admin ids
    $custommoduleviewids  = @explode(',', $usergroup['custommoduleviewids']);
    $custommoduleadminids = @explode(',', $usergroup['custommoduleadminids']);

    // search and if found then remove the deleted custom moduleid from the allow view column
    if(in_array($custommoduleid, $custommoduleviewids))
    {
      unset($custommoduleviewids[array_search($custommoduleid, $custommoduleviewids)]);
    }

    // search and if found then remove the deleted custom moduleid from the allow admin column
    if(in_array($custommoduleid, $custommoduleadminids))
    {
      unset($custommoduleadminids[array_search($custommoduleid, $custommoduleadminids)]);
    }

    // implode both arrays back to a string
    $newcustommoduleviewids  = @implode(',', $custommoduleviewids);
    $newcustommoduleadminids = @implode(',', $custommoduleadminids);

    // now update the usergroup with the updated custommodule values
    $DB->query("UPDATE " . TABLE_PREFIX . "usergroups SET custommoduleviewids  = '$newcustommoduleviewids',
                                                          custommoduleadminids = '$newcustommoduleadminids'
                                                    WHERE usergroupid          = " . $usergroup['usergroupid']);
  }

  echo '<BODY onLoad="parent.leftFrame.location.reload(true)">';
  PrintRedirect('modules.php?action=displaymodules', 1);
}



// ############################ UPDATE MODULE NAMES ############################

if($action == 'updatemodulenames')
{
  $moduleid    = $_POST['moduleid'];
  $nummodules  = $_POST['nummodules'];
  $displayname = $_POST['displayname'];

  $clonedmoduleid    = $_POST['clonedmoduleid'];
  $numclonedmodules  = $_POST['numclonedmodules'];
  $cloneddisplayname = $_POST['cloneddisplayname'];
  $clonedname        = $_POST['clonedname'];

  $custommoduleid    = $_POST['custommoduleid'];
  $numcustommodules  = $_POST['numcustommodules'];
  $customdisplayname = $_POST['customdisplayname'];
  $customname        = $_POST['customname'];

  $downloadedid          = $_POST['downloadedid'];
  $numdownloadedmodules  = $_POST['numdownloadedmodules'];
  $downloadeddisplayname = $_POST['downloadeddisplayname'];

  // update weencompany module display names
  for($i = 0; $i < $nummodules; $i++)
  {
    $DB->query("UPDATE " . TABLE_PREFIX . "modules SET displayname = '$displayname[$i]'
                WHERE moduleid = '$moduleid[$i]'");
  }

  // update weencompany's cloned modules
  for($i = 0; $i < $numclonedmodules; $i++)
  {
    $DB->query("UPDATE " . TABLE_PREFIX . "modules SET name        = '$clonedname[$i]',
                                                       displayname = '$cloneddisplayname[$i]'
                                                 WHERE moduleid    = '$clonedmoduleid[$i]'");
  }

  // update custom module display names
  for($i = 0; $i < $numcustommodules; $i++)
  {
    $DB->query("UPDATE " . TABLE_PREFIX . "custommodules SET name           = '$customname[$i]',
                                                             displayname    = '$customdisplayname[$i]'
                                                       WHERE custommoduleid = '$custommoduleid[$i]'");
  }

  // update downloaded module display names
  for($i = 0; $i < $numdownloadedmodules; $i++)
  {
    $DB->query("UPDATE " . TABLE_PREFIX . "modules SET displayname = '$downloadeddisplayname[$i]'
                WHERE moduleid = '$downloadedid[$i]'");
  }

  echo '<BODY onLoad="parent.leftFrame.location.reload(true)">';
  PrintRedirect('modules.php?action=displaymodules', 1);
}



// ############################### VIEW MODULES ################################

if($action == 'displaymodules')
{
  // display 'install a module' form
  PrintSection('安装模块');
  echo '<table width="100%" border="0" cellpadding="5" cellspacing="0">';

  if(!DisplayNewModules('../modules'))
  {
    echo '<tr>
            <td class="tdrow1" colspan="2">暂无可安装的模块，请先将需要安装的模块文件夹上传到网站根目录下的"modules/"目录!</td>
          </tr>
          <tr>
            <td class="tdrow2" width="70%" align="top">
              所有模块已安装在您的企业网站系统中.
            </td>
          </tr>';
  }

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


  // this is used for the cloner form:
  $moduleid = isset($_POST['moduleid']) ? $_POST['moduleid'] : '';

  // get all the modules
  $getmodules = $DB->query("SELECT moduleid, name FROM " . TABLE_PREFIX . "modules WHERE moduleid != '1' AND moduleid != '10' AND moduleid != '11' AND moduleid != '12' AND moduleid != '18' AND authorname != 'weencompany_cloner' ORDER BY moduleid");

  // display custom module form
  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="custommodules.php">
            <input type="submit" value="设计新模块" />
            </form>
          </td>
        </tr>
        <tr>
          <td class="tdrow1" colspan="2">复制模块</td>
          </tr>
          <tr>
            <td class="tdrow2" width="70%" align="top">复制模块在不同的网站菜单中使用:</td>
            <td class="tdrow3">
              <form action="./modules.php" method="POST">
              <input type="hidden" name="action" value="clonemodule" />
              <select name="moduleid">';

  while($module = $DB->fetch_array($getmodules))
  {
    echo '<option value="' . $module['moduleid'] . '" ' . iif($moduleid == $module['moduleid'], "SELECTED", "") . '>' . $module['name'] . '</option>';
  }

  echo '      </select>
              <input type="submit" value=" 复制 " />
              </form>
            </td>
          </tr>
        </table>';
  EndSection();


  // get weencompany's main modules excluding the --empty-- module
  $getmodules = $DB->query("SELECT * FROM " . TABLE_PREFIX . "modules WHERE authorname = 'weencompany' AND moduleid != '1' ORDER BY moduleid ASC");
  $modulerows = $DB->get_num_rows($getmodules);

  // get the cloned modules
  $getclonedmodules = $DB->query("SELECT * FROM " . TABLE_PREFIX . "modules WHERE authorname = 'weencompany_cloner' ORDER BY moduleid ASC");
  $clonedmodulerows = $DB->get_num_rows($getclonedmodules);

  // get the custom modules
  $getcustommodules = $DB->query("SELECT * FROM " . TABLE_PREFIX . "custommodules ORDER BY custommoduleid ASC");
  $custommodulerows = $DB->get_num_rows($getcustommodules);

  // get and display the downloaded modules
  $getdownloaded  = $DB->query("SELECT * FROM " . TABLE_PREFIX . "modules WHERE authorname != 'weencompany' AND authorname != 'weencompany_cloner' ORDER BY moduleid ASC");
  $downloadedrows = $DB->get_num_rows($getdownloaded);

  // display weencompany's modules
  PrintSection('网站模块');
  echo '<form action="./modules.php" method="post">

        <table width="100%" border="0" cellpadding="5" cellspacing="0">
        <tr>
          <td class="tdrow1">系统模块 - 后台名称</td>
          <td class="tdrow1">前台名称</td>
          <td class="tdrow1" width="160">设置</td>
        </tr>';

  for($modulecount = 0; $module = $DB->fetch_array($getmodules); $modulecount++)
  {
    echo '<input type="hidden" name="moduleid[]" value="'.$module['moduleid'].'">
          <tr>
            <td class="tdrow2">'.$module['name'].' (ID: '. $module['moduleid'] . ')</td>
            <td class="tdrow3"><input type="text" name="displayname[]" value="'.CleanFormValue($module['displayname']).'" size="35" /></td>
            <td class="tdrow2">'.iif($module['settingspath'] == '' || !@in_array($module['moduleid'], $userinfo['moduleadminids']) , '&nbsp;', '<a href="mymodules.php?moduleid='.$module['moduleid'].'"><img alt="设置模块" src="' . $stylepath . 'images/configure.gif" /></a>').'</td>
          </tr>';
  }



  if($clonedmodulerows)
  {
    echo '<tr>
            <td class="tdrow1">复制的模块 - 后台名称</td>
            <td class="tdrow1">前台名称</td>
            <td class="tdrow1">设置</td>
          </tr>';

    for($clonedmodulecount = 0; $clonedmodule = $DB->fetch_array($getclonedmodules); $clonedmodulecount++)
    {
      echo '<input type="hidden" name="clonedmoduleid[]" value="'.$clonedmodule['moduleid'].'">
            <tr>
              <td class="tdrow2"><input type="text" name="clonedname[]" value="' . CleanFormValue($clonedmodule['name']) . '" size="30" /> (ID: '. $clonedmodule['moduleid'] . ')</td>
              <td class="tdrow3"><input type="text" name="cloneddisplayname[]" value="'.CleanFormValue($clonedmodule['displayname']).'" size="35" /></td>
              <td class="tdrow2">'.iif($clonedmodule['settingspath'] == '' || !@in_array($clonedmodule['moduleid'], $userinfo['moduleadminids']) , '&nbsp;', '<a href="mymodules.php?moduleid='.$clonedmodule['moduleid'].'"><img alt="设置模块" src="' . $stylepath . 'images/configure.gif" /></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              <a href="modules.php?action=uninstallmodule&moduleid='.$clonedmodule['moduleid'].'"  onclick="return confirm(\'-'.$clonedmodule['name'].'-\n\n确定要删除此模块吗?\');"><img alt="删除此模块" src="' . $stylepath . 'images/trash.gif" /></a>') . '</td>
            </tr>';
    }
  }


  // display the custom plguins
  if($custommodulerows)
  {
    echo '<tr>
            <td class="tdrow1">自定义模块 - 后台名称</td>
            <td class="tdrow1">前台名称</td>
            <td class="tdrow1">设置</td>
          </tr>';

    for($custommodulecount = 0; $custommodule = $DB->fetch_array($getcustommodules); $custommodulecount++)
    {
      echo '<input type="hidden" name="custommoduleid[]" value="'.$custommodule['custommoduleid'].'">
            <tr>
              <td class="tdrow2"><input type="text" name="customname[]" value="'.CleanFormValue($custommodule['name']).'" size="30" /> (ID: '. $custommodule['custommoduleid'] . ')</td>
              <td class="tdrow3"><input type="text" name="customdisplayname[]" value="'.CleanFormValue($custommodule['displayname']).'" size="35" /></td>
              <td class="tdrow2">'.iif(!@in_array($custommodule['custommoduleid'], $userinfo['custommoduleadminids']) , '&nbsp;', '<a href="custommodules.php?action=edit&custommoduleid='.$custommodule['custommoduleid'].'"><img alt="设置模块" src="' . $stylepath . 'images/configure.gif" /></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="modules.php?action=deletecustommodule&custommoduleid='.$custommodule['custommoduleid'].'" onclick="return confirm(\'-'.$custommodule['name'].'-\n\n确定要删除此模块吗?\');"><img alt="删除此模块" src="' . $stylepath . 'images/trash.gif" /></a>') . '</td>
            </tr>';
    }
  }

  // display the downloaded modules
  if($downloadedrows)
  {
    echo '<tr>
            <td class="tdrow1">下载的模块 - 后台名称</td>
            <td class="tdrow1">前台名称</td>
            <td class="tdrow1">设置</td>
          </tr>';

    for($downloadedcount = 0; $downloaded = $DB->fetch_array($getdownloaded); $downloadedcount++)
    {
      echo '<input type="hidden" name="downloadedid[]" value="'.$downloaded['moduleid'].'">
            <tr>
              <td class="tdrow2">'.$downloaded['name'].' (ID: '. $downloaded['moduleid'] . ')</td>
              <td class="tdrow3"><input type="text" name="downloadeddisplayname[]" value="'.CleanFormValue($downloaded['displayname']).'" size="35" /></td>
              <td class="tdrow2">'.iif($downloaded['settingspath'] == '' || !@in_array($downloaded['moduleid'], $userinfo['moduleadminids']) , '&nbsp;', '<a href="mymodules.php?moduleid='.$downloaded['moduleid'].'"><img alt="设置模块" src="' . $stylepath . 'images/configure.gif" /></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              <a href="modules.php?action=uninstallmodule&moduleid='.$downloaded['moduleid'].'"  onclick="return confirm(\'-'.$downloaded['name'].'-\n\n确定要删除此模块吗?\');"><img alt="删除此模块" src="' . $stylepath . 'images/trash.gif" /></a>') . '</td>
            </tr>';
    }
  }

  echo '<tr>
          <td class="tdrow1" colspan="3" align="center">
            <input type="hidden" name="nummodules" value="'.$modulerows.'" />
            <input type="hidden" name="numclonedmodules" value="'.$clonedmodulerows.'" />
            <input type="hidden" name="numcustommodules" value="'.$custommodulerows.'" />
            <input type="hidden" name="numdownloadedmodules" value="'.$downloadedrows.'" />
            <input type="hidden" name="action" value="updatemodulenames" />
            <input type="submit" value="更新模块名称" />
          </td>
        </tr>
        </table>
        </form>';
  EndSection();

}



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

PrintFooter();

?>