« Предыдущая

Приложение 4. Листинги программных модулей

Access_admin.php

<?php

ini_set("display_errors", "1");

//admin mode access file

session_start();

include("./cfg/connect.inc.php");

if (isset($_POST["authorize"]))
{

if (!strcmp(base64_encode($_POST["login"]), ADMIN_LOGIN) && !strcmp(md5($_POST["password"]), ADMIN_PASS))

{ //login ok
$_SESSION["log"] = ADMIN_LOGIN;
$_SESSION["pass"] = ADMIN_PASS;
//redirect to the admin interface
header("Location: admin.php");
}
else $errorStr = "Invalid login and/or password";
}

?>
<html>
<head>
<link rel=STYLESHEET href="style1.css" type="text/css">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Administrator login</title></head>
<body>
<center>

<?php
if (isset($errorStr)) echo "<font color=red><b>$errorStr</b></font>";
?>

<form name="form1" method="post" action="access_admin.php">
<table border="0" cellpadding="2" cellspacing="1" bgcolor="#333333">
<tr bgcolor="#CCCCCC">
<td colspan="2" align=center><h4>Administrator login</h4></td>
</tr>
<tr bgcolor="#FFFFFF">
<td align="right">Login:</td>
<td>
<input type="text" name="login"<?php if (isset($_POST["login"])) echo ' value="'.str_replace("\"","&quot;",stripslashes($_POST["login"])).'"';?>></td>
</tr>
<tr bgcolor="#FFFFFF">
<td align="right">Password:</td>
<td>
<input type="password" name="password"></td>
</tr>
</table>

<p>
<input type="hidden" name="authorize" value="1">
<input type="submit" value="Login">
</p>
</form>
<p><a href="index.php">Go to front-end...</a></p>
</center>
</body>
</html>

Admin.php
<?php

ini_set("display_errors", "1");

//main admin module

function add_department($admin_dpt)
//adds new $admin_dpt to departments list
{
global $admin_departments;

$i = 0;
while ($i<count($admin_departments) && $admin_departments[$i]["sort_order"] < $admin_dpt["sort_order"]) $i++;
for ($j=count($admin_departments)-1; $j>=$i; $j--)
$admin_departments[$j+1] = $admin_departments[$j];
$admin_departments[$i] = $admin_dpt;
}

function __escape_string($_Data)
{
return str_replace("'", "\'", str_replace('\\', '\\\\', stripslashes($_Data)));
}

include("./cfg/connect.inc.php");
include("./includes/database/mysql.php");
include("./cfg/general.inc.php");
include("./cfg/appearence.inc.php");
include("./cfg/functions.php");
include("./cfg/category_functions.php");
include("./cfg/language_list.php");

session_start();

//authorized login check
include("./checklogin.php");
if (!isset($_SESSION["log"]) || !isset($_SESSION["pass"])) //unauthorized
{
//show authorization form
header("Location: access_admin.php");
die("<script>window.location='access_admin.php';</script>");
}

define('WORKING_THROUGH_ADMIN_SCRIPT', true); //for security purposes

//logout?
if (isset($_GET["logout"])) //logout
{
//show authorization form
$_SESSION["log"] = "";
$_SESSION["pass"] = "";
unset($_SESSION["log"]);
unset($_SESSION["pass"]);
die("<script>window.location='access_admin.php';</script>");
}

//init Smarty
require 'smarty/smarty.class.php';
$smarty = new Smarty; //core smarty object
$smarty_mail = new Smarty; //for e-mails

if (!isset($_SESSION["current_language"]) ||
$_SESSION["current_language"] < 0 || $_SESSION["current_language"] > count($lang_list))
$_SESSION["current_language"] = 0; //set default language

if (isset($lang_list[$_SESSION["current_language"]]) && file_exists("./languages/".$lang_list[$_SESSION["current_language"]]->filename))
include("./languages/".$lang_list[$_SESSION["current_language"]]->filename); //include current language file
else
{
die("<font color=red><b>ERROR: Couldn't find language file!</b></font>");
}

//connect to database
db_connect(DB_HOST,DB_USER,DB_PASS) or die (db_error());
db_select_db(DB_NAME) or die (db_error());

//set Smarty include files dir
$smarty->template_dir = $lang_list[$_SESSION["current_language"]]->template_path."/admin";
$smarty_mail->template_dir = $lang_list[$_SESSION["current_language"]]->template_path."/mail";

//get currency ISO 3 code
$currency_iso_3 = (defined('CONF_CURRENCY_ISO3')) ? CONF_CURRENCY_ISO3 : "USD" ;
$smarty->assign("currency_iso_3", $currency_iso_3);

// several functions

function mark_as_selected($a,$b) //required for excel import
//returns " selected" if $a == $b
{
return !strcmp($a,$b) ? " selected" : "";

} //mark_as_selected

function get_NOTempty_elements_count($arr) //required for excel import
//gets how many NOT NULL (not empty strings) elements are there in the $arr
{
$n = 0;
for ($i=0;$i<count($arr);$i++)
if (trim($arr[$i]) != "") $n++;
return $n;
} //get_NOTempty_elements_count

//end of functions definition

//define department and subdepartment
if (!isset($_GET["dpt"]))
{
$dpt = isset($_POST["dpt"]) ? $_POST["dpt"] : "";
}
else $dpt = $_GET["dpt"];
if (!isset($_GET["sub"]))
{
if (isset($_POST["sub"])) $sub = $_POST["sub"];
}
else $sub = $_GET["sub"];

//define smarty template
$smarty->assign("admin_main_content_template", "default.tpl.html");
$smarty->assign("current_dpt", $dpt);

//get new orders count
$q = db_query("select count(*) from ".ORDERS_TABLE) or die (db_error());
$n = db_fetch_row($q);
$smarty->assign("new_orders_count", $n[0]);

$admin_departments = array();

// includes all .php files from includes/ dir
$includes_dir = opendir("./includes/admin");
$file_count = 0;
while ( ($inc_file = readdir($includes_dir)) != false )
if (strstr($inc_file,".php"))
{
include("./includes/admin/$inc_file");
$file_count++;
}

