description = "Русский (win1251)"; $LangRu->filename = "russian.php"; $LangRu->iso2 = "ru"; $lang_list['ru'] = $LangRu; //ru-utf-8 $LangRuUtf8 = new Language(); $LangRuUtf8->description = "Русский (utf-8)"; $LangRuUtf8->filename = "russian-utf8.php"; $LangRuUtf8->iso2 = "ru-utf8"; $lang_list['ru-utf8'] = $LangRuUtf8; #pl-utf8 $LangPlUtf8 = new Language(); $LangPlUtf8->description = "Polska"; $LangPlUtf8->filename = "polska-utf8.php"; $LangPlUtf8->iso2 = "pl-utf8"; $lang_list['pl-utf8'] = $LangPlUtf8; ?> "text/javascript", "xml" => "text/plain", // In XMLHttpRequest mode we must return text/plain - stupid Opera 8.0. :( "form" => "text/html", "" => "text/plain", // for unknown loader ); // Internal: conversion to UTF-8 JSON cancelled because of non-ascii key. var $_toUtfFailed = false; // Internal: list of characters 128...255 (for strpbrk() ASCII check). var $_nonAsciiChars = ''; // Which Unicode conversion function is available? var $_unicodeConvMethod = null; // Emergency memory buffer to be freed on memory_limit error. var $_emergBuffer = null; /** * Constructor. * * Create new JsHttpRequest backend object and attach it * to script output buffer. As a result - script will always return * correct JavaScript code, even in case of fatal errors. * * QUERY_STRING is in form of: PHPSESSID=&a=aaa&b=bbb&JsHttpRequest=- * where is a request ID, is a loader name, - a session ID (if present), * PHPSESSID - session parameter name (by default = "PHPSESSID"). * * If an object is created WITHOUT an active AJAX query, it is simply marked as * non-active. Use statuc method isActive() to check. */ function JsHttpRequest($enc) { global $JsHttpRequest_Active; // Parse QUERY_STRING. if (preg_match('/^(.*)(?:&|^)JsHttpRequest=(?:(\d+)-)?([^&]+)((?:&|$).*)$/s', @$_SERVER['QUERY_STRING'], $m)) { $this->ID = $m[2]; $this->LOADER = strtolower($m[3]); $_SERVER['QUERY_STRING'] = preg_replace('/^&+|&+$/s', '', preg_replace('/(^|&)'.session_name().'=[^&]*&?/s', '&', $m[1] . $m[4])); unset( $_GET['JsHttpRequest'], $_REQUEST['JsHttpRequest'], $_GET[session_name()], $_POST[session_name()], $_REQUEST[session_name()] ); // Detect Unicode conversion method. $this->_unicodeConvMethod = function_exists('mb_convert_encoding')? 'mb' : (function_exists('iconv')? 'iconv' : null); // Fill an emergency buffer. We erase it at the first line of OB processor // to free some memory. This memory may be used on memory_limit error. $this->_emergBuffer = str_repeat('a', 1024 * 200); // Intercept fatal errors via display_errors (seems it is the only way). $this->_uniqHash = md5('JsHttpRequest' . microtime() . getmypid()); $this->_prevDisplayErrors = ini_get('display_errors'); ini_set('display_errors', $this->_magic); // ini_set('error_prepend_string', $this->_uniqHash . ini_get('error_prepend_string')); ini_set('error_append_string', ini_get('error_append_string') . $this->_uniqHash); // Start OB handling early. ob_start(array(&$this, "_obHandler")); $JsHttpRequest_Active = false; // Set up the encoding. $this->setEncoding($enc); // Check if headers are already sent (see Content-Type library usage). // If true - generate a debug message and exit. $file = $line = null; $headersSent = version_compare(PHP_VERSION, "4.3.0") < 0? headers_sent() : headers_sent($file, $line); if ($headersSent) { trigger_error( "HTTP headers are already sent" . ($line !== null? " in $file on line $line" : " somewhere in the script") . ". " . "Possibly you have an extra space (or a newline) before the first line of the script or any library. " . "Please note that JsHttpRequest uses its own Content-Type header and fails if " . "this header cannot be set. See header() function documentation for more details", E_USER_ERROR ); exit(); } } else { $this->ID = 0; $this->LOADER = 'unknown'; $JsHttpRequest_Active = false; } } /** * Static function. * Returns true if JsHttpRequest output processor is currently active. * * @return boolean True if the library is active, false otherwise. */ function isActive() { return !empty($GLOBALS['JsHttpRequest_Active']); } /** * string getJsCode() * * Return JavaScript part of the library. */ function getJsCode() { return file_get_contents(dirname(__FILE__) . '/JsHttpRequest.js'); } /** * void setEncoding(string $encoding) * * Set an active script encoding & correct QUERY_STRING according to it. * Examples: * "windows-1251" - set plain encoding (non-windows characters, * e.g. hieroglyphs, are totally ignored) * "windows-1251 entities" - set windows encoding, BUT additionally replace: * "&" -> "&" * hieroglyph -> &#XXXX; entity */ function setEncoding($enc) { // Parse an encoding. preg_match('/^(\S*)(?:\s+(\S*))$/', $enc, $p); $this->SCRIPT_ENCODING = strtolower(!empty($p[1])? $p[1] : $enc); $this->SCRIPT_DECODE_MODE = !empty($p[2])? $p[2] : ''; // Manually parse QUERY_STRING because of damned Unicode's %uXXXX. $this->_correctSuperglobals(); } /** * string quoteInput(string $input) * * Quote a string according to the input decoding mode. * If entities are used (see setEncoding()), no '&' character is quoted, * only '"', '>' and '<' (we presume that '&' is already quoted by * an input reader function). * * Use this function INSTEAD of htmlspecialchars() for $_GET data * in your scripts. */ function quoteInput($s) { if ($this->SCRIPT_DECODE_MODE == 'entities') return str_replace(array('"', '<', '>'), array('"', '<', '>'), $s); else return htmlspecialchars($s); } /** * Convert a PHP scalar, array or hash to JS scalar/array/hash. This function is * an analog of json_encode(), but it can work with a non-UTF8 input and does not * analyze the passed data. Output format must be fully JSON compatible. * * @param mixed $a Any structure to convert to JS. * @return string JavaScript equivalent structure. */ function php2js($a=false) { if (is_null($a)) return 'null'; if ($a === false) return 'false'; if ($a === true) return 'true'; if (is_scalar($a)) { if (is_float($a)) { // Always use "." for floats. $a = str_replace(",", ".", strval($a)); } // All scalars are converted to strings to avoid indeterminism. // PHP's "1" and 1 are equal for all PHP operators, but // JS's "1" and 1 are not. So if we pass "1" or 1 from the PHP backend, // we should get the same result in the JS frontend (string). // Character replacements for JSON. static $jsonReplaces = array( array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"') ); return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"'; } $isList = true; for ($i = 0, reset($a); $i < count($a); $i++, next($a)) { if (key($a) !== $i) { $isList = false; break; } } $result = array(); if ($isList) { foreach ($a as $v) { $result[] = JsHttpRequest::php2js($v); } return '[ ' . join(', ', $result) . ' ]'; } else { foreach ($a as $k => $v) { $result[] = JsHttpRequest::php2js($k) . ': ' . JsHttpRequest::php2js($v); } return '{ ' . join(', ', $result) . ' }'; } } /** * Internal methods. */ /** * Parse & decode QUERY_STRING. */ function _correctSuperglobals() { // In case of FORM loader we may go to nirvana, everything is already parsed by PHP. if ($this->LOADER == 'form') return; // ATTENTION!!! // HTTP_RAW_POST_DATA is only accessible when Content-Type of POST request // is NOT default "application/x-www-form-urlencoded"!!! // Library frontend sets "application/octet-stream" for that purpose, // see JavaScript code. In PHP 5.2.2.HTTP_RAW_POST_DATA is not set sometimes; // in such cases - read the POST data manually from the STDIN stream. $rawPost = strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') == 0? (isset($GLOBALS['HTTP_RAW_POST_DATA'])? $GLOBALS['HTTP_RAW_POST_DATA'] : @file_get_contents("php://input")) : null; $source = array( '_GET' => !empty($_SERVER['QUERY_STRING'])? $_SERVER['QUERY_STRING'] : null, '_POST'=> $rawPost, ); foreach ($source as $dst=>$src) { // First correct all 2-byte entities. $s = preg_replace('/%(?!5B)(?!5D)([0-9a-f]{2})/si', '%u00\\1', $src); // Now we can use standard parse_str() with no worry! $data = null; parse_str($s, $data); $GLOBALS[$dst] = $this->_ucs2EntitiesDecode($data); } $GLOBALS['HTTP_GET_VARS'] = $_GET; // deprecated vars $GLOBALS['HTTP_POST_VARS'] = $_POST; $_REQUEST = (isset($_COOKIE)? $_COOKIE : array()) + (isset($_POST)? $_POST : array()) + (isset($_GET)? $_GET : array()); if (ini_get('register_globals')) { // TODO? } } /** * Called in case of error too! */ function _obHandler($text) { unset($this->_emergBuffer); // free a piece of memory for memory_limit error unset($GLOBALS['JsHttpRequest_Active']); // Check for error & fetch a resulting data. if (preg_match("/{$this->_uniqHash}(.*?){$this->_uniqHash}/sx", $text, $m)) { if (!ini_get('display_errors') || (!$this->_prevDisplayErrors && ini_get('display_errors') == $this->_magic)) { // Display_errors: // 1. disabled manually after the library initialization, or // 2. was initially disabled and is not changed $text = str_replace($m[0], '', $text); // strip whole error message } else { $text = str_replace($this->_uniqHash, '', $text); } } if ($m && preg_match('/\bFatal error(<.*?>)?:/i', $m[1])) { // On fatal errors - force null result (generate 500 error). $this->RESULT = null; } else { // Make a resulting hash. if (!isset($this->RESULT)) { $this->RESULT = isset($GLOBALS['_RESULT'])? $GLOBALS['_RESULT'] : null; } } $encoding = $this->SCRIPT_ENCODING; $result = array( 'id' => $this->ID, 'js' => $this->RESULT, 'text' => $text, ); if (function_exists('array_walk_recursive') && function_exists('json_encode') && $this->_unicodeConvMethod) { $encoding = "UTF-8"; $this->_nonAsciiChars = join("", array_map('chr', range(128, 255))); $this->_toUtfFailed = false; array_walk_recursive($result, array(&$this, '_toUtf8_callback'), $this->SCRIPT_ENCODING); if (!$this->_toUtfFailed) { // If some key contains non-ASCII character, convert everything manually. $text = json_encode($result); } else { $text = $this->php2js($result); } } else { $text = $this->php2js($result); } // Content-type header. // In XMLHttpRequest mode we must return text/plain - damned stupid Opera 8.0. :( $ctype = !empty($this->_contentTypes[$this->LOADER])? $this->_contentTypes[$this->LOADER] : $this->_contentTypes['']; header("Content-type: $ctype; charset=$encoding"); if ($this->LOADER != "xml") { // In non-XML mode we cannot use plain JSON. So - wrap with JS function call. // If top.JsHttpRequestGlobal is not defined, loading is aborted and // iframe is removed, so - do not call dataReady(). $text = "" . ($this->LOADER == "form"? 'top && top.JsHttpRequestGlobal && top.JsHttpRequestGlobal' : 'JsHttpRequest') . ".dataReady(" . $text . ")\n" . ""; if ($this->LOADER == "form") { $text = ''; } } return $text; } /** * Internal function, used in array_walk_recursive() before json_encode() call. * If a key contains non-ASCII characters, this function sets $this->_toUtfFailed = true, * becaues array_walk_recursive() cannot modify array keys. */ function _toUtf8_callback(&$v, $k, $fromEnc) { if ($v === null || is_bool($v)) return; if ($this->_toUtfFailed || !is_scalar($v) || strpbrk($k, $this->_nonAsciiChars) !== false) { $this->_toUtfFailed = true; } else { $v = $this->_unicodeConv($fromEnc, 'UTF-8', $v); } } /** * Decode all %uXXXX entities in string or array (recurrent). * String must not contain %XX entities - they are ignored! */ function _ucs2EntitiesDecode($data) { if (is_array($data)) { $d = array(); foreach ($data as $k=>$v) { $d[$this->_ucs2EntitiesDecode($k)] = $this->_ucs2EntitiesDecode($v); } return $d; } else { if (strpos($data, '%u') !== false) { // improve speed $data = preg_replace_callback('/%u([0-9A-F]{1,4})/si', array(&$this, '_ucs2EntitiesDecodeCallback'), $data); } return $data; } } /** * Decode one %uXXXX entity (RE callback). */ function _ucs2EntitiesDecodeCallback($p) { $hex = $p[1]; $dec = hexdec($hex); if ($dec === "38" && $this->SCRIPT_DECODE_MODE == 'entities') { // Process "&" separately in "entities" decode mode. $c = "&"; } else { if ($this->_unicodeConvMethod) { $c = @$this->_unicodeConv('UCS-2BE', $this->SCRIPT_ENCODING, pack('n', $dec)); } else { $c = $this->_decUcs2Decode($dec, $this->SCRIPT_ENCODING); } if (!strlen($c)) { if ($this->SCRIPT_DECODE_MODE == 'entities') { $c = '&#' . $dec . ';'; } else { $c = '?'; } } } return $c; } /** * Wrapper for iconv() or mb_convert_encoding() functions. * This function will generate fatal error if none of these functons available! * * @see iconv() */ function _unicodeConv($fromEnc, $toEnc, $v) { if ($this->_unicodeConvMethod == 'iconv') { return iconv($fromEnc, $toEnc, $v); } return mb_convert_encoding($v, $toEnc, $fromEnc); } /** * If there is no ICONV, try to decode 1-byte characters manually * (for most popular charsets only). */ /** * Convert from UCS-2BE decimal to $toEnc. */ function _decUcs2Decode($code, $toEnc) { if ($code < 128) return chr($code); if (isset($this->_encTables[$toEnc])) { // TODO: possible speedup by using array_flip($this->_encTables) and later hash access in the constructor. $p = array_search($code, $this->_encTables[$toEnc]); if ($p !== false) return chr(128 + $p); } return ""; } /** * UCS-2BE -> 1-byte encodings (from #128). */ var $_encTables = array( 'windows-1251' => array( 0x0402, 0x0403, 0x201A, 0x0453, 0x201E, 0x2026, 0x2020, 0x2021, 0x20AC, 0x2030, 0x0409, 0x2039, 0x040A, 0x040C, 0x040B, 0x040F, 0x0452, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x0098, 0x2122, 0x0459, 0x203A, 0x045A, 0x045C, 0x045B, 0x045F, 0x00A0, 0x040E, 0x045E, 0x0408, 0x00A4, 0x0490, 0x00A6, 0x00A7, 0x0401, 0x00A9, 0x0404, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x0407, 0x00B0, 0x00B1, 0x0406, 0x0456, 0x0491, 0x00B5, 0x00B6, 0x00B7, 0x0451, 0x2116, 0x0454, 0x00BB, 0x0458, 0x0405, 0x0455, 0x0457, 0x0410, 0x0411, 0x0412, 0x0413, 0x0414, 0x0415, 0x0416, 0x0417, 0x0418, 0x0419, 0x041A, 0x041B, 0x041C, 0x041D, 0x041E, 0x041F, 0x0420, 0x0421, 0x0422, 0x0423, 0x0424, 0x0425, 0x0426, 0x0427, 0x0428, 0x0429, 0x042A, 0x042B, 0x042C, 0x042D, 0x042E, 0x042F, 0x0430, 0x0431, 0x0432, 0x0433, 0x0434, 0x0435, 0x0436, 0x0437, 0x0438, 0x0439, 0x043A, 0x043B, 0x043C, 0x043D, 0x043E, 0x043F, 0x0440, 0x0441, 0x0442, 0x0443, 0x0444, 0x0445, 0x0446, 0x0447, 0x0448, 0x0449, 0x044A, 0x044B, 0x044C, 0x044D, 0x044E, 0x044F, ), 'koi8-r' => array( 0x2500, 0x2502, 0x250C, 0x2510, 0x2514, 0x2518, 0x251C, 0x2524, 0x252C, 0x2534, 0x253C, 0x2580, 0x2584, 0x2588, 0x258C, 0x2590, 0x2591, 0x2592, 0x2593, 0x2320, 0x25A0, 0x2219, 0x221A, 0x2248, 0x2264, 0x2265, 0x00A0, 0x2321, 0x00B0, 0x00B2, 0x00B7, 0x00F7, 0x2550, 0x2551, 0x2552, 0x0451, 0x2553, 0x2554, 0x2555, 0x2556, 0x2557, 0x2558, 0x2559, 0x255A, 0x255B, 0x255C, 0x255d, 0x255E, 0x255F, 0x2560, 0x2561, 0x0401, 0x2562, 0x2563, 0x2564, 0x2565, 0x2566, 0x2567, 0x2568, 0x2569, 0x256A, 0x256B, 0x256C, 0x00A9, 0x044E, 0x0430, 0x0431, 0x0446, 0x0434, 0x0435, 0x0444, 0x0433, 0x0445, 0x0438, 0x0439, 0x043A, 0x043B, 0x043C, 0x043d, 0x043E, 0x043F, 0x044F, 0x0440, 0x0441, 0x0442, 0x0443, 0x0436, 0x0432, 0x044C, 0x044B, 0x0437, 0x0448, 0x044d, 0x0449, 0x0447, 0x044A, 0x042E, 0x0410, 0x0411, 0x0426, 0x0414, 0x0415, 0x0424, 0x0413, 0x0425, 0x0418, 0x0419, 0x041A, 0x041B, 0x041C, 0x041d, 0x041E, 0x041F, 0x042F, 0x0420, 0x0421, 0x0422, 0x0423, 0x0416, 0x0412, 0x042C, 0x042B, 0x0417, 0x0428, 0x042d, 0x0429, 0x0427, 0x042A ), ); } ?>keystring=''; for($i=0;$i<$length;$i++){ $this->keystring.=$allowed_symbols{mt_rand(0,strlen($allowed_symbols)-1)}; } if(!preg_match('/cp|cb|ck|c6|c9|rn|rm|mm|co|do|cl|db|qp|qb|dp/', $this->keystring)) break; } $font_file=$fonts[mt_rand(0, count($fonts)-1)]; $font=imagecreatefrompng($font_file); imagealphablending($font, true); $fontfile_width=imagesx($font); $fontfile_height=imagesy($font)-1; $font_metrics=array(); $symbol=0; $reading_symbol=false; // loading font for($i=0;$i<$fontfile_width && $symbol<$alphabet_length;$i++){ $transparent = (imagecolorat($font, $i, 0) >> 24) == 127; if(!$reading_symbol && !$transparent){ $font_metrics[$alphabet{$symbol}]=array('start'=>$i); $reading_symbol=true; continue; } if($reading_symbol && $transparent){ $font_metrics[$alphabet{$symbol}]['end']=$i; $reading_symbol=false; $symbol++; continue; } } $img=imagecreatetruecolor($width, $height); imagealphablending($img, true); $white=imagecolorallocate($img, 255, 255, 255); $black=imagecolorallocate($img, 0, 0, 0); imagefilledrectangle($img, 0, 0, $width-1, $height-1, $white); // draw text $x=1; for($i=0;$i<$length;$i++){ $m=$font_metrics[$this->keystring{$i}]; $y=mt_rand(-$fluctuation_amplitude, $fluctuation_amplitude)+($height-$fontfile_height)/2+2; if($no_spaces){ $shift=0; if($i>0){ $shift=1000; for($sy=7;$sy<$fontfile_height-20;$sy+=1){ //for($sx=$m['start']-1;$sx<$m['end'];$sx+=1){ for($sx=$m['start']-1;$sx<$m['end'];$sx+=1){ $rgb=imagecolorat($font, $sx, $sy); $opacity=$rgb>>24; if($opacity<127){ $left=$sx-$m['start']+$x; $py=$sy+$y; if($py>$height) break; for($px=min($left,$width-1);$px>$left-12 && $px>=0;$px-=1){ $color=imagecolorat($img, $px, $py) & 0xff; if($color+$opacity<190){ if($shift>$left-$px){ $shift=$left-$px; } break; } } break; } } } if($shift==1000){ $shift=mt_rand(4,6); } } }else{ $shift=1; } imagecopy($img,$font,$x-$shift,$y,$m['start'],1,$m['end']-$m['start'],$fontfile_height); $x+=$m['end']-$m['start']-$shift; } if($x<$width-10) break; // fit in canvas } $center=$x/2; // credits. To remove, see configuration file $img2=imagecreatetruecolor($width, $height+($show_credits?12:0)); $foreground=imagecolorallocate($img2, $foreground_color[0], $foreground_color[1], $foreground_color[2]); $background=imagecolorallocate($img2, $background_color[0], $background_color[1], $background_color[2]); imagefilledrectangle($img2, 0, $height, $width-1, $height+12, $foreground); $credits=empty($credits)?$_SERVER['HTTP_HOST']:$credits; imagestring($img2, 2, $width/2-ImageFontWidth(2)*strlen($credits)/2, $height-2, $credits, $background); // periods $rand1=mt_rand(750000,1200000)/10000000; $rand2=mt_rand(750000,1200000)/10000000; $rand3=mt_rand(750000,1200000)/10000000; $rand4=mt_rand(750000,1200000)/10000000; // phases $rand5=mt_rand(0,3141592)/500000; $rand6=mt_rand(0,3141592)/500000; $rand7=mt_rand(0,3141592)/500000; $rand8=mt_rand(0,3141592)/500000; // amplitudes $rand9=mt_rand(330,420)/110; $rand10=mt_rand(330,450)/110; //wave distortion for($x=0;$x<$width;$x++){ for($y=0;$y<$height;$y++){ $sx=$x+(sin($x*$rand1+$rand5)+sin($y*$rand3+$rand6))*$rand9-$width/2+$center+1; $sy=$y+(sin($x*$rand2+$rand7)+sin($y*$rand4+$rand8))*$rand10; if($sx<0 || $sy<0 || $sx>=$width-1 || $sy>=$height-1){ $color=255; $color_x=255; $color_y=255; $color_xy=255; }else{ $color=imagecolorat($img, $sx, $sy) & 0xFF; $color_x=imagecolorat($img, $sx+1, $sy) & 0xFF; $color_y=imagecolorat($img, $sx, $sy+1) & 0xFF; $color_xy=imagecolorat($img, $sx+1, $sy+1) & 0xFF; } if($color==0 && $color_x==0 && $color_y==0 && $color_xy==0){ $newred=$foreground_color[0]; $newgreen=$foreground_color[1]; $newblue=$foreground_color[2]; }else if($color==255 && $color_x==255 && $color_y==255 && $color_xy==255){ $newred=$background_color[0]; $newgreen=$background_color[1]; $newblue=$background_color[2]; }else{ $frsx=$sx-floor($sx); $frsy=$sy-floor($sy); $frsx1=1-$frsx; $frsy1=1-$frsy; $newcolor=( $color*$frsx1*$frsy1+ $color_x*$frsx*$frsy1+ $color_y*$frsx1*$frsy+ $color_xy*$frsx*$frsy); if($newcolor>255) $newcolor=255; $newcolor=$newcolor/255; $newcolor0=1-$newcolor; $newred=$newcolor0*$foreground_color[0]+$newcolor*$background_color[0]; $newgreen=$newcolor0*$foreground_color[1]+$newcolor*$background_color[1]; $newblue=$newcolor0*$foreground_color[2]+$newcolor*$background_color[2]; } imagesetpixel($img2, $x, $y, imagecolorallocate($img2, $newred, $newgreen, $newblue)); } } if(function_exists("imagejpeg")){ header("Content-Type: image/jpeg"); imagejpeg($img2, null, $jpeg_quality); }else if(function_exists("imagegif")){ header("Content-Type: image/gif"); imagegif($img2); }else if(function_exists("imagepng")){ header("Content-Type: image/x-png"); imagepng($img2); } } // returns keystring function getKeyString(){ return $this->keystring; } } ?> LanguageDir = 'core/modules/payment/languages/'; $this->ModuleType = PAYMENT_MODULE; $this->MethodsTable = PAYMENT_TYPES_TABLE; virtualModule::virtualModule($_ModuleConfigID); } // ***************************************************************************** // Purpose html form to get information from customer about payment, // this functions does not return
tags - these tags are already defined in // the // Inputs // Remarks // Returns nothing function payment_form_html() { return ""; } // ***************************************************************************** // Purpose core payment processing routine // Inputs $order is array with the following elements: // "customer_email" - customer's email address // "customer_ip" - customer IP address // "order_amount" - total order amount (in conventional units) // "currency_code" - currency ISO 3 code (e.g. USD, GBP, EUR) // "currency_value" - currency exchange rate defined in the backend in 'Configuration' -> 'Currencies' section // "shipping_info" - shipping information - array of the following data: // "first_name", "last_name", "country_name", "state", "city", "address" // "billing_info" - billing information - array of the following data: // "first_name", "last_name", "country_name", "state", "city", "address" // Remarks function payment_process($order) { return 1; } // ***************************************************************************** // Purpose PHP code executed after order has been placed // Inputs // Remarks // Returns function after_processing_php($orderID) { return ""; } // ***************************************************************************** // Purpose html code printed after order has been placed and after_processing_php // has been executed // Inputs // Remarks // Returns function after_processing_html( $orderID ) { return ""; } } ?>LanguageDir = 'core/modules/shipping/languages/'; $this->ModuleType = SHIPPING_RATE_MODULE; $this->MethodsTable = SHIPPING_METHODS_TABLE; virtualModule::virtualModule($_ModuleConfigID); } function _getServiceType($_ServiceID){ $ShippingTypes = $this->_getShippingTypes(); foreach ($ShippingTypes as $_Type=>$_Services) if(in_array($_ServiceID, $_Services)) return $_Type; return ''; } function _convertDecLBStoPoundsOunces($_Dec){ return array( 'lbs' => floor($_Dec), 'oz' => ceil(16*($_Dec - floor($_Dec))), ); } /** * Return list of rates for services * * @param array $_Services * @param array $order * @param array $address */ function _getRates(&$_Services, $order, $address){ $Query = $this->_prepareQuery($_Services, $order, $address); $Answer = $this->_sendQuery($Query); $parsedAnswer = $this->_parseAnswer($Answer); $newServices = array(); $_TC = count($_Services); for ( $_ind=0; $_ind<$_TC; $_ind++ ){ $_Service = &$_Services[$_ind]; if(isset($parsedAnswer[$_Service['id']])) foreach ($parsedAnswer[$_Service['id']] as $_indV=>$_Variant){ $newServices[] = array( 'id' => sprintf("%02d%02d", $_Service['id'], $_indV), 'name' => $_Variant['name'], 'rate' => $_Variant['rate'], ); } } $_Services = $newServices; } /** * Return information by available shipping services * The same for all shipping modules * * @param array $order * @param array $address * @param integer $_shServiceID * @return array 'name'=>'', 'id'=>, 'rate'=>'' */ function calculate_shipping_rate($order, $address, $_shServiceID = 0){ $_shServiceID = (int)$_shServiceID; if($_shServiceID>99){ if(strlen($_shServiceID)<4)$_shServiceID = sprintf("%04d", $_shServiceID); $_orinServiceID = $_shServiceID; list($_shServiceID, $_serviceOffset) = sscanf($_shServiceID, "%02d%02d"); } $Rates = array(); if($_shServiceID){ $AvailableServices = $this->getShippingServices(); $Rates[] = array( 'name' => (isset($AvailableServices[$_shServiceID]['name'])?$AvailableServices[$_shServiceID]['name']:''), 'code' => (isset($AvailableServices[$_shServiceID]['code'])?$AvailableServices[$_shServiceID]['code']:''), 'id' => $_shServiceID, 'rate' => 0, ); }else { $AvailableServices = $this->_getServicesByCountry($address['countryID']); foreach ($AvailableServices as $_Service){ $_Service['rate'] = 0; $Rates[] = $_Service; } } $this->_getRates($Rates, $order, $address); if(isset($_orinServiceID)){ if(isset($Rates[$_serviceOffset])){ $Rates = array($Rates[$_serviceOffset]); }else { $Rates = array(array( 'name' => '', 'id' => 0, 'rate' => 0, )); } } if(is_array($Rates) && !count($Rates)){ $Rates = array(array( 'name' => '', 'id' => 0, 'rate' => 0, )); } return $Rates; } #заглушка function allow_shipping_to_address(){ return true; } /** * Convert from one Measurement to another Measurement * * @param unknown_type $_Units * @param unknown_type $_From * @param unknown_type $_To */ function _convertMeasurement($_Units, $_From, $_To){ switch (strtolower($_From).'_'.strtolower($_To)){ case 'lb_kg': case 'lbs_kgs': case 'lbs_kg': case 'lb_kgs': $_Units = $_Units/2.2046; break; case 'kg_lb': case 'kg_lbs': case 'kgs_lb': case 'kgs_lbs': $_Units = $_Units*2.2046; break; case 'g_lb': case 'g_lbs': $_Units = $_Units/1000*2.2046; break; case 'lb_g': case 'lbs_g': $_Units = $_Units/2.2046*1000; break; case 'g_kg': case 'g_kgs': $_Units = $_Units/1000; } return $_Units; } function _getOrderWeight(&$Order){ $TC = count($Order['orderContent']['cart_content']); $OrderWeight = 0; $ShippingProducts = 0; for( $i = 0; $i<$TC; $i++ ){ $Product = GetProduct($Order['orderContent']['cart_content'][$i]['productID']); if($Product['free_shipping'])continue; $ShippingProducts++; if(!isset($Product['weight']))continue; if(!$Product['weight'])continue; $OrderWeight += $Order['orderContent']['cart_content'][$i]['quantity']*$Product['weight']; } if($OrderWeight<=0 && $ShippingProducts)$OrderWeight=0.1; return $OrderWeight; } function _getOrderpSumm(&$Order){ $TC = count($Order['orderContent']['cart_content']); $OrderpSumm = 0; $ShippingProducts = 0; for( $i = 0; $i<$TC; $i++ ){ $Product = GetProduct($Order['orderContent']['cart_content'][$i]['productID']); if($Product['free_shipping'])continue; $ShippingProducts++; $OrderpSumm += $Order['orderContent']['cart_content'][$i]['quantity']*$Order['orderContent']['cart_content'][$i]['costUC']; } return $OrderpSumm; } function _getShippingProducts($_Order){ $Products = array(); $_TC = count($_Order['orderContent']['cart_content'])-1; for (; $_TC>=0;$_TC--){ if($_Order['orderContent']['cart_content'][$_TC]['free_shipping'])continue; $Products[] = $_Order['orderContent']['cart_content'][$_TC]; } return $Products; } /* abstract methods */ /** * Return array of shipping types */ function _getShippingTypes(){ return array(); } /** * Return services for country * * @param integer $_CountryID - country id */ function _getServicesByCountry(){ return $this->getShippingServices(); } /** * Return list of shipping services * * @param string $_Type shipping type (Domestic, Inrenational) * @return array */ function getShippingServices(){return array();} function _prepareQuery(&$_Services, $order, $address){ return $this->_prepareXMLQuery($_Services, $order, $address); } function _sendQuery($_Query){ return $this->_sendXMLQuery($_Query); } function _parseAnswer($_Answer){ return $this->_parseXMLAnswer($_Answer); } function _sendXMLQuery(){ } function _prepareXMLQuery(){ } function _parseXMLAnswer(){;} } ?>resParser = xml_parser_create (); xml_set_object($this->resParser,$this); xml_set_element_handler($this->resParser, "tagOpen", "tagClosed"); xml_set_character_data_handler($this->resParser, "tagData"); $this->strXmlData = xml_parse($this->resParser,$strInputXML ); if(!$this->strXmlData) { die(sprintf("XML error: %s at line %d", xml_error_string(xml_get_error_code($this->resParser)), xml_get_current_line_number($this->resParser))); } xml_parser_free($this->resParser); return $this->arrOutput; } function tagOpen($parser, $name, $attrs) { $tag=array("name"=>$name,"attrs"=>$attrs); array_push($this->arrOutput,$tag); } function tagData($parser, $tagData) { if(trim($tagData)) { if(isset($this->arrOutput[count($this->arrOutput)-1]['tagData'])) { $this->arrOutput[count($this->arrOutput)-1]['tagData'] .= $tagData; } else { $this->arrOutput[count($this->arrOutput)-1]['tagData'] = $tagData; } } } function tagClosed($parser, $name) { $this->arrOutput[count($this->arrOutput)-2]['children'][] = $this->arrOutput[count($this->arrOutput)-1]; array_pop($this->arrOutput); } } ?>=$_offset && $i<$_till && $_till>0) || (!$_till && !$_offset) ){ $_t = explode(' ', $_row['reg_datetime']); $_row['reg_datetime'] = TransformDATEToTemplate($_t[0]); $customers["{$_row['customerID']}"] = $_row; $customers["{$_row['customerID']}"]['orders_num'] = 0; $customers["{$_row['customerID']}"]['currencies'] = array(); } $i++; } if(!count($customers))return array(); $sql = "select customerID, currency_code, currency_value, order_amount FROM ".ORDERS_TABLE." WHERE customerID IN(".implode(", ", array_keys($customers)).") and statusID = '".CONF_COMPLETED_ORDER_STATUS."' "; $result = db_query($sql); while (list($__customerID, $__currency_code, $__currency_value, $__order_amount) = db_fetch_row($result)) { if(!key_exists($__currency_code, $customers[$__customerID]['currencies'])) $customers[$__customerID]['currencies'][$__currency_code] = 0; $customers[$__customerID]['currencies'][$__currency_code] += floatval(sprintf("%.2f",($__order_amount*$__currency_value))); $customers[$__customerID]['orders_num']++; } return $customers; } /** * remove recruited customer * * @param integer - customer id */ function affp_cancelRecruitedCustomer($_customerID){ $sql = " UPDATE `".CUSTOMERS_TABLE."` SET affiliateID = 0 WHERE customerID = ".(int)$_customerID; db_query($sql); } /** * return payments by params * * @return array */ function affp_getPayments($_customerID, $_pID = '', $_from = '', $_till = '', $_order = ''){ $sql = "select pID, customerID, Amount, CurrencyISO3, xDate, Description FROM ".AFFILIATE_PAYMENTS_TABLE." WHERE 1 ".($_pID?" AND pID = ".(int)$_pID:"")." ".($_customerID?" AND customerID = ".(int)$_customerID:"")." ".($_from?" AND xDate>='".xEscSQL($_from)."'":"")." ".($_till?" AND xDate<='".xEscSQL($_till)."'":"")." ".($_order?" ORDER BY ".xEscSQL($_order):"")." "; $result = db_query($sql); $payments = array(); while ($_row = db_fetch_row($result)){ $_row['Amount'] = sprintf("%.2f", $_row['Amount']); $_row['CustomerLogin'] = regGetLoginById($_row['customerID']); $_row['xDate'] = TransformDATEToTemplate($_row['xDate']); $payments[] = $_row; } return $payments; } /** * add new payment * * @param hash $_payment * @return new payment id */ function affp_addPayment($_payment){ if(isset($_payment['Amount']))$_payment['Amount'] = sprintf("%.2f", $_payment['Amount']); $sql = " INSERT ".AFFILIATE_PAYMENTS_TABLE." (`".implode("`, `", xEscSQL(array_keys($_payment)))."`) VALUES('".implode("', '", xEscSQL($_payment))."') "; db_query($sql); if(CONF_AFFILIATE_EMAIL_NEW_PAYMENT){ $Settings = affp_getSettings($_payment['customerID']); if(!$Settings['EmailPayments'])return db_insert_id(); $t = ''; $Email = ''; $FirstName = ''; regGetContactInfo(regGetLoginById($_payment['customerID']), $t, $Email, $FirstName, $t, $t, $t); xMailTxtTemplateSmarty($Email, AFFP_NEW_PAYMENT, 'customer.affiliate.payment_notifi.tpl.html', array( 'customer_firstname' => $FirstName, '_AFFP_NEW_PAYMENT' => str_replace('{MONEY}', $_payment['Amount'].' '.$_payment['CurrencyISO3'],AFFP_MAIL_NEW_PAYMENT) )); } return db_insert_id(); } /** * save payment * * @param array $_payment * @return bool */ function affp_savePayment($_payment){ if(isset($_payment['Amount']))$_payment['Amount'] = round($_payment['Amount'], 2); if(!isset($_payment['pID'])) return false; $_pID = $_payment['pID']; unset($_payment['pID']); foreach ($_payment as $_ind=>$_val) $_payment[$_ind] = "`".xEscSQL($_ind)."`='".xEscSQL($_val)."'"; $sql = " UPDATE ".AFFILIATE_PAYMENTS_TABLE." SET ".implode(", ", $_payment)." WHERE pID=".(int)$_pID; db_query($sql); return true; } /** * Delete payment * * @param integer - payment id */ function affp_deletePayment($_pID){ $sql = "DELETE FROM `".AFFILIATE_PAYMENTS_TABLE."` WHERE pID=".(int)$_pID; db_query($sql); } /** * Add commission to customer from order * * @param integer - order id */ function affp_addCommissionFromOrder($_orderID){ $Commission = affp_getCommissionByOrder($_orderID); if($Commission['cID'])return 0; $Order = ordGetOrder( $_orderID ); if($Order['customerID']) $RefererID = affp_getReferer($Order['customerID']); else $RefererID = $Order['affiliateID']; if(!$RefererID)return 0; $CustomerLogin = regGetLoginById($Order['customerID']); if(!$CustomerLogin) $CustomerLogin = $Order['customer_email']; $Commission = array( 'Amount' => sprintf("%.2f", ($Order['currency_value']*$Order['order_amount']*CONF_AFFILIATE_AMOUNT_PERCENT)/100), 'CurrencyISO3' => $Order['currency_code'], 'xDateTime' => date("Y-m-d H:i:s"), 'OrderID' => $_orderID, 'CustomerID' => $RefererID, 'Description' => xEscSQL(str_replace(array('{ORDERID}', '{USERLOGIN}'), array($_orderID, $CustomerLogin), AFFP_COMMISSION_DESCRIPTION)) ); do{ if(CONF_AFFILIATE_EMAIL_NEW_COMMISSION){ $Settings = affp_getSettings($RefererID); if(!$Settings['EmailOrders'])break; $t = ''; $Email = ''; $FirstName = ''; regGetContactInfo(regGetLoginById($RefererID), $t, $Email, $FirstName, $t, $t, $t); xMailTxtTemplateSmarty($Email, AFFP_NEW_COMMISSION, 'customer.affiliate.commission_notifi.tpl.html', array( 'customer_firstname' => $FirstName, '_AFFP_MAIL_NEW_COMMISSION' => str_replace('{MONEY}', $Commission['Amount'].' '.$Commission['CurrencyISO3'],AFFP_MAIL_NEW_COMMISSION) )); } }while (0); affp_addCommission($Commission); } /** * Add commission to customer from commission array * * @param array - commission */ function affp_addCommission($_Commission){ if(isset($_Commission['Amount']))$_Commission['Amount'] = round($_Commission['Amount'], 2); $sql = " INSERT `".AFFILIATE_COMMISSIONS_TABLE."` (`".implode("`, `", xEscSQL(array_keys($_Commission)))."`) VALUES('".implode("', '",$_Commission)."') "; db_query($sql); return db_insert_id(); } /** * Delete commission by cID * * @param integer cID - commission id */ function affp_deleteCommission($_cID){ $sql = "DELETE FROM `".AFFILIATE_COMMISSIONS_TABLE."` WHERE cID=".(int)$_cID; db_query($sql); } /** * return commissions by params * @param integer $_customerID - customer id * @param integer $_cID - commission id * @param string $_from - from date in DATETIME format * @param string $_till - till date in DATETIME format * @param string $_order - order by this->...<-this * @return array */ function affp_getCommissions($_customerID, $_cID, $_from = '', $_till = '', $_order = ''){ $sql = "select cID, customerID, Amount, CurrencyISO3, xDateTime, Description, CustomerID FROM ".AFFILIATE_COMMISSIONS_TABLE." WHERE 1 ".($_cID?" AND cID = ".(int)$_cID:"")." ".($_customerID?" AND customerID = ".(int)$_customerID:"")." ".($_from?" AND xDateTime>='".xEscSQL($_from)."'":"")." ".($_till?" AND xDateTime<='".xEscSQL($_till)."'":"")." ".($_order?" ORDER BY ".xEscSQL($_order):"")." "; $result = db_query($sql); $commissions = array(); while ($_row = db_fetch_row($result)){ $_row['CustomerLogin'] = regGetLoginById($_row['customerID']); $_row['Amount'] = sprintf("%.2f", $_row['Amount']); $_t = explode(' ', $_row['xDateTime']); $_row['xDateTime'] = TransformDATEToTemplate($_t[0]); $commissions[] = $_row; } return $commissions; } /** * save commission * * @param array * @return bool */ function affp_saveCommission($_commission){ if(isset($_commission['Amount']))$_commission['Amount'] = round($_commission['Amount'], 2); if(!isset($_commission['cID'])) return false; $_cID = $_commission['cID']; unset($_commission['cID']); foreach ($_commission as $_ind=>$_val) $_commission[$_ind] = "`".xEscSQL($_ind)."`='".xEscSQL($_val)."'"; $sql = "UPDATE ".AFFILIATE_COMMISSIONS_TABLE." SET ".implode(", ", $_commission)." WHERE cID=".(int)$_cID; db_query($sql); return true; } /** * return commissions(earnings) for customer * @param integer - customer id * @return array */ function affp_getCommissionsAmount($_CustomerID){ $CurrencyAmount = array(); $sql = "select SUM(`Amount`) AS CurrencyAmount, CurrencyISO3 FROM `".AFFILIATE_COMMISSIONS_TABLE."` WHERE CustomerID = ".(int)$_CustomerID." GROUP BY `CurrencyISO3` "; $result = db_query($sql); while ($_row = db_fetch_row($result)){ $CurrencyAmount[$_row['CurrencyISO3']] = sprintf("%.2f", $_row['CurrencyAmount']); } return $CurrencyAmount; } /** * return payments to customer * @param integer - customer id * @return array */ function affp_getPaymentsAmount($_CustomerID){ $PaymentAmount = array(); $sql = "select SUM(`Amount`) AS CurrencyAmount, CurrencyISO3 FROM `".AFFILIATE_PAYMENTS_TABLE."` WHERE CustomerID = ".(int)$_CustomerID." GROUP BY `CurrencyISO3` "; $result = db_query($sql); while ($_row = db_fetch_row($result)){ $PaymentAmount[$_row['CurrencyISO3']] = sprintf("%.2f", $_row['CurrencyAmount']); } return $PaymentAmount; } /** * return settings for customer * @param integer - customer id * @return array */ function affp_getSettings($_CustomerID){ $Settings = array(); $sql = "select affiliateEmailOrders, affiliateEmailPayments FROM `".CUSTOMERS_TABLE."` WHERE customerID=".(int)$_CustomerID; list($Settings['EmailOrders'], $Settings['EmailPayments']) = db_fetch_row(db_query($sql)); return $Settings; } /** * save settings for customer * @param integer * @param integer */ function affp_saveSettings($_CustomerID, $_EmailOrders, $_EmailPayments){ $sql = "UPDATE `".CUSTOMERS_TABLE."` SET affiliateEmailOrders = '".(int)$_EmailOrders."', affiliateEmailPayments = '".(int)$_EmailPayments."' WHERE customerID=".(int)$_CustomerID; db_query($sql); } /** * get customer referer * @param integer - customer id * @return integer */ function affp_getReferer($_CustomerID){ $sql = "select affiliateID FROM `".CUSTOMERS_TABLE."` WHERE customerID=".(int)$_CustomerID; list($affiliateID) = db_fetch_row(db_query($sql)); return $affiliateID; } /** * Return array with commission information by order id * * @param integer $_OrderID * @return array */ function affp_getCommissionByOrder($_OrderID){ $sql = "select cID, customerID, Amount, CurrencyISO3, xDateTime, Description, CustomerID FROM ".AFFILIATE_COMMISSIONS_TABLE." WHERE OrderID=".(int)$_OrderID; $commission = db_fetch_row(db_query($sql)); if(!$commission['cID']) return $commission; $commission['CustomerLogin'] = regGetLoginById($commission['customerID']); $commission['Amount'] = sprintf("%.2f", $commission['Amount']); list($_t) = explode(' ', $commission['xDateTime']); $commission['xDateTime'] = TransformDATEToTemplate($_t); return $commission; } ?> $val ) { if ( isset ( $val["sort"] )) { db_query("UPDATE ".BLOCKS_TABLE." SET sort=".( int ) $val["sort"]." WHERE bid=".( int ) $key); } } } function blockspgGetblocksPage($page_ID) { $q = db_query("select title, content, bposition, active, which, html, url, admin, pages, dpages, categories, products, about from ".BLOCKS_TABLE." where bid=".( int ) $page_ID); if ( $row = db_fetch_row($q)) { $row["bid"] = ( int ) $page_ID; $row["pages"] = unserialize($row["pages"]); $row["dpages"] = unserialize($row["dpages"]); $row["categories"] = unserialize($row["categories"]); $row["products"] = unserialize($row["products"]); } return $row; } function blockspgUpdateblocksPage($page_ID, $page_name, $page_text, $which, $bposition, $active, $admin, $s, $d, $c, $p) { $rs = isset ( $s ) ? serialize($s) : serialize(array()); $rd = isset ( $d ) ? serialize($d) : serialize(array()); $rc = isset ( $c ) ? serialize($c) : serialize(array()); $rpt = explode("\n",chop($p)); $rp = array(); for ($i=0; $i 0 && rtrim($rpt[$i]) !== "") $rp[] = (int) rtrim($rpt[$i]); $rp = serialize($rp); db_query("update ".BLOCKS_TABLE." set title='".xToText($page_name)."', "." content='".xEscSQL($page_text)."', "." bposition=".( int ) $bposition.", "." active=".( int ) $active.", "." which=".( int ) $which.", "." admin=".( int ) $admin.", "." pages='".xEscSQL($rs)."', "." dpages='".xEscSQL($rd)."', "." categories='".xEscSQL($rc)."', "." products='".xEscSQL($rp)."' "." where bid=".( int ) $page_ID); } function blockspgAddblocksPage($page_name, $page_text, $which, $bposition, $active, $admin, $s, $d, $c, $p) { $rs = isset ( $s ) ? serialize($s) : serialize(array()); $rd = isset ( $d ) ? serialize($d) : serialize(array()); $rc = isset ( $c ) ? serialize($c) : serialize(array()); $rpt = explode("\n",chop($p)); $rp = array(); for ($i=0; $i 0 && rtrim($rpt[$i]) !== "") $rp[] = (int) rtrim($rpt[$i]); $rp = serialize($rp); db_query("insert into ".BLOCKS_TABLE." ( title, content, bposition, active, which, admin, pages, dpages, categories, products ) "." values( '".xToText($page_name)."', '".xEscSQL($page_text)."', ".( int ) $bposition.", ".( int ) $active.", ".( int ) $which.", ".( int ) $admin.", '".xEscSQL($rs)."', '".xEscSQL($rd)."', '".xEscSQL($rc)."', '".xEscSQL($rp)."') "); } function blockspgAddblocksPageFile($page_name, $page_file, $which, $bposition, $active, $admin, $s, $d, $c, $p) { $rs = isset ( $s ) ? serialize($s) : serialize(array()); $rd = isset ( $d ) ? serialize($d) : serialize(array()); $rc = isset ( $c ) ? serialize($c) : serialize(array()); $rpt = explode("\n",chop($p)); $rp = array(); for ($i=0; $i 0 && rtrim($rpt[$i]) !== "") $rp[] = (int) rtrim($rpt[$i]); $rp = serialize($rp); db_query("insert into ".BLOCKS_TABLE." ( title, bposition, active, which, html, url, admin, pages, dpages, categories, products ) "." values( '".xToText($page_name)."', ".( int ) $bposition.", ".( int ) $active.", ".( int ) $which.", '1', '".$page_file."', ".( int ) $admin.", '".xEscSQL($rs)."', '".xEscSQL($rd)."', '".xEscSQL($rc)."', '".xEscSQL($rp)."') "); } function blockspgDeleteblocks($page_ID) { db_query("delete from ".BLOCKS_TABLE." where bid=".( int ) $page_ID); } ?> $value ) { if ( (int)$_SESSION["gids"][$key] != (int)$productID ) continue; if ( CompareConfiguration($variants, $value) ) return $key; } return -1; } // search configuration in database function SearchConfigurationInDataBase($variants, $productID) { $q=db_query( "select itemID from ".SHOPPING_CARTS_TABLE. " where customerID=".(int)regGetIdByLogin($_SESSION["log"])); while( $r = db_fetch_row($q) ) { $q1=db_query( "select COUNT(*) from ".SHOPPING_CART_ITEMS_TABLE. " where productID=".(int)$productID." AND itemID=".(int)$r["itemID"]); $r1=db_fetch_row($q1); if ( $r1[0] != 0 ) { $variants_from_db=GetConfigurationByItemId( $r["itemID"] ); if ( CompareConfiguration($variants, $variants_from_db) ) return $r["itemID"]; } } return -1; } function GetConfigurationByItemId($itemID) { $q=db_query("select variantID from ". SHOPPING_CART_ITEMS_CONTENT_TABLE." where itemID=".(int)$itemID); $variants=array(); while( $r=db_fetch_row( $q ) ) $variants[]=$r["variantID"]; return $variants; } function InsertNewItem($variants, $productID) { db_query( "insert into ".SHOPPING_CART_ITEMS_TABLE. "(productID) values('".(int)$productID."')" ); $itemID=db_insert_id(); foreach( $variants as $vars ) { db_query("insert into ". SHOPPING_CART_ITEMS_CONTENT_TABLE."(itemID, variantID) ". "values( '".(int)$itemID."', '".(int)$vars."')" ); } return $itemID; } function InsertItemIntoCart($itemID) { db_query("insert ".SHOPPING_CARTS_TABLE."(customerID, itemID, Quantity)". "values( '".(int)regGetIdByLogin($_SESSION["log"])."', '".(int)$itemID."', 1 )" ); } function GetStrOptions($variants) { $first_flag=true; $res = ""; foreach( $variants as $vars ) { $q=db_query("select option_value from ". PRODUCTS_OPTIONS_VALUES_VARIANTS_TABLE. " where variantID=".(int)$vars); if ( $r=db_fetch_row($q) ) { if ( $first_flag ) { $res.=$r["option_value"]; $first_flag = false; } else $res.=", ".$r["option_value"]; } } return $res; } function CodeItemInClient($variants, $productID) { $array=array(); $array[]=$productID; foreach($variants as $var) $array[]=$var; return implode("_", $array); } function DeCodeItemInClient($str) { // $variants, $productID $array=explode("_", $str ); $productID=$array[0]; $variants=array(); for($i=1; $i 0 ) $productComplexName = "[".$product["product_code"]."] ".$productComplexName; // $price = GetPriceProductWithOption( $variants, $productID ); $tax = taxCalculateTax( $productID, $shippingAddressID, $billingAddressID ); db_query("INSERT INTO ".ORDERED_CARTS_TABLE. "( itemID, orderID, name, ". " Price, Quantity, tax ) ". " VALUES ". " (".(int)$item["itemID"].",".(int)$orderID.", '".xEscSQL($productComplexName)."', ".xEscSQL($price). ", ".(int)$item["Quantity"].", ".xEscSQL($tax)." )"); if ( $statusID != ostGetCanceledStatusId() && CONF_CHECKSTOCK ) { db_query( "update ".PRODUCTS_TABLE." set in_stock = in_stock - ".(int)$item["Quantity"]. " where productID=".(int)$productID ); $q = db_query("select name, in_stock FROM ".PRODUCTS_TABLE." WHERE productID=".(int)$productID); $productsta = db_fetch_row($q); if ( $productsta["in_stock"] == 0){ if (CONF_AUTOOFF_STOCKADMIN) db_query( "update ".PRODUCTS_TABLE." set enabled=0 where productID=".(int)$productID); if (CONF_NOTIFY_STOCKADMIN){ $smarty_mail->assign( "productstaname", $productsta["name"] ); $smarty_mail->assign( "productstid", $productID ); $stockadmin = $smarty_mail->fetch( "notify_stockadmin.tpl.html" ); $ressta = xMailHtml(CONF_ORDERS_EMAIL,CUSTOMER_ACTIVATE_99,$stockadmin); } } } } db_query("DELETE FROM ".SHOPPING_CARTS_TABLE." WHERE customerID=".(int)regGetIdByLogin($_SESSION["log"])); } // ***************************************************************************** // Purpose clear cart content // Inputs // Remarks // Returns function cartClearCartContet() { if ( isset($_SESSION["log"]) ) db_query("DELETE FROM ".SHOPPING_CARTS_TABLE." WHERE customerID=".(int)regGetIdByLogin($_SESSION["log"])); else { unset($_SESSION["gids"]); unset($_SESSION["counts"]); unset($_SESSION["configurations"]); session_unregister("gids"); //calling session_unregister() is required since unset() may not work on some systems session_unregister("counts"); session_unregister("configurations"); } } // ***************************************************************************** // Purpose clear cart content // Inputs // Remarks // Returns function cartGetCartContent() { $cart_content = array(); $total_price = 0; $freight_cost = 0; if (isset($_SESSION["log"])) //get cart content from the database { $q = db_query("select itemID, Quantity FROM ".SHOPPING_CARTS_TABLE. " WHERE customerID=".(int)regGetIdByLogin($_SESSION["log"])); while ($cart_item = db_fetch_row($q)) { // get variants $variants=GetConfigurationByItemId( $cart_item["itemID"] ); // shopping cart item $q_shopping_cart_item = db_query("select productID from ". SHOPPING_CART_ITEMS_TABLE." where ". " itemID=".(int)$cart_item["itemID"]); $shopping_cart_item = db_fetch_row( $q_shopping_cart_item ); $q_products = db_query("select name, Price, productID, min_order_amount, shipping_freight, free_shipping, product_code FROM ". PRODUCTS_TABLE." WHERE productID=".(int)$shopping_cart_item["productID"]); if ( $product = db_fetch_row($q_products) ) { $costUC = GetPriceProductWithOption( $variants, $shopping_cart_item["productID"] ); $tmp = array( "productID" => $product["productID"], "id" => $cart_item["itemID"], "name" => $product["name"], "quantity" => $cart_item["Quantity"], "free_shipping" => $product["free_shipping"], "costUC" => $costUC, "cost" => show_price($cart_item["Quantity"]* GetPriceProductWithOption($variants, $shopping_cart_item["productID"])), "product_code" => $product["product_code"] ); $freight_cost += $cart_item["Quantity"]*$product["shipping_freight"]; $strOptions=GetStrOptions( GetConfigurationByItemId( $tmp["id"] )); if ( trim($strOptions) != "" ) $tmp["name"].=" (".$strOptions.")"; if ( $product["min_order_amount"] > $cart_item["Quantity"] ) $tmp["min_order_amount"] = $product["min_order_amount"]; $cart_content[] = $tmp; $total_price += $cart_item["Quantity"]* GetPriceProductWithOption($variants, $shopping_cart_item["productID"]); } } } else //unauthorized user - get cart from session vars { $total_price = 0; //total cart value $cart_content = array(); //shopping cart items count if ( isset($_SESSION["gids"]) ) for ($j=0; $j 0) { for ($tmp1=0;$tmp1 $_SESSION["gids"][$j], "id" => $id, //$_SESSION["gids"][$j], "name" => $r[0], "quantity" => $_SESSION["counts"][$j], "free_shipping" => $r["free_shipping"], "costUC" => $costUC, "cost" => show_price($costUC * $_SESSION["counts"][$j]), "product_code" => $r["product_code"] ); $strOptions=GetStrOptions( $_SESSION["configurations"][$j] ); if ( trim($strOptions) != "" ) $tmp["name"].=" (".$strOptions.")"; $q_product = db_query( "select min_order_amount, shipping_freight from ".PRODUCTS_TABLE. " where productID=". (int)$_SESSION["gids"][$j] ); $product = db_fetch_row( $q_product ); if ( $product["min_order_amount"] > $_SESSION["counts"][$j] ) $tmp["min_order_amount"] = $product["min_order_amount"]; $freight_cost += $_SESSION["counts"][$j]*$product["shipping_freight"]; $cart_content[] = $tmp; $total_price += GetPriceProductWithOption( $_SESSION["configurations"][$j], $_SESSION["gids"][$j] )*$_SESSION["counts"][$j]; } } } } return array( "cart_content" => $cart_content, "total_price" => $total_price, "freight_cost" => $freight_cost ); } function cartCheckMinOrderAmount() { $cart_content = cartGetCartContent(); $cart_content = $cart_content["cart_content"]; foreach( $cart_content as $cart_item ) if ( isset($cart_item["min_order_amount"]) ) return false; return true; } function cartCheckMinTotalOrderAmount(){ $res = cartGetCartContent(); $d = oaGetDiscountPercent( $res, "" ); $order["order_amount"] = $res["total_price"] - ($res["total_price"]/100)*$d; if($order["order_amount"]= $count_to_order) //no item - add it to $gids array { $_SESSION["gids"][] = $productID; $_SESSION["counts"][] = $count_to_order; $_SESSION["configurations"][]=$variants; } else return false; } else //authorized customer - get cart from database { $itemID=SearchConfigurationInDataBase($variants, $productID ); if ( $itemID !=-1 ) // if this configuration exists in database { $q = db_query("select Quantity FROM ".SHOPPING_CARTS_TABLE. " WHERE customerID=".(int)regGetIdByLogin($_SESSION["log"])." AND itemID=".(int)$itemID); $row = db_fetch_row($q); $quantity = $row[0]; if (CONF_CHECKSTOCK==0 || $quantity + $count_to_order <= $is) db_query("UPDATE ".SHOPPING_CARTS_TABLE. " SET Quantity=".(int)($row[0]+$count_to_order). " WHERE customerID=".(int)regGetIdByLogin($_SESSION["log"]). " AND itemID=".(int)$itemID); else return false; } else //insert new item { $count_to_order = $min_order_amount; if (CONF_CHECKSTOCK==0 || $is >= $count_to_order) { $itemID=InsertNewItem($variants, $productID ); InsertItemIntoCart($itemID); db_query("UPDATE ".SHOPPING_CARTS_TABLE. " SET Quantity=".(int)$count_to_order. " WHERE customerID=".(int)regGetIdByLogin($_SESSION["log"]). " AND itemID=".(int)$itemID); } else return false; } } return true; } // ***************************************************************************** // Purpose // Inputs $customerID - customer ID // Remarks // Returns returns true if cart is empty for this customer function cartCartIsEmpty( $log ) { $customerID = regGetIdByLogin( $log ); if ( (int)$customerID > 0 ) { $customerID = (int)$customerID; $q_count = db_query( "select count(*) from ".SHOPPING_CARTS_TABLE." where customerID=".(int)$customerID ); $count = db_fetch_row( $q_count ); $count = $count[0]; return ( $count == 0 ); } else return true; } ?> ,," // Remarks // Returns function _getPictureFilename( $stringToParse ) { $files=explode(",",$stringToParse); if ( count($files) >= 1 ) return trim($files[0]); else return ""; } // ***************************************************************************** // Purpose gets thumbnail picture filename // Inputs string ",," // Remarks // Returns function _getPictureThumbnail( $stringToParse ) { $files=explode(",",$stringToParse); if ( count($files) >= 2 ) return trim($files[1]); else return ""; } // ***************************************************************************** // Purpose gets big picture filename // Inputs string ",," // Remarks // Returns function _getPictureBigPicture( $stringToParse ) { $files=explode(",",$stringToParse); if ( count($files) >= 3 ) return trim($files[2]); else return ""; } // ***************************************************************************** // Purpose insert pictures // Inputs // $stringToParse string has formats ",," // $productID - product ID // Remarks // Returns function _insertPictures( $stringToParse, $productID ) { // get filename $filename = _getPictureFilename( $stringToParse ); // get thumbnail $thumbnail = _getPictureThumbnail( $stringToParse ); // get big_picture $big_picture = _getPictureBigPicture( $stringToParse ); if ( trim($filename)!="" || trim($thumbnail)!="" || trim($big_picture)!="" ) { db_query("insert into ".PRODUCT_PICTURES. "(productID, filename, thumbnail, enlarged) ". "values( '".(int)$productID."', ". " '".xEscSQL($filename)."', ". " '".xEscSQL($thumbnail)."', ". " '".xEscSQL($big_picture)."' )" ); } } // ***************************************************************************** // Purpose // Inputs // $row - row from file to import // $dbc - array of column index, $dbc[] -index of column // Remarks // Returns true if column value for current row is set function _columnIsSet($row, $dbc, $column_name) { if ( !strcmp($dbc[$column_name], "not defined") ) return false; return ( trim($row[$dbc[$column_name]]) != "" ); } // ***************************************************************************** // Purpose // Inputs // $row from file to import // Remarks // Returns true if column value is set function _isCategory($row, $dbc) { if ( !strcmp($dbc["name"], "not defined") ) return false; if ( _columnIsSet($row, $dbc, "product_code") ) return false; if ( _columnIsSet($row, $dbc, "Price") ) return false; if ( _columnIsSet($row, $dbc, "in_stock") ) return false; if ( _columnIsSet($row, $dbc, "list_price") ) return false; if ( _columnIsSet($row, $dbc, "items_sold") ) return false; if ( _columnIsSet($row, $dbc, "brief_description") ) return false; return true; } function fgetcsvs($f, $d, $q='"') { $list = array(); $st = fgets($f); if ($st === false || $st === null) return $st; while ($st !== "" && $st !== false) { if ($st[0] !== $q) { # Non-quoted. list ($field) = explode($d, $st, 2); $st = substr($st, strlen($field)+strlen($d)); } else { # Quoted field. $st = substr($st, 1); $field = ""; while (1) { # Find until finishing quote (EXCLUDING) or eol (including) preg_match("/^((?:[^$q]+|$q$q)*)/sx", $st, $p); $part = $p[1]; $partlen = strlen($part); $st = substr($st, strlen($p[0])); $field .= str_replace($q.$q, $q, $part); if (strlen($st) && $st[0] === $q) { # Found finishing quote. list ($dummy) = explode($d, $st, 2); $st = substr($st, strlen($dummy)+strlen($d)); break; } else { # No finishing quote - newline. $st = fgets($f); } } } $list[] = $field; } return $list; } function myfgetcsv($fname, $del) { $f = fopen( $fname, "r" ); $res = array(); $firstFlag = true; $columnCount = 0; while( $row = fgetcsvs($f, $del) ) { if ( $firstFlag ) $columnCount = count($row); $firstFlag = false; while( count($row) < $columnCount ) $row[] = ""; $res[] = $row; } fclose($f); return $res; } function fgetcsvsgz($f, $d, $q='"') { $list = array(); $st = gzgets($f); if ($st === false || $st === null) return $st; while ($st !== "" && $st !== false) { if ($st[0] !== $q) { # Non-quoted. list ($field) = explode($d, $st, 2); $st = substr($st, strlen($field)+strlen($d)); } else { # Quoted field. $st = substr($st, 1); $field = ""; while (1) { # Find until finishing quote (EXCLUDING) or eol (including) preg_match("/^((?:[^$q]+|$q$q)*)/sx", $st, $p); $part = $p[1]; $partlen = strlen($part); $st = substr($st, strlen($p[0])); $field .= str_replace($q.$q, $q, $part); if (strlen($st) && $st[0] === $q) { # Found finishing quote. list ($dummy) = explode($d, $st, 2); $st = substr($st, strlen($dummy)+strlen($d)); break; } else { # No finishing quote - newline. $st = gzgets($f); } } } $list[] = $field; } return $list; } function myfgetcsvgz($fname, $del) { $f = gzopen( $fname, "r" ); $res = array(); $firstFlag = true; $columnCount = 0; while( $row = fgetcsvsgz($f, $del) ) { if ( $firstFlag ) $columnCount = count($row); $firstFlag = false; while( count($row) < $columnCount ) $row[] = ""; $res[] = $row; } gzclose($f); return $res; } // ***************************************************************************** // Purpose clears database content // Inputs // Remarks // Returns nothing function imDeleteAllProducts() { db_query("DELETE FROM ".PRODUCTS_OPTIONS_SET_TABLE); db_query("UPDATE ".PRODUCT_OPTIONS_VALUES_TABLE." SET variantID=NULL"); db_query("DELETE FROM ".PRODUCTS_OPTIONS_VALUES_VARIANTS_TABLE ); db_query("DELETE FROM ".PRODUCT_OPTIONS_VALUES_TABLE); db_query("DELETE FROM ".PRODUCT_OPTIONS_TABLE); db_query("DELETE FROM ".RELATED_PRODUCTS_TABLE); db_query("DELETE FROM ".PRODUCT_PICTURES); db_query("DELETE FROM ".DISCUSSIONS_TABLE); db_query("DELETE FROM ".SPECIAL_OFFERS_TABLE); db_query("UPDATE ".SHOPPING_CART_ITEMS_TABLE." SET productID = NULL"); db_query("DELETE FROM ".SHOPPING_CART_ITEMS_CONTENT_TABLE); db_query("DELETE FROM ".CATEGORIY_PRODUCT_TABLE); db_query("DELETE FROM ".PRODUCTS_TABLE); //db_query("DELETE FROM ".CATEGORIES_TABLE." WHERE categoryID>1"); db_query("DELETE FROM ".CATEGORIES_TABLE); db_query("INSERT INTO ".CATEGORIES_TABLE." ( name, parent, categoryID ) values( '".ADMIN_CATEGORY_ROOT."', NULL, 1 )"); } // ***************************************************************************** // Purpose clears database content // Inputs $data is returned by myfgetcsv ( see comment for this function ) // Remarks // Returns import configurator html code function imGetImportConfiguratorHtmlCode($data) { //skip empty lines $i = 0; while ($i0 && ($n = get_NOTempty_elements_count($data[$i])) < count($data[$i])) { $i++; } $notl = $i; // display all headers into a form that allows to // assign each column a value into database $excel_configurator = ""; for ($j=0; $j<$n; $j++) if (isset($data[$i][$j])) { $excel_configurator .= " "; } $excel_configurator .= "
=>
"; return $excel_configurator; } // ***************************************************************************** // Purpose read db_association select control // ( see GetImportConfiguratorHtmlCode ) // Inputs // Remarks // Returns function _readDb_associationSelectControl() { $db_association = array(); // array select control values foreach( $_POST as $key => $val ) { if (strstr($key, "db_association_")) { $i = str_replace("db_association_", "", $key); if ( $val != "pictures" ) $db_association[$i] = $val; } } return $db_association; } // ***************************************************************************** // Purpose get index select control set to "pictures" value // ( see GetImportConfiguratorHtmlCode ) // Inputs // Remarks // Returns function _getIndexArraySelectPictures() { $dbcPhotos = array(); // index array of "pictures" foreach( $_POST as $key => $val ) { if (strstr($key, "db_association_")) { $i = str_replace("db_association_", "", $key); if ( $val == "pictures" ) $dbcPhotos[] = $i; } } return $dbcPhotos; } // ***************************************************************************** // Purpose read column_name control // ( see GetImportConfiguratorHtmlCode ) // Inputs // Remarks // Returns function _readColumn_nameControl($dbcPhotos) { $cname = array(); foreach( $_POST as $key => $val ) { if (strstr($key, "column_name_")) { $i = str_replace("column_name_", "", $key); $searchFlag = false; for( $j=0; $j < count($dbcPhotos); $j ++ ) if ($i == $dbcPhotos[$j]) $searchFlag = true; if ( ! $searchFlag ) $cname[$i] = $val; } } return $cname; } // ***************************************************************************** // Purpose now reverse -- create backwards // association table: db_column -> file_column // Inputs // Remarks // Returns function _createBackwards( $db_association ) { $dbc = array( "name" => "not defined", "product_code" => "not defined", "Price" => "not defined", "in_stock" => "not defined", "list_price" => "not defined", "items_sold" => "not defined", "description" => "not defined", "brief_description" => "not defined", "sort_order" => "not defined", "meta_keywords" => "not defined", "meta_description" => "not defined", "shipping_freight" => "not defined", "weight" => "not defined", "free_shipping" => "not defined", "min_order_amount" => "not defined", "title" => "not defined", "eproduct_filename" => "not defined", "eproduct_available_days" => "not defined", "eproduct_download_times" => "not defined" ); foreach( $db_association as $i => $value ) { if ($value == "name") $dbc["name"] = $i; else if ($value == "product_code") $dbc["product_code"] = $i; else if ($value == "Price") $dbc["Price"] = $i; else if ($value == "in_stock") $dbc["in_stock"] = $i; else if ($value == "list_price") $dbc["list_price"] = $i; else if ($value == "items_sold") $dbc["items_sold"] = $i; else if ($value == "description") $dbc["description"] = $i; else if ($value == "brief_description") $dbc["brief_description"] = $i; else if ($value == "pictures") $dbc["pictures"] = $i; else if ($value == "sort_order") $dbc["sort_order"] = $i; else if ($value == "meta_keywords" ) $dbc["meta_keywords"] = $i; else if ($value == "meta_description" ) $dbc["meta_description"] = $i; else if ($value == "shipping_freight" ) $dbc["shipping_freight"] = $i; else if ($value == "weight" ) $dbc["weight"] = $i; else if ($value == "free_shipping" ) $dbc["free_shipping"] = $i; else if ($value == "min_order_amount" ) $dbc["min_order_amount"] = $i; else if ($value == "title" ) $dbc["title"] = $i; else if ($value == "eproduct_filename" ) $dbc["eproduct_filename"] = $i; else if ($value == "eproduct_available_days" ) $dbc["eproduct_available_days"] = $i; else if ($value == "eproduct_download_times" ) $dbc["eproduct_download_times"] = $i; } return $dbc; } // ***************************************************************************** // Purpose add new product extra option // Inputs // Remarks // Returns function _addExtraOptionToDb( $db_association, $cname ) { $updated_extra_option = array(); for ($i=0; $i $value ) { if ($value == "add") { $q = db_query("select count(*) from ".PRODUCT_OPTIONS_TABLE. " where name LIKE '".xToText(trim($cname[$i]))."'"); $row = db_fetch_row($q); if (!$row[0]) // no option exists => insert new { db_query("insert into ".PRODUCT_OPTIONS_TABLE. " (name) values ('".xToText(trim($cname[$i]))."')"); $op_id = db_insert_id("PRODUCT_OPTIONS_GEN"); } else // get current $id { $q = db_query("select optionID from ".PRODUCT_OPTIONS_TABLE. " where name LIKE '".xToText(trim($cname[$i]))."'"); $op_id = db_fetch_row($q); $op_id = $op_id[0]; } //update extra options list $updated_extra_option[$i] = $op_id; } } return $updated_extra_option; } function imReadImportConfiguratorSettings() { //echo "
";
        // read db_association select control ( see GetImportConfiguratorHtmlCode )
        $db_association = _readDb_associationSelectControl();
        //var_dump($db_association);

        // get index select control set to "pictures" value ( see GetImportConfiguratorHtmlCode )
        $dbcPhotos = _getIndexArraySelectPictures();
        //var_dump($dbcPhotos);
        // read column_name input field ( see GetImportConfiguratorHtmlCode )
        $cname = _readColumn_nameControl( $dbcPhotos );
        //echo "cname";        var_dump($cname);

        // now reverse -- create backwards association table: db_column -> file_column
        $dbc = _createBackwards( $db_association );
        //var_dump($dbc);
        //var_dump($db_association);
        //var_dump($cname);

        // add new extra option to database
        $updated_extra_option = _addExtraOptionToDb( $db_association, $cname );

        $res = array();
        $res["db_association"]       = $db_association;
        $res["dbcPhotos"]            = $dbcPhotos;
        $res["dbc"]                  = $dbc;
        $res["updated_extra_option"] = $updated_extra_option;
        return $res;
}


