/**
  *
  */
 function onAction()
 {
     global $application;
     CCacheFactory::clearAll();
     modApiFunc("Tools", "clearBackupSession");
     modApiFunc("Tools", "setDBStat", modApiFunc("Modules_Manager", "getTablesAndRecordsCount"));
     modApiFunc("Tools", "setCurrentBackupTable", 0);
     modApiFunc("Tools", "setCurrentBackupTableLimit", 0);
     modApiFunc("Tools", "setDBRecordsExported", 0);
     $request = $application->getInstance('Request');
     $filename = $request->getValueByKey('BackupFile');
     if ($filename) {
         modApiFunc("Tools", "setRestoreStatus", 'BACKUP');
         modApiFunc("Tools", "setRestoreFile", $filename);
         $filename = modApiFunc("Tools", "getRestoreFile");
         $full_filename = $application->getAppIni('PATH_BACKUP_DIR') . $filename . "/dump.sql";
         $handle = @fopen($full_filename, "rb");
         $backup_file_content = @fread($handle, 1024);
         @fclose($handle);
         $error = "";
         $backup_info = @_parse_ini_file($application->getAppIni('PATH_BACKUP_DIR') . $filename . "/info/backup.ini");
         if (!isset($backup_info["asc_version"]) || $backup_info["asc_version"] != PRODUCT_VERSION) {
             $error = "BCP_RESTORE_ERR_003";
         } elseif (!$backup_file_content) {
             $error = "BCP_RESTORE_ERR_001";
         } elseif (_ml_strpos($backup_file_content, "-- HASH: ") === false) {
             $error = "BCP_RESTORE_ERR_002";
         } else {
             $hash = _byte_substr($backup_file_content, 9, 32);
             //
             $handle = fopen($full_filename, "rb");
             $md5_temp = '';
             //
             $begin = _byte_strpos($backup_file_content, "\n") + _byte_strlen("\n");
             fseek($handle, $begin);
             while (!feof($handle)) {
                 $contents = fread($handle, 1048576);
                 $md5_temp .= md5($contents);
             }
             $counted_file_hash = md5($md5_temp);
             fclose($handle);
             //                :
             if ($hash != $counted_file_hash) {
                 $error = "BCP_RESTORE_ERR_002";
             }
         }
         if ($error) {
             modApiFunc("Tools", "setRestoreError", $error);
         } else {
             modApiFunc("Tools", "setStringsCountInRestoreFile", $filename);
         }
     }
     modApiFunc("Tools", "saveState");
 }