if (isset($sub)) $smarty->assign("current_sub", $sub);

$smarty->assign("admin_departments", $admin_departments);
$smarty->assign("admin_departments_count", $file_count);

//show Smarty output
$smarty->display($lang_list[$_SESSION["current_language"]]->template_path."admin/index.tpl.html");

?>

Category.php

<?php

ini_set("display_errors", "1");

//ADMIN :: categories managment

include("./cfg/connect.inc.php");
include("./includes/database/mysql.php");
include("./cfg/category_functions.php");
include("./cfg/general.inc.php");

//connect to database
db_connect(DB_HOST,DB_USER,DB_PASS) or die (db_error());
db_select_db(DB_NAME) or die (db_error());

//checking for authorized access
session_start();

//current language
include("./cfg/language_list.php");
if (!isset($_SESSION["current_language"]) ||
$_SESSION["current_language"] < 0 || $_SESSION["current_language"] > count($lang_list))
$_SESSION["current_language"] = 0; //set default language

if (isset($lang_list[$_SESSION["current_language"]]) && file_exists("./languages/".$lang_list[$_SESSION["current_language"]]->filename))
include("./languages/".$lang_list[$_SESSION["current_language"]]->filename); //include current language file
else
{
die("<font color=red><b>ERROR: Couldn't find language file!</b></font>");
}

include("./checklogin.php");
if (!isset($_SESSION["log"]) || strcmp($_SESSION["log"],ADMIN_LOGIN)) //unauthorized
{
die ("You are not authorized to view this page");
}

?><html>

<head>
<link rel=STYLESHEET href="images/backend/style-backend.css" type="text/css">
<meta http-equiv="Content-Type" content="text/html; charset=<?php echo DEFAULT_CHARSET;?>">
<title><?php echo ADMIN_CATEGORY_TITLE;?></title>
<script>
function confirmDelete(text,url)
{
temp = window.confirm(text);
if (temp) //delete
{
window.location=url;
}
}
</script>
</head>

<body bgcolor=#D2D2FF>

<?php
function deleteSubCategories($parent) //deletes all subcategories of category with categoryID=$parent
{


//subcategories
$q = db_query("SELECT categoryID FROM ".CATEGORIES_TABLE." WHERE parent=$parent and categoryID<>0") or die (db_error());
while ($row = db_fetch_row($q))
{
deleteSubCategories($row[0]); //recurrent call
}
$q = db_query("DELETE FROM ".CATEGORIES_TABLE." WHERE parent=$parent and categoryID<>0") or die (db_error());

//move all product of this category to the root category
$q = db_query("UPDATE ".PRODUCTS_TABLE." SET categoryID=0 WHERE categoryID=$parent") or die (db_error());
}

function category_Moves_To_Its_SubDirectories($cid, $new_parent)
{
//return true/false

$a = false;
$q = db_query("SELECT categoryID FROM ".CATEGORIES_TABLE." WHERE parent=$cid and categoryID<>0") or die (db_error());
while ($row = db_fetch_row($q))
{
if ($row[0] == $new_parent) $a = true;
else
$a = category_Moves_To_Its_SubDirectories($row[0],$new_parent);
}
return $a;
}

if (!isset($w)) $w=-1; //parent

if (isset($_GET["picture_remove"])) //delete category thumbnail from server
{
$q = db_query("SELECT picture FROM ".CATEGORIES_TABLE." WHERE categoryID='".$_GET["c_id"]."' and categoryID<>0") or die (db_error());
$r = db_fetch_row($q);
if ($r[0] && file_exists("./products_pictures/$r[0]")) unlink("./products_pictures/$r[0]");
db_query("UPDATE ".CATEGORIES_TABLE." SET picture='' WHERE categoryID='".$_GET["c_id"]."'") or die (db_error());
}