// *****************************************************************************
// Purpose         import row to database
// Inputs
// Remarks
// Returns
function _importCategory( $row, $dbc, &$parents, $dbcPhotos, & $currentCategoryID )
{
        $sort_order = 0;
        if ( strcmp( $dbc["sort_order"], "not defined") )
                $sort_order = (int)$row[ $dbc["sort_order"] ];

        // set picture file name
        $picture_file_name="";
        if ( count($dbcPhotos) > 0 )
                $picture_file_name=trim($row[ $dbcPhotos[0] ]);

        //
        $row[ "not defined" ] = "";
        $cname = trim($row[$dbc["name"]]);
        if ($cname == "") return;
        for ($sublevel=0;
                $sublevel0 && !isset($parents[$sl]); $sl--);
        }

        $q = db_query("select count(*) from ".CATEGORIES_TABLE.
                        " where categoryID>1 and name LIKE '".xToText(trim($cname))."' ".
                        " and parent=".(int)$parents[$sl]);
        $rowdb = db_fetch_row($q);
        if ( $rowdb[0] == 0  ) // insert category
        {
                db_query("insert into ".CATEGORIES_TABLE.
                         " (name, parent, products_count, description, ".
                         " picture, products_count_admin, meta_keywords, meta_description, sort_order, title) ".
                         "values ('".xToText(trim($cname))."',".(int)$parents[$sl].",0, ".
                                " '".xEscSQL($row[ $dbc["description"] ])."', ".
                                " '".xEscSQL(trim($picture_file_name))."',0, ".
                                " '".xToText(trim($row[ $dbc["meta_keywords"] ]))."', ".
                                " '".xToText(trim($row[ $dbc["meta_description"] ]))."', ".(int)$sort_order.", '".xToText(trim($row[ $dbc["title"] ]))."');");
                $currentCategoryID = db_insert_id("CATEGORIES_GEN");
        }
        else
        {
                $q = db_query("select categoryID from ".CATEGORIES_TABLE.
                        " where categoryID>1 and name LIKE '".xToText(trim($cname))."' and parent=".(int)$parents[$sl]);
                $rowdb = db_fetch_row($q);
                $currentCategoryID = $rowdb[0];

                $query = "";
                if (strcmp($dbc["description"], "not defined"))
                        $query .= " description = '".xEscSQL($row[$dbc["description"]])."'";
                if (strcmp($dbc["sort_order"], "not defined"))
                {
                        if (strlen($query)>0) $query .= ",";
                        $query .= " sort_order = ".(int)$sort_order;
                }
                if (count($dbcPhotos) > 0)
                {
                        if (strlen($query)>0) $query .= ",";
                        $query .= " picture = '".xEscSQL(trim($picture_file_name))."'";
                }

                if (strlen($query) > 0)
                        db_query("update ".CATEGORIES_TABLE.
                                " set ".$query." where categoryID=".(int)$currentCategoryID);
        }
        $parents[$sublevel+1] = $currentCategoryID;
}


