<?php

/***************************************************************************

 m_subcontentform.php
 ---------------------
 copyright : (C) 2002-2003 The ezContents Development Team

 ***************************************************************************/

/***************************************************************************
 The ezContents Development Team offers no warranties on this script.
 The owner/licensee of the script is solely responsible for any problems
 caused by installation of the script or use of the script.

 All copyright notices regarding ezContents must remain intact on the
 scripts and in the HTML for the scripts.

 For more info on ezContents,
 visit http://www.ezcontents.org/

/***************************************************************************

/***************************************************************************
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the License which can be found within the
 *   zipped package.
 *
 ***************************************************************************/


$ImageFileTypes = array( 'gif', 'jpg', 'jpeg', 'png');

include_once ("rootdatapath.php");
require_once ($GLOBALS["rootdp"]."include/config.php");
require_once ($GLOBALS["rootdp"]."include/db.php");
require_once ($GLOBALS["rootdp"]."include/session.php");

include ($GLOBALS["rootdp"]."include/access.php");


// Security vet.
// Start by setting all security access to false.
// Do it in the code to overwrite any spurious values that a hacker may
//    have tried to pass in the url
$GLOBALS["specialedit"] = $GLOBALS["canedit"] = $GLOBALS["canadd"] = $GLOBALS["canview"] = False;
$GLOBALS["fieldstatus"] = '';

// Validate the user's level of access for this form.
$GLOBALS["form"] = 'subcontent';
$validaccess = VerifyAdminLogin2();


include ($GLOBALS["rootdp"]."include/settings.php");
include ($GLOBALS["rootdp"]."include/functions.php");
include ("adminfunctions.php");
includeLanguageFiles('admin','subcontent');


$GLOBALS["tabindex"] = 1024;

if (!isset($HTTP_POST_VARS["SCID"])) $HTTP_POST_VARS["SCID"] = $HTTP_GET_VARS["SCID"];
if (!isset($HTTP_POST_VARS["page"])) $HTTP_POST_VARS["page"] = $HTTP_GET_VARS["page"];
if (!isset($HTTP_POST_VARS["sort"])) $HTTP_POST_VARS["sort"] = $HTTP_GET_VARS["sort"];

if ($HTTP_POST_VARS["submitted"] == "yes") {
   if ($HTTP_POST_VARS["SCID"] != '') {
      // User has submitted the data
      if (bCheckForm()) {
         AddSubContent();
         Header("Location: ".BuildLink('m_subcontent.php')."&page=".$HTTP_POST_VARS["page"]);
      } else {
         // Invalid data has been submitted
         GetFormData();
      }
   } else {
      if ($HTTP_POST_VARS["mname"] != '') {
         AddNewModule($HTTP_POST_VARS["mname"]);
      }
      Header("Location: ".BuildLink('m_subcontent.php')."&page=".$HTTP_POST_VARS["page"]);
   }
} else {
   if ($HTTP_GET_VARS["SCID"] != '') {
      // First visit to the form
      GetGlobalData();
   }
}

if (($HTTP_GET_VARS["SCID"] != '') || (!($bFormOK))) {
   frmSubContentForm();
} else {
   frmNewModuleForm();
}