if (isset($_POST["save"]) && $_POST["name"]) { //save changes

if (!isset($_POST["must_delete"])) //add new category
{
$q = db_query("INSERT INTO ".CATEGORIES_TABLE." (name, parent, products_count, description, picture, products_count_admin) VALUES ('".$_POST["name"]."',".$_POST["parent"].",0,'".$_POST["desc"]."','',0)") or die (db_error());
$pid = db_insert_id();
}
else //update existing category
{
if ($_POST["must_delete"] != $_POST["parent"]) //if not moving category to itself
{

//if category is being moved to any of it's subcategories - it's
//neccessary to 'lift up' all it's subcategories

if (category_Moves_To_Its_SubDirectories($_POST["must_delete"], $_POST["parent"]))
{
//lift up is required

//get parent
$q = db_query("SELECT parent FROM ".CATEGORIES_TABLE." WHERE categoryID<>0 and categoryID='".$_POST["must_delete"]."'") or die (db_error());
$r = db_fetch_row($q);

//lift up
db_query("UPDATE ".CATEGORIES_TABLE." SET parent='$r[0]' WHERE parent='".$_POST["must_delete"]."'") or die (db_error());

//move edited category
db_query("UPDATE ".CATEGORIES_TABLE." SET name='".str_replace("<","&lt;",$_POST["name"])."', description='".$_POST["desc"]."', parent='".$_POST["parent"]."' WHERE categoryID='".$_POST["must_delete"]."'") or die (db_error());

}
else //just move category
db_query("UPDATE ".CATEGORIES_TABLE." SET name='".str_replace("<","&lt;",$_POST["name"])."', description='".$_POST["desc"]."', parent='".$_POST["parent"]."' WHERE categoryID='".$_POST["must_delete"]."'") or die (db_error());
}
$pid = $_POST["must_delete"];

update_products_Count_Value_For_Categories(0);

}

if (isset($_FILES["picture"]) && $_FILES["picture"]["name"] && preg_match('/\.(jpg|jpeg|gif|jpe|pcx|bmp)$/i', $_FILES["picture"]["name"])) //upload category thumbnail
{

//old picture
$q = db_query("SELECT picture FROM ".CATEGORIES_TABLE." WHERE categoryID='$pid' and categoryID<>0") or die (db_error());
$row = db_fetch_row($q);

//upload new photo
$picture_name = str_replace(" ","_", $_FILES["picture"]["name"]);
if (!move_uploaded_file($_FILES["picture"]["tmp_name"], "./products_pictures/$picture_name")) //failed to upload
{
echo "<center><font color=red>".ERROR_FAILED_TO_UPLOAD_FILE."</font>\n<br><br>\n";
echo "<a href=\"javascript:window.close();\">".CLOSE_BUTTON."</a></center></body>\n</html>";
exit;
}
else //update db
{
db_query("UPDATE ".CATEGORIES_TABLE." SET picture='$picture_name' WHERE categoryID='$pid'") or die (db_error());
SetRightsToUploadedFile( "./products_pictures/".$picture_name );
}

//remove old picture...
if ($row[0] && strcmp($row[0], $picture_name) && file_exists("./products_pictures/$row[0]"))
unlink("./products_pictures/$row[0]");

}

//now close the window (in case of success)
echo "<script>\n";
echo "window.opener.location.reload();\n";
echo "window.close();\n";
echo "</script>\n</body>\n</html>";
}
else { //category edition from

if (isset($_GET["c_id"])) //edit existing category
{
$q = db_query("SELECT name, description, picture FROM ".CATEGORIES_TABLE." WHERE categoryID='".$_GET["c_id"]."' and categoryID<>0") or die (db_error());
$row = db_fetch_row($q);
if (!$row) //can't find category....
{
echo "<center><font color=red>".ERROR_CANT_FIND_REQUIRED_PAGE."</font>\n<br><br>\n";
echo "<a href=\"javascript:window.close();\">".CLOSE_BUTTON."</a></center></body>\n</html>";
exit;
}
$title = "<b>$row[0]</b>";
$n = $row[0];
$d = $row[1];
$picture = $row[2];

if (isset($_GET["del"])) //delete category
{

//photo
$q = db_query("SELECT picture FROM ".CATEGORIES_TABLE." WHERE categoryID='".$_GET["c_id"]."' and categoryID<>0") or die (db_error());
$r = db_fetch_row($q);
if ($r[0] && file_exists("./products_pictures/$r[0]")) unlink("./products_pictures/$r[0]");

//delete from db
$q = db_query("DELETE FROM ".CATEGORIES_TABLE." WHERE categoryID='".$_GET["c_id"]."' and categoryID<>0") or die (db_error());

deleteSubCategories($_GET["c_id"]);

update_products_Count_Value_For_Categories(0);

//close window
echo "<script>\n";
echo "window.opener.location.reload();\n";
echo "window.close();";
echo "</script>\n</body>\n</html>";
}
}
else //create new
{
$title = ADMIN_CATEGORY_NEW;
$n = "";
$d = "";
$picture = "";
}

?>

<center><font color=purple><?php echo $title; ?></font></center>
<form enctype="multipart/form-data" action="category.php" method=post>

<table width=100% border=0>
<tr>
<td align=right>
<?php
if (!isset($_GET["c_id"])) echo ADMIN_CATEGORY_PARENT;
else echo ADMIN_CATEGORY_MOVE_TO;
?>
</td>
<td width=5%>&nbsp;</td>
<td>
<select name="parent">
<option value="0"><?php echo ADMIN_CATEGORY_ROOT;?></option>
<?php
//fill the category combobox
$tmp = isset($_GET["w"]) ? $_GET["w"] : $_POST["parent"];
$cats = fillTheCList(0,0);
for ($i=0; $i<count($cats); $i++)
{
echo "<option value=\"".$cats[$i][0]."\"";
if ($tmp == $cats[$i][0]) //select category
echo " selected";
echo ">";
for ($j=0;$j<$cats[$i][5];$j++) echo "&nbsp;&nbsp;";
echo $cats[$i][1];
echo "</option>";
}
?>
</select>
</td>
</tr>

<tr>
<td align=right><?php echo ADMIN_CATEGORY_NAME;?></td>
<td>&nbsp;</td>
<td><input type="text" name="name" value="<?php echo str_replace("\"","&quot;",$n); ?>" size=13></td>
</tr>

<tr>
<td align=right><?php echo ADMIN_CATEGORY_LOGO;?></td>
<td>&nbsp;</td>
<td><input type="file" name="picture"></td>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>
<?php
if ($picture != "" && file_exists("./products_pictures/".$picture))
{
echo "<font class=average></font> <a class=small href=\"products_pictures/".$picture."\">$picture</a>\n";
echo "<br><a href=\"javascript:confirmDelete('".QUESTION_DELETE_PICTURE."','category.php?c_id=".$_GET["c_id"]."&w=".$_GET["w"]."&picture_remove=yes');\">".DELETE_BUTTON."</a>\n";
}
else echo "<font class=average>".ADMIN_PICTURE_NOT_UPLOADED."</font>";
?>
</td>
</tr>

<tr>
<td align=right><?php echo ADMIN_CATEGORY_DESC;?><br>(HTML)</td>
<td></td>
<td><textarea name="desc" rows=7 cols=22><?php echo str_replace("\"","&quot;",$d); ?></textarea></td>
</tr>

</table>
<p><center>
<input type="submit" value="<?php echo SAVE_BUTTON;?>" width=5>
<input type="hidden" name="save" value="yes">
<input type="button" value="<?php echo CANCEL_BUTTON;?>" onClick="window.close();">
<?php
//$must_delete indicated which query should be made: insert/update
if (isset($_GET["c_id"]))
{
echo "<input type=\"hidden\" name=\"must_delete\" value=\"".str_replace("\"","",$_GET["c_id"])."\">\n";
echo "<input type=\"button\" value=\"".DELETE_BUTTON."\" onClick=\"confirmDelete('".QUESTION_DELETE_CONFIRMATION."','category.php?c_id=".str_replace("\"","",$_GET["c_id"])."&del=1');\"";
}
?>
</center></p>
</form>

</body>

</html>
<?php }; ?>

Index.php

<?php

//core file

ini_set("display_errors", "1");

// -------------------------INITIALIZATION-----------------------------//

//make sure that URL does not contain something like index.php/?parameter1=1&... //