function _importProductPictures( $row, $dbcPhotos, $productID )
{
        // delete pictures for this product
        db_query( "delete from ".PRODUCT_PICTURES." where productID=".(int)$productID );

        for( $j=0; $j < count($dbcPhotos); $j++ ) _insertPictures( $row[ $dbcPhotos[$j] ], $productID );

        $q = db_query( "select default_picture from ".PRODUCTS_TABLE." where productID=".(int)$productID );
        $row = db_fetch_row($q);
        //if (!$row || !$row[0])
        {
                $q = db_query( "select photoID from ".PRODUCT_PICTURES." where productID=".(int)$productID );
                $row = db_fetch_row($q);
                if ($row)
                {
                        // update DEFAULT PICTURE information
                        db_query( "update ".PRODUCTS_TABLE." set default_picture=".(int)$row[0]." where productID=".(int)$productID);
                }
        }
}

function _importExtraOptionValues($row, $productID, $updated_extra_option)
{

/*var_dump($updated_extra_option);

var_dump($row);*/

        //now setup all product's extra options
        for ($j=0; $j add new variant value
                                        {
                                                $variantID = optAddOptionValue($optionID, $val_name, 0);
                                        }
                                        if (!$default_variantID) $default_variantID = $variantID;

                                        //now append this variant value to the product
                                        db_query("insert into ".PRODUCTS_OPTIONS_SET_TABLE.
                                                " (productID, optionID, variantID, price_surplus) ".
                                                " values (".(int)$productID.", ".(int)$optionID.", ".(int)$variantID.", ".xEscSQL($val_surcharge).");");

                                }

                                //assign default variant ID - first option in the variants list is default
                                if ($default_variantID)
                                {
                                        db_query("insert into ".PRODUCT_OPTIONS_VALUES_TABLE.
                                                " (optionID, productID, option_type, option_show_times, variantID) ".
                                                " values (".(int)$optionID.", ".(int)$productID.", 1, 1, ".(int)$default_variantID.")");
                                }

                        }
                        else // a custom fixed value
                        {
                                db_query("delete from ".PRODUCT_OPTIONS_VALUES_TABLE.
                                        " where optionID=".(int)$optionID." and productID=".(int)$productID);
                                db_query("insert into ".PRODUCT_OPTIONS_VALUES_TABLE.
                                        " (optionID, productID, option_value) ".
                                        " values (".(int)$optionID.", ".(int)$productID.", '".xEscSQL($curr_value)."')");
                        }
                }
        }
}


// *****************************************************************************
// Purpose         import row to database
// Inputs
// Remarks
// Returns
function _importProduct( $row, $dbc, $identity_column, $dbcPhotos,
                        $updated_extra_option, $currentCategoryID  )
{
        $row["not defined"] = "";
        $row[$identity_column] = trim($row[$identity_column]);
        //search for product within current category
        $q = db_query("select productID, categoryID, customers_rating  from ".
                PRODUCTS_TABLE." where categoryID=".(int)$currentCategoryID." and ".xEscSQL($_POST["update_column"]).
                " LIKE '".xEscSQL(trim($row[$identity_column]))."'");
        $rowdb = db_fetch_row($q);

        if (!$rowdb && $_POST["update_column"] == 'product_code') //not found
        {
         //search for product in all categories
                $q = db_query("select productID, categoryID, customers_rating  from ".
                        PRODUCTS_TABLE." where ".xEscSQL($_POST["update_column"]).
                        " LIKE '".xEscSQL(trim($row[$identity_column]))."'");
                $rowdb = db_fetch_row($q);
        }

        if ( $rowdb ) //update product info
        {
                $productID = $rowdb["productID"];

                $rowdb =  GetProduct( $productID );

                if ( strcmp($dbc["Price"], "not defined") )
                {
                        $Price        = $row[ $dbc["Price"] ];
                        $Price        = str_replace( " ",  "", $Price );
                        $Price        = str_replace( ",", ".", $Price );
                        $Price        = (float)$Price;
                }
                else $Price = $rowdb["Price"];
                if ( strcmp($dbc["list_price"], "not defined") )
                {
                        $list_price        = $row[ $dbc["list_price"] ];
                        $list_price        = str_replace( " ",  "", $list_price );
                        $list_price        = str_replace( ",", ".", $list_price );
                        $list_price = (float)$list_price;
                }
                else $list_price = $rowdb["list_price"];
                if ( strcmp($dbc["sort_order"], "not defined") )
                        $sort_order = (int)$row[ $dbc["sort_order"] ];
                else $sort_order = $rowdb["sort_order"];
                if ( strcmp($dbc["in_stock"], "not defined") )
                        $in_stock = (int)$row[ $dbc["in_stock"] ];
                else $in_stock = $rowdb["in_stock"];
                if ( strcmp($dbc["eproduct_filename"], "not defined") )
                        $eproduct_filename = $row[ $dbc["eproduct_filename"] ];
                else $eproduct_filename = $rowdb["eproduct_filename"];
                if ( strcmp($dbc["eproduct_available_days"], "not defined") )
                        $eproduct_available_days = (int)$row[ $dbc["eproduct_available_days"] ];
                else $eproduct_available_days = $rowdb["eproduct_available_days"];
                if ( strcmp($dbc["eproduct_download_times"], "not defined") )
                        $eproduct_download_times = (int)$row[ $dbc["eproduct_download_times"] ];
                else $eproduct_download_times = $rowdb["eproduct_download_times"];
                if ( strcmp($dbc["weight"], "not defined") )
                        $weight = (float)$row[ $dbc["weight"] ];
                else $weight = $rowdb["weight"];
                if ( strcmp($dbc["free_shipping"], "not defined") )
                        $free_shipping = ( trim($row[$dbc["free_shipping"]])=="+"?1:0 );
                else $free_shipping = $rowdb["free_shipping"];
                if ( strcmp($dbc["min_order_amount"], "not defined") )
                        $min_order_amount = (int)$row[ $dbc["min_order_amount"] ];
                else $min_order_amount = $rowdb["min_order_amount"];
                if ( strcmp($dbc["shipping_freight"], "not defined") )
                        $shipping_freight = (float)$row[ $dbc["shipping_freight"] ];
                else $shipping_freight = $rowdb["shipping_freight"];
                if ( strcmp($dbc["description"], "not defined") )
                        $description = $row[ $dbc["description"] ];
                else $description = $rowdb["description"];
                if ( strcmp($dbc["brief_description"], "not defined") )
                        $brief_description = $row[ $dbc["brief_description"] ];
                else $brief_description = $rowdb["brief_description"];
                if ( strcmp($dbc["product_code"], "not defined") )
                        $product_code = $row[ $dbc["product_code"] ];
                else $product_code = xHtmlSpecialCharsDecode($rowdb["product_code"]);
                if ( strcmp($dbc["meta_description"], "not defined") )
                        $meta_description = $row[ $dbc["meta_description"] ];
                else $meta_description = xHtmlSpecialCharsDecode($rowdb["meta_description"]);
                if ( strcmp($dbc["meta_keywords"], "not defined") )
                        $meta_keywords = $row[ $dbc["meta_keywords"] ];
                else $meta_keywords = xHtmlSpecialCharsDecode($rowdb["meta_keywords"]);
                if ( strcmp($dbc["name"], "not defined") )
                        $name = $row[ $dbc["name"] ];
                else $name = xHtmlSpecialCharsDecode($rowdb["name"]);
                if ( strcmp($dbc["title"], "not defined") )
                        $title = $row[ $dbc["title"] ];
                else $title = xHtmlSpecialCharsDecode($rowdb["title"]);


                $categoryID       = $rowdb["categoryID"];
                $customers_rating = $rowdb["customers_rating"];
                $ProductIsProgram = trim($eproduct_filename) != "";
                UpdateProduct( $productID,
                                $categoryID, $name, $Price, $description,
                                $in_stock, $customers_rating,
                                $brief_description, $list_price,
                                $product_code, $sort_order,
                                $ProductIsProgram,
                                "",
                                $eproduct_available_days,
                                $eproduct_download_times,
                                $weight, $meta_description, $meta_keywords,
                                $free_shipping, $min_order_amount, $shipping_freight, null, $title, 0 );
        }
        else // add new product
        {
                $Price                   = 0.0;
                $list_price              = 0.0;
                $sort_order              = 0;
                $in_stock                = 0;
                $eproduct_filename       = "";
                $eproduct_available_days = 0;
                $eproduct_download_times = 0;
                $weight                  = 0.0;
                $free_shipping           = 0;
                $min_order_amount        = 1;
                $shipping_freight        = 0.0;

                if ( strcmp($dbc["Price"], "not defined") )
                        $Price        = (float)$row[ $dbc["Price"] ];
                if ( strcmp($dbc["list_price"], "not defined") )
                        $list_price = (float)$row[ $dbc["list_price"] ];
                if ( strcmp($dbc["sort_order"], "not defined") )
                        $sort_order = (int)$row[ $dbc["sort_order"] ];
                if ( strcmp($dbc["in_stock"], "not defined") )
                        $in_stock = (int)$row[ $dbc["in_stock"] ];
                if ( strcmp($dbc["eproduct_filename"], "not defined") )
                        $eproduct_filename = $row[ $dbc["eproduct_filename"] ];
                if ( strcmp($dbc["eproduct_available_days"], "not defined") )
                        $eproduct_available_days = (int)$row[ $dbc["eproduct_available_days"] ];
                if ( strcmp($dbc["eproduct_download_times"], "not defined") )
                        $eproduct_download_times = (int)$row[ $dbc["eproduct_download_times"] ];
                if ( strcmp($dbc["weight"], "not defined") )
                        $weight = (float)$row[ $dbc["weight"] ];
                if ( strcmp($dbc["free_shipping"], "not defined") )
                        $free_shipping = ( trim($row[$dbc["free_shipping"]])=="+"?1:0 );
                if ( strcmp($dbc["min_order_amount"], "not defined") )
                        $min_order_amount = (int)$row[ $dbc["min_order_amount"] ];
                if ( strcmp($dbc["shipping_freight"], "not defined") )
                        $shipping_freight = (float)$row[ $dbc["shipping_freight"] ];

                $ProductIsProgram = trim($row[$dbc["eproduct_filename"]]) != "";
                $productID = AddProduct(
                                $currentCategoryID, $row[ $dbc["name"] ], $Price, $row[ $dbc["description"] ],
                            $in_stock,
                                $row[ $dbc["brief_description"] ], $list_price,
                            $row[ $dbc["product_code"] ], $sort_order,
                                $ProductIsProgram, "",
                                $eproduct_available_days, $eproduct_download_times,
                                $weight, $row[$dbc["meta_description"]], $row[$dbc["meta_keywords"]],
                                $free_shipping, $min_order_amount, $shipping_freight,
                                CONF_DEFAULT_TAX_CLASS, $row[ $dbc["title"] ],0 );
        }
        if (strlen($eproduct_filename))
                SetProductFile( $productID, $eproduct_filename );

        _importExtraOptionValues( $row, $productID, $updated_extra_option );

        if ( count($dbcPhotos) > 0 )
                _importProductPictures( $row, $dbcPhotos, $productID );

}

// *****************************************************************************
// Purpose         import row to database
// Inputs
// Remarks
// Returns
function imImportRowToDataBase( $row, $dbc, $identity_column,
        $dbcPhotos, $updated_extra_option, &$parents, &$currentCategoryID )
{
        if ( _isCategory($row, $dbc) )
        {
                _importCategory( $row, $dbc, $parents, $dbcPhotos, $currentCategoryID );
        }
        else
                _importProduct( $row, $dbc, $identity_column,
                        $dbcPhotos, $updated_extra_option, $currentCategoryID );
}


