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 .= "
=>