//include core files
include("./cfg/connect.inc.php");
include("./includes/database/mysql.php");
include("./cfg/general.inc.php");
include("./cfg/appearence.inc.php");
include("./cfg/functions.php");
include("./cfg/category_functions.php");
include("./cfg/language_list.php");

session_start();

ini_set("display_errors", "1");

//init Smarty
require 'smarty/smarty.class.php';
$smarty = new Smarty; //core smarty object
$smarty_mail = new Smarty; //for e-mails

//select a new language?
if (isset($_POST["new_language"]))
{
$_SESSION["current_language"] = $_POST["new_language"];
}

//current language session variable
if (!isset($_SESSION["current_language"]) ||
$_SESSION["current_language"] < 0 || $_SESSION["current_language"] > count($lang_list))
$_SESSION["current_language"] = 0; //set default language
//include a language file
if (isset($lang_list[$_SESSION["current_language"]]) && file_exists("./languages/".$lang_list[$_SESSION["current_language"]]->filename))
include("./languages/".$lang_list[$_SESSION["current_language"]]->filename); //include current language file
else
{
die("<font color=red><b>ERROR: Couldn't find language file!</b></font>");
}

//connect to the database
db_connect(DB_HOST,DB_USER,DB_PASS) or die (db_error());
db_select_db(DB_NAME) or die (db_error());

//get currency ISO 3 code
$currency_iso_3 = (defined('CONF_CURRENCY_ISO3')) ? CONF_CURRENCY_ISO3 : "USD" ;
$smarty->assign("currency_iso_3", $currency_iso_3);

//load all categories to array $cats to avoid multiple DB queries (frequently used in future - but not always!)
$cats = array();
$i=0;
$q = db_query("SELECT categoryID, name, parent, products_count, description, picture FROM ".CATEGORIES_TABLE." where categoryID<>0 ORDER BY name") or die (db_error());
while ($row = db_fetch_row($q))
{
$cats[$i++] = $row;
}

//set $categoryID
if (isset($_GET["categoryID"]) || isset($_POST["categoryID"]))
$categoryID = isset($_GET["categoryID"]) ? $_GET["categoryID"] : $_POST["categoryID"];
else $categoryID = 0;

$categoryID = (int)$categoryID;

//$productID
if (!isset($_GET["productID"]))
{
if (isset($_POST["productID"]))
{
$productID = (int)$_POST["productID"];
}
}
else
{
$productID = (int)$_GET["productID"];
}

//and different vars...
if (isset($_GET["register"]) || isset($_POST["register"]))
$register = isset($_GET["register"]) ? $_GET["register"] : $_POST["register"];
if (isset($_GET["update_details"]) || isset($_POST["update_details"]))
$update_details = isset($_GET["update_details"]) ? $_GET["update_details"] : $_POST["update_details"];
if (isset($_GET["order"]) || isset($_POST["order"]))
$order = isset($_GET["order"]) ? $_GET["order"] : $_POST["order"];
if (isset($_GET["check_order"]) || isset($_POST["check_order"]))
$check_order = isset($_GET["check_order"]) ? $_GET["check_order"] : $_POST["check_order"];
if (isset($_GET["proceed_ordering"]) || isset($_POST["proceed_ordering"]))
$proceed_ordering = isset($_GET["proceed_ordering"]) ? $_GET["proceed_ordering"] : $_POST["proceed_ordering"];

if (!isset($_SESSION["vote_completed"])) $_SESSION["vote_completed"] = array();

//checking for proper $offset init
$offset = isset($_GET["offset"]) ? $_GET["offset"] : 0;
if ($offset<0 || $offset % CONF_PRODUCTS_PER_PAGE) $offset = 0;

// -------------SET SMARTY VARS AND INCLUDE SOURCE FILES------------//

if (isset($productID)) //to rollout categories navigation table
{
$q = db_query("SELECT categoryID FROM ".PRODUCTS_TABLE." WHERE productID='$productID'") or die (db_error());
$r = db_fetch_row($q);
if ($r) $categoryID = $r[0];
}

//set Smarty include files dir
$smarty->template_dir = $lang_list[$_SESSION["current_language"]]->template_path;
$smarty_mail->template_dir = $lang_list[$_SESSION["current_language"]]->template_path."/mail";

//assign core Smarty variables

$smarty->assign("lang_list", $lang_list);
$smarty->assign("lang_list_count", count($lang_list));

if (isset($_SESSION["current_language"])) $smarty->assign("current_language", $_SESSION["current_language"]);
// - following vars are used as hidden in the customer survey form
$smarty->assign("categoryID", $categoryID);
if (isset($productID)) $smarty->assign("productID", $productID);
if (isset($_GET["currency"])) $smarty->assign("currency", $_GET["currency"]);
if (isset($_GET["user_details"])) $smarty->assign("user_details", $_GET["user_details"]);
if (isset($_GET["aux_page"])) $smarty->assign("aux_page", $_GET["aux_page"]);
if (isset($_GET["show_price"])) $smarty->assign("show_price", $_GET["show_price"]);
if (isset($_GET["adv_search"])) $smarty->assign("adv_search", $_GET["adv_search"]);
if (isset($_GET["searchstring"])) $smarty->assign("searchstring", $_GET["searchstring"]);
if (isset($register)) $smarty->assign("register", $register);
if (isset($order)) $smarty->assign("order", $order);
if (isset($check_order)) $smarty->assign("check_order", $check_order);

//set defualt main_content template to homepage
$smarty->assign("main_content_template", "home.tpl.html");
// includes all .php files from includes/ dir
$includes_dir = opendir("./includes");
while ( ($inc_file = readdir($includes_dir)) != false )
if (strstr($inc_file,".php"))
{
include("./includes/$inc_file");
}

// output:

//security warnings!
if (file_exists("./install.php"))
{
echo "<center>".WARNING_DELETE_INSTALL_PHP."</center>";
}
if (file_exists("./forgot_password.php"))
{
echo "<center>".WARNING_DELETE_FORGOTPW_PHP."</center>";
}

if (!is_writable("./products_pictures") || !is_writable("./templates_c"))
{
echo "<center>".WARNING_WRONG_CHMOD."</center>";
}