?>array(),'city'=>array());
		while( $row=db_fetch_row($q) )
		{
			if (strpos($row["name"],' район') !== false || strpos($row["name"],'Район ') !== false || strpos($row["name"],' улус') !== false || strpos($row["name"],' кожуун') !== false)
			{
				$res['raion'][] = array('UID' => $row['UID'], 'name' => $row['cat_h1']);
			}else{  
				$res['city'][] = array('UID' => $row['UID'], 'name' => $row['cat_h1']);
			}
		}

		return $res;
	}

	function catExpandCategory( $categoryID, $sessionArrayName )
	{
		$existFlag = false;
		foreach( $_SESSION[$sessionArrayName] as $key => $value )
			if ( $value == $categoryID )
			{
				$existFlag = true;
				break;
			}
			if ( !$existFlag ) $_SESSION[$sessionArrayName][] = $categoryID;

	}

	function catShrinkCategory( $categoryID, $sessionArrayName )
	{
		foreach( $_SESSION[$sessionArrayName] as $key => $value )
		{
			if ( $value == $categoryID ) unset( $_SESSION[$sessionArrayName][$key] );
		}
	}

	function catExpandCategoryp( $sessionArrayName )
	{
		$categoryID = 0;
		$cats = array();
		$q = db_query("select categoryID FROM ".CATEGORIES_TABLE." ORDER BY sort_order, name");
		while ($row = db_fetch_row($q)) $_SESSION[$sessionArrayName][] = $row[0];
	}

	function catShrinkCategorym( $sessionArrayName )
	{
		unset( $_SESSION[$sessionArrayName]);
		$_SESSION["expcat"] = array(1);
	}

	function catGetCategoryCompactCList( $selectedCategoryID )
	{
		$path = catCalculatePathToCategory( $selectedCategoryID );
		$res = array();
		$res[] = array( 
			"categoryID" => 1,
			"parent" => null,
			"name" => ADMIN_CATEGORY_ROOT,
			"level" => 0 
		);

		$q = db_query( "select categoryID, parent, name, products_count, sort_order, UID from ".CATEGORIES_TABLE.
			" where parent=1 ".
			" order by sort_order, name " );
		$c_path = count($path);
		while( $row = db_fetch_row($q) )
		{
			//$row["name"] = TransformDataBaseStringToText($row["name"]);
			$row["level"] = 1;
			$res[] = $row;
			if ( $c_path > 1 )
			{
				if ( $row["categoryID"] == $path[1]["categoryID"] )
				{
					$arres = _recursiveGetCategoryCompactCList( $path, 2 );
					$c_arres = count($arres);
					//for ($i=0; $i<$c_arres; $i++) $res[] = $arres[$i];
					$res = array_merge($res,$arres);
				}
			}
		}
		return $res;
	}



	// *****************************************************************************
	// Purpose        gets category tree to render it on HTML page
	// Inputs
	//		$parent 	- must be 0
	//      $level      - must be 0
	//      $expcat 	- array of category ID that expanded
	// Remarks
	// 		array of item
	//      for each item
	//      "products_count" -	count product in category including
	//							subcategories excluding enabled product
	//		"products_count_admin" -count product in category
	//								 
	//		"products_count_category" - 
	// Returns        nothing
	function _recursiveGetCategoryCList( $parent, $level, $expcat, $_indexType = 'NUM', $cprod = false, $ccat = true)
	{
		global $fc, $mc;
        if($mc === null) $mc = array();
		$rcat  = array_keys ($mc, (int)$parent);
		$result = array(); //parents

		$crcat = count($rcat);
		for ($i=0; $i<$crcat; $i++) {

			$row = $fc[(int)$rcat[$i]];
			if (!file_exists("data/category/".$row["picture"])) $row["picture"] = "";
			$row["level"] = $level;
			$row["ExpandedCategory"] = false;
			if ( $expcat != null )
			{
				foreach( $expcat as $categoryID )
				{
					if ( (int)$categoryID == (int)$row["categoryID"] )
					{
						$row["ExpandedCategory"] = true;
						break;
					}
				}
			}
			else
				$row["ExpandedCategory"] = true;

			if ($ccat) {$row["products_count_category"] = catGetCategoryProductCount( $row["categoryID"], $cprod );}

			$row["ExistSubCategories"] = ( $row["subcount"] != 0 );

			if($_indexType=='NUM')
				$result[] = $row;
			elseif ($_indexType=='ASSOC')
				$result[$row['categoryID']] = $row;


			if ( $row["ExpandedCategory"] )
			{
				//process subcategories
				$subcategories = _recursiveGetCategoryCList( $row["categoryID"],
					$level+1, $expcat, $_indexType, $cprod, $ccat);

				if($_indexType=='NUM'){

					//add $subcategories[] to the end of $result[]
					for ($j=0; $j 0) {
			while ($row = mysql_fetch_assoc($sql)) {	
				$cat_arr[] = array( 
					'categoryID' => $row['categoryID'],
					'name' => $row['name'], 
					'parent' => $row['parent'],
					'level' => $cat_level,
					'products_count' => $row['products_count'],
					'products_count_admin' => $row['products_count_admin'],
					'ExistSubCategories' => ($row['products_count_admin'] > 10) ? true : false);
			}
		}
		return $cat_arr;
	}

	function GetParentCatId($cat_id) {
		$sql = mysql_query("SELECT parent FROM ".CATEGORIES_TABLE." WHERE categoryID=".$cat_id);
		$cat_count = mysql_num_rows($sql);
		if ($cat_count > 0) {
			$row = mysql_fetch_assoc($sql);
			return $row['parent'];
		} else {
			return 0;
		}
	}

	function catGetCategoryCList($select_cat = 1) { 
		if (isset($category_list) && isset($category_list_id) && $category_list_id == $select_cat) {
			return $category_list;
		} else {
			static $category_list;
			$category_list = array();
			//Определение уровня выбранной категории
			$sel_cat_1 = GetParentCatId($select_cat);
			if ($select_cat != NULL && ($sel_cat_1 == 1 || $sel_cat_1 == NULL)) {
				$sel_cat = array(
					1 => $select_cat, 
					2 => 0, 
					3 => 0);
			} else {
				$sel_cat_2 = GetParentCatId($sel_cat_1);
				if ($select_cat != NULL && ($sel_cat_2 == 1 || $sel_cat_2 == NULL)) {
					$sel_cat = array(
						1 => $sel_cat_1, 
						2 => $select_cat, 
						3 => 0);
				} else {
					$sel_cat_3 = GetParentCatId($sel_cat_2);
					if ($select_cat != NULL && ($sel_cat_3 == 1 || $sel_cat_3 == NULL)) {
						$sel_cat = array(
							1 => $sel_cat_2, 
							2 => $sel_cat_1, 
							3 => $select_cat);
					} else if ($select_cat == NULL) {
						$sel_cat = array(
							1 => -1, 
							2 => -1, 
							3 => -1);
					} else {
						$sel_cat = array(
							1 => 1, 
							2 => 0, 
							3 => 0);
					}
				}
			}
			//Построение дерева категорий
			$cats_1 = CreateChildCats(1, 1);
			$num = -1;
			foreach ($cats_1 as $cat1) {
				if ($cat1 != NULL) {
					$num++;
					$category_list[$num] = $cat1;
					//Уровень 2
					if ($sel_cat[1] == -1 || $sel_cat[1] == $cat1['categoryID']) {
						$category_list[$num]['ExpandedCategory'] = true;
						$cats_2 = CreateChildCats($cat1['categoryID'], 2);
						foreach ($cats_2 as $cat2) {
							if ($cat2 != NULL) {
								$num++;
								$category_list[$num] = $cat2;
								//Уровень 3
								if ($sel_cat[2] == -1 || $sel_cat[2] == $cat2['categoryID']) {
									$category_list[$num]['ExpandedCategory'] = true;
									$cats_3 = CreateChildCats($cat2['categoryID'], 3);
									foreach ($cats_3 as $cat3) {
										if ($cat3 != NULL) {
											$num++;
											$category_list[$num] = $cat3;
											//Уровень 4
											if ($sel_cat[3] == -1 || $sel_cat[3] == $cat3['categoryID']) {
												$category_list[$num]['ExpandedCategory'] = true;
												$cats_4 = CreateChildCats($cat3['categoryID'], 4);
												foreach ($cats_4 as $cat4) {
													if ($cat4 != NULL) {
														$num++;
														$category_list[$num] = $cat4;
														$category_list[$num]['ExpandedCategory'] = false;
													}
												}
											} else {
												$category_list[$num]['ExpandedCategory'] = false;
											}
										} 
									}
								} else {
									$category_list[$num]['ExpandedCategory'] = false;
								}
							}
						}
					} else {
						$category_list[$num]['ExpandedCategory'] = false;
					}
				}
			}

			return $category_list;
		}
	}

	function GetProductsByCategoryIdMS($CategoryId)
	{
		//Товары этой категории
		$sql_query="SELECT REPLACE( tp.name,'{city}',p.tpl_city ) as name, UID,
		IF(p.tplID>0,tp.folder_pictures, p.folder_pictures) as folder_pictures, p.pictures FROM ".PRODUCTS_TABLE." p
		LEFT JOIN ".PRODUCTS_TPL_TABLE." tp USING(tplID) 
		WHERE categoryID=".$CategoryId.' ORDER BY IF(p.tplID>0,tp.sort_order,p.sort_order), name';
		$sql = mysql_query($sql_query);
		$Products = array();
		while ($row = mysql_fetch_assoc($sql))
		{
			$row['pictures'] = explode(',', $row['pictures']);
			$Products[]=$row;
		}
		return $Products;
	}

	function GetSubCategoriesByCategoryIdMS($CategoryId,$SelectedCategory)
	{
		global $category,$VirtualRootCategory,$ShowVirtualRootCategory;

		if(($CategoryId!=1) && ($SelectedCategory['child'])) return array($SelectedCategory);
		//Подкатегории
		//Если корень - эмулируем
		$sql = mysql_query("SELECT categoryID, parent, cat_h1 as name, UID, sort_order, level FROM ".CATEGORIES_TABLE." WHERE parent=".$CategoryId.' ORDER BY level DESC, sort_order, cat_h1');

		$Categories=array();
		$SelectedCategoryId = $SelectedCategory['categoryID'];
		while ($row = mysql_fetch_assoc($sql)) 
		{
			//if ($CategoryId != 1 || ($row['categoryID'] != 135 && $row['categoryID'] != 229)) 
			{
				if($row['categoryID'] != $SelectedCategoryId )
				{
					$row['categoryID']=(int)$row['categoryID'];
					$row['parent']=(int)$row['parent'];
					$Categories[]=$row;
				}
				else $Categories[]=$SelectedCategory;
			}
		}


		//Добавляем виртуальный
		if(($CategoryId==1) && ($ShowVirtualRootCategory==true))
		{
			//if(($SelectedCategory) && ($SelectedCategory['sort_order']<10000)) return array($SelectedCategory);

			$VirtualCategoryRussia = $VirtualRootCategory;

			$MayBeNewCategories = array_slice($Categories,-2);

			//Set new categories
			$NewCategories = array();
			foreach ($MayBeNewCategories as $MayBeNewCategory )
			{
			 	if($MayBeNewCategory['sort_order']<10000) $NewCategories[] = $MayBeNewCategory;
			}
			
			$NewCategoriesCount = count($NewCategories);

			//$VirtualCategoryRussia['child']=array_slice($Categories,2);

			if(!$SelectedCategory){
				if($NewCategoriesCount > 0) $VirtualCategoryRussia['child']=array_slice($Categories,0,-$NewCategoriesCount);
				else $VirtualCategoryRussia['child'] = $Categories;
			}
			elseif($SelectedCategory['sort_order']>10000)
				$VirtualCategoryRussia['child']=array($SelectedCategory);
			else 
				$VirtualCategoryRussia['child']=array();

			$NewCategories[]=$VirtualCategoryRussia;
			$Categories = $NewCategories;
		}
		
		return $Categories;
	}

	function CreateChildCatsNewMS($cat_id = 1, $SelectedCategory=null) 
	{
		//if ($cat_id == 234) {$cat_id = 1;}

		//Данные про категорию
		$sql = mysql_query("SELECT parent, cat_h1 as name, UID, sort_order,level FROM ".CATEGORIES_TABLE." WHERE categoryID=".$cat_id);
		$row = mysql_fetch_assoc($sql);

		$cat_arr = array();
		$row['categoryID']=$cat_id;
		$row['parent'] = (int)$row['parent'];
		//$cat_arr['name'] = ($cat_id != 1) ? 'Карты '.$row['cat_h1'] : 'Карты России';
		if($cat_id == 1) $row['UID']='/';
		$row['prods']=GetProductsByCategoryIdMS($cat_id);

		$row['child'] = GetSubCategoriesByCategoryIdMS($cat_id,$SelectedCategory);
		//if($cat_id!=1)
		//..	$row['child']=array($SelectedCategory);
		/*else
		{
		/*			if(!$SelectedCategory)
		{
		}
		else 
		*/		


		return $row;
	}

	//Вывод списка категорий для моего шаблона
	function catGetCategoryNewMS($select_cat = 1) {
		//$all_world = CreateChildCatsNew(135);
		$sel_cat = array();
		$sel_cat_1 = CreateChildCatsNewMS($select_cat);
		$sel_cat=$sel_cat_1;
		while($sel_cat_1['parent'] != 0)
		{
			$sel_cat_1 = CreateChildCatsNewMS($sel_cat_1['parent'],$sel_cat);
			$sel_cat=$sel_cat_1;
		}
		return $sel_cat_1;
	}

	//Вывод списка категорий для моего шаблона
	function catGetCategoryNew($select_cat = 1) {
		$sel_cat = array();
		$all_world = CreateChildCatsNew(135);

		$sel_cat_1 = CreateChildCatsNew($select_cat);
		//var_dump($sel_cat_1);die;
		if ($sel_cat_1['categoryID'] == 135) {
			$sel_cat[0] = $all_world;
		} else if ($sel_cat_1['parent'] == NULL || $sel_cat_1['parent'] == 135) {
			$sel_cat[0] = $all_world;
			$sel_cat[1] = $sel_cat_1;
		} else {
			$sel_cat_2 = CreateChildCatsNew($sel_cat_1['parent']);
			if ($sel_cat_2['parent'] == NULL || $sel_cat_2['parent'] == 135) {
				$sel_cat[0] = $all_world;
				$sel_cat[1] = $sel_cat_2; 
				$sel_cat[2] = $sel_cat_1;
			} else {
				$sel_cat_3 = CreateChildCatsNew($sel_cat_2['parent']);
				if ($sel_cat_3['parent'] == NULL || $sel_cat_3['parent'] == 135) {
					$sel_cat[0] = $all_world;
					$sel_cat[1] = $sel_cat_3; 
					$sel_cat[2] = $sel_cat_2; 
					$sel_cat[3] = $sel_cat_1;
				} else {
					$sel_cat_4 = CreateChildCatsNew($sel_cat_3['parent']);
					if ($sel_cat_4['parent'] == NULL || $sel_cat_4['parent'] == 135) {
						$sel_cat[0] = $all_world;
						$sel_cat[1] = $sel_cat_4; 
						$sel_cat[2] = $sel_cat_3;
						$sel_cat[3] = $sel_cat_2;
						$sel_cat[4] = $sel_cat_1;
					}
				}
			}
		}
		//var_dump($sel_cat);die;
		return $sel_cat;
	}

	function CreateChildCatsNew($cat_id = 1) {
		if ($cat_id == 234) {$cat_id = 1;}
		$cat_arr = array();

		//Данные про категорию
		$sql = mysql_query("SELECT parent, cat_h1, UID FROM ".CATEGORIES_TABLE." WHERE categoryID=".$cat_id);
		if (mysql_num_rows($sql) > 0) {
			$row = mysql_fetch_assoc($sql);
			$cat_arr['categoryID'] = $cat_id; 
			$cat_arr['parent'] = (int)$row['parent'];
			$cat_arr['name'] = ($cat_id != 1) ? FUNCS_CATEGORY_MAPS.$row['cat_h1'] : FUNCS_CATEGORY_MAPS_ROOT;
			$cat_arr['UID'] = ($cat_id == 1) ? '/' : $row['UID'];
			$cat_arr['prods'] = array();
		}

		//Товары этой категории
		$sql_query="SELECT REPLACE( tp.name,'{city}',p.tpl_city ) as name, UID,
		IF(p.tplID>0,tp.folder_pictures, p.folder_pictures) as folder_pictures, p.pictures FROM ".PRODUCTS_TABLE." p
		LEFT JOIN ".PRODUCTS_TPL_TABLE." tp USING(tplID) 
		WHERE categoryID=".$cat_id.' ORDER BY IF(p.tplID>0,tp.sort_order,p.sort_order), name';
		$sql = mysql_query($sql_query);
		if (mysql_num_rows($sql) > 0) {
			while ($row = mysql_fetch_assoc($sql)) {
				$pic = explode('jpg', $row['pictures']);
				$cat_arr['prods'][] = array( 
					'name' => $row['name'],
					'UID' => $row['UID'].'.html',
					'folder_pictures' => $row['folder_pictures'],
					'pictures' => $pic[0].'jpg'
				);
			}
		}

		//Подкатегории
		$sql = mysql_query("SELECT categoryID, parent, cat_h1, UID FROM ".CATEGORIES_TABLE." WHERE parent=".$cat_id.' ORDER BY sort_order, cat_h1');
		if (mysql_num_rows($sql) > 0) {
			$cats = array();
			//Число столбцов для подкатегорий
			$x = (count($cat_arr['prods']) > 0 && count($cat_arr['prods']) <= 1) ? count($cat_arr['prods']) : 1;
			//Подкатегории
			while ($row = mysql_fetch_assoc($sql)) {
				if ($cat_id != 1 || ($row['categoryID'] != 135 && $row['categoryID'] != 229)) {
					$cats[] = array(
						'categoryID' => (int)$row['categoryID'], 
						'parent' => (int)$row['parent'],
						'name' => FUNCS_CATEGORY_MAPS.$row['cat_h1'],
						'UID' => $row['UID']
					);
				}
			}
			//Число строк для подкатегорий
			$y = ceil(count($cats)/$x);
			$res = array();
			$k = 0;
			for ($i = 0; $i < $x; $i++) {
				$res[$i] = array();
				for ($j = 0; $j < $y; $j++) {
					if (isset($cats[$k])) {
						$res[$i][$j] = $cats[$k];
						$k++;
					}
				}
			}

			$cat_arr['child'] = $res;
		}

		return $cat_arr;
	}


	function catGetCategoryCListMin()
	{
		return _recursiveGetCategoryCList( 1, 0, null, 'NUM', false, false);
	}

	// *****************************************************************************
	// Purpose        gets product count in category
	// Inputs
	// Remarks  this function does not keep in mind subcategories
	// Returns        nothing
	function catGetCategoryProductCount( $categoryID, $cprod = false )
	{
		if (!$categoryID) return 0;

		$res = 0;
		$sql = "
		select count(*) FROM ".PRODUCTS_TABLE."
		WHERE categoryID=".(int)$categoryID."".($cprod?" AND enabled>0":"");
		$q = db_query($sql);
		$t = db_fetch_row($q);
		$res += $t[0];
		if($cprod)
			$sql = "
			select COUNT(*) FROM ".PRODUCTS_TABLE." AS prot
			LEFT JOIN ".CATEGORIY_PRODUCT_TABLE." AS catprot
			ON prot.productID=catprot.productID
			WHERE catprot.categoryID=".(int)$categoryID." AND prot.enabled>0
			";
		else
			$sql = "
			select count(*) from ".CATEGORIY_PRODUCT_TABLE.
			" where categoryID=".(int)$categoryID
			;
		$q1 = db_query($sql);
		$row = db_fetch_row($q1);
		$res += $row[0];
		return $res;
	}

	function update_sCount($parent)
	{
		global $fc, $mc;

		$rcat = array_keys ($mc, (int)$parent);
		$crcat = count($rcat);
		for ($i=0; $i<$crcat; $i++) {

			$rowsub = $fc[(int)$rcat[$i]];
			$countsub  = count(array_keys ($mc, (int)$rowsub["categoryID"]));

			db_query("UPDATE ".CATEGORIES_TABLE.
				" SET subcount=".(int)$countsub." ".
				" WHERE categoryID=".(int)$rcat[$i]);

			$rowsubExist = ( $countsub != 0 );
			if ( $rowsubExist ) update_sCount($rowsub["categoryID"]);
		}
	}

	function update_pCount($parent)
	{
		update_sCount($parent);

		$q = db_query("select categoryID FROM ".CATEGORIES_TABLE.
			" WHERE categoryID>1 AND parent=".(int)$parent);

		$cnt = array();
		$cnt["admin_count"] = 0;
		$cnt["customer_count"] = 0;

		// process subcategories
		while( $row=db_fetch_row($q) )
		{
			$t = update_pCount( $row["categoryID"] );
			$cnt["admin_count"]     += $t["admin_count"];
			$cnt["customer_count"]  += $t["customer_count"];
		}

		// to administrator
		$q = db_query("select count(*) FROM ".PRODUCTS_TABLE.
			" WHERE categoryID=".(int)$parent);
		$t = db_fetch_row($q);
		$cnt["admin_count"] += $t[0];
		$q1 = db_query("select count(*) from ".CATEGORIY_PRODUCT_TABLE.
			" where categoryID=".(int)$parent);
		$row = db_fetch_row($q1);
		$cnt["admin_count"] += $row[0];

		// to customer
		$q = db_query("select count(*) FROM ".PRODUCTS_TABLE.
			" WHERE enabled=1 AND categoryID=".(int)$parent);
		$t = db_fetch_row($q);
		$cnt["customer_count"] += $t[0];
		$q1 = db_query("select productID, categoryID from ".CATEGORIY_PRODUCT_TABLE.
			" where categoryID=".(int)$parent);
		while( $row = db_fetch_row($q1) )
		{
			$q2 = db_query("select productID from ".PRODUCTS_TABLE.
				" where enabled=1 AND productID=".(int)$row["productID"]);
			if ( db_fetch_row($q2) )
				$cnt["customer_count"] ++;
		}

		db_query("UPDATE ".CATEGORIES_TABLE.
			" SET products_count=".(int)$cnt["customer_count"].", products_count_admin=".
			(int)$cnt["admin_count"]." WHERE categoryID=".(int)$parent);
		return $cnt;
	}

	function update_psCount($parent)
	{
		global $fc, $mc;

		$q = db_query("select categoryID, name, products_count, ".
			"products_count_admin, parent, picture, subcount FROM ".
			CATEGORIES_TABLE. " ORDER BY sort_order, name");
		$fc = array(); //parents
		$mc = array(); //parents
		while ($row = db_fetch_row($q)) {
			$fc[(int)$row["categoryID"]] = $row;
			$mc[(int)$row["categoryID"]] = (int)$row["parent"];
		}
		update_pCount($parent);
	}
	// *****************************************************************************
	// Purpose        get subcategories by category id
	// Inputs   $categoryID
	//                                parent category ID
	// Remarks  get current category's subcategories IDs (of all levels!)
	// Returns        array of category ID
	function catGetSubCategories( $categoryID )
	{
		$q = db_query("select categoryID from ".CATEGORIES_TABLE." where parent=".(int)$categoryID);
		$r = array();
		while ($row = db_fetch_row($q))
		{
			$a = catGetSubCategories($row[0]);
			$c_a = count($a);
			for ($i=0;$i<$c_a;$i++) $r[] = $a[$i];
			$r[] = $row[0];
		}
		return $r;
	}


	// *****************************************************************************
	// Purpose        get subcategories by category id
	// Inputs           $categoryID
	//                                parent category ID
	// Remarks          get current category's subcategories IDs (of all levels!)
	// Returns        array of category ID
	function catGetSubCategoriesSingleLayer( $categoryID )
	{
		$q = db_query("select categoryID, name, products_count FROM ".
			CATEGORIES_TABLE." WHERE parent=".(int)$categoryID." order by sort_order, name");
		$result = array();
		while ($row = db_fetch_row($q)) $result[] = $row;
		return $result;
	}



	// *****************************************************************************
	// Purpose        get category by id
	// Inputs   $categoryID
	//                                - category ID
	// Remarks
	// Returns
	function catGetCategoryById($categoryID)
	{
		$sql_query = "SELECT cat.categoryID, cat.name, cat.parent, cat.products_count, cat.picture, cat.products_count_admin, cat.sort_order, cat.viewed_times,  cat.allow_products_comparison, cat.allow_products_search, cat.show_subcategories_products, 
		tpl_id, UID, typ,
		REPLACE(REPLACE(tpl.description,'{city}',cat.cat_h1), '{year}', YEAR(CURDATE())) as description,
		REPLACE(tpl.meta_description,'{city}',cat.name)as meta_description,
		REPLACE(tpl.meta_keywords,'{city}',cat.name) as meta_keywords,
		REPLACE(tpl.title,'{city}',cat.name) as title,
		REPLACE(tpl.cat_h1,'{city}',cat.cat_h1) as cat_h1,
		REPLACE(tpl.cat_h2_c,'{city}',cat.cat_h1) as cat_h2_c,
		REPLACE(tpl.cat_h2_o,'{city}',cat.cat_h1) as cat_h2_o,
		REPLACE(tpl.cat_h2_r,'{city}',cat.cat_h1) as cat_h2_r,
		level
		FROM ".CATEGORIES_TABLE." cat LEFT JOIN ".CATEGORIES_TPL_TABLE." tpl ON(cat.tpl_id = tpl.id)
		WHERE categoryID=".$categoryID;

		$q = db_query($sql_query);
		$catrow = db_fetch_row($q);
		if($catrow==false)
		{
			$sql_query = 'SELECT * FROM '.CATEGORIES_TABLE.' WHERE categoryID='.$categoryID;
			$catrow = db_fetch_row($q);
		}

		$catrow["name"] = ToText($catrow["name"]);
		$catrow["meta_description"] = ToText($catrow["meta_description"]);
		$catrow["meta_keywords"] = ToText($catrow["meta_keywords"]);
		$catrow["title"] = ToText($catrow["title"]);
		$catrow["cat_h1"] = ToText($catrow["cat_h1"]);
		$catrow["cat_h2_c"] = ToText($catrow["cat_h2_c"]);
		$catrow["cat_h2_o"] = ToText($catrow["cat_h2_o"]);
		$catrow["cat_h2_r"] = ToText($catrow["cat_h2_r"]);

		return $catrow;
	}

	// *****************************************************************************
	// Purpose        gets category META information in HTML form
	// Inputs   $categoryID
	//                                - category ID
	// Remarks
	// Returns
	function catGetMetaTags($categoryID)
	{
		$q = db_query( "select meta_description, meta_keywords from ".
			CATEGORIES_TABLE." where categoryID=".(int)$categoryID );
		$row = db_fetch_row($q);

		$res = "";

		if  ( $row["meta_description"] != "" )
			$res .= "\n";
		if  ( $row["meta_keywords"] != "" )
			$res .= "\n";

		return $res;
	}



	// *****************************************************************************
	// Purpose        adds product to appended category
	// Inputs
	// Remarks      this function uses CATEGORIY_PRODUCT_TABLE table in data base instead of
	//                        PRODUCTS_TABLE.categoryID. In CATEGORIY_PRODUCT_TABLE saves appended
	//                        categories
	// Returns        array of item
	//                        "categoryID"
	//                        "category_name"
	function catGetAppendedCategoriesToProduct( $productID )
	{
		$q = db_query( "select ".CATEGORIES_TABLE.".categoryID as categoryID, name as category_name ".
			" from ".CATEGORIY_PRODUCT_TABLE.", ".CATEGORIES_TABLE." ".
			" where ".CATEGORIY_PRODUCT_TABLE.".categoryID = ".CATEGORIES_TABLE.".categoryID ".
			" AND productID = ".(int)$productID  );
		$data = array();
		while( $row = db_fetch_row( $q ) ){
			$wayadd = '';
			$way = catCalculatePathToCategoryA($row["categoryID"]);
			$cway = count($way);
			for ($i=$cway-1; $i>=0; $i--){ if($way[$i]['categoryID']!=1) $wayadd .= $way[$i]['name'].' / '; }
			$row["category_way"]=$wayadd."".$row["category_name"]."";
			$data[] = $row;
		}
		return $data;
	}



	// *****************************************************************************
	// Purpose        adds product to appended category
	// Inputs
	// Remarks      this function uses CATEGORIY_PRODUCT_TABLE table in data base instead of
	//                        PRODUCTS_TABLE.categoryID. In CATEGORIY_PRODUCT_TABLE saves appended
	//                        categories
	// Returns        true if success, false otherwise
	function catAddProductIntoAppendedCategory($productID, $categoryID)
	{
		$q = db_query("select count(*) from ".CATEGORIY_PRODUCT_TABLE.
			" where productID=".(int)$productID." AND categoryID=".(int)$categoryID);
		$row = db_fetch_row( $q );

		$qh = db_query( "select categoryID from ".PRODUCTS_TABLE.
			" where productID=".(int)$productID);
		$rowh = db_fetch_row( $qh );
		$basic_categoryID = $rowh["categoryID"];

		if ( !$row[0] && $basic_categoryID != $categoryID )
		{
			db_query("insert into ".CATEGORIY_PRODUCT_TABLE.
				"( productID, categoryID ) ".
				"values( ".(int)$productID.", ".(int)$categoryID." )" );
			return true;
		}
		else
			return false;
	}


	// *****************************************************************************
	// Purpose        removes product to appended category
	// Inputs
	// Remarks      this function uses CATEGORIY_PRODUCT_TABLE table in data base instead of
	//                        PRODUCTS_TABLE.categoryID. In CATEGORIY_PRODUCT_TABLE saves appended
	//                        categories
	// Returns        nothing
	function catRemoveProductFromAppendedCategory($productID, $categoryID)
	{
		db_query("delete from ".CATEGORIY_PRODUCT_TABLE.
			" where productID = ".(int)$productID." AND categoryID = ".(int)$categoryID);

	}


	// *****************************************************************************
	// Purpose        calculate a path to the category ( $categoryID )
	// Inputs
	// Remarks
	// Returns        path to category
	function catCalculatePathToCategory( $categoryID )
	{
		if (!$categoryID) return NULL;

		$path = array();

		$q = db_query("select count(*) from ".CATEGORIES_TABLE.
			" where categoryID=".(int)$categoryID);
		$row = db_fetch_row($q);
		if ( $row[0] == 0 ) return $path;

		do
		{
			$q = db_query("select categoryID, parent, cat_h1 as name, UID FROM ".
				CATEGORIES_TABLE." WHERE categoryID=".(int)$categoryID);
			$row = db_fetch_row($q);
			$path[] = $row;

			//if ($row["parent"] == $row["categoryID"]) break;
			$categoryID = $row["parent"];
		}
		while ( $categoryID );
		//now reverse $path
		$path = array_reverse($path);
		return $path;
	}

	// *****************************************************************************
	// Purpose        calculate a path to the category ( $categoryID )
	// Inputs
	// Remarks
	// Returns        path to category
	function catCalculatePathToCategoryA( $categoryID )
	{
		if (!$categoryID) return NULL;

		$path = array();

		$q = db_query("select count(*) from ".CATEGORIES_TABLE.
			" where categoryID=".(int)$categoryID);
		$row = db_fetch_row($q);
		if ( $row[0] == 0 ) return $path;
		$curr = $categoryID;
		do
		{
			$q = db_query("select categoryID, parent, name FROM ".
				CATEGORIES_TABLE." WHERE categoryID=".(int)$categoryID);
			$row = db_fetch_row($q);
			if($categoryID != $curr) $path[] = $row;

			if ( $categoryID == 1 ) break;

			$categoryID = $row["parent"];
		}
		while ( 1 );
		//now reverse $path
		$path = array_reverse($path);
		return $path;
	}

	function _deleteSubCategories( $parent )
	{

		$q1 = db_query("select picture FROM ".CATEGORIES_TABLE." WHERE categoryID=".(int)$parent);
		$r = db_fetch_row($q1);
		if ($r["picture"] && file_exists("data/category/".$r["picture"])) unlink("data/category/".$r["picture"]);


		$q = db_query("select categoryID FROM ".CATEGORIES_TABLE." WHERE parent=".(int)$parent);
		while ($row = db_fetch_row($q)){
			$qp = db_query("select productID FROM ".PRODUCTS_TABLE." where categoryID=".(int)$row["categoryID"] );
			while ( $picture = db_fetch_row($qp) )
			{
				DeleteThreePictures2($picture["productID"]);
			}
			db_query("delete FROM ".PRODUCTS_TABLE." WHERE categoryID=".(int)$row["categoryID"]);
			_deleteSubCategories( $row["categoryID"] );
		}
		db_query("delete FROM ".CATEGORIES_TABLE." WHERE parent=".(int)$parent);

	}


	// *****************************************************************************
	// Purpose        deletes category
	// Inputs
	//                 $categoryID - ID of category to be deleted
	// Remarks      delete also all subcategories, all prodoctes remove into root
	// Returns        nothing
	function catDeleteCategory( $categoryID )
	{
		_deleteSubCategories( $categoryID );

		$q=db_query("select productID FROM ".PRODUCTS_TABLE." where categoryID=".(int)$categoryID );
		if ( $picture=db_fetch_row($q) )
		{
			DeleteThreePictures2($picture["productID"]);
		}

		db_query("delete FROM ".PRODUCTS_TABLE." WHERE categoryID=".(int)$categoryID);

		db_query("delete FROM ".CATEGORIES_TABLE." WHERE parent=".(int)$categoryID);
		$q = db_query("select picture FROM ".CATEGORIES_TABLE." WHERE categoryID=".(int)$categoryID);
		$r = db_fetch_row($q);
		if ($r["picture"] && file_exists("data/category/".$r["picture"])) unlink("data/category/".$r["picture"]);

		db_query("delete FROM ".CATEGORIES_TABLE." WHERE categoryID=".(int)$categoryID);
	}

?> $value )
        {
                if ( $updatedValues[$key]["option_radio_type"] == "UN_DEFINED" ||
                                $updatedValues[$key]["option_radio_type"] == "ANY_VALUE" )
                        $option_type=0;
                else
                        $option_type=1;
                if ( $updatedValues[$key]["option_radio_type"] == "UN_DEFINED" )
                        $option_value=null;
                else
                {
                        if ( isset($updatedValues[$key]["option_value"]) )
                                $option_value=$updatedValues[$key]["option_value"];
                        else
                                $option_value=null;
                }

                $where_clause = " where optionID=".(int)$key." AND productID=".(int)$productID;

                $q=db_query("select count(*) from ".PRODUCT_OPTIONS_VALUES_TABLE." ".$where_clause );

                $r = db_fetch_row($q);

                if ( $r[0]==1 ) // if row exists
                {
                        db_query("update ".PRODUCT_OPTIONS_VALUES_TABLE." set option_value='".
                                xEscSQL($option_value)."', option_type=".(int)$option_type." ".
                                $where_clause );
                }
                else // insert query
                {
                        db_query("insert into ".
                                PRODUCT_OPTIONS_VALUES_TABLE.
                                "(optionID, productID, option_value, option_type)".
                                "values ('".(int)$key."', '".(int)$productID."', '".xEscSQL($option_value).
                                        "', '".(int)$option_type."')");
                }
        }
}


// *****************************************************************************
// Purpose        this function updates product option that can be configurated by customer
// Inputs                     $option_show_times - how many times do show in user part
//                        $variantID_default - option id (FK) refers to
//                                PRODUCTS_OPTIONS_VALUES_VARIANTS_TABLE (PK)
//                        $setting - structure
//                                $setting[  ]["switchOn"] - if true show this
//                                                value in user part
//                                $setting[  ]["price_surplus"] - price surplus when
//                                                this option is selected by user
// Remarks
// Returns                nothing
function UpdateConfiguriableProductOption($optionID, $productID,
                $option_show_times, $variantID_default, $setting )
{
        $where_clause=" where optionID=".(int)$optionID." AND productID=".(int)$productID;
        $q=db_query( "select count(*) from ".PRODUCT_OPTIONS_VALUES_TABLE.$where_clause );
        $r=db_fetch_row($q);
        if ( $r[0]!=0 )
        {
                 db_query("update ".PRODUCT_OPTIONS_VALUES_TABLE.
                         " set option_value='', ".
                         " option_show_times='".(int)$option_show_times."', ".
                         " variantID=".(int)$variantID_default." ".
                         $where_clause );
        }
        else
        {
                 db_query("insert into ".PRODUCT_OPTIONS_VALUES_TABLE.
                         "(optionID, productID, option_type, option_value, ".
                         "option_show_times, variantID) ".
                         "values('".(int)$optionID."', '".(int)$productID."', 0, '', '".
                         (int)$option_show_times."',  ".
                         (int)$variantID_default."  )");
        }

        $q1=db_query("select variantID from ".PRODUCTS_OPTIONS_VALUES_VARIANTS_TABLE.
                         " where optionID=".(int)$optionID);
        $if_only = false;
        while( $r1=db_fetch_row($q1) )
        {
                $key = $r1["variantID"];
                $where_clause=" where productID=".(int)$productID." AND optionID=".(int)$optionID.
                                 " AND variantID=".(int)$key;
                if ( !isset($setting[$key]["switchOn"]) )
                {
                        db_query( "delete from ".PRODUCTS_OPTIONS_SET_TABLE.$where_clause );
                }
                else
                {
                        $q=db_query("select count(*) from ".PRODUCTS_OPTIONS_SET_TABLE.
                                        $where_clause);
                        $r=db_fetch_row($q);
                        if ( $r[0]!=0 )
                        {
                                db_query("update ".PRODUCTS_OPTIONS_SET_TABLE." set price_surplus='".
                                        (float)$setting[$key]["price_surplus"]."'".$where_clause );
                                $if_only = true;
                        }
                        else
                        {
                                db_query("insert into ".PRODUCTS_OPTIONS_SET_TABLE.
                                         "(productID, optionID, variantID, price_surplus)".
                                         "values( '".(int)$productID."', '".
                                                (int)$optionID."', '".(int)$key."', '".
                                                (float)$setting[$key]["price_surplus"]."' )"
                                 );
                                $if_only = true;
                        }
                }
        }
        if ( !$if_only )
        {
                db_query("update ".PRODUCT_OPTIONS_VALUES_TABLE.
                         " set option_show_times=0 where optionID=".(int)$optionID." AND ".
                                " productID=".(int)$productID);
        }
}

?>= $offset && $i < $offset + $CountRowOnPage) ||
                                $navigatorParams == null  )
                {
                        $data[] = $r;
                }
                $i++;
        }
        $count_row = $i;
        return $data;
}