Beispiel #2
0
 /**
  * Returns part of number $num, starting at bit
  * position $start with length $length
  *
  * @param gmp resource $num
  * @param int start
  * @param int length
  * @return gmp resource
  * @access public
  */
 function subint($num, $start, $length)
 {
     $start_byte = intval($start / 8);
     $start_bit = $start % 8;
     $byte_length = intval($length / 8);
     $bit_length = $length % 8;
     if ($bit_length) {
         $byte_length++;
     }
     $num = gmp_div($num, 1 << $start_bit);
     $tmp = _byte_substr($this->int2bin($num), $start_byte, $byte_length);
     $tmp = str_pad($tmp, $byte_length, "");
     $tmp = _byte_substr_replace($tmp, $tmp[$byte_length - 1] & _byte_chr(0xff >> 8 - $bit_length), $byte_length - 1, 1);
     return $this->bin2int($tmp);
 }
 function uploadImages(&$SessionPost)
 {
     global $application;
     // not to duplicate the code.
     $images = array('SmallImage', 'LargeImage');
     foreach ($images as $image) {
         // if the file really exists.
         if (array_key_exists($image, $_FILES) && $_FILES[$image]['size'] > 0 && getimagesize($_FILES[$image]['tmp_name']) != FALSE) {
             // define an image type. It should be one of the allowed types.
             if ($application->isAllowedImageType($_FILES[$image])) {
                 // define the image file extension
                 $ext = $application->getImageTypeExtension($_FILES[$image]);
                 if ($ext != false) {
                     // upload a unique file name.
                     $uploadfile = $application->getUploadImageName($_FILES[$image]['name']);
                     // move the uploaded file to the general catalog.
                     if (move_uploaded_file($_FILES[$image]['tmp_name'], $uploadfile)) {
                         @chmod($uploadfile, 0644);
                         // save the file to view it to the user.
                         //                                $images_dir = $application->getAppIni('RELATIVE_PATH_IMAGES_DIR_ADMIN');
                         $SessionPost["ViewState"][$image] = basename($uploadfile);
                         if ($image == 'LargeImage') {
                             $large_image_path = $uploadfile;
                         }
                     } else {
                         $SessionPost["ViewState"]["ErrorsArray"][$image] = new ActionMessage(array("PRDADD_006", $image));
                     }
                 } else {
                     $SessionPost["ViewState"]["ErrorsArray"][$image] = new ActionMessage(array("PRDADD_005", $image));
                 }
             } else {
                 $SessionPost["ViewState"]["ErrorsArray"][$image] = new ActionMessage(array("PRDADD_005", $image));
             }
         } else {
             if (array_key_exists($image, $_FILES) && $_FILES[$image]['size'] > 0) {
                 $SessionPost["ViewState"]["ErrorsArray"][$image] = new ActionMessage(array("PRDADD_005", $image));
             }
         }
     }
     // generate small image from the large image
     if (@$_FILES['SmallImage']['error'] == UPLOAD_ERR_NO_FILE && isset($SessionPost["ViewState"]['LargeImage']) && !isset($SessionPost["ViewState"]["ErrorsArray"]['LargeImage']) && isset($large_image_path)) {
         $pi_settings = modApiFunc('Product_Images', 'getSettings');
         if ($pi_settings['AUTO_GEN_CAT_SMALL_IMAGE'] == 'Y' && function_exists('gd_info')) {
             $thumb_path = modApiFunc('Product_Images', 'genThumbnail', 0, $large_image_path, $pi_settings['CAT_IMAGE_SIDE']);
             $thumb_path_info = pathinfo($thumb_path);
             $large_image_path_parts = pathinfo($SessionPost["ViewState"]['LargeImage']);
             $large_image_basename = $large_image_path_parts['basename'];
             $large_image_ext = $large_image_path_parts['extension'];
             $large_image_basename_without_ext = _byte_substr($large_image_basename, 0, -1 * _byte_strlen("." . $large_image_ext));
             $thumb_path_parts = pathinfo($thumb_path);
             $thumb_path_ext = $large_image_path_parts['extension'];
             $thumb_short_name = "thumb_" . $large_image_basename_without_ext . "." . $thumb_path_ext;
             $thumb_path_2 = $application->_img_path($thumb_short_name);
             if (@rename($thumb_path, $thumb_path_2)) {
                 $SessionPost["ViewState"]['SmallImage'] = basename($thumb_path_2);
             }
         }
     }
 }