//show administrative mode link if logged in as administrator
include("./checklogin.php");
if (isset($_SESSION["log"]) && isset($_SESSION["pass"]))
echo "<br><center><a href=\"admin.php\"><font color=red>".ADMINISTRATE_LINK."</font></a></center><p>";

//show Smarty output
$smarty->display($lang_list[$_SESSION["current_language"]]->template_path."index.tpl.html");

?>

Product.php

<?php

//ADMIN :: products managment

ini_set("display_errors", "1");

include("./cfg/connect.inc.php");
include("./includes/database/mysql.php");
include("./cfg/category_functions.php");
include("./cfg/general.inc.php");

//connect 2 database
db_connect(DB_HOST,DB_USER,DB_PASS) or die (db_error());
db_select_db(DB_NAME) or die (db_error());

session_start();
include("./checklogin.php");
if (!isset($_SESSION["log"]) || strcmp($_SESSION["log"],ADMIN_LOGIN)) //unauthorized
{
die ("You are not authorized to view this page");
}

//get currency ISO 3 code
$currency_iso_3 = (defined('CONF_CURRENCY_ISO3')) ? CONF_CURRENCY_ISO3 : "USD" ;

//current language
include("./cfg/language_list.php");
if (!isset($_SESSION["current_language"]) ||
$_SESSION["current_language"] < 0 || $_SESSION["current_language"] > count($lang_list))
$_SESSION["current_language"] = 0; //set default language

if (isset($lang_list[$_SESSION["current_language"]]) && file_exists("./languages/".$lang_list[$_SESSION["current_language"]]->filename))
include("./languages/".$lang_list[$_SESSION["current_language"]]->filename); //include current language file
else
{
die("<font color=red><b>ERROR: Couldn't find language file!</b></font>");
}

if (!isset($_GET["productID"])) $_GET["productID"] = 0;

if (isset($_POST["save_product"])) //save item to the database
{

if (!isset($_POST["price"]) || !$_POST["price"] || $_POST["price"] < 0)
$_POST["price"] = 0; //price can not be negative

if (!isset($_POST["name"]) || trim($_POST["name"])=="") $_POST["name"] = "not defined";

$instock = (isset($_POST["in_stock"])) ? 1 : 0;

if ($_POST["save_product"]) { //if $_POST["save_product"] != 0 then update item

//delete old product photos if they're being replaced

$q = db_query("SELECT picture, big_picture, thumbnail FROM ".PRODUCTS_TABLE." WHERE productID='".$_POST["save_product"]."'") or die (db_error());
$row = db_fetch_row($q);

//generating query

$s = "UPDATE ".PRODUCTS_TABLE." SET categoryID='".$_POST["categoryID"]."', name='".$_POST["name"]."', Price='".$_POST["price"]."', description='".$_POST["description"]."', in_stock=".$instock.", customers_rating='".$_POST["rating"]."', brief_description='".$_POST["brief_description"]."', list_price='".$_POST["list_price"]."', product_code='".$_POST["product_code"]."'";

$s1 = "";

//old pictures?
if (isset($_FILES["picture"]) && $_FILES["picture"]["name"])
{
//delete old picture
if ($row[0] && file_exists("./products_pictures/".$row[0]))
unlink("./products_pictures/".$row[0]);
}
if (isset($_FILES["big_picture"]) && $_FILES["big_picture"]["name"])
{
//delete old picture
if ($row[1] && file_exists("./products_pictures/".$row[1]))
unlink("./products_pictures/".$row[1]);
}
if (isset($_FILES["thumbnail"]) && $_FILES["thumbnail"]["name"])
{
//delete old picture
if ($row[2] && file_exists("./products_pictures/".$row[2]))
unlink("./products_pictures/".$row[2]);
}

$pid = $_POST["save_product"];

}
else
{
//add new product
db_query("INSERT INTO ".PRODUCTS_TABLE." (categoryID, name, description, customers_rating, Price, in_stock, customer_votes, items_sold, enabled, brief_description, list_price, product_code, picture, thumbnail, big_picture) VALUES ('".$_POST["categoryID"]."','".$_POST["name"]."','".$_POST["description"]."', 0, '".$_POST["price"]."', ".$instock.", 0, 0, 1, '".$_POST["brief_description"]."', '".$_POST["list_price"]."', '".$_POST["product_code"]."','','','');") or die (db_error());
$pid = db_insert_id();

$dont_update = 1; //don't update product

$s  = "";
$s1 = "UPDATE ".PRODUCTS_TABLE." SET categoryID=categoryID";
}

//add pictures?
//regular photo
if (isset($_FILES["picture"]) && $_FILES["picture"]["name"] && preg_match('/\.(jpg|jpeg|gif|jpe|pcx|bmp)$/i', $_FILES["picture"]["name"])) //upload
{
$_FILES["picture"]["name"] = str_replace(" ","_",$_FILES["picture"]["name"]);
$r = move_uploaded_file($_FILES["picture"]["tmp_name"], "./products_pictures/".$_FILES["picture"]["name"]);
if (!$r) //failed 2 upload
{
echo "<center><font color=red>".ERROR_FAILED_TO_UPLOAD_FILE."</font>\n<br><br>\n";
echo "<a href=\"javascript:window.close();\">".CLOSE_BUTTON."</a></center></body>\n</html>";
exit;
}

SetRightsToUploadedFile( "./products_pictures/".$_FILES["picture"]["name"] );

$s .= ", picture='".$_FILES["picture"]["name"]."'";
$s1.= ", picture='".$_FILES["picture"]["name"]."'";
}
//enlarged photo
if (isset($_FILES["big_picture"]) && $_FILES["big_picture"]["name"] && preg_match('/\.(jpg|jpeg|gif|jpe|pcx|bmp)$/i', $_FILES["big_picture"]["name"]))
{
$_FILES["big_picture"]["name"] = str_replace(" ","_",$_FILES["big_picture"]["name"]);
$r = move_uploaded_file($_FILES["big_picture"]["tmp_name"], "./products_pictures/".$_FILES["big_picture"]["name"]);
if (!$r) //failed 2 upload
{
echo "<center><font color=red>".ERROR_FAILED_TO_UPLOAD_FILE."</font>\n<br><br>\n";
echo "<a href=\"javascript:window.close();\">".CLOSE_BUTTON."</a></center></body>\n</html>";
exit;
}

SetRightsToUploadedFile( "./products_pictures/".$_FILES["big_picture"]["name"] );

$s .= ", big_picture='".$_FILES["big_picture"]["name"]."'";
$s1.= ", big_picture='".$_FILES["big_picture"]["name"]."'";
}
//thumbnail
if (isset($_FILES["thumbnail"]) && $_FILES["thumbnail"]["name"] && preg_match('/\.(jpg|jpeg|gif|jpe|pcx|bmp)$/i', $_FILES["thumbnail"]["name"]))
{
$_FILES["thumbnail"]["name"] = str_replace(" ","_",$_FILES["thumbnail"]["name"]);
$r = move_uploaded_file($_FILES["thumbnail"]["tmp_name"], "./products_pictures/".$_FILES["thumbnail"]["name"]);
if (!$r) //failed 2 upload
{
echo "<center><font color=red>".ERROR_FAILED_TO_UPLOAD_FILE."</font>\n<br><br>\n";
echo "<a href=\"javascript:window.close();\">".CLOSE_BUTTON."</a></center></body>\n</html>";
exit;
}

SetRightsToUploadedFile( "./products_pictures/".$_FILES["thumbnail"]["name"] );

$s .= ", thumbnail='".$_FILES["thumbnail"]["name"]."'";
$s1.= ", thumbnail='".$_FILES["thumbnail"]["name"]."'";
}

if (!isset($dont_update)) //update product info
{
$s .= " WHERE productID='".$_POST["save_product"]."'";
db_query($s) or die (db_error());
$productID = $_POST["save_product"];
}
else //don't update (insert query is already completed)
{
$s1.= " WHERE productID=$pid";
db_query($s1) or die (db_error());
$productID = $pid;
}

update_products_Count_Value_For_Categories(0);

//close window
echo "<script>\n";
echo "window.opener.location.reload();\n";
echo "window.close();\n";
echo "</script>\n</body>\n</html>";
exit;
}
else //get product from db
{
if ($_GET["productID"])
{

$q = db_query("SELECT categoryID, name, description, customers_rating, Price, picture, in_stock, thumbnail, big_picture, brief_description, list_price, product_code FROM ".PRODUCTS_TABLE." WHERE productID='".$_GET["productID"]."'") or die (db_error());
$row = db_fetch_row($q);
if (!$row) //product wasn't found
{
echo "<center><font color=red>".ERROR_CANT_FIND_REQUIRED_PAGE."</font>\n<br><br>\n";
echo "<a href=\"javascript:window.close();\">".CLOSE_BUTTON."</a></center></body>\n</html>";
exit;
}

if (isset($_GET["picture_remove"])) //delete items picture from server if requested
{
if ($_GET["picture_remove"] && file_exists("./products_pictures/".$row[$_GET["picture_remove"]]))
unlink("./products_pictures/".$row[$_GET["picture_remove"]]);
$picture = "none";
}

if (isset($_GET["delete"])) //delete product
{
//at first photos...
if ($row[5] != "none" && $row[5] != "" && file_exists("./products_pictures/".$row[5]))
unlink("./products_pictures/".$row[5]);
if ($row[7] != "none" && $row[7] != "" && file_exists("./products_pictures/".$row[7]))
unlink("./products_pictures/".$row[7]);
if ($row[8] != "none" && $row[8] != "" && file_exists("./products_pictures/".$row[8]))
unlink("./products_pictures/".$row[8]);

$q = db_query("DELETE FROM ".PRODUCTS_TABLE." WHERE productID='".$_GET["productID"]."'") or die (db_error());

//close window
echo "<script>\n";
echo "window.opener.location.reload();\n";
echo "window.close();\n";
echo "</script>\n</body>\n</html>";
exit;
}

$title = $row[1];

}
else //creating new item
{
$title = ADMIN_PRODUCT_NEW;
$cat = isset($_GET["categoryID"]) ? $_GET["categoryID"] : 0;
$row = array($cat,"","","",0,"",1,"","","",0,"");
}
}