// *****************************************************************************
// Purpose        deletes country
// Inputs                     id
// Remarks
// Returns                nothing
function cnDeleteCountry($countryID)
{

        $tax_classes = taxGetTaxClasses();
        foreach( $tax_classes as $class ) taxDeleteRate( $class["classID"], $countryID );

        db_query("update ".CUSTOMER_ADDRESSES_TABLE.
                " set countryID=NULL where countryID=".(int)$countryID);
        $q = db_query("select zoneID from ".ZONES_TABLE." where countryID=".(int)$countryID);
        while( $r = db_fetch_row( $q ) )
        {
                db_query( "update ".CUSTOMER_ADDRESSES_TABLE.
                        " set zoneID=NULL where zoneID=".(int)$r["zoneID"]);
        }
        db_query("delete from ".ZONES_TABLE." where countryID=".(int)$countryID);
        db_query("delete from ".COUNTRIES_TABLE." where countryID=".(int)$countryID);
}


// *****************************************************************************
// Purpose        updates manufacturers
// Inputs                     $countryID        - id
//                        $country_name        - name
//                        $country_iso_2        - ISO abbreviation ( 2 chars )
//                        $country_iso_3        - ISO abbreviation ( 3 chars )
// Remarks
// Returns                nothing
function cnUpdateCountry( $countryID, $country_name, $country_iso_2, $country_iso_3 )
{
        db_query("update ".COUNTRIES_TABLE." set ".
                "  country_name='".xToText(trim($country_name))."', ".
                "  country_iso_2='".xToText(trim($country_iso_2))."', ".
                "  country_iso_3='".xToText(trim($country_iso_3))."' ".
                "  where countryID=".(int)$countryID);
}


// *****************************************************************************
// Purpose        adds manufacturers
// Inputs
//                        $country_name        - name
//                        $country_iso_2        - ISO abbreviation ( 2 chars )
//                        $country_iso_3        - ISO abbreviation ( 3 chars )
// Remarks
// Returns                nothing
function cnAddCountry($country_name, $country_iso_2, $country_iso_3  )
{
        db_query("insert into ".COUNTRIES_TABLE."( country_name, country_iso_2, country_iso_3 )".
                "values( '".xToText(trim($country_name))."', '".xToText(trim($country_iso_2))."', '".
                xToText(trim($country_iso_3))."' )" );
        return db_insert_id();
}