Beispiel #4
0
 /**
  * Decrypts an encrypted string
  *
  * The value was padded with NUL characters when encrypted. You may
  * need to trim the result or cast its type.
  *
  * @param string $cipherText
  * @return string|PEAR_Error Returns plain text on success, PEAR_Error on failure
  * @access public
  */
 function decrypt($cipherText)
 {
     if (!is_string($cipherText)) {
         return PEAR::raiseError('Cipher text must be a string', 1);
     }
     if (empty($this->_P)) {
         return PEAR::raiseError('The key is not initialized.', 8);
     }
     $plainText = '';
     $len = _byte_strlen($cipherText);
     $cipherText .= str_repeat(_byte_chr(0), (8 - $len % 8) % 8);
     for ($i = 0; $i < $len; $i += 8) {
         list(, $Xl, $Xr) = unpack('N2', _byte_substr($cipherText, $i, 8));
         $this->_decipher($Xl, $Xr);
         $plainText .= pack('N2', $Xl, $Xr);
     }
     return $plainText;
 }
 /**
  * quoteadPrintableEncode()
  *
  * Encodes data to quoted-printable standard.
  *
  * @param $input    The data to encode
  * @param $line_max Optional max line length. Should
  *                  not be more than 76 chars
  *
  * @access private
  */
 function _quotedPrintableEncode($input, $line_max = 76)
 {
     $lines = preg_split("/\r?\n/", $input);
     $eol = MAIL_MIMEPART_CRLF;
     $escape = '=';
     $output = '';
     while (list(, $line) = each($lines)) {
         $linlen = _byte_strlen($line);
         $newline = '';
         for ($i = 0; $i < $linlen; $i++) {
             $char = _byte_substr($line, $i, 1);
             $dec = _byte_ord($char);
             if ($dec == 32 and $i == $linlen - 1) {
                 // convert space at eol only
                 $char = '=20';
             } elseif ($dec == 9) {
                 // Do nothing if a tab.
             } elseif ($dec == 61 or $dec < 32 or $dec > 126) {
                 $char = $escape . _ml_strtoupper(sprintf('%02s', dechex($dec)));
             }
             if (_byte_strlen($newline) + _byte_strlen($char) >= $line_max) {
                 // MAIL_MIMEPART_CRLF is not counted
                 $output .= $newline . $escape . $eol;
                 // soft line break; " =\r\n" is okay
                 $newline = '';
             }
             $newline .= $char;
         }
         // end of for
         $output .= $newline . $eol;
     }
     $output = _byte_substr($output, 0, -1 * _byte_strlen($eol));
     // Don't want last crlf
     return $output;
 }
 /**
  * see blowfish_ab_pad_text
  */
 function blowfish_ab_unpad_text($text)
 {
     if (empty($text)) {
         //Perhaps it's a wrong situation.
         return "";
     }
     //        $pad_char = $text[_byte_strlen($text)-1];
     $pad_char = _byte_substr($text, -1, 1);
     $i = _byte_strlen($text) - 1;
     for (; $i >= 0 && _byte_substr($text, $i, 1) == $pad_char; $i--) {
     }
     $new_len = $i + 1;
     $text = _byte_substr($text, 0, $new_len);
     return $text;
 }
 /**
  * Calculates bitwise or of $num1 and $num2,
  * starting from bit $start_pos for number $num1
  *
  * @param string $num1
  * @param string $num2
  * @param int $start_pos
  * @return string
  * @access public
  */
 function bitOr($num1, $num2, $start_pos)
 {
     //        $num1 = new Math_BigInteger($num1, 10);
     $num2 = new Math_BigInteger($num2, 10);
     $start_byte = intval($start_pos / 8);
     $start_bit = $start_pos % 8;
     $tmp1 = $this->int2bin($num1);
     $num2 = $num2->multiply(new Math_BigInteger(1 << $start_bit));
     $tmp2 = $this->int2bin($num2->toString());
     if ($start_byte < _byte_strlen($tmp1)) {
         $tmp2 |= _byte_substr($tmp1, $start_byte);
         $tmp1 = _byte_substr($tmp1, 0, $start_byte) . $tmp2;
     } else {
         $tmp1 = str_pad($tmp1, $start_byte, "") . $tmp2;
     }
     return $this->bin2int($tmp1);
 }
 /**
  * Logical Right Shift
  *
  * Shifts binary strings $shift bits, essentially dividing by 2**$shift and returning the remainder.
  *
  * @param $x String
  * @param $shift Integer
  * @return String
  * @access private
  */
 function _base256_rshift(&$x, $shift)
 {
     if ($shift == 0) {
         $x = ltrim($x, _byte_chr(0));
         return '';
     }
     $num_bytes = $shift >> 3;
     // eg. floor($shift/8)
     $shift &= 7;
     // eg. $shift % 8
     $remainder = '';
     if ($num_bytes) {
         $start = $num_bytes > _byte_strlen($x) ? -_byte_strlen($x) : -$num_bytes;
         $remainder = _byte_substr($x, $start);
         $x = _byte_substr($x, 0, -$num_bytes);
     }
     $carry = 0;
     $carry_shift = 8 - $shift;
     for ($i = 0; $i < _byte_strlen($x); $i++) {
         $temp = _byte_ord($x[$i]) >> $shift | $carry;
         $carry = _byte_ord($x[$i]) << $carry_shift & 0xff;
         $x[$i] = _byte_chr($temp);
     }
     $x = ltrim($x, _byte_chr(0));
     $remainder = _byte_chr($carry >> $carry_shift) . $remainder;
     return ltrim($remainder, _byte_chr(0));
 }
 /**
  * Converts the answer from the remote host to the array of headers, cookies
  * and body.
  *
  * @param $result answer from the remote host
  * @return array of headers, cookies and body
  */
 function parseRequestResult($result)
 {
     $headers = array();
     $cookies = array();
     $body = "";
     $dp = 4096;
     $delimiter = false;
     $dtrs = array("\n", "\r\n", "\n\r");
     foreach ($dtrs as $v) {
         // trying to find a delimiter pair - headers/body border
         $tdp = _byte_strpos($result, $v . $v);
         if ($tdp != false && $dp > $tdp) {
             $dp = $tdp;
             $delimiter = $v;
         }
     }
     if ($delimiter == false) {
         CTrace::wrn('Failed to parse response, I cannot guess headers/body delimiter.');
         return;
     }
     $headers = _byte_substr($result, 0, $dp);
     $hstr = explode($delimiter, $headers);
     foreach ($hstr as $key => $string) {
         if (preg_match("/^HTTP/", $string)) {
             continue;
         }
         if (trim($string) == "") {
             break;
         }
         $header_array = explode(": ", trim($string), 2);
         $header_array[0] = _ml_strtoupper($header_array[0]);
         $headers[$header_array[0]] = chop($header_array[1]);
         if ($header_array[0] == "SET-COOKIE") {
             array_push($cookies, $header_array[1]);
         }
     }
     $cookies = $this->parseCookies($cookies);
     $body = _byte_substr($result, $dp + _byte_strlen($delimiter) * 2);
     return array("headers" => $headers, "cookies" => $cookies, "body" => $body);
 }
 /**
  * Prepares the query of type LOCK TABLES.
  *
  * @return a string, containing the SQL query 'LOCK TABLES'
  * @param DB_LockTables object $QueryData
  */
 function PrepareLockTablesQuery($QueryData)
 {
     $SQL = ' LOCK TABLES ';
     $tables = $QueryData->getTablesToLock();
     if (sizeof($tables) > 0) {
         foreach ($tables as $key => $info) {
             $SQL .= $key;
             if (!empty($info['alias'])) {
                 $SQL .= ' AS ' . $info['alias'];
             }
             if (!empty($info['locking_mode'])) {
                 $SQL .= ' ' . $info['locking_mode'];
             }
             $SQL .= ', ';
         }
         $SQL = _byte_substr($SQL, 0, _byte_strlen($SQL) - 2);
     } else {
         //Error - No Tables to Lock
     }
     return $SQL;
 }
 /**
  * Converts the key into standart format (XXXX-XXXX-XXXX-XXXX-XXXX)
  * @param string $key
  * @return string or bool if $key is not a valid key
  */
 function formatKey($key)
 {
     if ($this->_is_license_key_valid($key)) {
         $_key = preg_replace("/[^0-9a-fA-F]/i", "", $key);
         $result = _ml_strtoupper(_byte_substr(chunk_split($_key, 4, KEY_DELIMITER), 0, 24));
         return $result;
     } else {
         return false;
     }
 }
 function evalImage($image)
 {
     global $application;
     $avactis_url = $this->templates_url . $this->template['template']['directory'];
     $replace = "";
     if (_ml_strpos($image[2], '://') != 0) {
         $replace = $image[0];
     } elseif (_byte_substr($image[2], 0, 1) == '/') {
         $replace = $image[1] . $this->site_url . _byte_substr($image[2], 1) . $image[3];
     } else {
         $replace = $image[1] . $avactis_url . '/' . $image[2] . $image[3];
     }
     return $replace;
 }