?>

<html>

<head>
<link rel=STYLESHEET href="images/backend/style-backend.css" type="text/css">
<meta http-equiv="Content-Type" content="text/html; charset=<?php echo DEFAULT_CHARSET;?>">
<title><?php echo ADMIN_PRODUCT_TITLE;?></title>
<script>
function confirmDelete(question, where)
{
temp = window.confirm(question);
if (temp) //delete
{
window.location=where;
}
}
function open_window(link,w,h) //opens new window
{
var win = "width="+w+",height="+h+",menubar=no,location=no,resizable=yes,scrollbars=yes";
wishWin = window.open(link,'wishWin',win);
}
</script>
</head>

<body bgcolor=#FFFFE2>
<center>
<p>
<b><?php echo $title; ?></b>

<form enctype="multipart/form-data" action="products.php" method=post>

<table width=100% border=0 cellpadding=3 cellspacing=0>

<tr>
<td align=right><?php echo ADMIN_CATEGORY_PARENT;?></td>
<td>
<select name="categoryID">
<option value="0"><?php echo ADMIN_CATEGORY_ROOT;?></option>
<?php
//show categories select element
$cats = fillTheCList(0,0);
for ($i=0; $i<count($cats); $i++)
{
echo "<option value=\"".$cats[$i][0]."\"";
if ($row[0] == $cats[$i][0]) //select category
echo " selected";
echo ">";
for ($j=0;$j<$cats[$i][5];$j++) echo "&nbsp;&nbsp;";
echo $cats[$i][1];
echo "</option>";
}
?>
</select>
</td>
</tr>

<tr>
<td align=right><?php echo ADMIN_PRODUCT_NAME;?></td>
<td><input type="text" name="name" value="<?php echo str_replace("\"","&quot;",$row[1]); ?>"></td>
</tr>