?>bitArray = array();
                for( $i=1; $i<=32;  $i++)
                        $this->bitArray[$i-1] = 0;
        }

        function _setByte( $byte, $displacement )
        {
                // 00000001 = 1
                $this->bitArray[$displacement + 0] = (($byte&1)   != 0)?1:0;
                // 00000010 = 2
                $this->bitArray[$displacement + 1] = (($byte&2)   != 0)?1:0;
                // 00000100 = 4
                $this->bitArray[$displacement + 2] = (($byte&4)   != 0)?1:0;
                // 00001000 = 8
                $this->bitArray[$displacement + 3] = (($byte&8)   != 0)?1:0;
                // 00010000 = 16
                $this->bitArray[$displacement + 4] = (($byte&16)  != 0)?1:0;
                // 00100000 = 32
                $this->bitArray[$displacement + 5] = (($byte&32)  != 0)?1:0;
                // 01000000 = 64
                $this->bitArray[$displacement + 6] = (($byte&64)  != 0)?1:0;
                // 10000000 = 128
                $this->bitArray[$displacement + 7] = (($byte&128) != 0)?1:0;
        }

        function _getByte( $displacement )
        {
                return $this->bitArray[$displacement + 0]*1  +
                                        $this->bitArray[$displacement + 1]*2 +
                                        $this->bitArray[$displacement + 2]*4 +
                                        $this->bitArray[$displacement + 3]*8 +
                                        $this->bitArray[$displacement + 4]*16 +
                                        $this->bitArray[$displacement + 5]*32 +
                                        $this->bitArray[$displacement + 6]*64 +
                                        $this->bitArray[$displacement + 7]*128;
        }

        function SetValue( $byte1, $byte2, $byte3, $byte4  )
        {
                $this->_setByte( $byte1, 0  );
                $this->_setByte( $byte2, 8  );
                $this->_setByte( $byte3, 16 );
                $this->_setByte( $byte4, 24 );
        }

        function GetValue( &$byte1, &$byte2, &$byte3, &$byte4 )
        {
                $byte1 = $this->_getByte( 0  );
                $byte2 = $this->_getByte( 8  );
                $byte3 = $this->_getByte( 16 );
                $byte4 = $this->_getByte( 24 );
        }

        function GetCount()
        {
                $coeff = 1;
                $res = 0;
                for($i=1; $i<=32; $i++)
                {
                        $res += $this->bitArray[$i-1]*$coeff;
                        $coeff *= 2;
                }
                return $res;
        }

        function SetBit( $bitValue, $bitIndex  )
        {
                $this->bitArray[ $bitIndex ] = $bitValue;
        }

        function GetHTML_Representation()
        {
                $res = "";
                $res .= "";

                // head row
                $res .= "        ";
                for( $i=31; $i>=0; $i-- )
                {
                        $res .= "                ";
                }
                $res .= "        ";

                // bit values
                $res .= "        ";
                for( $i=31; $i>=0; $i-- )
                {
                        $res .= "                ";
                }
                $res .= "        ";
                $res .= "
"; $res .= " $i"; $res .= "
"; $res .= " ".$this->bitArray[$i]; $res .= "
"; return $res; } function ShiftToLeft( $countBit ) { $resBitArray = $this->bitArray; for( $i=31; $i>=0; $i-- ) if ( $i + $countBit <= 31 ) $resBitArray[$i + $countBit] = $resBitArray[$i]; for( $i=1; $i<=$countBit; $i++ ) $resBitArray[$i-1]=0; $res = new DWord(); $res->bitArray = $resBitArray; return $res; } function ShiftToRight( $countBit ) { $resBitArray = $this->bitArray; for( $i=0; $i<=31; $i++ ) if ( $i - $countBit >= 0 ) $resBitArray[$i - $countBit] = $resBitArray[$i]; for( $i=31; $i>=31-$countBit+1; $i-- ) $resBitArray[$i]=0; $res = new DWord(); $res->bitArray = $resBitArray; return $res; } function BitwiseOR( $dwordObject ) { $res = new DWord(); for( $i=0; $i<=31; $i++ ) { if ( $this->bitArray[$i]+$dwordObject->bitArray[$i] != 0 ) $res->SetBit( 1, $i ); else $res->SetBit( 0, $i ); } return $res; } function BitwiseAND( $dwordObject ) { $res = new DWord(); for( $i=0; $i<=31; $i++ ) $res->SetBit( $this->bitArray[$i]*$dwordObject->bitArray[$i], $i ); return $res; } function BitwiseXOR( $dwordObject ) { $res = new DWord(); for( $i=0; $i<=31; $i++ ) { if ($this->bitArray[$i] == $dwordObject->bitArray[$i]) $res->SetBit( 1, $i ); else $res->SetBit( 0, $i ); } return $res; } function Plus( $dwordObject ) { $res = new DWord(); $cf = 0; for( $i=0; $i<=3; $i++ ) { $byte1 = $this->_getByte( $i*8 ); $byte2 = $dwordObject->_getByte( $i*8 ); $res->_setByte( $byte1 + $byte2 + $cf, $i*8 ); if ( $byte1 + $byte2 + $cf >= 256 ) $cf = 1; } return $res; } } // ***************************************************************************** // Purpose encrypts cc_number field ( see ORDERS_TABLE in database_structure.xml ) // Inputs // Remarks // Returns function cryptCCNumberCrypt( $cc_number, $key ) { return base64_encode($cc_number); /* $res = ""; $strlen = strlen( $cc_number ); for( $i=1; $i<=32-$strlen; $i++ ) $cc_number .= " "; $res .= chr( $strlen ); $dWordArray = array(); for( $i=1; $i<=8; $i++ ) { $dWordObject = DWord(); $dWordObject->SetValue( $cc_number[ ($i-1)*4 + 0 ], $cc_number[ ($i-1)*4 + 1 ], $cc_number[ ($i-1)*4 + 2 ], $cc_number[ ($i-1)*4 + 3 ] ); $dWordArray[] = $dWordObject; } $dWordArrayCifered = array(); for( $i=1; $i<=4; $i++ ) { $ciferedData = _gostCrypt( array( $dWordArray[($i-1)*2], $dWordArray[($i-1)*2 + 1]), $key ); $dWordArrayCifered[] = $ciferedData[0]; $dWordArrayCifered[] = $ciferedData[1]; } foreach( $dWordArrayCifered as $dWordCifered ) { $byte1 = 0; $byte2 = 0; $byte3 = 0; $byte4 = 0; $dWordCifered->GetValue( &$byte1, &$byte2, &$byte3, &$byte4 ); $res .= chr($byte1); $res .= chr($byte2); $res .= chr($byte3); $res .= chr($byte4); } return $res; */ } // ***************************************************************************** // Purpose decrypts cc_number field ( see ORDERS_TABLE in database_structure.xml ) // Inputs // Remarks // Returns function cryptCCNumberDeCrypt( $cifer, $key ) { return base64_decode($cifer); /* $res = ""; $strlen = (int)($cifer[0]); $dWordArray = array(); for( $i=1; $i<=8; $i++ ) { $dWordObject = DWord(); $dWordObject->SetValue( $cifer[ ($i-1)*4 + 1 ], $cifer[ ($i-1)*4 + 2 ], $cifer[ ($i-1)*4 + 3 ], $cifer[ ($i-1)*4 + 4 ] ); $dWordArray[] = $dWordObject; } $dWordArrayDeCifered = array(); for( $i=1; $i<=4; $i++ ) { $deCiferedData = _gostDeCrypt( array( $dWordArray[($i-1)*2], $dWordArray[($i-1)*2 + 1]), $key ); $dWordArrayCifered[] = $deCiferedData[0]; $dWordArrayCifered[] = $deCiferedData[1]; } foreach( $dWordArrayCifered as $dWordCifered ) { $byte1 = 0; $byte2 = 0; $byte3 = 0; $byte4 = 0; $dWordCifered->GetValue( &$byte1, &$byte2, &$byte3, &$byte4 ); $res .= chr($byte1); $res .= chr($byte2); $res .= chr($byte3); $res .= chr($byte4); } $temp = $res; for( $i=1; $i<=$strlen; $i++ ) $res .= $temp[$i-1]; return $res; */ } // ***************************************************************************** // Purpose encrypts cc_holdername field ( see ORDERS_TABLE in database_structure.xml ) // Inputs // Remarks // Returns function cryptCCHoldernameCrypt( $cc_holdername, $key ) { return base64_encode( $cc_holdername ); } // ***************************************************************************** // Purpose decrypts cc_holdername field ( see ORDERS_TABLE in database_structure.xml ) // Inputs // Remarks // Returns function cryptCCHoldernameDeCrypt( $cifer, $key ) { return base64_decode( $cifer ); } // ***************************************************************************** // Purpose encrypts cc_expires field ( see ORDERS_TABLE in database_structure.xml ) // Inputs // Remarks // Returns function cryptCCExpiresCrypt( $cc_expires, $key ) { return base64_encode( $cc_expires ); } // ***************************************************************************** // Purpose decrypts cc_expires field ( see ORDERS_TABLE in database_structure.xml ) // Inputs // Remarks // Returns function cryptCCExpiresDeCrypt( $cifer, $key ) { return base64_decode( $cifer ); } // ***************************************************************************** // Purpose encrypts customer ( and admin ) password field // ( see ORDERS_TABLE in database_structure.xml ) // Inputs // Remarks // Returns function cryptPasswordCrypt( $password, $key ) { return base64_encode( $password ); } // ***************************************************************************** // Purpose decrypts customer ( and admin ) password field ( see ORDERS_TABLE in database_structure.xml ) // Inputs // Remarks // Returns function cryptPasswordDeCrypt( $cifer, $key ) { return base64_decode( $cifer ); } // ***************************************************************************** // Purpose encrypts getFileParam // Inputs // Remarks see also get_file.php // Returns function cryptFileParamCrypt( $getFileParam, $key ) { return base64_encode( $getFileParam ); } // ***************************************************************************** // Purpose decrypt getFileParam // Inputs // Remarks see also get_file.php // Returns function cryptFileParamDeCrypt( $cifer, $key ) { return base64_decode( $cifer ); } //-------------------------------------- // initialize // it is single byte values $bK8 = array( 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7 ); $bK7 = array( 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10 ); $bK6 = array( 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8 ); $bK5 = array( 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15 ); $bK4 = array( 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9 ); $bK3 = array( 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11 ); $bK2 = array( 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1 ); $bK1 = array( 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7 ); // it is single byte values $bK87 = array(); $bK65 = array(); $bK43 = array(); $bK21 = array(); for ($i=0; $i<256; $i++) { $bK87[$i] = $bK8[$i >> 4] << 4 | $bK7[$i & 15]; $bK65[$i] = $bK6[$i >> 4] << 4 | $bK5[$i & 15]; $bK43[$i] = $bK4[$i >> 4] << 4 | $bK3[$i & 15]; $bK21[$i] = $bK2[$i >> 4] << 4 | $bK1[$i & 15]; } function _f( $x ) { global $bK87; global $bK65; global $bK43; global $bK21; // $bK87[$x>>24 & 255] << 24 $x1 = $x->ShiftToRight(24); $x1 = $x1->BitwiseAND(255); $temp = $bK87[ (int)$x1->GetCount() ]; $x1 = new DWord(); $x1->SetValue( $temp, 0, 0, 0 ); $x1->ShiftToLeft( 24 ); debug( $x1->GetCount() ); // $bK65[$x>>16 & 255] << 16 $x2 = $x->ShiftToLeft(16); $x2 = $x2->BitwiseAND(255); $temp = $bK65[ $x2->GetCount() ]; $x2 = new DWord(); $x2->SetValue( $temp, 0, 0, 0 ); $x2->ShiftToLeft(16); // $bK43[$x>> 8 & 255] << 8 $x3 = $x->ShiftToRight(8); $x3 = $x3->BitwiseAND(255); $temp = $bK43[ $x3->GetCount() ]; $x3 = new DWord(); $x3->SetValue( $temp, 0, 0, 0 ); $x3->ShiftToLeft(8); // $bK21[$x & 255] $x4 = $x->BitwiseAND(255); $temp = $bK21[ $x4->GetCount() ]; $x4 = new DWord(); $x4->SetValue( $temp, 0, 0, 0 ); //$x = $bK87[$x>>24 & 255] << 24 | $bK65[$x>>16 & 255] << 16 | // $bK43[$x>> 8 & 255] << 8 | $bK21[$x & 255]; $res = $x1->BitwiseOR( $x2 ); $res = $res->BitwiseOR( $x3 ); $res = $res->BitwiseOR( $x4 ); return $res; } // ***************************************************************************** // Purpose GOST cryptography function // Inputs $in - 2 item of 32 values ( source data ) // $key - 8 item of 32 values ( key to encrypted ) // Remarks // Returns cyfered data function _gostCrypt( $in, $key ) { $n1 = $in[0]; $n2 = $in[1]; /* Instead of swapping halves, swap names each round */ $n2 = $n2->BitwiseXOR( _f($n1->Plus($key[0])) ); debug( $n1->GetCount() ); debug( $key[0]->GetCount() ); $n2 = _f($n1->Plus($key[0])); debug( $n2." = ".$n2->GetCount() ); debug("=========================== Cifer ============================"); debug( $n2->GetHTML_Representation() ); $byte1 = null; $byte2 = null; $byte3 = null; $byte4 = null; $n2->GetValue( $byte1, $byte2, $byte3, $byte4 ); debug( $byte1 ); debug( $byte2 ); debug( $byte3 ); debug( $byte4 ); debug("=============================================================="); $n1 = $n1->BitwiseXOR( _f($n2->Plus($key[1])) ); $n2 = $n2->BitwiseXOR( _f($n1->Plus($key[2])) ); $n1 = $n1->BitwiseXOR( _f($n2->Plus($key[3])) ); $n2 = $n2->BitwiseXOR( _f($n1->Plus($key[4])) ); $n1 = $n1->BitwiseXOR( _f($n2->Plus($key[5])) ); $n2 = $n2->BitwiseXOR( _f($n1->Plus($key[6])) ); $n1 = $n1->BitwiseXOR( _f($n2->Plus($key[7])) ); $n2 = $n2->BitwiseXOR( _f($n1->Plus($key[0])) ); $n1 = $n1->BitwiseXOR( _f($n2->Plus($key[1])) ); $n2 = $n2->BitwiseXOR( _f($n1->Plus($key[2])) ); $n1 = $n1->BitwiseXOR( _f($n2->Plus($key[3])) ); $n2 = $n2->BitwiseXOR( _f($n1->Plus($key[4])) ); $n1 = $n1->BitwiseXOR( _f($n2->Plus($key[5])) ); $n2 = $n2->BitwiseXOR( _f($n1->Plus($key[6])) ); $n1 = $n1->BitwiseXOR( _f($n2->Plus($key[7])) ); $n2 = $n2->BitwiseXOR( _f($n1->Plus($key[0])) ); $n1 = $n1->BitwiseXOR( _f($n2->Plus($key[1])) ); $n2 = $n2->BitwiseXOR( _f($n1->Plus($key[2])) ); $n1 = $n1->BitwiseXOR( _f($n2->Plus($key[3])) ); $n2 = $n2->BitwiseXOR( _f($n1->Plus($key[4])) ); $n1 = $n1->BitwiseXOR( _f($n2->Plus($key[5])) ); $n2 = $n2->BitwiseXOR( _f($n1->Plus($key[6])) ); $n1 = $n1->BitwiseXOR( _f($n2->Plus($key[7])) ); $n2 = $n2->BitwiseXOR( _f($n1->Plus($key[7])) ); $n1 = $n1->BitwiseXOR( _f($n2->Plus($key[6])) ); $n2 = $n2->BitwiseXOR( _f($n1->Plus($key[5])) ); $n1 = $n1->BitwiseXOR( _f($n2->Plus($key[4])) ); $n2 = $n2->BitwiseXOR( _f($n1->Plus($key[3])) ); $n1 = $n1->BitwiseXOR( _f($n2->Plus($key[2])) ); $n2 = $n2->BitwiseXOR( _f($n1->Plus($key[1])) ); $n1 = $n1->BitwiseXOR( _f($n2->Plus($key[0])) ); $out = array(); $out[0] = $n2; $out[1] = $n1; return $out; } function _gostDeCrypt( $out, $key ) { $n1 = $in[0]; $n2 = $in[1]; /* Instead of swapping halves, swap names each round */ $n2 = $n2->BitwiseXOR( _f($n1->Plus($key[0])) ); $n1 = $n1->BitwiseXOR( _f($n2->Plus($key[1])) ); $n2 = $n2->BitwiseXOR( _f($n1->Plus($key[2])) ); $n1 = $n1->BitwiseXOR( _f($n2->Plus($key[3])) ); $n2 = $n2->BitwiseXOR( _f($n1->Plus($key[4])) ); $n1 = $n1->BitwiseXOR( _f($n2->Plus($key[5])) ); $n2 = $n2->BitwiseXOR( _f($n1->Plus($key[6])) ); $n1 = $n1->BitwiseXOR( _f($n2->Plus($key[7])) ); $n2 = $n2->BitwiseXOR( _f($n1->Plus($key[7])) ); $n1 = $n1->BitwiseXOR( _f($n2->Plus($key[6])) ); $n2 = $n2->BitwiseXOR( _f($n1->Plus($key[5])) ); $n1 = $n1->BitwiseXOR( _f($n2->Plus($key[4])) ); $n2 = $n2->BitwiseXOR( _f($n1->Plus($key[3])) ); $n1 = $n1->BitwiseXOR( _f($n2->Plus($key[2])) ); $n2 = $n2->BitwiseXOR( _f($n1->Plus($key[1])) ); $n1 = $n1->BitwiseXOR( _f($n2->Plus($key[0])) ); $n2 = $n2->BitwiseXOR( _f($n1->Plus($key[7])) ); $n1 = $n1->BitwiseXOR( _f($n2->Plus($key[6])) ); $n2 = $n2->BitwiseXOR( _f($n1->Plus($key[5])) ); $n1 = $n1->BitwiseXOR( _f($n2->Plus($key[4])) ); $n2 = $n2->BitwiseXOR( _f($n1->Plus($key[3])) ); $n1 = $n1->BitwiseXOR( _f($n2->Plus($key[2])) ); $n2 = $n2->BitwiseXOR( _f($n1->Plus($key[1])) ); $n1 = $n1->BitwiseXOR( _f($n2->Plus($key[0])) ); $n2 = $n2->BitwiseXOR( _f($n1->Plus($key[7])) ); $n1 = $n1->BitwiseXOR( _f($n2->Plus($key[6])) ); $n2 = $n2->BitwiseXOR( _f($n1->Plus($key[5])) ); $n1 = $n1->BitwiseXOR( _f($n2->Plus($key[4])) ); $n2 = $n2->BitwiseXOR( _f($n1->Plus($key[3])) ); $n1 = $n1->BitwiseXOR( _f($n2->Plus($key[2])) ); $n2 = $n2->BitwiseXOR( _f($n1->Plus($key[1])) ); $n1 = $n1->BitwiseXOR( _f($n2->Plus($key[0])) ); $out = array(); $out[0] = $n2; $out[1] = $n1; return $out; } ?>0) return $_SESSION["current_currency"]; } if ( isset($_SESSION["current_currency"])){ $q = db_query("select currency_value FROM ".CURRENCY_TYPES_TABLE." WHERE CID=".(int)$_SESSION["current_currency"]); $customerInfo = db_fetch_row($q); $_SESSION["current_currency"] = $customerInfo["CID"]; if ( $_SESSION["current_currency"] != null && $_SESSION["current_currency"]>0) return $_SESSION["current_currency"]; } $q = db_query( "select count(*) from ".CURRENCY_TYPES_TABLE." where CID=".(int)CONF_DEFAULT_CURRENCY); $count = db_fetch_row($q); if ( $count[0] ) return CONF_DEFAULT_CURRENCY; else return null; } // ***************************************************************************** // Purpose gets current selected by user currency unit // Inputs nothing // Remarks // Returns currency unit ID ( see CURRENCY_TYPES_TABLE table in DataBase ) function currGetCurrencyByID( $currencyID ) { $q = db_query( "select CID, Name, code, currency_value, where2show, sort_order, currency_iso_3, roundval from ". CURRENCY_TYPES_TABLE." where CID=".(int)$currencyID); $row = db_fetch_row($q); if (!$row) $row = NULL; return $row; } // ***************************************************************************** // Purpose get all currencies // Inputs nothing // Remarks // Returns currency array function currGetAllCurrencies() { $q = db_query("select Name, code, currency_iso_3, currency_value, where2show, CID, sort_order, roundval from ". CURRENCY_TYPES_TABLE." order by sort_order"); $data = array(); while( $row = db_fetch_row($q) ) $data[] = $row; return $data; } // ***************************************************************************** // Purpose delete currency by ID // Inputs CID // Remarks // Returns nothing function currDeleteCurrency( $CID ) { $q = db_query( "select CID from ".CURRENCY_TYPES_TABLE." where CID!=".(int)$CID ); if ( $currency=db_fetch_row($q) ) db_query("update ".CUSTOMERS_TABLE." set CID=".$currency["CID"]." where CID=".(int)$CID ); else db_query("update ".CUSTOMERS_TABLE." set CID=NULL where CID=".(int)$CID ); db_query( "delete from ".CURRENCY_TYPES_TABLE." where CID=".(int)$CID); } // ***************************************************************************** // Purpose update currency by ID // Inputs CID // Remarks // Returns nothing function currUpdateCurrency( $CID, $name, $code, $currency_iso_3, $value, $where, $sort_order, $roundval ) { db_query( "update ". CURRENCY_TYPES_TABLE. " set ". " Name='".xToText(trim($name))."', ". " code='".xEscSQL($code)."', ". " currency_value='".xEscSQL(trim($value))."', ". " where2show=".(int)$where.", ". " sort_order=".(int)$sort_order.", ". " currency_iso_3='".xToText(trim($currency_iso_3))."', ". " roundval=".(int)$roundval." ". " where CID=".(int)$CID); } // ***************************************************************************** // Purpose add currency by ID // Inputs CID // Remarks // Returns nothing function currAddCurrency( $name, $code, $currency_iso_3, $value, $where, $sort_order, $roundval ) { db_query( "insert into ".CURRENCY_TYPES_TABLE. " (Name, code, currency_value, where2show, sort_order, currency_iso_3, roundval) ". " values ('".xToText(trim($name))."', '".xEscSQL($code)."', '".xEscSQL(trim($value))."', '".(int)$where."', '". (int)$sort_order."', '".xToText(trim($currency_iso_3))."', '".(int)$roundval."')" ); } function currGetCurrencyByISO3( $_ISO3 ) { $q = db_query( "select CID, Name, code, currency_value, where2show, sort_order, currency_iso_3 from ". CURRENCY_TYPES_TABLE." where currency_iso_3='".xEscSQL($_ISO3)."' " ); $row = db_fetch_row($q); if (!$row) $row = NULL; return $row; } ?> (int)$dateArray[2], "month" => (int)$dateArray[1], "year" => (int)$dateArray[0] ); } //$dt is a datetime string in MySQL default format (e.g. 2005-12-25 23:59:59) //this functions converts it to format selected in the administrative mode function format_datetime($dt) { $dformat = (!strcmp(CONF_DATE_FORMAT,"DD.MM.YYYY")) ? "d.m.Y H:i:s" : "m/d/Y h:i:s A"; $a = @date($dformat, strtotime($dt)); return $a; } //$dt is a datetime string to MySQL default format (e.g. 2005-12-25) //this functions converts it to format selected in the administrative mode function dtDateConvert($dt) { $dformat = (!strcmp(CONF_DATE_FORMAT,"DD.MM.YYYY")) ? "." : "/"; $array = explode( $dformat, $dt ); $date = $array[2]."-".$array[1]."-".$array[0]; return $date; } ?> 0, "discount_standart_unit" => 0, "discount_current_unit" => 0, "rest_standart_unit" => 0, "rest_current_unit" => 0, "priceUnit" => getPriceUnit() ); $customerID = (int)regGetIdByLogin($log); switch( CONF_DISCOUNT_TYPE ) { // discount is switched off case 1: return $discount; break; // discount is based on customer group case 2: if ( !is_bool($customerID=regGetIdByLogin($log)) ) { $customer_group = GetCustomerGroupByCustomerId( $customerID ); if ( $customer_group ) $discount["discount_percent"] = $customer_group["custgroup_discount"]; else $discount["discount_percent"] = 0; } else return $discount; break; // discount is calculated with help general order price case 3: $discount["discount_percent"] = _calculateGeneralPriceDiscount( $orderPrice, $log ); break; // discount equals to discount is based on customer group plus // discount calculated with help general order price case 4: if ( !is_bool($customerID) ) { $customer_group = GetCustomerGroupByCustomerId( $customerID ); if ( !$customer_group ) $customer_group = array( "custgroup_discount" => 0 ); } else $customer_group["custgroup_discount"] = 0; $discount["discount_percent"] = $customer_group["custgroup_discount"] + _calculateGeneralPriceDiscount( $orderPrice, $log ); break; // discount is calculated as MAX( discount is based on customer group, // discount calculated with help general order price ) case 5: if ( !is_bool($customerID) ) $customer_group = GetCustomerGroupByCustomerId( $customerID ); else $customer_group["custgroup_discount"] = 0; if ( $customer_group["custgroup_discount"] >= _calculateGeneralPriceDiscount( $orderPrice, $log ) ) $discount["discount_percent"] = $customer_group["custgroup_discount"]; else $discount["discount_percent"] = _calculateGeneralPriceDiscount( $orderPrice, $log ); break; } $discount["discount_standart_unit"] = ((float)$orderPrice/100)*(float)$discount["discount_percent"]; $discount["discount_current_unit"] = show_priceWithOutUnit( $discount["discount_standart_unit"] ); $discount["rest_standart_unit"] = $orderPrice - $discount["discount_standart_unit"]; $discount["rest_current_unit"] = show_priceWithOutUnit( $discount["rest_standart_unit"] ); return $discount; } // ***************************************************************************** // Purpose gets all order price discounts // Inputs // Remarks // Returns function dscGetAllOrderPriceDiscounts() { $q = db_query( "select discount_id, price_range, percent_discount from ".ORDER_PRICE_DISCOUNT_TABLE. " order by price_range" ); $data = array(); while( $row = db_fetch_row($q) ) $data[] = $row; return $data; } // ***************************************************************************** // Purpose add order price discount // Inputs // Remarks // Returns if discount with $price_range already exists this function returns false and does not add new discount // otherwise true function dscAddOrderPriceDiscount( $price_range, $percent_discount ) { $q=db_query( "select price_range, percent_discount from ".ORDER_PRICE_DISCOUNT_TABLE. " where price_range=".xEscSQL($price_range)); if ( ($row=db_fetch_row($q)) ) return false; else { db_query("insert into ".ORDER_PRICE_DISCOUNT_TABLE." ( price_range, percent_discount ) ". " values( ".xEscSQL($price_range).", ".xEscSQL($percent_discount)." ) "); return true; } } // ***************************************************************************** // Purpose delete discount // Inputs // Remarks // Returns function dscDeleteOrderPriceDiscount( $discount_id ) { db_query("delete from ".ORDER_PRICE_DISCOUNT_TABLE." where discount_id=".(int)$discount_id); } // ***************************************************************************** // Purpose update discount // Inputs // Remarks // Returns function dscUpdateOrderPriceDiscount( $discount_id, $price_range, $percent_discount ) { $q=db_query( "select price_range, percent_discount from ".ORDER_PRICE_DISCOUNT_TABLE. " where price_range=".xEscSQL($price_range)." AND discount_id <> ".xEscSQL($discount_id)); if ( ($row=db_fetch_row($q)) ) return false; else { db_query("update ".ORDER_PRICE_DISCOUNT_TABLE. " set price_range=".xEscSQL($price_range).", percent_discount=".xEscSQL($percent_discount)." ". " where discount_id=".(int)$discount_id); return true; } } ?>= $offset && $i < $offset + $CountRowOnPage) || $navigatorParams == null ) { $row["add_time"] = format_datetime( $row["add_time"] ); $data[] = $row; } $i ++; } $count_row = $i; return $data; } function discGetAllDiscussedProducts() { $q = db_query( "select name AS product_name, ".PRODUCTS_TABLE.".productID AS productID from ". DISCUSSIONS_TABLE.", ".PRODUCTS_TABLE. " where ".DISCUSSIONS_TABLE.".productID=".PRODUCTS_TABLE.".productID ". " group by ".PRODUCTS_TABLE.".productID, ".PRODUCTS_TABLE.".name order by product_name" ); $data = array(); while( $row = db_fetch_row($q) ) $data[] = $row; return $data; } function discGetDiscussion( $DID ) { $q = db_query("select DID, Author, Body, add_time, Topic, name AS product_name, ". " ".PRODUCTS_TABLE.".productID AS productID from ". DISCUSSIONS_TABLE.", ".PRODUCTS_TABLE. " where ".DISCUSSIONS_TABLE.".productID=".PRODUCTS_TABLE.".productID AND DID=".(int)$DID); $row = db_fetch_row( $q ); $row["add_time"] = format_datetime( $row["add_time"] ); return $row; } function discAddDiscussion( $productID, $Author, $Topic, $Body ) { db_query("insert into ".DISCUSSIONS_TABLE. "(productID, Author, Body, add_time, Topic) ". "values( ".(int)$productID.", '".xToText($Author)."', '".xToText($Body)."', '".get_current_time()."', '".xToText($Topic)."' )"); } function discDeleteDiscusion( $DID ) { db_query( "delete from ".DISCUSSIONS_TABLE." where DID=".(int)$DID ); } ?>", ">", $str); return $str; } function isWindows() { if (isset($_SERVER["WINDIR"]) || isset($_SERVER["windir"])) return true; else return false; } function myfile_get_contents($fileName) { return implode("", file($fileName)); } function correct_URL($url, $mode = "http") //converts { $URLprefix = trim($url); $URLprefix = str_replace("http://", "", $URLprefix); $URLprefix = str_replace("https://", "", $URLprefix); $URLprefix = str_replace("index.php", "", $URLprefix); if ($URLprefix[strlen($URLprefix) - 1] == '/') { $URLprefix = substr($URLprefix, 0, strlen($URLprefix) - 1); } return ($mode . "://" . $URLprefix . "/"); } // ***************************************************************************** // Purpose sets access rights to files which uploaded with help move_uploaded_file // function // Inputs $file_name - file name // Remarks // Returns nothing function SetRightsToUploadedFile($file_name) { @chmod($file_name, 0666); } function getmicrotime() { list($usec, $sec) = explode(" ", microtime()); return ((float)$usec + (float)$sec); } // ***************************************************************************** // Purpose this function works without errors ( as is_writable PHP functoin ) // Inputs $url // Remarks // Returns nothing function IsWriteable($fileName) { $f = @fopen($fileName, "a"); return !is_bool($f); } // ***************************************************************************** // Purpose redirects to other PHP page specified URL ( $url ) // Inputs $url // Remarks this function uses header // Returns nothing function Redirect($url, $permanently = false) { if ($permanently) header('HTTP/1.1 301 Moved Permanently'); header("Location: " . $url); exit(); } // ***************************************************************************** // Purpose redirects to other PHP page specified URL ( $url ) // Inputs // Remarks if CONF_PROTECTED_CONNECTION == '1' this function uses protected ( https:// ) connection // else it uses unsecure http:// // $url is relative URL, NOT an absolute one, e.g. index.php, index.php?productID=x, but not http://www.example.com/ // Returns nothing function RedirectProtected($url) { if (CONF_PROTECTED_CONNECTION == '1') { Redirect(correct_URL(CONF_FULL_SHOP_URL, "https") . $url); //redirect to HTTPS part of the website } else Redirect($url); //relative URL } // ***************************************************************************** // Purpose redirects to other PHP page specified URL ( $url ) // Inputs $url // Remarks this function uses JavaScript client script // Returns nothing function RedirectJavaScript($url) { die(""); } // ***************************************************************************** // Purpose round float value to 0.01 precision // Inputs $float_value - value to float // Remarks // Returns rounded value function roundf($float_value) { return round(100 * $float_value) / 100; } function _testExtension($filename, $extension) { if ($extension == null || trim($extension) == "") return true; $i = strlen($filename) - 1; for (; $i >= 0; $i--) { if ($filename[$i] == '.') break; } if ($filename[$i] != '.') return false; else { $ext = substr($filename, $i + 1); return (strtolower($extension) == strtolower($ext)); } } function checklogin() { $rls = array(); if (isset($_SESSION["log"])) //look for user in the database { $q = db_query("select cust_password, actions FROM " . CUSTOMERS_TABLE . " WHERE Login='" . xEscSQL($_SESSION["log"]) . "'"); $row = db_fetch_row($q); //found customer - check password if (!$row || !isset($_SESSION["pass"]) || $row[0] != $_SESSION["pass"]) //unauthorized access { unset($_SESSION["log"]); unset($_SESSION["pass"]); session_unregister("log"); //calling session_unregister() is required since unset() may not work on some systems session_unregister("pass"); } else { $rls = unserialize($row[1]); unset($row); } } return $rls; } // ***************************************************************************** // Purpose gets all files in specified directory // Inputs $dir - full path directory // Remarks // Returns function GetFilesInDirectory($dir, $extension = "") { $dh = opendir($dir); $files = array(); while (false !== ($filename = readdir($dh))) { if (!is_dir($dir . '/' . $filename) && $filename != "." && $filename != "..") { if (_testExtension($filename, $extension)) $files[] = $dir . "/" . $filename; } } return $files; } // ***************************************************************************** // Purpose gets class name in file // Inputs $fileName - full file name // Remarks this file must contains only one class syntax valid declaration // Returns class name function GetClassName($fileName) { $strContent = myfile_get_contents($fileName); $_match = array(); $strContent = substr($strContent, strpos($strContent, '@connect_module_class_name'), 100); if (preg_match("|\@connect_module_class_name[\t ]+([0-9a-z_]*)|mi", $strContent, $_match)) { return $_match[1]; } else { return false; } } function InstallModule($module) { db_query("insert into " . MODULES_TABLE . " ( module_name ) " . " values( '" . xEscSQL($module->title) . "' ) "); } function GetModuleId($module) { $q = db_query("select module_id from " . MODULES_TABLE . " where module_name='" . xEscSQL($module->title) . "' "); $row = db_fetch_row($q); return (int)$row["module_id"]; } function _formatPrice($price, $rval = 2, $dec = '.', $term = ' ') { return number_format($price, $rval, $dec, $term); } //show a number and selected currency sign $price is in universal currency function show_price($price, $custom_currency = 0, $code = true, $d = ".", $t = "") { global $selected_currency_details; //if $custom_currency != 0 show price this currency with ID = $custom_currency if ($custom_currency == 0) { if (!isset($selected_currency_details) || !$selected_currency_details) //no currency found { return $price; } } else //show price in custom currency { $q = db_query("select code, currency_value, where2show, currency_iso_3, Name, roundval from " . CURRENCY_TYPES_TABLE . " where CID=" . (int)$custom_currency); if ($row = db_fetch_row($q)) { $selected_currency_details = $row; //for show_price() function } else //no currency found. In this case check is there any currency type in the database { $q = db_query("select code, currency_value, where2show, roundval from " . CURRENCY_TYPES_TABLE); if ($row = db_fetch_row($q)) { $selected_currency_details = $row; //for show_price() function } } } //is exchange rate negative or 0? if ($selected_currency_details[1] == 0) return ""; $price = roundf($price * $selected_currency_details[1]); //now show price $price = _formatPrice($price, $selected_currency_details["roundval"], $d, $t); if ($code) return $selected_currency_details[2] ? $price . $selected_currency_details[0] : $selected_currency_details[0] . $price; else return $price; } function ShowPriceInTheUnit($price, $currencyID) { $q_currency = db_query("select currency_value, where2show, code, roundval from " . CURRENCY_TYPES_TABLE . " where CID=" . (int)$currencyID); $currency = db_fetch_row($q_currency); $price = _formatPrice(roundf($price * $currency["currency_value"]), $currency["roundval"]); return $currency["where2show"] ? $price . $currency["code"] : $currency["code"] . $price; } function addUnitToPrice($price) { global $selected_currency_details; $price = _formatPrice($price, $selected_currency_details["roundval"]); return $selected_currency_details[2] ? $price . $selected_currency_details[0] : $selected_currency_details[0] . $price; } function ConvertPriceToUniversalUnit($priceWithOutUnit) { global $selected_currency_details; return (float)$priceWithOutUnit / (float)$selected_currency_details[1]; } function show_priceWithOutUnit($price) { global $selected_currency_details; if (!isset($selected_currency_details) || !$selected_currency_details) //no currency found { return $price; } //is exchange rate negative or 0? if ($selected_currency_details[1] == 0) return ""; //now show price $price = round(100 * $price * $selected_currency_details[1]) / 100; if (round($price * 10) == $price * 10 && round($price) != $price) $price = "$price" . "0"; //to avoid prices like 17.5 - write 17.50 instead return (float)$price; } function getPriceUnit() { global $selected_currency_details; if (!isset($selected_currency_details) || !$selected_currency_details) //no currency found { return ""; } return $selected_currency_details[0]; } function getLocationPriceUnit() { global $selected_currency_details; if (!isset($selected_currency_details) || !$selected_currency_details) //no currency found { return true; } return $selected_currency_details[2]; } /* function get_current_time() //get current date and time as a string //required to do INSERT queries of DATETIME/TIMESTAMP in different DBMSes { $timestamp = time(); if (DBMS == 'mssql') // $s = strftime("%H:%M:%S %d/%m/%Y", $timestamp); $s = strftime("%m.%d.%Y %H:%M:%S", $timestamp); else // MYSQL or IB $s = strftime("%Y-%m-%d %H:%M:%S", $timestamp); return $s; } */ function ShowNavigator($a, $offset, $q, $path, &$out) { //shows navigator [prev] 1 2 3 4 … [next] //$a - count of elements in the array, which is being navigated //$offset - current offset in array (showing elements [$offset ... $offset+$q]) //$q - quantity of items per page //$path - link to the page (f.e: "index.php?categoryID=1&") if ($a > $q) //if all elements couldn't be placed on the page { //[prev] if ($offset > 0) $out .= "<< " . STRING_PREVIOUS . "  "; //digital links $k = $offset / $q; //not more than 4 links to the left $min = $k - 5; if ($min < 0) { $min = 0; } else { if ($min >= 1) { //link on the 1st page $out .= "1  "; if ($min != 1) { $out .= "...   "; }; } } for ($i = $min; $i < $k; $i++) { $m = $i * $q + $q; if ($m > $a) $m = $a; $out .= "" . ($i + 1) . "  "; } //# of current page if (strcmp($offset, "show_all")) { $min = $offset + $q; if ($min > $a) $min = $a; $out .= "" . ($k + 1) . "  "; } else { $min = $q; if ($min > $a) $min = $a; $out .= "1  "; } //not more than 5 links to the right $min = $k + 6; if ($min > $a / $q) { $min = $a / $q; }; for ($i = $k + 1; $i < $min; $i++) { $m = $i * $q + $q; if ($m > $a) $m = $a; $out .= "" . ($i + 1) . "  "; } if (ceil($min * $q) < $a) { //the last link if ($min * $q < $a - $q) $out .= "...   "; $out .= "" . (floor($a / $q) + 1) . "  "; } //[next] if (strcmp($offset, "show_all")) if ($offset < $a - $q) $out .= "" . STRING_NEXT . " >>  "; //[show all] if (strcmp($offset, "show_all")) $out .= "|  " . STRING_SHOWALL . ""; else $out .= "|  " . STRING_SHOWALL . ""; } } function ShowNavigatormd($a, $offset, $q, $path, &$out) { //shows navigator [prev] 1 2 3 4 … [next] //$a - count of elements in the array, which is being navigated //$offset - current offset in array (showing elements [$offset ... $offset+$q]) //$q - quantity of items per page //$path - link to the page (f.e: "index.php?categoryID=1&") if ($a > $q) //if all elements couldn't be placed on the page { //[prev] if ($offset > 0) $out .= "<< " . STRING_PREVIOUS . "  "; //digital links $k = $offset / $q; //not more than 4 links to the left $min = $k - 5; if ($min < 0) { $min = 0; } else { if ($min >= 1) { //link on the 1st page $out .= "1  "; if ($min != 1) { $out .= "...  "; }; } } for ($i = $min; $i < $k; $i++) { $m = $i * $q + $q; if ($m > $a) $m = $a; $out .= "" . ($i + 1) . "  "; } //# of current page if (strcmp($offset, "show_all")) { $min = $offset + $q; if ($min > $a) $min = $a; $out .= "" . ($k + 1) . "  "; } else { $min = $q; if ($min > $a) $min = $a; $out .= "1  "; } //not more than 5 links to the right $min = $k + 6; if ($min > $a / $q) { $min = $a / $q; }; for ($i = $k + 1; $i < $min; $i++) { $m = $i * $q + $q; if ($m > $a) $m = $a; $out .= "" . ($i + 1) . "  "; } if (ceil($min * $q) < $a) { //the last link if ($min * $q < $a - $q) $out .= "...   "; $out .= "" . (floor($a / $q) + 1) . "  "; } //[next] if (strcmp($offset, "show_all")) if ($offset < $a - $q) $out .= "" . STRING_NEXT . " >>  "; //[show all] if (strcmp($offset, "show_all")) $out .= "|  " . STRING_SHOWALL . ""; else $out .= "|  " . STRING_SHOWALL . ""; } } function GetNavigatorHtmlmd($url, $countRowOnPage = CONF_PRODUCTS_PER_PAGE, $callBackFunction, $callBackParam, &$tableContent, &$offset, &$count, $urlflag) { if (isset($_GET["offset"])) $offset = (int)$_GET["offset"]; else $offset = 0; $offset -= $offset % $countRowOnPage; //CONF_PRODUCTS_PER_PAGE; if ($offset < 0) $offset = 0; $count = 0; if (!isset($_GET["show_all"])) //show 'CONF_PRODUCTS_PER_PAGE' products on this page { $tableContent = $callBackFunction($callBackParam, $count, array("offset" => $offset, "CountRowOnPage" => $countRowOnPage)); } else //show all products { $tableContent = $callBackFunction($callBackParam, $count, null); $offset = "show_all"; } if ($urlflag) ShowNavigatormd($count, $offset, $countRowOnPage, html_spchars($url . "_"), $out); else ShowNavigator($count, $offset, $countRowOnPage, html_spchars($url . "&"), $out); return $out; } function GetCurrentURL($file, $exceptKeys) { $res = $file; foreach ($_GET as $key => $val) { $exceptFlag = false; foreach ($exceptKeys as $exceptKey) if ($exceptKey == $key) { $exceptFlag = true; break; } if (!$exceptFlag) { if ($res == $file) $res .= "?" . $key . "=" . $val; else $res .= "&" . $key . "=" . $val; } } return $res; } function GetNavigatorHtml($url, $countRowOnPage = CONF_PRODUCTS_PER_PAGE, $callBackFunction, $callBackParam, &$tableContent, &$offset, &$count) { if (isset($_GET["offset"])) $offset = (int)$_GET["offset"]; else $offset = 0; $offset -= $offset % $countRowOnPage; //CONF_PRODUCTS_PER_PAGE; if ($offset < 0) $offset = 0; $count = 0; if (!isset($_GET["show_all"])) //show 'CONF_PRODUCTS_PER_PAGE' products on this page { $tableContent = $callBackFunction($callBackParam, $count, array("offset" => $offset, "CountRowOnPage" => $countRowOnPage)); } else //show all products { $tableContent = $callBackFunction($callBackParam, $count, null); $offset = "show_all"; } ShowNavigator($count, $offset, $countRowOnPage, html_spchars($url . "&"), $out); return $out; } function moveCartFromSession2DB() //all products in shopping cart, which are in session vars, move to the database { if (isset($_SESSION["gids"]) && isset($_SESSION["log"])) { $customerID = regGetIdByLogin($_SESSION["log"]); $q = db_query("select itemID from " . SHOPPING_CARTS_TABLE . " where customerID=" . (int)$customerID); $items = array(); while ($item = db_fetch_row($q)) $items[] = (int)$item["itemID"]; //$i=0; foreach ($_SESSION["gids"] as $key => $productID) { if ($productID == 0) continue; // search product in current user's shopping cart content $itemID = null; for ($j = 0; $j < count($items); $j++) { $q = db_query("select count(*) from " . SHOPPING_CART_ITEMS_TABLE . " where productID=" . (int)$productID . " AND itemID=" . (int)$items[$j]); $count = db_fetch_row($q); $count = $count[0]; if ($count != 0) { // compare configuration $configurationFromSession = $_SESSION["configurations"][$key]; $configurationFromDB = GetConfigurationByItemId($items[$j]); if (CompareConfiguration($configurationFromSession, $configurationFromDB)) { $itemID = $items[$j]; break; } } } if ($itemID == null) { // create new item db_query("insert into " . SHOPPING_CART_ITEMS_TABLE . " (productID) values(" . (int)$productID . ")"); $itemID = db_insert_id(); // set content item foreach ($_SESSION["configurations"][$key] as $vars) { db_query("insert into " . SHOPPING_CART_ITEMS_CONTENT_TABLE . " ( itemID, variantID ) " . " values( " . (int)$itemID . ", " . (int)$vars . " )"); } // insert item into cart db_query("insert " . SHOPPING_CARTS_TABLE . " (customerID, itemID, Quantity) values ( " . (int)$customerID . ", " . (int)$itemID . ", " . (int)$_SESSION["counts"][$key] . " )"); } else { db_query("update " . SHOPPING_CARTS_TABLE . " set Quantity=Quantity + " . (int)$_SESSION["counts"][$key] . " where customerID=" . (int)$customerID . " and itemID=" . (int)$itemID); } } unset($_SESSION["gids"]); unset($_SESSION["counts"]); unset($_SESSION["configurations"]); session_unregister("gids"); //calling session_unregister() is required since unset() may not work on some systems session_unregister("counts"); session_unregister("configurations"); } } // moveCartFromSession2DB function validate_search_string($s) //validates $s - is it good as a search query { //exclude special SQL symbols $s = str_replace("%", "", $s); $s = str_replace("_", "", $s); //",',\ $s = stripslashes($s); $s = str_replace("'", "\'", $s); return $s; } //validate_search_string function string_encode($s) // encodes a string with a simple algorythm { $result = base64_encode($s); return $result; } function string_decode($s) // decodes a string encoded with string_encode() { $result = base64_decode($s); return $result; } // ***************************************************************************** // Purpose this function creates array it containes value POST variables // Inputs name array // Remarks if is contained in $varnames, then for POST variable // _ in result array $data (see body) item is added // with key and POST variable _ value // Returns array $data ( see Remarks ) function ScanPostVariableWithId($varnames) { $data = array(); foreach ($varnames as $name) { foreach ($_POST as $key => $value) { if (strstr($key, $name . "_")) { $key = str_replace($name . "_", "", $key); $data[$key][$name] = $value; } } } return $data; } function ScanFilesVariableWithId($varnames) { $data = array(); foreach ($varnames as $name) { foreach ($_FILES as $key => $value) { if (strstr($key, $name . "_")) { $key = str_replace($name . "_", "", $key); $data[$key][$name] = $value; } } } return $data; } // ***************************************************************************** // Purpose this functin does also as ScanPostVariableWithId // but it uses GET variables // Inputs see ScanPostVariableWithId // Remarks see ScanPostVariableWithId // Returns see ScanPostVariableWithId function ScanGetVariableWithId($varnames) { $data = array(); foreach ($varnames as $name) { foreach ($_GET as $key => $value) { if (strstr($key, $name . "_")) { $key = str_replace($name . "_", "", $key); $data[$key][$name] = $value; } } } return $data; } function value($variable) { if (!isset($variable)) return "undefined"; $res = ""; if (is_null($variable)) { $res .= "NULL"; } else if (is_array($variable)) { $res .= "array"; $res .= "
    "; foreach ($variable as $key => $value) { $res .= "
  • "; $res .= "[ " . value($key) . " ]=" . value($value); $res .= "
  • "; } $res .= "