function frmSubContentForm()
{
   global $HTTP_POST_VARS;

   adminformheader();
   adminformopen('mname');
   adminformtitle(4,$GLOBALS["tFormTitle2"]);
   if (isset($GLOBALS["strErrors"])) { formError(4); }
   adminsubheader(4,$GLOBALS["thGeneral"]);
   ?>
   <tr class="tablecontent">
       <?php FieldHeading("ModuleName","mname"); ?>
       <td colspan="3" valign="top" class="content">
           <input type="text" name="mname" size="32" value="<?php echo htmlspecialchars($GLOBALS["fsName"]) ?>" maxlength=32>
       </td>
   </tr>
   <tr class="tablecontent">
       <?php FieldHeading("ModuleTitle","title"); ?>
       <td colspan="3" valign="top" class="content">
           <input type="text" name="title" size="70" value="<?php echo htmlspecialchars($GLOBALS["fsTitle"]) ?>" maxlength=255>
       </td>
   </tr>
   <?php adminsubheader(4,$GLOBALS["thSubmissions"]); ?>
   <tr class="tablecontent">
       <?php FieldHeading("SText","stext"); ?>
       <td colspan="3" valign="top" class="content">
           <input type="text" name="stext" size="70" value="<?php echo htmlspecialchars($GLOBALS["fsText"]) ?>" maxlength=255>
       </td>
   </tr>
   <tr class="tablecontent">
       <?php FieldHeading("STextDisplay","stextdisplay"); ?>
       <td colspan="3" valign="top" class="content">
           <input type="checkbox" name="stextdisplay" value="Y" <?php if($GLOBALS["fsTextDisplay"] == 'Y') echo "checked"?>>
       </td>
   </tr>
   <tr class="tablecontent">
       <?php FieldHeading("SGraphic","sgraphic"); ?>
       <td colspan="3" valign="top" class="content">
           <input type="text" name="sgraphic" size="64" value="<?php echo $GLOBALS["fsGraphic"]; ?>" maxlength=255>
	   <?php adminimagedisplay('sgraphic',$GLOBALS["fsGraphic"],$GLOBALS["tShowBanner"]); ?>
       </td>
   </tr>
   <tr class="tablecontent">
       <?php FieldHeading("SGraphicDisplay","sgraphicdisplay"); ?>
       <td colspan="3" valign="top" class="content">
           <input type="checkbox" name="sgraphicdisplay" value="Y" <?php if($GLOBALS["fsGraphicDisplay"] == 'Y') echo "checked"?>>
       </td>
   </tr>
   <?php adminsubheader(4,$GLOBALS["thSubmissionRules"]); ?>
   <tr class="tablecontent">
       <?php FieldHeading("RegOnly","registered"); ?>
       <td valign="top" class="content">
           <input type="checkbox" name="registered" value="Y" <?php if($GLOBALS["fsRegistered"] == 'Y') echo "checked"?>>
       </td>
       <?php FieldHeading("Usergroups",6); ?>
       <td valign="top" class="content" rowspan="2">
           <select name="usergroups[]" multiple size="4"<?php echo $GLOBALS["fieldstatus"]; ?>><?php RenderUsergroups($GLOBALS["fsUsergroups"]); ?></select>
       </td>
   </tr>
   <tr class="tablecontent">
       <?php FieldHeading("ValReq","validate"); ?>
       <td valign="top" class="content">
           <input type="checkbox" name="validate" value="Y" <?php if($GLOBALS["fsValidate"] == 'Y') echo "checked"?>>
       </td>
       <td valign="top" class="content">
           &nbsp;
       </td>
   </tr>
   <?php adminsubheader(4,$GLOBALS["thDisplay"]); ?>
   <tr class="tablecontent">
       <?php FieldHeading("PerPage","perpage"); ?>
       <td colspan="3" valign="top" class="content">
           <input type="text" name="perpage" size="4" value="<?php echo $GLOBALS["fsPerPage"]; ?>" maxlength="4">
       </td>
   </tr>
   <tr class="tablecontent">
       <?php FieldHeading("UseCategories","usecategories"); ?>
       <td valign="top" class="content">
           <input type="checkbox" name="usecategories" value="Y" <?php if($GLOBALS["fsUseCategories"] == 'Y') echo "checked"?>>
       </td>
       <?php FieldHeading("OrderBy","orderby"); ?>
       <td valign="top" class="content">
           <select name="orderby" size="1"<?php echo $GLOBALS["fieldstatus"]; ?>>
               <option value="C" <?php if($GLOBALS["fsOrderBy"] == "C") echo "selected"; ?>><?php echo $GLOBALS["toCategory"]; ?>
               <option value="D" <?php if($GLOBALS["fsOrderBy"] != "C") echo "selected"; ?>><?php echo $GLOBALS["toDate"]; ?>
           </select>
       </td>
   </tr>
   <tr class="tablecontent">
       <?php FieldHeading("PostedBy","postedby"); ?>
       <td valign="top" class="content">
           <input type="checkbox" name="postedby" value="Y" <?php if($GLOBALS["fsPostedBy"] == 'Y') echo "checked"?>>
       </td>
       <?php FieldHeading("PostedDate","posteddate"); ?>
       <td valign="top" class="content">
           <input type="checkbox" name="posteddate" value="Y" <?php if($GLOBALS["fsPostedDate"] == 'Y') echo "checked"?>>
       </td>
   </tr>
   <?php
   adminformsavebar(4,'m_subcontent.php');
   if ($GLOBALS["specialedit"] == True) {
      adminhelpmsg(4);
      ?><input type="hidden" name="SCID" value="<?php echo $HTTP_POST_VARS["SCID"]; ?>"><?php
   }
   adminformclose();
} // function frmSubContentForm()