<tr>
<td align=right><?php echo ADMIN_PRODUCT_CODE;?></td>
<td><input type="text" name="product_code" value="<?php echo str_replace("\"","&quot;",$row[11]); ?>"></td>
</tr>

<?php        if ($_GET["productID"]) { ?>
<tr>
<td align=right><?php echo ADMIN_PRODUCT_RATING;?>:</td>
<td><input type=text name="rating" value="<?php echo str_replace("\"","&quot;",$row[3]); ?>"></b></td>
</tr>

<?php }; ?>

<tr>

<td align=right><?php echo ADMIN_PRODUCT_PRICE;?>, <?php echo $currency_iso_3; ?><br>(<?php echo STRING_NUMBER_ONLY;?>):</td>
<td><input type="text" name="price" value=<?php echo $row[4]; ?>></td>
</tr>

<tr>
<td align=right><?php echo ADMIN_PRODUCT_LISTPRICE;?>, <?php echo $currency_iso_3; ?><br>(<?php echo STRING_NUMBER_ONLY;?>):</td>
<td><input type="text" name="list_price" value=<?php echo $row[10]; ?>></td>
</tr>

<?php
if ($row[6]<0) $is = 0;
else $is = $row[6];

?>
<tr>
<td align=right><?php echo ADMIN_PRODUCT_INSTOCK;?>:</td>
<td><input type="checkbox" name="in_stock"<?php if ($is > 0) echo " checked"; ?>></td>
</tr>

<tr><td>&nbsp;</td></tr>

<tr>
<td align=right><?php echo ADMIN_PRODUCT_PICTURE;?></td>
<td><input type="file" name="picture"></td>
<tr><td></td><td>
<?php
if ($row[5]!="" && file_exists("./products_pictures/".$row[5]))
{
echo "<a class=small href=\"products_pictures/".$row[5]."\">$row[5]</a>\n";
echo "<br><a href=\"javascript:confirmDelete('".QUESTION_DELETE_PICTURE."','products.php?productID=".$_GET["productID"]."&picture_remove=5');\">".DELETE_BUTTON."</a>\n";
}
else echo "<font class=average color=brown>".ADMIN_PICTURE_NOT_UPLOADED."</font>";
?>
</td>
</tr>
<tr>
<td align=right><?php echo ADMIN_PRODUCT_THUMBNAIL;?></td>
<td><input type="file" name="thumbnail"></td>
<tr><td></td><td>
<?php
if ($row[7]!="" && file_exists("./products_pictures/".$row[7]))
{
echo "<a class=small href=\"products_pictures/".$row[7]."\">$row[7]</a>\n";
echo "<br><a href=\"javascript:confirmDelete('".QUESTION_DELETE_PICTURE."','products.php?productID=".$_GET["productID"]."&picture_remove=7');\">".DELETE_BUTTON."</a>\n";
}
else echo "<font class=average color=brown>".ADMIN_PICTURE_NOT_UPLOADED."</font>";
?>
</td>
</tr>
<tr>
<td align=right><?php echo ADMIN_PRODUCT_BIGPICTURE;?></td>
<td valign=top><input type="file" name="big_picture"></td>
<tr><td></td><td valign=top>
<?php
if ($row[8] && file_exists("./products_pictures/".$row[8]))
{
echo "<a class=small href=\"products_pictures/".$row[8]."\">$row[8]</a>\n";
echo "<br><a href=\"javascript:confirmDelete('".QUESTION_DELETE_PICTURE."','products.php?productID=".$_GET["productID"]."&picture_remove=8');\">".DELETE_BUTTON."</a>\n";
}
else echo "<font class=average color=brown>".ADMIN_PICTURE_NOT_UPLOADED."</font>";
?>
</td>
</tr>

<tr>
<td align=right><?php echo ADMIN_PRODUCT_DESC;?><br>(HTML):</td>
<td><textarea name="description" rows=15 cols=40><?php echo str_replace("<","&lt;",$row[2]); ?></textarea></td>
</tr>

<tr>
<td align=right><?php echo ADMIN_PRODUCT_BRIEF_DESC;?><br>(HTML):</td>
<td><textarea name="brief_description" rows=7 cols=40><?php echo str_replace("<","&lt;",$row[9]); ?></textarea></td>
</tr>

</table>

<p><center>
<input type="submit" value="<?php echo SAVE_BUTTON;?>" width=5>
<input type="hidden" name="save_product" value=<?php echo $_GET["productID"]; ?>>
<input type="button" value="<?php echo CANCEL_BUTTON;?>" onClick="window.close();">
<?php        if ($_GET["productID"]) echo "<input type=button value=\"".DELETE_BUTTON."\" onClick=\"confirmDelete('".QUESTION_DELETE_CONFIRMATION."','products.php?productID=".$_GET["productID"]."&delete=1');\">"; ?>
</center></p>
</form>

</center>
</body>

</html>

index.tpl.html

<html>

{include file="head.tpl.html"}

<body marginwidth="0" marginheight="0" leftmargin="0" topmargin="0" background="images/background.png">

<script type="text/javascript" src="images/niftycube.js"></script>

<center>
<table width="1000" border="0" cellspacing="0" cellpadding="0">
<tr>
<td bgcolor="white"><table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td valign="bottom" width="220">
<a href="index.php"><img src="images/companyname.jpg"  valign=""  width="220" height="50" border="0" alt="{$smarty.const.CONF_SHOP_NAME}"></a>
</td>
<td valign="bottom" width="400">
<table id="tabnav" border="0" cellspacing="0" cellpadding="0" >
<tr valign="top" align="center">
<td>&nbsp;&nbsp;&nbsp;&nbsp;</td>
<td><div {if $main_content_template == "home.tpl.html"} class="topmenu_selected"{else} class="topmenu_notselected"{/if}><a href="index.php" class="menu">{$smarty.const.LINK_TO_HOMEPAGE}</a></div></td>
<td>&nbsp;</td>
<td><div {if $main_content_template == "pricelist.tpl.html"} class="topmenu_selected"{else} class="topmenu_notselected"{/if}><a href="index.php?show_price=yes" class="menu">{$smarty.const.STRING_PRICELIST}</a></div></td>
<td>&nbsp;</td>
<td><div {if ($main_content_template == "aux_page.tpl.html") && ($aux_page == "aux1")} class="topmenu_selected"{else} class="topmenu_notselected"{/if}><a href="index.php?aux_page=aux1" class="menu"><nobr>{$smarty.const.ADMIN_ABOUT_PAGE}</nobr></a></div></td>
<td>&nbsp;</td>
<td><div {if ($main_content_template == "aux_page.tpl.html") && ($aux_page == "aux2")} class="topmenu_selected"{else} class="topmenu_notselected"{/if}><a href="index.php?aux_page=aux2" class="menu">{$smarty.const.ADMIN_SHIPPING_PAGE}</a></div></td>