"; } else if (is_int($variable)) { $res .= "integer\n"; $res .= (string )$variable; } else if (is_bool($variable)) { $res .= "bool\n"; if ($variable) $res .= "True"; else $res .= "False"; } else if (is_string($variable)) { $res .= "string\n"; $res .= "'" . (string )$variable . "'"; } else if (is_float($variable)) { $res .= "float\n"; $res .= (string )$variable; } return $res; } function debug($variable) { if (!isset($variable)) { echo("undefined"); } else { echo "
"; echo(value($variable) . "
"); echo "
"; } } function set_query($_vars, $_request = '', $_store = false) { if (!$_request) { global $_SERVER; $_request = $_SERVER['REQUEST_URI']; } $_anchor = ''; @list($_request, $_anchor) = explode('#', $_request); if (strpos($_vars, '#') !== false) { @list($_vars, $_anchor) = explode('#', $_vars); } if (!$_vars && !$_anchor) return preg_replace('|\?.*$|', '', $_request) . ($_anchor ? '#' . $_anchor : ''); elseif (!$_vars && $_anchor) return $_request . '#' . $_anchor; $_rvars = array(); $tr_vars = explode('&', strpos($_request, '?') !== false ? preg_replace('|.*\?|', '', $_request) : ''); foreach ($tr_vars as $_var) { $_t = explode('=', $_var); if ($_t[0]) $_rvars[$_t[0]] = $_t[1]; } $tr_vars = explode('&', preg_replace(array('|^\&|', '|^\?|'), '', $_vars)); foreach ($tr_vars as $_var) { $_t = explode('=', $_var); if (!$_t[1]) unset($_rvars[$_t[0]]); else $_rvars[$_t[0]] = $_t[1]; } $tr_vars = array(); foreach ($_rvars as $_var => $_val) $tr_vars[] = "$_var=$_val"; if ($_store) { global $_SERVER; $_request = $_SERVER['REQUEST_URI']; $_SERVER['REQUEST_URI'] = preg_replace('|\?.*$|', '', $_request) . (count($tr_vars) ? '?' . implode ('&', $tr_vars) : '') . ($_anchor ? '#' . $_anchor : ''); return $_SERVER['REQUEST_URI']; } else return preg_replace('|\?.*$|', '', $_request) . (count($tr_vars) ? '?' . implode('&', $tr_vars) : '') . ($_anchor ? '#' . $_anchor : ''); } function getListerRange($_pagenumber, $_totalpages, $_lister_num = 20) { if ($_pagenumber <= 0) return array('start' => 1, 'end' => 1); $lister_start = $_pagenumber - floor($_lister_num / 2); $lister_start = ($lister_start + $_lister_num <= $_totalpages ? $lister_start : $_totalpages - $_lister_num + 1); $lister_start = ($lister_start > 0 ? $lister_start : 1); $lister_end = $lister_start + $_lister_num - 1; $lister_end = ($lister_end <= $_totalpages ? $lister_end : $_totalpages); return array('start' => $lister_start, 'end' => $lister_end); } function html_spchars($_data) { if (is_array($_data)) { foreach ($_data as $_ind => $_val) { $_data[$_ind] = html_spchars($_val); } return $_data; } else return htmlspecialchars($_data, ENT_QUOTES, 'cp1252'); } function html_amp($_data) { if (is_array($_data)) { foreach ($_data as $_ind => $_val) { $_data[$_ind] = strtr($_val, array('&' => '&')); } return $_data; } else return strtr($_data, array('&' => '&')); } function ToText($str) { $str = htmlspecialchars(trim($str), ENT_QUOTES, 'cp1251'); return $str; } function xToText($str) { $str = xEscSQL(xHtmlSpecialChars($str)); return $str; } function xStripSlashesGPC($_data) { if (!get_magic_quotes_gpc()) return $_data; if (is_array($_data)) { foreach ($_data as $_ind => $_val) { $_data[$_ind] = xStripSlashesGPC($_val); } return $_data; } return stripslashes($_data); } /** * Transform date from template format to DATETIME format * * @param string $_date * @param string $_template template for transform * @return string */ function TransformTemplateToDATE($_date, $_template = '') { if (!$_template) $_template = CONF_DATE_FORMAT; $day = substr($_date, strpos($_template, 'DD'), 2); $month = substr($_date, strpos($_template, 'MM'), 2); $year = substr($_date, strpos($_template, 'YYYY'), 4); return "{$year}-{$month}-{$day} "; } /** * Transform DATE to template format * * @param string $_date * @param string $_template template for transform * @return string */ function TransformDATEToTemplate($_date, $_template = '') { if (!$_template) $_template = CONF_DATE_FORMAT; preg_match('|(\d{4})-(\d{2})-(\d{2})|', $_date, $mathes); unset($mathes[0]); return str_replace(array('YYYY', 'MM', 'DD'), $mathes, $_template); } /** * Check date in template format * * @param string $_date * @param string $_template template for check * @return bool */ function isTemplateDate($_date, $_template = '') { if (!$_template) $_template = CONF_DATE_FORMAT; $ok = (strlen($_date) == strlen($_template) && (preg_replace('|\d{2}|', '', $_date) == str_replace (array('MM', 'DD', 'YYYY'), '', $_template))); $ok = ($ok && substr($_date, strpos($_template, 'DD'), 2) < 32 && substr($_date, strpos($_template, 'MM'), 2) < 13); return $ok; } function validateEmail($email) { if (!$email || !preg_match("/^[_\.a-z0-9-]{1,20}@(([a-z0-9-]+\.)+(com|net|org|mil|edu|gov|arpa|info|biz|inc|name|[a-z]{2})|[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})$/is", $email)) { throw new \Exception("Invalid e-mail: {$email}"); } } function renderEmailTemplateSmarty($templateName, $data) { $mailSmarty = new Smarty(); foreach ($data as $_var => $_val) { $mailSmarty->assign($_var, $_val); } return $mailSmarty->fetch('email/' . $templateName); } function renderEmailTemplateTwig($templateName, $data = array()) { $host = $_SERVER['HTTP_HOST']; $loader = new FilesystemLoader('./core/tpl/email'); $twig = new Environment($loader, array( 'cache' => "./core/cache/{$host}/email" )); return $twig->load($templateName)->render($data); } function mailByMailerWithDefaults($subject, $body, $charset, $to, $replyTo, $isHtml) { $from = [CONF_GENERAL_EMAIL, CONF_SHOP_NAME]; return mailByMailer($subject, $body, $charset, $from, $to, $replyTo, $isHtml, CONF_MAIL_METHOD, CONF_MAIL_HOST, CONF_MAIL_LOGIN, CONF_MAIL_PASS); } function mailByMailer($subject, $body, $charset, $from, $to, $replyTo, $isHtml, $useMail, $host, $login, $password) { $mail = new PHPMailer(); $useMail ? $mail->IsMail() : $mail->IsSMTP(); $mail->Subject = $subject; $mail->Body = $body; $mail->Host = $host; $mail->Username = $login; $mail->Password = $password; $mail->Port = 465; $mail->SMTPSecure = 'ssl'; $mail->SMTPAuth = true; if ($from) { list($fromEmail, $fromName) = $from; $mail->From = $fromEmail; $mail->FromName = $fromName; } if ($to) { list($toEmail, $toName) = $to; $mail->AddAddress($toEmail, $toName); } if ($replyTo) { list($replyToEmail, $replyToName) = $replyTo; $mail->AddReplyTo($replyToEmail, $replyToName); } $mail->CharSet = $charset; // $mail->CharSet = 'utf-8'; // $mail->Encoding = "8bit"; $mail->SetLanguage("ru"); $mail->IsHTML($isHtml); // $mail->AltBody = ERROR_NO_TEXT_IN_MAILDATA; return $mail->Send(); } /** * mail txt message from template * @param string email * @param string email subject * @param string template name */ function xMailTxtTemplateSmarty($toEmail, $subject, $templateName, $templateData = array(), $charset = DEFAULT_CHARSET) { validateEmail($toEmail); $_msg = renderEmailTemplateSmarty($templateName, $templateData); $to = [$toEmail, null]; return mailByMailerWithDefaults($subject, $_msg, $to, null, true); // include_once("core/classes/class.phpmailer.php"); // $mail = new PHPMailer(); // if (!CONF_MAIL_METHOD) $mail->IsSMTP(); // else $mail->IsMail(); // $mail->Host = CONF_MAIL_HOST; // $mail->Username = CONF_MAIL_LOGIN; // $mail->Password = CONF_MAIL_PASS; // $mail->SMTPAuth = true; // $mail->From = CONF_GENERAL_EMAIL; // $mail->FromName = CONF_SHOP_NAME; // $mail->CharSet = DEFAULT_CHARSET; // $mail->Encoding = "8bit"; // $mail->SetLanguage("ru"); // $mail->AddReplyTo(CONF_GENERAL_EMAIL, CONF_SHOP_NAME); // $mail->IsHTML(true); // $mail->Subject = $_Subject; // $mail->Body = $_msg; // $mail->AltBody = ERROR_NO_TEXT_IN_MAILDATA; // // // $mail->ClearAddresses(); // $mail->AddAddress($_Email, ''); // // return $mail->Send(); } function xMailTxtTemplateTwig($toEmail, $subject, $templateName, $templateData = array(), $charset = DEFAULT_CHARSET) { return xMailTemplateTwig($toEmail, $subject, $templateName, $templateData, false, $charset); } function xMailHtmlTemplateTwig($toEmail, $subject, $templateName, $templateData = array(), $charset = DEFAULT_CHARSET) { return xMailTemplateTwig($toEmail, $subject, $templateName, $templateData, true, $charset); } function xMailTemplateTwig($toEmail, $subject, $templateName, $templateData, $isHtml, $charset = DEFAULT_CHARSET) { validateEmail($toEmail); $_msg = renderEmailTemplateTwig($templateName, $templateData); $to = [$toEmail, null]; return mailByMailerWithDefaults($subject, $_msg, $charset, $to, null, $isHtml, $charset); } function xMailTxt($toEmail, $subject, $body, $replyToEmail = null, $replyToName = null, $charset = DEFAULT_CHARSET) { validateEmail($toEmail); $to = [$toEmail, null]; return mailByMailerWithDefaults($subject, $body, $charset, $to, [$replyToEmail, $replyToName], false); // if (!$_Email) return 0; // // include_once("core/classes/class.phpmailer.php"); // $mail = new PHPMailer(); // if (!CONF_MAIL_METHOD) $mail->IsSMTP(); // else $mail->IsMail(); // $mail->Host = CONF_MAIL_HOST; // $mail->Username = CONF_MAIL_LOGIN; // $mail->Password = CONF_MAIL_PASS; // $mail->SMTPAuth = true; // $mail->From = $_Email; // $mail->FromName = $castname; // $mail->CharSet = DEFAULT_CHARSET; // $mail->Encoding = "8bit"; // $mail->SetLanguage("ru"); // $mail->AddReplyTo($castmail, $castname); // $mail->IsHTML(false); // $mail->Subject = $_Subject; // $mail->Body = $_Text; // // if (preg_match("/^[_\.a-z0-9-]{1,20}@(([a-z0-9-]+\.)+(com|net|org|mil|edu|gov|arpa|info|biz|inc|name|[a-z]{2})|[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})$/is", // $_Email)) { // $mail->ClearAddresses(); // $mail->AddAddress($_Email, ''); // return $mail->Send(); // } else return false; } function xMailHtml($toEmail, $subject, $body, $charset = DEFAULT_CHARSET, $replyToEmail = null, $replyToName = null) { validateEmail($toEmail); $to = [$toEmail, null]; return mailByMailerWithDefaults($subject, $body, $charset, $to, [$replyToEmail, $replyToName], true); // if (!$_Email) return 0; // // include_once("core/classes/class.phpmailer.php"); // $mail = new PHPMailer(); // if (!CONF_MAIL_METHOD) $mail->IsSMTP(); // else $mail->IsMail(); // $mail->Host = CONF_MAIL_HOST; // $mail->Username = CONF_MAIL_LOGIN; // $mail->Password = CONF_MAIL_PASS; // $mail->SMTPAuth = true; // $mail->From = $castmail; // $mail->FromName = $castname; // $mail->CharSet = DEFAULT_CHARSET; // $mail->Encoding = "8bit"; // $mail->SetLanguage("ru"); // $mail->AddReplyTo($castmail, $castname); // $mail->IsHTML(true); // $mail->Subject = $_Subject; // $mail->Body = $_Text; // $mail->AltBody = ERROR_NO_TEXT_IN_MAILDATA; // // if (preg_match("/^[_\.a-z0-9-]{1,20}@(([a-z0-9-]+\.)+(com|net|org|mil|edu|gov|arpa|info|biz|inc|name|[a-z]{2})|[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})$/is", // $_Email)) { // $mail->ClearAddresses(); // $mail->AddAddress($_Email, ''); // return $mail->Send(); // } else return false; } function _deleteHTML_Elements($str) { $search = array("'&(deg|#176);'i", "'&(nbsp|#160);'i", "'&(ndash|#8211);'i", "'&(mdash|#8212);'i", "'&(bull|#149);'i", "'&(quot|#34|#034);'i", "'&(amp|#38|#038);'i", "'&(lt|#60|#060);'i", "'&(gt|#62|#062);'i", "'&(apos|#39|#039);'i", "'&(minus|#45|#045);'i", "'&(circ|#94|#094);'i", "'&(sup2|#178);'i", "'&(tilde|#126);'i", "'&(Scaron|#138);'i", "'&(lsaquo|#139);'i", "'&(OElig|#140);'i", "'&(lsquo|#145);'i", "'&(rsquo|#146);'i", "'&(ldquo|#147);'i", "'&(rdquo|#148);'i", "'&(ndash|#150);'i", "'&(mdash|#151);'i", "'&(tilde|#152);'i", "'&(trade|#153);'i", "'&(scaron|#154);'i", "'&(rsaquo|#155);'i", "'&(oelig|#156);'i", "'&(Yuml|#159);'i", "'&(yuml|#255);'i", "'&(OElig|#338);'i", "'&(oelig|#339);'i", "'&(Scaron|#352);'i", "'&(scaron|#353);'i", "'&(Yuml|#376);'i", "'&(fnof|#402);'i", "'&(circ|#710);'i", "'&(tilde|#732);'i", "'&(Alpha|#913);'i", "'&(Beta|#914);'i", "'&(Gamma|#915);'i", "'&(Delta|#916);'i", "'&(Epsilon|#917);'i", "'&(Zeta|#918);'i", "'&(Eta|#919);'i", "'&(Theta|#920);'i", "'&(Iota|#921);'i", "'&(Kappa|#922);'i", "'&(Lambda|#923);'i", "'&(Mu|#924);'i", "'&(Nu|#925);'i", "'&(Xi|#926);'i", "'&(Omicron|#927);'i", "'&(Pi|#928);'i", "'&(Rho|#929);'i", "'&(Sigma|#931);'i", "'&(Tau|#932);'i", "'&(Upsilon|#933);'i", "'&(Phi|#934);'i", "'&(Chi|#935);'i", "'&(Psi|#936);'i", "'&(Omega|#937);'i", "'&(alpha|#945);'i", "'&(beta|#946);'i", "'&(gamma|#947);'i", "'&(delta|#948);'i", "'&(epsilon|#949);'i", "'&(zeta|#950);'i", "'&(eta|#951);'i", "'&(theta|#952);'i", "'&(iota|#953);'i", "'&(kappa|#954);'i", "'&(lambda|#955);'i", "'&(mu|#956);'i", "'&(nu|#957);'i", "'&(xi|#958);'i", "'&(omicron|#959);'i", "'&(pi|#960);'i", "'&(rho|#961);'i", "'&(sigmaf|#962);'i", "'&(sigma|#963);'i", "'&(tau|#964);'i", "'&(upsilon|#965);'i", "'&(phi|#966);'i", "'&(chi|#967);'i", "'&(psi|#968);'i", "'&(omega|#969);'i", "'&(thetasym|#977);'i", "'&(upsih|#978);'i", "'&(piv|#982);'i", "'&(ensp|#8194);'i", "'&(emsp|#8195);'i", "'&(thinsp|#8201);'i", "'&(zwnj|#8204);'i", "'&(zwj|#8205);'i", "'&(lrm|#8206);'i", "'&(rlm|#8207);'i", "'&(lsquo|#8216);'i", "'&(rsquo|#8217);'i", "'&(sbquo|#8218);'i", "'&(ldquo|#8220);'i", "'&(rdquo|#8221);'i", "'&(bdquo|#8222);'i", "'&(dagger|#8224);'i", "'&(Dagger|#8225);'i", "'&(bull|#8226);'i", "'&(hellip|#8230);'i", "'&(permil|#8240);'i", "'&(prime|#8242);'i", "'&(Prime|#8243);'i", "'&(lsaquo|#8249);'i", "'&(rsaquo|#8250);'i", "'&(oline|#8254);'i", "'&(frasl|#8260);'i", "'&(euro|#8364);'i", "'&(image|#8465);'i", "'&(weierp|#8472);'i", "'&(real|#8476);'i", "'&(trade|#8482);'i", "'&(alefsym|#8501);'i", "'&(larr|#8592);'i", "'&(uarr|#8593);'i", "'&(rarr|#8594);'i", "'&(darr|#8595);'i", "'&(harr|#8596);'i", "'&(crarr|#8629);'i", "'&(lArr|#8656);'i", "'&(uArr|#8657);'i", "'&(rArr|#8658);'i", "'&(dArr|#8659);'i", "'&(hArr|#8660);'i", "'&(forall|#8704);'i", "'&(part|#8706);'i", "'&(exist|#8707);'i", "'&(empty|#8709);'i", "'&(nabla|#8711);'i", "'&(isin|#8712);'i", "'&(notin|#8713);'i", "'&(ni|#8715);'i", "'&(prod|#8719);'i", "'&(sum|#8721);'i", "'&(minus|#8722);'i", "'&(lowast|#8727);'i", "'&(radic|#8730);'i", "'&(prop|#8733);'i", "'&(infin|#8734);'i", "'&(ang|#8736);'i", "'&(and|#8743);'i", "'&(or|#8744);'i", "'&(cap|#8745);'i", "'&(cup|#8746);'i", "'&(int|#8747);'i", "'&(there4|#8756);'i", "'&(sim|#8764);'i", "'&(cong|#8773);'i", "'&(asymp|#8776);'i", "'&(ne|#8800);'i", "'&(equiv|#8801);'i", "'&(le|#8804);'i", "'&(ge|#8805);'i", "'&(sub|#8834);'i", "'&(sup|#8835);'i", "'&(nsub|#8836);'i", "'&(sube|#8838);'i", "'&(supe|#8839);'i", "'&(oplus|#8853);'i", "'&(otimes|#8855);'i", "'&(perp|#8869);'i", "'&(sdot|#8901);'i", "'&(lceil|#8968);'i", "'&(rceil|#8969);'i", "'&(lfloor|#8970);'i", "'&(rfloor|#8971);'i", "'&(lang|#9001);'i", "'&(rang|#9002);'i", "'&(loz|#9674);'i", "'&(spades|#9824);'i", "'&(clubs|#9827);'i", "'&(hearts|#9829);'i", "'&(diams|#9830);'i", "'&(copy|#169);'i", "'&(reg|#174);'i", "'&(pound|#163);'i", "'&(laquo|#171);'i", "'&(raquo|#187);'i", "'&(sect|#167);'i", "!\s+!"); $replace = array("d", " ", "_", "-", "-", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", " "); return trim(strtr(preg_replace($search, $replace, $str), array("\"" => "", "'" => "", "<" => "", ">" => "", "&" => "", " ," => ","))); } /** * replace newline symbols to <br /> * @param mixed data for action * @param array which elements test * @return mixed */ function xNl2Br($_Data, $_Key = array()) { if (!is_array($_Data)) { return nl2br($_Data); } if (!is_array($_Key)) $_Key = array($_Key); foreach ($_Data as $__Key => $__Data) { if (count($_Key) && !is_array($__Data)) { if (in_array($__Key, $_Key)) { $_Data[$__Key] = xNl2Br($__Data, $_Key); } } else $_Data[$__Key] = xNl2Br($__Data, $_Key); } return $_Data; } function xStrReplace($_Search, $_Replace, $_Data, $_Key = array()) { if (!is_array($_Data)) { return str_replace($_Search, $_Replace, $_Data); } if (!is_array($_Key)) $_Key = array($_Key); foreach ($_Data as $__Key => $__Data) { if (count($_Key) && !is_array($__Data)) { if (in_array($__Key, $_Key)) { $_Data[$__Key] = xStrReplace($_Search, $_Replace, $__Data, $_Key); } } else $_Data[$__Key] = xStrReplace($_Search, $_Replace, $__Data, $_Key); } return $_Data; } function xHtmlSpecialCharsDecode($_Data, $_Params = array(), $_Key = array()) { if (!is_array($_Data)) { return html_entity_decode($_Data, ENT_QUOTES); } if (!is_array($_Key)) $_Key = array($_Key); foreach ($_Data as $__Key => $__Data) { if (count($_Key) && !is_array($__Data)) { if (in_array($__Key, $_Key)) { $_Data[$__Key] = xHtmlSpecialCharsDecode($__Data, $_Params, $_Key); } } else $_Data[$__Key] = xHtmlSpecialCharsDecode($__Data, $_Params, $_Key); } return $_Data; } function xHtmlSpecialChars($_Data, $_Params = array(), $_Key = array()) { if (!is_array($_Data)) { return htmlspecialchars($_Data, ENT_QUOTES, 'cp1251'); } if (!is_array($_Key)) $_Key = array($_Key); foreach ($_Data as $__Key => $__Data) { if (count($_Key) && !is_array($__Data)) { if (in_array($__Key, $_Key)) { $_Data[$__Key] = xHtmlSpecialChars($__Data, $_Params, $_Key); } } else $_Data[$__Key] = xHtmlSpecialChars($__Data, $_Params, $_Key); } return $_Data; } function xEscSQL($_Data, $_Params = array(), $_Key = array()) { if (!is_array($_Data)) { return mysql_real_escape_string($_Data); } if (!is_array($_Key)) $_Key = array($_Key); foreach ($_Data as $__Key => $__Data) { if (count($_Key) && !is_array($__Data)) { if (in_array($__Key, $_Key)) { $_Data[$__Key] = xEscSQL($__Data, $_Params, $_Key); } } else $_Data[$__Key] = xEscSQL($__Data, $_Params, $_Key); } return $_Data; } function xEscapeSQLstring($_Data, $_Params = array(), $_Key = array()) { return xEscSQL($_Data, $_Params, $_Key); } function xSaveData($_ID, $_Data, $_TimeControl = 0) { if (!session_is_registered('_xSAVE_DATA')) { session_register('_xSAVE_DATA'); $_SESSION['_xSAVE_DATA'] = array(); } if (intval($_TimeControl)) { $_SESSION['_xSAVE_DATA'][$_ID] = array($_ID . '_DATA' => $_Data, $_ID . '_TIME_CTRL' => array('timetag' => time(), 'timelimit' => $_TimeControl,),); } else { $_SESSION['_xSAVE_DATA'][$_ID] = $_Data; } } function xPopData($_ID) { if (!isset($_SESSION['_xSAVE_DATA'][$_ID])) { return null; } if (is_array($_SESSION['_xSAVE_DATA'][$_ID])) { if (isset($_SESSION['_xSAVE_DATA'][$_ID][$_ID . '_TIME_CTRL'])) { if (($_SESSION['_xSAVE_DATA'][$_ID][$_ID . '_TIME_CTRL']['timetag'] + $_SESSION['_xSAVE_DATA'][$_ID][$_ID . '_TIME_CTRL']['timelimit']) < time()) { return null; } else { $Return = $_SESSION['_xSAVE_DATA'][$_ID][$_ID . '_DATA']; unset($_SESSION['_xSAVE_DATA'][$_ID]); return $Return; } } } $Return = $_SESSION['_xSAVE_DATA'][$_ID]; unset($_SESSION['_xSAVE_DATA'][$_ID]); return $Return; } function xDataExists($_ID) { if (!isset($_SESSION['_xSAVE_DATA'][$_ID])) return 0; if (is_array($_SESSION['_xSAVE_DATA'][$_ID])) { if (isset($_SESSION['_xSAVE_DATA'][$_ID][$_ID . '_TIME_CTRL'])) { if (($_SESSION['_xSAVE_DATA'][$_ID][$_ID . '_TIME_CTRL']['timetag'] + $_SESSION['_xSAVE_DATA'][$_ID][$_ID . '_TIME_CTRL']['timelimit']) >= time()) { return 1; } else { return 0; } } else { return 1; } } else { return 1; } } function xGetData($_ID) { if (!isset($_SESSION['_xSAVE_DATA'][$_ID])) { return null; } if (is_array($_SESSION['_xSAVE_DATA'][$_ID])) { if (isset($_SESSION['_xSAVE_DATA'][$_ID][$_ID . '_TIME_CTRL'])) { if (($_SESSION['_xSAVE_DATA'][$_ID][$_ID . '_TIME_CTRL']['timetag'] + $_SESSION['_xSAVE_DATA'][$_ID][$_ID . '_TIME_CTRL']['timelimit']) < time()) { return null; } else { $Return = $_SESSION['_xSAVE_DATA'][$_ID][$_ID . '_DATA']; return $Return; } } } $Return = $_SESSION['_xSAVE_DATA'][$_ID]; return $Return; } function generateRndCode($_RndLength, $_RndCodes = 'qwertyuiopasdfghjklzxcvbnm0123456789') { $l_name = ''; $top = strlen($_RndCodes) - 1; srand((double)microtime() * 1000000); for ($j = 0; $j < $_RndLength; $j++) $l_name .= $_RndCodes{rand(0, $top)}; return $l_name; } function endsWith($haystack, $needle) { return $needle === "" || substr($haystack, -strlen($needle)) === $needle; } function startsWith($haystack, $needle) { return $needle === "" || strpos($haystack, $needle) === 0; } ?> $_val) $_where[$_col] = $_col." = '".$_val."'"; $_where = implode(" AND ", $_where); } if(is_array($_what)) $_what = implode(", ", xEscSQL($_what)); else $_what = xEscSQL($_what); $sql = "select ".$_what." FROM ".LINK_EXCHANGE_CATEGORIES_TABLE." WHERE ".$_where." ORDER BY ".xEscSQL($_order); $result = db_query($sql); while ($_row = db_fetch_row($result)) $categories[] = $_row; return $categories; } /** * return array of links by requested params * * @return array */ function le_getLinks($_offset = 0, $_lpp = '20', $_where = '1', $_what = 'le_lID, le_lText, le_lURL, le_lCategoryID, le_lVerified', $_order = '`le_lURL` ASC'){ $_offset = ($_offset-1)*$_lpp; $links = array(); if(is_array($_where)){ foreach ($_where as $_col=>$_val) $_where[$_col] = "`".$_col."` = '".$_val."'"; $_where = implode(" AND ", $_where); } if(is_array($_what)) $_what = "`".implode("`, `", $_what)."`"; $sql = " SELECT {$_what} FROM ".LINK_EXCHANGE_LINKS_TABLE." WHERE {$_where} ORDER BY {$_order} "; $result = db_query($sql); $i = 0; while($_row = db_fetch_row($result)) if(($_offset+$_lpp)>$i&&$_offset<=$i++){ if(isset($_row['le_lVerified'])){ $_row['le_lVerified'] = format_datetime($_row['le_lVerified']); } $links[] = $_row; } return $links; } /** * return number of links by requested params * * @return integer */ function le_getLinksNumber($_where = '1'){ if(is_array($_where)){ foreach ($_where as $_col=>$_val) $_where[$_col] = $_col." = '".$_val."'"; $_where = implode(" AND ", $_where); } $sql = "select COUNT(*) FROM ".LINK_EXCHANGE_LINKS_TABLE." WHERE ".$_where; $result = db_query($sql); list($links_number) = db_fetch_row($result); return $links_number; } /** * add new link to category and return new link id * * @return integer */ function le_addLink($_link){ $sql = "select le_lID FROM ".LINK_EXCHANGE_LINKS_TABLE." WHERE le_lURL='".$_link['le_lURL']."'"; list($_le_lID) = db_fetch_row(db_query($sql)); if(!empty($_le_lID))return false; $sql = "INSERT INTO ".LINK_EXCHANGE_LINKS_TABLE." (".implode(", ", (array_keys($_link))).") VALUES('".implode("', '", $_link)."')"; db_query($sql); return db_insert_id(); } /** * update link * * @param array of new values * @return bool */ function le_SaveLink($_link){ if(key_exists('le_lURL', $_link)){ $sql = "select le_lID FROM ".LINK_EXCHANGE_LINKS_TABLE." WHERE le_lURL='".$_link['le_lURL']."' AND le_lID!=".(int)$_link['le_lID']; list($_le_lID) = db_fetch_row(db_query($sql)); if($_le_lID) return false; $_le_lID = $_link['le_lID']; } else $_le_lID = $_link['le_lID']; foreach($_link as $_col => $_val){ if($_val == 'NULL' && $_col=='le_lVerified'){ $_link[$_col] = $_col." = NULL"; }else{ $_link[$_col] = $_col." = '".$_val."'"; } } $sql = "UPDATE ".LINK_EXCHANGE_LINKS_TABLE." SET ".implode(", ", $_link)." WHERE le_lID=".(int)$_le_lID; db_query($sql); return true; } function le_DeleteLink($_le_lID){ $sql = "DELETE FROM ".LINK_EXCHANGE_LINKS_TABLE." WHERE le_lID=".(int)$_le_lID; db_query($sql); } ?> getCode()."\nMessage: ".$e->getMessage()."\nStackTrace: ".$e->getTraceAsString(); LogError($Message); } function LogInfo($Message) { $Message = "\nINFO:".$Message."\n"; LogMessage($Message); } function LogObject($Name, $Object) { $Message = "{$Name}: "; ob_start(); var_dump($Object); $Message .= ob_get_contents()."\n"; ob_end_clean(); LogMessage($Message); } function LogFuncCall($Callable) { ob_start(); call_user_func($Callable); $Message = ob_get_contents()."\n"; ob_end_clean(); LogMessage($Message); } function LogStackTrace() { ob_start(); debug_print_backtrace(); $Message = ob_get_contents()."\n"; ob_end_clean(); LogInfo($Message); } function LogSqlQuery($Sql) { $Message = "SQL QUERY: ".$Sql."\n"; LogMessage($Message); } function LogSqlQueryError($Sql) { $Message = "MY_SQL ERROR: ".mysql_errno().": ". mysql_error()." \n QUERY: ".$Sql." \n "; $Filename = ERROR_LOG_FILE_SQL; LogMessage($Message, $Filename); } function LogSqlResult( $Result) { LogObject("SQL_QUERY_RESULT", $Result); } ?>is_installed() ) $modules[] = $objectModule; } return $modules; } function modGetModuleObjects( $moduleFiles ) { $modules = array(); foreach( $moduleFiles as $fileName ) { $className = GetClassName( $fileName ); if(!$className) continue; eval( "\$objectModule = new ".$className."();" ); $modules[] = $objectModule; } return $modules; } function modGetModuleConfigs($_ModuleClassName){ $ModuleConfigs = array(); $sql = "select * FROM ".MODULES_TABLE." WHERE ModuleClassName='".xEscSQL($_ModuleClassName)."' ORDER BY module_name ASC "; $Result = db_query($sql); while ($_Row = db_fetch_row($Result)) { $ModuleConfigs[] = array( 'ConfigID' => $_Row['module_id'], 'ConfigName' => $_Row['module_name'], 'ConfigClass' => $_ModuleClassName, ); } return $ModuleConfigs; } function modGetModuleConfig($_ConfigID){ $sql = "select * FROM ".MODULES_TABLE." WHERE module_id=".(int)$_ConfigID; return db_fetch_row(db_query($sql)); } function modUninstallModuleConfig($_ConfigID){ $ModuleConfig = modGetModuleConfig($_ConfigID); eval('$_tClass = new '.$ModuleConfig['ModuleClassName'].'();'); $_tClass->uninstall($ModuleConfig['module_id']); } function modGetAllInstalledModuleObjs($_ModuleType = 0){ $ModuleObjs = array(); $sql = 'select module_id FROM '.MODULES_TABLE.' ORDER BY module_name ASC, module_id ASC'; $Result = db_query($sql); while ($_Row = db_fetch_row($Result)) { $_TObj = modGetModuleObj($_Row['module_id'], $_ModuleType); if($_TObj && $_TObj->get_id() && $_TObj->is_installed()) $ModuleObjs[] = $_TObj; } return $ModuleObjs; } function modGetModuleObj($_ID, $_ModuleType = 0){ $ModuleConfig = modGetModuleConfig($_ID); $objectModule = null; if(!$_ID) return $objectModule; if ($ModuleConfig['ModuleClassName']) { if(class_exists($ModuleConfig['ModuleClassName'])){ eval('$objectModule = new '.$ModuleConfig['ModuleClassName'].'('.$_ID.');'); if($_ModuleType && $objectModule->getModuleType()!=$_ModuleType) $objectModule = null; }else{ $moduleFiles = array(); $IncludeDir = ''; switch ($_ModuleType){ case SHIPPING_RATE_MODULE: $IncludeDir = "core/modules/shipping"; break; case PAYMENT_MODULE: $IncludeDir = "core/modules/payment"; break; case SMSMAIL_MODULE: $IncludeDir = "core/modules/smsmail"; break; } $moduleFiles = GetFilesInDirectory( $IncludeDir, "php" ); foreach( $moduleFiles as $fileName ) { $className = GetClassName( $fileName ); if(strtolower($className) != strtolower($ModuleConfig['ModuleClassName'])) continue; require_once($fileName); eval( '$objectModule = new '.$className.'('.$_ID.');' ); return $objectModule; } } }else { $moduleFiles = array(); switch ($_ModuleType){ case SHIPPING_RATE_MODULE: $moduleFiles = GetFilesInDirectory( "core/modules/shipping", "php" ); break; case PAYMENT_MODULE: $moduleFiles = GetFilesInDirectory( "core/modules/payment", "php" ); break; case SMSMAIL_MODULE: $IncludeDir = "core/modules/smsmail"; break; } foreach( $moduleFiles as $fileName ) { $className = GetClassName( $fileName ); if(!$className) continue; if(!class_exists($className))require_once($fileName); eval( '$objectModule = new '.$className.'();' ); if ( $objectModule->get_id() == $_ID && $objectModule->title==$ModuleConfig['module_name']) return $objectModule; else $objectModule = null; } } return $objectModule; } ?>= $offset && $i < $offset + $CountRowOnPage) || $navigatorParams == null ) { $r["add_date"]=dtConvertToStandartForm($r["add_date"]); $data[] = $r; } $i++; } $count_row = $i; return $data; } function newsAddNews( $add_date, $title, $textToPrePublication, $textToPublication, $textToMail ) { $stamp = microtime(); $stamp = explode(" ", $stamp); $stamp = $stamp[1]; db_query( "insert into ".NEWS_TABLE." ( add_date, title, textToPrePublication, textToPublication, textToMail, add_stamp ) ". " values( '".xEscSQL(dtDateConvert($add_date))."', '".xToText(trim($title))."', '".xEscSQL($textToPrePublication)."', '".xEscSQL($textToPublication)."', '".xEscSQL($textToMail)."', ".$stamp." ) "); return db_insert_id(); } function newsUpdateNews( $add_date, $title, $textToPrePublication, $textToPublication, $textToMail, $id_news ) { db_query("update ".NEWS_TABLE. " set add_date='".xEscSQL(dtDateConvert($add_date))."', ". " title='".xToText($title)."', ". " textToPrePublication='".xEscSQL($textToPrePublication)."', ". " textToPublication='".xEscSQL($textToPublication)."', ". " textToMail='".xEscSQL($textToMail)."' ". " where NID = ".(int)$id_news); } function newsDeleteNews( $newsid ) { db_query( "delete from ".NEWS_TABLE." where NID=".(int)$newsid ); } function newsSendNews($newsid) { $q = db_query( "select add_date, title, textToMail from ".NEWS_TABLE." where NID=".(int)$newsid ); $news = db_fetch_row( $q ); $news["add_date"]=dtConvertToStandartForm($news["add_date"]); $q = db_query( "select Email from ".MAILING_LIST_TABLE ); while( $subscriber = db_fetch_row($q) ) xMailHtml($subscriber["Email"], EMAIL_NEWS_OF." - ".CONF_SHOP_NAME, $news["title"]."

".$news["textToMail"]); } ?> $val) { if (isset($val["extra_option"]) && $val["extra_option"]!="") { db_query("update ".PRODUCT_OPTIONS_TABLE." set name='".xToText(trim($val["extra_option"])). "', sort_order=".(int)$val["extra_sort"]." where optionID=".(int)$key); } } } // ***************************************************************************** // Purpose adds new option // Inputs // $extra_option - option name // $extra_sort - sort order // Remarks // Returns nothig function optAddOption($extra_option, $extra_sort) { if ( trim($extra_option) == "" ) return; db_query("insert into ".PRODUCT_OPTIONS_TABLE. " (name, sort_order) values ('".xToText($extra_option)."', '".(int)$extra_sort."')"); } // ***************************************************************************** // Purpose get option values // Inputs // Remarks // Returns function optGetOptionValues($optionID) { $q = db_query("select variantID, optionID, option_value, sort_order from ". PRODUCTS_OPTIONS_VALUES_VARIANTS_TABLE. " where optionID=".(int)$optionID. " order by sort_order, option_value"); $result=array(); while($row=db_fetch_row($q)) $result[] = $row; return $result; } // ***************************************************************************** // Purpose get option values // Inputs // Remarks // Returns function optOptionValueExists($optionID, $value_name) { $q = db_query("select variantID from ". PRODUCTS_OPTIONS_VALUES_VARIANTS_TABLE. " where optionID=".(int)$optionID." and option_value='".xEscSQL(trim($value_name))."';"); $row = db_fetch_row($q); if ($row) return $row[0]; //return variant ID else return false; } // ***************************************************************************** // Purpose updates option values // Inputs array of item // each item consits of // "option_value" - option name // "sort_order" - enlarged picture // key is option ID // Remarks // Returns function optUpdateOptionValues($updateOptions) { foreach($updateOptions as $key => $value) { db_query("update ".PRODUCTS_OPTIONS_VALUES_VARIANTS_TABLE. " set option_value='".xToText($value["option_value"])."', ". " sort_order=".(int)$value["sort_order"]." ". " where variantID=".(int)$key); } } // ***************************************************************************** // Purpose updates option values // Inputs // $optionID - option ID // $value - value // $sort_order - sort order // Remarks // Returns function optAddOptionValue($optionID, $value, $sort_order) { db_query("insert into ".PRODUCTS_OPTIONS_VALUES_VARIANTS_TABLE. "(optionID, option_value, sort_order) ". "values('".(int)$optionID."', '".xToText($value)."', '". (int)$sort_order."' )" ); return db_insert_id(); } ?> $orderDetails["first_name"], "last_name" => $orderDetails["last_name"], "email" => $orderDetails["email"], "orderContent" => $cartContent, "order_amount" => $orderDetails["order_amount"] ); $Rates = $shippingModule->calculate_shipping_rate( $order, $shippingAddress, $shServiceID ); if(!is_array($Rates)){ $Rates = array(array('name'=>'','rate'=>$Rates)); } } } if(!count($Rates)) { $Rates[] = array('rate'=>'0','name'=>''); } foreach ($Rates as $_ind=>$_Rate) $Rates[$_ind]['rate'] += $cartContent["freight_cost"]; if ($CALC_TAX) { if ( is_array($addresses[0]) ) $rate = taxCalculateTaxByClass2( CONF_CALCULATE_TAX_ON_SHIPPING, $addresses[0], $addresses[1] ); else $rate = taxCalculateTaxByClass( CONF_CALCULATE_TAX_ON_SHIPPING, $addresses[0], $addresses[1] ); foreach ($Rates as $_ind=>$_Rate) $Rates[$_ind]['rate'] += ($Rates[$_ind]['rate']/100)*$rate; } return $Rates; } // ***************************************************************************** // Purpose get discount percent // Inputs // $cartContent is result of cartGetCartContent function // Remarks // Returns function oaGetDiscountPercent( $cartContent, $log ) { $price = oaGetClearPrice( $cartContent ); $res = dscCalculateDiscount( $price, $log ); return (float) $res["discount_percent"]; } // ***************************************************************************** // Purpose get order amount (with discount) excluding shipping rate // Inputs // $cartContent is result of cartGetCartContent function // $addresses array of // $shippingAddressID, // $billingAddressID // OR // $shippingAddress - array of // "countryID" // "zoneID" // $billingAddress - array of // "countryID" // "zoneID" // Remarks // Returns function oaGetOrderAmountExShippingRate( $cartContent, $addresses, $log, $CALC_TAX = TRUE ) { $clearPrice = oaGetClearPrice( $cartContent ); $d = oaGetDiscountPercent( $cartContent, $log ); $res = $clearPrice - ($clearPrice/100)*$d; if ($CALC_TAX) { $res += oaGetProductTax( $cartContent, $d, $addresses ); } return $res; } // ***************************************************************************** // Purpose get order amount // Inputs // $cartContent is result of cartGetCartContent function // $addresses array of // $shippingAddressID, // $billingAddressID // OR // $shippingAddress - array of // "countryID" // "zoneID" // $billingAddress - array of // "countryID" // "zoneID" // Remarks // Returns function oaGetOrderAmount( $cartContent, $addresses, $shippingMethodID, $log, $orderDetails, $CALC_TAX = TRUE, $shServiceID = 0 ) { $Rate = oaGetShippingCostTakingIntoTax( $cartContent, $shippingMethodID, $addresses, $orderDetails, $CALC_TAX, $shServiceID ); $res = oaGetOrderAmountExShippingRate( $cartContent, $addresses, $log, $CALC_TAX ) + $Rate[0]['rate']; return $res; } ?>= $offset && $i < $offset + $CountRowOnPage) || $navigatorParams == null ) { $row["OrderStatus"] = ostGetOrderStatusName( $row["statusID"] ); $total_sum += $row["order_amount"]; $row["order_amount"] = _formatPrice(roundf($row["currency_value"]*$row["order_amount"]),$row["currency_round"])." ".$row["currency_code"]; $q_orderContent = db_query( "select name, Price, Quantity, tax, load_counter, itemID from ". ORDERED_CARTS_TABLE." where orderID=".(int)$row["orderID"] ); $content = array(); while( $orderContentItem = db_fetch_row($q_orderContent) ) { $productID = GetProductIdByItemId( $orderContentItem["itemID"] ); $product = GetProduct( $productID ); if ( $product["eproduct_filename"] != null && strlen($product["eproduct_filename"]) > 0 ) { if ( file_exists("core/files/".$product["eproduct_filename"]) ) { $orderContentItem["eproduct_filename"] = $product["eproduct_filename"]; $orderContentItem["file_size"] = (string) round(filesize("core/files/".$product["eproduct_filename"]) / 1048576, 3); if ( isset($callBackParam["customerID"]) ) { $custID = $callBackParam["customerID"]; } else { $custID = -1; } $orderContentItem["getFileParam"] = "orderID=".$row["orderID"]."&". "productID=".$productID."&". "customerID=".$custID; //additional security for non authorized customers if ($custID == -1) { $orderContentItem["getFileParam"] .= "&order_time=".base64_encode($row["order_time"]); } $orderContentItem["getFileParam"] = cryptFileParamCrypt( $orderContentItem["getFileParam"], null ); $orderContentItem["load_counter_remainder"] = $product["eproduct_download_times"] - $orderContentItem["load_counter"]; $currentDate = dtGetParsedDateTime( get_current_time() ); $betweenDay = _getDayBetweenDate( dtGetParsedDateTime( $row["order_time"] ), $currentDate ); $orderContentItem["day_count_remainder"] = $product["eproduct_available_days"] - $betweenDay; //if ( $orderContentItem["day_count_remainder"] < 0 ) // $orderContentItem["day_count_remainder"] = 0; } } $content[] = $orderContentItem; } $row["content"] = $content; $row["order_time"] = format_datetime( $row["order_time"] ); $res[] = $row; } $i++; } $count_row = $i; if ( isset($callBackParam["customerID"]) ) { if ( count($res) > 0 ) { $q = db_query( "select CID from ".CUSTOMERS_TABLE. " where customerID=".(int)$callBackParam["customerID"] ); $row = db_fetch_row($q); if ( $row["CID"]!=null && $row["CID"]!="" ) { $q = db_query( "select currency_value, currency_iso_3, roundval from ". CURRENCY_TYPES_TABLE." where CID=".(int)$row["CID"] ); $row = db_fetch_row($q); $res[0]["total_sum"] = _formatPrice(roundf($row["currency_value"]*$total_sum),$row["roundval"])." ".$row["currency_iso_3"]; } else { $res[0]["total_sum"] = _formatPrice(roundf($selected_currency_details["currency_value"]*$total_sum),$row["roundval"])." ".$selected_currency_details["currency_iso_3"]; } } } return $res; } function ordGetDistributionByStatuses( $log ) { $q = db_query( "select statusID, status_name, sort_order from ". ORDER_STATUES_TABLE." order by sort_order, status_name" ); $data = array(); while( $row = db_fetch_row( $q ) ) { $q1 = db_query( "select count(*) from ".ORDERS_TABLE. " where statusID=".(int)$row["statusID"]." AND ". " customerID=".(int)regGetIdByLogin($log)); $row1= db_fetch_row($q1); if ( $row["statusID"] == ostGetCanceledStatusId() ) $row["status_name"] = STRING_CANCELED_ORDER_STATUS; $item = array( "status_name" => $row["status_name"], "count" => $row1[0] ); $data[] = $item; } return $data; } function _moveSessionCartContentToOrderedCart( $orderID ) { $i=0; $sql = "DELETE FROM ".ORDERED_CARTS_TABLE." WHERE orderID=".(int)$orderID; db_query($sql); foreach( $_SESSION["gids"] as $productID ) { if ( $productID == 0 ) { $i++; continue; } $q = db_query( "select count(*) from ".PRODUCTS_TABLE. " where productID=".(int)$productID ); $row = db_fetch_row($q); if ( $row[0] == 0 ){ $i++; continue; } // create new item db_query( "insert into ".SHOPPING_CART_ITEMS_TABLE. "(productID) values('".(int)$productID."')" ); $itemID=db_insert_id(); foreach( $_SESSION["configurations"][$i] as $vars ) { db_query("insert into ". SHOPPING_CART_ITEMS_CONTENT_TABLE."(itemID, variantID) ". "values( '".(int)$itemID."', '".(int)$vars."')" ); } $q_product = db_query( "select name, Price, product_code from ".PRODUCTS_TABLE." where productID=".(int)$productID); $product = db_fetch_row( $q_product ); $quantity = $_SESSION["counts"][$i]; $variants = array(); foreach( $_SESSION["configurations"][$i] as $vars ) $variants[] = $vars; $options = GetStrOptions( $variants ); if ( $options != "" ) $productComplexName = $product["name"]."(".$options.")"; else $productComplexName = $product["name"]; if ( strlen($product["product_code"]) > 0 ) $productComplexName = "[".$product["product_code"]."] ".$productComplexName; $price = GetPriceProductWithOption( $variants, $productID ); $shippingAddress = array( "countryID" => $_SESSION["receiver_countryID"], "zoneID" => $_SESSION["receiver_zoneID"]); $billingAddress = array( "countryID" => $_SESSION["billing_countryID"], "zoneID" => $_SESSION["billing_zoneID"]); $tax = taxCalculateTax2( $productID, $shippingAddress, $billingAddress ); db_query( "insert into ".ORDERED_CARTS_TABLE." ( itemID, orderID, name, Price, Quantity, tax ) ". "values( ".(int)$itemID.", ".(int)$orderID.", '".xEscSQL($productComplexName)."', '".xEscSQL($price)."', ". (int)$quantity.", ".xEscSQL($tax)." ) " ); $i++; } unset($_SESSION["gids"]); unset($_SESSION["counts"]); unset($_SESSION["configurations"]); session_unregister("gids"); //calling session_unregister() is required since unset() may not work on some systems session_unregister("counts"); session_unregister("configurations"); } function _quickOrderUnsetSession() { unset( $_SESSION["first_name"] ); unset( $_SESSION["last_name"] ); unset( $_SESSION["email"] ); unset( $_SESSION["billing_first_name"] ); unset( $_SESSION["billing_last_name"] ); unset( $_SESSION["billing_state"] ); unset( $_SESSION["billing_city"] ); unset( $_SESSION["billing_address"] ); unset( $_SESSION["billing_countryID"] ); unset( $_SESSION["billing_zoneID"] ); unset( $_SESSION["receiver_first_name"] ); unset( $_SESSION["receiver_last_name"] ); unset( $_SESSION["receiver_state"] ); unset( $_SESSION["receiver_city"] ); unset( $_SESSION["receiver_address"] ); unset( $_SESSION["receiver_countryID"] ); unset( $_SESSION["receiver_zoneID"] ); } function _getOrderById( $orderID ) { $sql = "select ". " orderID, ". " customerID, ". " order_time, ". " customer_ip, ". " shipping_type, ". " payment_type, ". " customers_comment, ". " statusID, ". " shipping_cost, ". " order_discount, ". " order_amount, ". " currency_code, ". " currency_value, ". " customer_firstname, ". " customer_lastname, ". " customer_email, ". " shipping_firstname, ". " shipping_lastname, ". " shipping_country, ". " shipping_state, ". " shipping_city, ". " shipping_address, ". " billing_firstname, ". " billing_lastname, ". " billing_country, ". " billing_state, ". " billing_city, ". " billing_address, ". " cc_number, ". " cc_holdername, ". " cc_expires, ". " cc_cvv, ". " shippingServiceInfo, ". " currency_round ". " from ".ORDERS_TABLE." where orderID=".(int)$orderID; $q = db_query( $sql ); return db_fetch_row($q); } function _sendOrderNotifycationToCustomer( $orderID, &$smarty_mail, $email, $login, $payment_email_comments_text, $shipping_email_comments_text, $tax, $order_active_link ) { $order = _getOrderById( $orderID ); $smarty_mail->assign( "customer_firstname", $order["customer_firstname"] ); $smarty_mail->assign( "orderID", $order["orderID"] ); $smarty_mail->assign( "discount", roundf($order["order_discount"])); $smarty_mail->assign( "shipping_type", $order["shipping_type"] ); $smarty_mail->assign( "shipping_firstname", $order["shipping_firstname"] ); $smarty_mail->assign( "shipping_lastname", $order["shipping_lastname"] ); $smarty_mail->assign( "shipping_country", $order["shipping_country"] ); $smarty_mail->assign( "shipping_state", $order["shipping_state"] ); $smarty_mail->assign( "shipping_city", $order["shipping_city"] ); $smarty_mail->assign( "shipping_address", $order["shipping_address"] ); $smarty_mail->assign( "shipping_cost", _formatPrice(roundf($order["currency_value"]*$order["shipping_cost"]),$order["currency_round"])." ".$order["currency_code"] ); $smarty_mail->assign( "order_active_link", $order_active_link ); $smarty_mail->assign( "payment_type", $order["payment_type"] ); $smarty_mail->assign( "billing_firstname", $order["billing_firstname"] ); $smarty_mail->assign( "billing_lastname", $order["billing_lastname"] ); $smarty_mail->assign( "billing_country", $order["billing_country"] ); $smarty_mail->assign( "billing_state", $order["billing_state"] ); $smarty_mail->assign( "billing_city", $order["billing_city"] ); $smarty_mail->assign( "billing_address", $order["billing_address"] ); $smarty_mail->assign( "order_amount", _formatPrice(roundf($order["currency_value"]*$order["order_amount"]),$order["currency_round"])." ".$order["currency_code"] ); $smarty_mail->assign( "payment_comments", $payment_email_comments_text ); $smarty_mail->assign( "shipping_comments", $shipping_email_comments_text ); $smarty_mail->assign( "order_total_tax", _formatPrice(roundf($order["currency_value"]*$tax),$order["currency_round"])." ".$order["currency_code"] ); $smarty_mail->assign( "shippingServiceInfo", $order["shippingServiceInfo"] ); // clear cost ( without shipping, discount, tax ) $q1 = db_query( "select Price, Quantity from ".ORDERED_CARTS_TABLE." where orderID=".(int)$orderID); $clear_total_price = 0; while( $row=db_fetch_row($q1) ) $clear_total_price += $row["Price"]*$row["Quantity"]; $order_discount_ToShow = _formatPrice(roundf($order["currency_value"]*$clear_total_price*((100-$order["order_discount"])/100)),$order["currency_round"])." ".$order["currency_code"]; $smarty_mail->assign( "order_discount_ToShow", $order_discount_ToShow); //additional reg fields $addregfields = GetRegFieldsValuesByOrderID( $orderID ); $smarty_mail->assign("customer_add_fields", $addregfields); $content = ordGetOrderContent( $orderID ); for( $i=0; $iis_installed() ) $shipping_modules[] = $shipping_module; } return $shipping_modules; } // ***************************************************************************** // Purpose add shipping method // Inputs // Remarks // Returns nothing function shAddShippingMethod( $Name, $description, $Enabled, $sort_order, $module_id, $email_comments_text ) { db_query("insert into ".SHIPPING_METHODS_TABLE. " ( Name, description, email_comments_text, Enabled, module_id, sort_order ) values". " ( '".xToText(trim($Name))."', '".xEscSQL($description)."', '".xEscSQL($email_comments_text)."', ".(int)$Enabled.", ".(int)$module_id.", ".(int)$sort_order." )" ); return db_insert_id(); } // ***************************************************************************** // Purpose update shipping method // Inputs // Remarks // Returns nothing function shUpdateShippingMethod($SID, $Name, $description, $Enabled, $sort_order, $module_id, $email_comments_text ) { db_query("update ".SHIPPING_METHODS_TABLE. " set Name='".xToText(trim($Name))."', description='".xEscSQL($description)."', email_comments_text='".xEscSQL($email_comments_text)."', ". " Enabled=".(int)$Enabled.", module_id=".(int)$module_id.", sort_order=".(int)$sort_order." where SID=".(int)$SID); } // ***************************************************************************** // Purpose // Inputs $shippingMethodID - shipping exists // Remarks // Returns true if shipping method is exists function shShippingMethodIsExist( $shippingMethodID ) { $q_count = db_query( "select count(*) from ".SHIPPING_METHODS_TABLE. " where SID=".(int)$shippingMethodID." AND Enabled=1" ); $counts = db_fetch_row( $q_count ); return ( $counts[0] != 0 ); } ?>