function frmNewModuleForm()
{
   adminformheader();
   adminformopen('mname');
   adminformtitle(2,$GLOBALS["tFormTitle2"]);

   echo '<tr class="tablecontent">';
   FieldHeading("ModuleName","mname");
   echo '<td valign="top" class="content">';
   $savedir = getcwd();
   chdir($GLOBALS["rootdp"].'modules');
   $count = 0;
   if ($handle = @opendir('.')) {
      while ($filename = readdir($handle)) {
         if ((is_dir($filename)) && (!($filename == '..') && !($filename == '.'))) {
            $strQuery="SELECT * FROM ".$GLOBALS["eztbModules"]." WHERE moduledirectory='".$filename."'";
            $result = dbRetrieve($strQuery,true,0,1);
            $rs     = dbFetch($result);
            $lRecCount = dbRowsReturned($result);
            if ($lRecCount == 0) {
               $NewModules[] = $filename;
               $count++;
            }
            dbFreeResult($result);
         }
      }
      closedir($handle);
   }
   chdir($savedir);

	echo '<select name="mname" size="1">';
	if ($count > 0) {
		for ($i=0; $i < $count; $i++) {
			echo '<option value="'.$NewModules[$i].'">'.$NewModules[$i];
		}
	} else {
		echo '<option value="">'.$GLOBALS["eNoModules"];
	}
	echo '</select>';

   echo '</td></tr>';
   adminformsavebar(2,'m_subcontent.php');
   adminformclose();
} // function frmNewModuleForm()


function AddSubContent()
{
   global $HTTP_POST_VARS;

   $sTitle = dbString($HTTP_POST_VARS["title"]);
   $sSText = dbString($HTTP_POST_VARS["stext"]);

   $sUserGroups = '';
   if (isset($HTTP_POST_VARS["usergroups"])) {
      reset ($HTTP_POST_VARS["usergroups"]);
      while (list ($userkey, $userval) = each ($HTTP_POST_VARS["usergroups"])) {
         $sUserGroups .= ','.$userval;
      }
   }

   $strQuery = "UPDATE ".$GLOBALS["eztbSpecialcontents"]." SET scname='".$HTTP_POST_VARS["mname"]."', sctitle='".$sTitle."', screg='".$HTTP_POST_VARS["registered"]."', scvalid='".$HTTP_POST_VARS["validate"]."', stext='".$sSText."', stextdisplay='".$HTTP_POST_VARS["stextdisplay"]."', sgraphic='".$HTTP_POST_VARS["sgraphic"]."', sgraphicdisplay='".$HTTP_POST_VARS["sgraphicdisplay"]."', usergroups='".$sUserGroups."', scusecategories='".$HTTP_POST_VARS["usecategories"]."', orderby='".$HTTP_POST_VARS["orderby"]."', showpostedby='".$HTTP_POST_VARS["postedby"]."', showposteddate='".$HTTP_POST_VARS["posteddate"]."', perpage='".$HTTP_POST_VARS["perpage"]."' WHERE scid=".$HTTP_POST_VARS["SCID"];
   $result = dbExecute($strQuery,true);
   dbCommit();
} // function AddSubContent()