</tr>
</table>
</td>
<td valign="middle" align="right" style="background: #ffffff url(images/gradientbg1.gif) repeat-y; background-position: right; height:70px; width:160px;">
<center>
{include file="language.tpl.html"}

{include file="search_form.tpl.html"}</center>
<a href="index.php?search_with_change_category_ability=yes" class="lightsmall"></a>
</td>
</tr>
<tr>
<td bgcolor="white" height="6" align="right"><img src="images/gradient-dark-strip.gif"></td>
<td bgcolor="#7ba05b" colspan="2" height="6"></td> <!-- Главная?-->
</tr>
<tr>
<td width="220" valign="top" align="right">
<table cellspacing="0" cellpadding="0" border="0"><tr><td style="background: white url(images/gradientbg2.gif) repeat-y; background-position: right;width:220px;height:100%;">

<p style="padding:10px;">

<table width="200" border="0" align="right" cellpadding="0" cellspacing="0">
{if $smarty.const.CONF_SHOW_ADD2CART eq 1}
<tr>
<td align="left" valign="top" bgcolor="#7ba05b" class="topcorners"><!-- Корзина-->
<div style="padding:5px;font-size:130%;">
<a href="index.php?shopping_cart=yes" class="menu">{$smarty.const.CART_TITLE}</a>
</div>
</td>
</tr>
<tr>
<td style="background: #cadaba; background-position: right; padding: 10px;" class="bottomcorners">
{include file="shopping_cart_info.tpl.html"}
</td>
</tr>
<tr>
<td>&nbsp;</td>
</tr>
{/if}
<tr>
<td align="left" valign="top" bgcolor="#7ba05b" class="topcorners"> <!-- Каталог-->
<div style="padding:5px;font-size:130%;">
<a href="index.php#catalog" class="menu">{$smarty.const.ADMIN_CATALOG}</a>
</div>
</td>
</tr>
<tr>
<td align="left" valign="top" style="background: #cadaba; background-position: right; padding: 10px;" class="bottomcorners">
{include file="category_tree.tpl.html"}
</td>
</tr>
<!-- Контакты-->
<tr>
<td>&nbsp;</td>
</tr>
<tr>
<td align="left" valign="top" bgcolor="#7ba05b" class="topcorners"> <!-- Контакты-->
<p class=menu1>Контакты</p>
</div>
</td>
</tr>
<tr>
<td align="left" valign="top" style="background: #cadaba; background-position: right; padding: 10px;" class="bottomcorners">
Телефон +7(495) 456-90-09<br>
ICQ - 567-678-098<br>
Адрес:<br>
Москва, ул. Калинина д. 6В офис 1
</td>
</tr>

</table>
</p>

</td></tr>
<tr><td align="right"><img src="images/gradientbg3.gif" border="0" width="200" height="121"></td></tr>
</table>
</td>
<td width="100%" align="left" valign="top" style="padding:10px;" colspan="2">

{include file="$main_content_template"}

</td>
</tr>
<tr>
<td>&nbsp;</td>
<td colspan="2" align="center">

<hr width="300" align="center" size="1" style="margin-top:0px;">

<p class="small" align="center" style="margin-top:-5px;"><i>Copyright &copy; <a href="{$smarty.const.CONF_FULL_SHOP_URL}"> <u>{$smarty.const.CONF_SHOP_NAME}</u></a>. All rights reserved.</i></p>

</td>
</tr>
</table></td>
</tr>
</table>

<script type="text/javascript">
{literal}
if ( ! (navigator.userAgent.indexOf('Opera') != -1) )
{
Nifty("div.topmenu_notselected,div.topmenu_selected","top transparent");

Nifty("td.topcorners","tl transparent")
var tt_layers= getElementsBySelector("td.topcorners");
for(var k=0, len=tt_layers.length; k<len; k++)
{
tt_layers[k].parentNode.style.backgroundColor = "#e0e7ff";
}
Nifty("td.topcorners","tr transparent");

Nifty("td.bottomcorners","bl transparent");
var tt_layers= getElementsBySelector("td.bottomcorners");
for(var k=0, len=tt_layers.length; k<len; k++)
{
tt_layers[k].parentNode.style.backgroundColor = "#e0e7ff";
}
Nifty("td.bottomcorners","br transparent");
}
{/literal}
</script>
<!--
конец кода nifty
-->

</body>
</html>

« Предыдущая
Похожие публикации
Роль психологических и биологических факторов в исследовании женской преступности
Дипломная работа по теме "Роль психологических и биологических факторов в исследовании женской преступности" состоит из 65 страниц.
Разработка методики реинжиниринга архитектурных и промышленных комплексов с целью создания информационных моделей для систем управления данными объектами
Диплом «Разработка методики создания информационных моделей для систем управления гражданскими и промышленными строительными объектами» содержит 125 страниц, 30 рисунков, 22 таблицы.
Вопросы духовно-нравственного воспитания младшего школьника
Диплом "Вопросы духовно-нравственного воспитания младшего школьника" состоит из 80 страниц. Содержит таблицы, задания, игры, упражнения.
Целостное развитие творческого воображения в дидактической игре «необитаемый остров»
Дипломная работа "Целостное развитие творческого воображения в дидактической игре «необитаемый остров»" по специальности «Педагогическая психология».
Разработка системы «Умный дом»
Бакалаврская работа «Разработка системы «Умный дом»». Объём работы - 59 страниц, на которых размещены 23 рисунка и 4 таблицы.