Beispiel #13
0
 /**
  * Decrypts $enc_data by the key $this->_dec_key or $key.
  *
  * @param string $enc_data  encrypted data as binary string
  * @param object $key       decryption key (object of RSA_Crypt_Key class)
  * @return mixed
  *         decrypted data as string on success or false on error
  *
  * @access public
  */
 function decryptBinary($enc_data, $key = null)
 {
     if (is_null($key)) {
         // use current decryption key
         $key = $this->_dec_key;
     } elseif (!Crypt_RSA_Key::isValid($key)) {
         $obj = PEAR::raiseError('invalid decryption key. It must be an object of Crypt_RSA_Key class', CRYPT_RSA_ERROR_WRONG_KEY);
         $this->pushError($obj);
         return false;
     }
     $exp = $this->_math_obj->bin2int($key->getExponent());
     $modulus = $this->_math_obj->bin2int($key->getModulus());
     $data_len = _byte_strlen($enc_data);
     $chunk_len = $key->getKeyLength() - 1;
     $block_len = (int) ceil($chunk_len / 8);
     $curr_pos = 0;
     $bit_pos = 0;
     $plain_data = $this->_math_obj->bin2int("");
     while ($curr_pos < $data_len) {
         $tmp = $this->_math_obj->bin2int(_byte_substr($enc_data, $curr_pos, $block_len));
         $tmp = $this->_math_obj->powmod($tmp, $exp, $modulus);
         $plain_data = $this->_math_obj->bitOr($plain_data, $tmp, $bit_pos);
         $bit_pos += $chunk_len;
         $curr_pos += $block_len;
     }
     $result = $this->_math_obj->int2bin($plain_data);
     // delete tail, containing of \x01
     $tail = _byte_ord($result[_byte_strlen($result) - 1]);
     if ($tail != 1) {
         $obj = PEAR::raiseError("Error tail of decrypted text = {$tail}. Expected 1", CRYPT_RSA_ERROR_WRONG_TAIL);
         $this->pushError($obj);
         return false;
     }
     return _byte_substr($result, 0, -1);
 }
 function _httpsrequest($url, $URI, $http_method, $content_type = "", $body = "")
 {
     if ($this->passcookies && $this->_redirectaddr) {
         $this->setcookies();
     }
     $headers = array();
     $URI_PARTS = parse_url($URI);
     if (empty($url)) {
         $url = "/";
     }
     // GET ... header not needed for curl
     //$headers[] = $http_method." ".$url." ".$this->_httpversion;
     if (!empty($this->agent)) {
         $headers[] = "User-Agent: " . $this->agent;
     }
     if (!empty($this->host)) {
         $headers[] = "Host: " . $this->host;
     }
     if (!empty($this->accept)) {
         $headers[] = "Accept: " . $this->accept;
     }
     if (!empty($this->referer)) {
         $headers[] = "Referer: " . $this->referer;
     }
     if (!empty($this->cookies)) {
         if (!is_array($this->cookies)) {
             $this->cookies = (array) $this->cookies;
         }
         reset($this->cookies);
         if (count($this->cookies) > 0) {
             $cookie_str = 'Cookie: ';
             foreach ($this->cookies as $cookieKey => $cookieVal) {
                 $cookie_str .= $cookieKey . "=" . urlencode($cookieVal) . "; ";
             }
             $headers[] = _byte_substr($cookie_str, 0, -2);
         }
     }
     if (!empty($this->rawheaders)) {
         if (!is_array($this->rawheaders)) {
             $this->rawheaders = (array) $this->rawheaders;
         }
         while (list($headerKey, $headerVal) = each($this->rawheaders)) {
             $headers[] = $headerKey . ": " . $headerVal;
         }
     }
     if (!empty($content_type)) {
         if ($content_type == "multipart/form-data") {
             $headers[] = "Content-type: {$content_type}; boundary=" . $this->_mime_boundary;
         } else {
             $headers[] = "Content-type: {$content_type}";
         }
     }
     if (!empty($body)) {
         $headers[] = "Content-length: " . _byte_strlen($body);
     }
     if (!empty($this->user) || !empty($this->pass)) {
         $headers[] = "Authorization: BASIC " . base64_encode($this->user . ":" . $this->pass);
     }
     for ($curr_header = 0; $curr_header < count($headers); $curr_header++) {
         $cmdline_params .= " -H \"" . $headers[$curr_header] . "\"";
     }
     if (!empty($body)) {
         $cmdline_params .= " -d \"{$body}\"";
     }
     if ($this->read_timeout > 0) {
         $cmdline_params .= " -m " . $this->read_timeout;
     }
     $headerfile = tempnam($temp_dir, "sno");
     $safer_URI = strtr($URI, "\"", " ");
     // strip quotes from the URI to avoid shell access
     exec($this->curl_path . " -D \"{$headerfile}\"" . $cmdline_params . " \"" . $safer_URI . "\"", $results, $return);
     if ($return) {
         $this->error = "Error: cURL could not retrieve the document, error {$return}.";
         return false;
     }
     $results = implode("\r\n", $results);
     $file = new CFile($headerfile);
     $result_headers = $file->getLines();
     $this->_redirectaddr = false;
     unset($this->headers);
     for ($currentHeader = 0; $currentHeader < count($result_headers); $currentHeader++) {
         // if a header begins with Location: or URI:, set the redirect
         if (preg_match("/^(Location: |URI: )/i", $result_headers[$currentHeader])) {
             // get URL portion of the redirect
             preg_match("/^(Location: |URI:)\\s+(.*)/", chop($result_headers[$currentHeader]), $matches);
             // look for :// in the Location header to see if hostname is included
             if (!preg_match("|\\:\\/\\/|", $matches[2])) {
                 // no host in the path, so prepend
                 $this->_redirectaddr = $URI_PARTS["scheme"] . "://" . $this->host . ":" . $this->port;
                 // eliminate double slash
                 if (!preg_match("|^/|", $matches[2])) {
                     $this->_redirectaddr .= "/" . $matches[2];
                 } else {
                     $this->_redirectaddr .= $matches[2];
                 }
             } else {
                 $this->_redirectaddr = $matches[2];
             }
         }
         if (preg_match("|^HTTP/|", $result_headers[$currentHeader])) {
             $this->response_code = $result_headers[$currentHeader];
         }
         $this->headers[] = $result_headers[$currentHeader];
     }
     // check if there is a a redirect meta tag
     if (preg_match("'<meta[\\s]*http-equiv[^>]*?content[\\s]*=[\\s]*[\"\\']?\\d+;[\\s]+URL[\\s]*=[\\s]*([^\"\\']*?)[\"\\']?>'i", $results, $match)) {
         $this->_redirectaddr = $this->_expandlinks($match[1], $URI);
     }
     // have we hit our frame depth and is there frame src to fetch?
     if ($this->_framedepth < $this->maxframes && preg_match_all("'<frame\\s+.*src[\\s]*=[\\'\"]?([^\\'\"\\>]+)'i", $results, $match)) {
         $this->results[] = $results;
         for ($x = 0; $x < count($match[1]); $x++) {
             $this->_frameurls[] = $this->_expandlinks($match[1][$x], $URI_PARTS["scheme"] . "://" . $this->host);
         }
     } elseif (is_array($this->results)) {
         $this->results[] = $results;
     } else {
         $this->results = $results;
     }
     unlink("{$headerfile}");
     return true;
 }
 /**
  * creates an image resource from given .BMP file
  *
  * @param unknown_type $filename
  * @return unknown
  */
 function ImageCreateFromBMP($filename)
 {
     if (!($f1 = fopen($filename, "rb"))) {
         return FALSE;
     }
     $FILE = unpack("vfile_type/Vfile_size/Vreserved/Vbitmap_offset", fread($f1, 14));
     if ($FILE['file_type'] != 19778) {
         return FALSE;
     }
     $BMP = unpack('Vheader_size/Vwidth/Vheight/vplanes/vbits_per_pixel' . '/Vcompression/Vsize_bitmap/Vhoriz_resolution' . '/Vvert_resolution/Vcolors_used/Vcolors_important', fread($f1, 40));
     $BMP['colors'] = pow(2, $BMP['bits_per_pixel']);
     if ($BMP['size_bitmap'] == 0) {
         $BMP['size_bitmap'] = $FILE['file_size'] - $FILE['bitmap_offset'];
     }
     $BMP['bytes_per_pixel'] = $BMP['bits_per_pixel'] / 8;
     $BMP['bytes_per_pixel2'] = ceil($BMP['bytes_per_pixel']);
     $BMP['decal'] = $BMP['width'] * $BMP['bytes_per_pixel'] / 4;
     $BMP['decal'] -= floor($BMP['width'] * $BMP['bytes_per_pixel'] / 4);
     $BMP['decal'] = 4 - 4 * $BMP['decal'];
     if ($BMP['decal'] == 4) {
         $BMP['decal'] = 0;
     }
     $PALETTE = array();
     if ($BMP['colors'] < 16777216) {
         $PALETTE = unpack('V' . $BMP['colors'], fread($f1, $BMP['colors'] * 4));
     }
     $IMG = fread($f1, $BMP['size_bitmap']);
     $VIDE = _byte_chr(0);
     $res = imagecreatetruecolor($BMP['width'], $BMP['height']);
     $P = 0;
     $Y = $BMP['height'] - 1;
     while ($Y >= 0) {
         $X = 0;
         while ($X < $BMP['width']) {
             if ($BMP['bits_per_pixel'] == 24) {
                 $COLOR = unpack("V", _byte_substr($IMG, $P, 3) . $VIDE);
             } elseif ($BMP['bits_per_pixel'] == 16) {
                 $COLOR = unpack("n", _byte_substr($IMG, $P, 2));
                 $COLOR[1] = $PALETTE[$COLOR[1] + 1];
             } elseif ($BMP['bits_per_pixel'] == 8) {
                 $COLOR = unpack("n", $VIDE . _byte_substr($IMG, $P, 1));
                 $COLOR[1] = $PALETTE[$COLOR[1] + 1];
             } elseif ($BMP['bits_per_pixel'] == 4) {
                 $COLOR = unpack("n", $VIDE . _byte_substr($IMG, floor($P), 1));
                 if ($P * 2 % 2 == 0) {
                     $COLOR[1] = $COLOR[1] >> 4;
                 } else {
                     $COLOR[1] = $COLOR[1] & 0xf;
                 }
                 $COLOR[1] = $PALETTE[$COLOR[1] + 1];
             } elseif ($BMP['bits_per_pixel'] == 1) {
                 $COLOR = unpack("n", $VIDE . _byte_substr($IMG, floor($P), 1));
                 if ($P * 8 % 8 == 0) {
                     $COLOR[1] = $COLOR[1] >> 7;
                 } elseif ($P * 8 % 8 == 1) {
                     $COLOR[1] = ($COLOR[1] & 0x40) >> 6;
                 } elseif ($P * 8 % 8 == 2) {
                     $COLOR[1] = ($COLOR[1] & 0x20) >> 5;
                 } elseif ($P * 8 % 8 == 3) {
                     $COLOR[1] = ($COLOR[1] & 0x10) >> 4;
                 } elseif ($P * 8 % 8 == 4) {
                     $COLOR[1] = ($COLOR[1] & 0x8) >> 3;
                 } elseif ($P * 8 % 8 == 5) {
                     $COLOR[1] = ($COLOR[1] & 0x4) >> 2;
                 } elseif ($P * 8 % 8 == 6) {
                     $COLOR[1] = ($COLOR[1] & 0x2) >> 1;
                 } elseif ($P * 8 % 8 == 7) {
                     $COLOR[1] = $COLOR[1] & 0x1;
                 }
                 $COLOR[1] = $PALETTE[$COLOR[1] + 1];
             } else {
                 return FALSE;
             }
             imagesetpixel($res, $X, $Y, $COLOR[1]);
             $X++;
             $P += $BMP['bytes_per_pixel'];
         }
         $Y--;
         $P += $BMP['decal'];
     }
     fclose($f1);
     return $res;
 }