function create_module($Module,$DBPrefix,&$Status)
{
   $Status = True;
   $fp = fopen('./'.$Module.'/install.sql', "r");
   if (!$fp) {
      install_message('red','Unable to open '.$Module.' install.sql file');
      $Status = False;
   } else {
      $file = fread($fp, 10485760);
      $file = str_replace("\r", "", $file);
      $query = explode(";\n",$file);
      for ($i=0; $i < count($query) - 1; $i++) {
         if ($Status) {
            $sqlQuery = trim($query[$i]);
            $workquery = explode("\n",$sqlQuery);
            for ($j=0; $j < count($workquery) - 1; $j++) {
               $test_workquery = trim($workquery[$j]);
               if (substr($test_workquery,0,1) == '#') { $workquery[$j] = ''; }
            }
            $sqlQuery = implode("",$workquery);
            if ((substr($sqlQuery,0,4) == 'DROP') || (substr($sqlQuery,0,6) == 'CREATE') || (substr($sqlQuery,0,6) == 'INSERT')) {
               if (substr($sqlQuery,0,4) == 'DROP') {
                  $sqlQuery = str_replace('DROP TABLE IF EXISTS ','DROP TABLE IF EXISTS '.$DBPrefix, $sqlQuery);
               }
               if (substr($sqlQuery,0,6) == 'CREATE') {
                  $sqlQuery = str_replace('CREATE TABLE ','CREATE TABLE '.$DBPrefix, $sqlQuery);
               }
               if (substr($sqlQuery,0,6) == 'INSERT') {
                  $sqlQuery = str_replace('INSERT INTO ','INSERT INTO '.$DBPrefix, $sqlQuery);
               }
               if ($GLOBALS["Log"] == 'Y') { dbWriteLog($sqlQuery); }
               $result = dbExecute($sqlQuery,true);
               if (!$result) { $Status = False; }
            }
         }
      }
      $fp = fclose($fp);
   }
} // function create_module()


function AddNewModule($modulename)
{
	$Status = True;

	$savedir = getcwd();
	chdir($GLOBALS["rootdp"].'modules');
	create_module($modulename,$GLOBALS["eztbMasterPrefix"],$Status);

	if (($Status) && ($GLOBALS["eztbMasterPrefix"] != '')) {
		$sqlQuery = "UPDATE ".$GLOBALS["eztbSpecialcontents"]." SET scuseprefix='Y' WHERE scname='".$modulename."'";
		$result = dbExecute($sqlQuery,true);
		if (!$result) { $Status = False; }
	}

	if ($GLOBALS["gsMultiSite"] == 'Y') {
		if ($Status) {
			$strQuery = "SELECT sitecode FROM ".$GLOBALS["eztbSites"];
			$sresult = dbRetrieve($strQuery,true,0,0);
			while (($Status) && ($rs = dbFetch($sresult))) {
				create_module($modulename,$rs["sitecode"],$Status);
				if ($Status) {
					if ($GLOBALS["eztbMasterPrefix"] != '') {
						$sqlQuery = "UPDATE ".$rs["sitecode"].substr($GLOBALS["eztbSpecialcontents"],strlen($GLOBALS["eztbMasterPrefix"]))." SET scuseprefix='Y' WHERE scname='".$modulename."'";
					} else {
						$sqlQuery = "UPDATE ".$rs["sitecode"].$GLOBALS["eztbSpecialcontents"]." SET scuseprefix='Y' WHERE scname='".$modulename."'";
					}
					$result = dbExecute($sqlQuery,true);
					if (!$result) { $Status = False; }
				}
			}
			dbFreeResult($sresult);
		}
	}

	chdir($savedir);
} // function AddNewModule()


function GetGlobalData()
{
   global $HTTP_GET_VARS;

   $strQuery="SELECT * FROM ".$GLOBALS["eztbSpecialcontents"]." WHERE scid='".$HTTP_GET_VARS["SCID"]."'";
   $result = dbRetrieve($strQuery,true,0,0);
   $rs     = dbFetch($result);

   $GLOBALS["fsName"]           = $rs["scname"];
   $GLOBALS["fsTitle"]          = $rs["sctitle"];
   $GLOBALS["fsRegistered"]     = $rs["screg"];
   $GLOBALS["fsValidate"]       = $rs["scvalid"];
   $GLOBALS["fsText"]           = $rs["stext"];
   $GLOBALS["fsTextDisplay"]    = $rs["stextdisplay"];
   $GLOBALS["fsGraphic"]        = $rs["sgraphic"];
   $GLOBALS["fsGraphicDisplay"] = $rs["sgraphicdisplay"];
   $GLOBALS["fsUsergroups"]     = $rs["usergroups"];
   $GLOBALS["fsUseCategories"]  = $rs["scusecategories"];
   $GLOBALS["fsOrderBy"]        = $rs["orderby"];
   $GLOBALS["fsPostedBy"]       = $rs["showpostedby"];
   $GLOBALS["fsPostedDate"]     = $rs["showposteddate"];
   $GLOBALS["fsPerPage"]        = $rs["perpage"];
   dbFreeResult($result);
} // function GetGlobalData()


function GetFormData()
{
   global $HTTP_POST_VARS;

   $GLOBALS["fsName"]           = $HTTP_POST_VARS["mname"];
   $GLOBALS["fsTitle"]          = $HTTP_POST_VARS["title"];
   $GLOBALS["fsRegistered"]     = $HTTP_POST_VARS["screg"];
   $GLOBALS["fsValidate"]       = $HTTP_POST_VARS["validate"];
   $GLOBALS["fsText"]           = $HTTP_POST_VARS["stext"];
   $GLOBALS["fsTextDisplay"]    = $HTTP_POST_VARS["stextdisplay"];
   $GLOBALS["fsGraphic"]        = $HTTP_POST_VARS["sgraphic"];
   $GLOBALS["fsGraphicDisplay"] = $HTTP_POST_VARS["sgraphicdisplay"];
   $GLOBALS["fsUsergroups"]     = $HTTP_POST_VARS["usergroups"];
   $GLOBALS["fsUseCategories"]  = $HTTP_POST_VARS["usecategories"];
   $GLOBALS["fsOrderBy"]        = $HTTP_POST_VARS["orderby"];
   $GLOBALS["fsPostedBy"]       = $HTTP_POST_VARS["postedby"];
   $GLOBALS["fsPostedDate"]     = $HTTP_POST_VARS["posteddate"];
   $GLOBALS["fsPerPage"]        = $HTTP_POST_VARS["perpage"];
} // function GetFormData()


function RenderUsergroups($GroupNames)
{
   $sqlQuery = "SELECT * FROM ".$GLOBALS["eztbUsergroups"]." WHERE language='".$GLOBALS["gsLanguage"]."' ORDER BY usergroupname";
   $result = dbRetrieve($sqlQuery,true,0,0);
   while ($rs = dbFetch($result)) {
      echo '<option ';
      if (strpos($GroupNames, $rs["usergroupname"], 0)) { echo 'selected '; }
      echo 'value="'.$rs["usergroupname"].'">'.$rs["usergroupdesc"];
   }
   dbFreeResult($result);
} // function RenderUsergroups()


function bCheckForm()
{
   global $HTTP_POST_VARS;

   $bFormOK = true;
   if (!is_numeric($HTTP_POST_VARS["perpage"])) {
      $GLOBALS["strErrors"][] = $GLOBALS["ePerPageNumber"];
   } else {
      if ($HTTP_POST_VARS["perpage"] == 0) {
         $GLOBALS["strErrors"][] = $GLOBALS["ePerPageZero"];
      }
   }

   if (isset($GLOBALS["strErrors"])) { $bFormOK = false; }
   return $bFormOK;
} // function bCheckForm()

include($GLOBALS["rootdp"]."include/javafuncs.php");

?>
