当前位置: 首页>>代码示例>>PHP>>正文


PHP reset_mbstring_encoding函数代码示例

本文整理汇总了PHP中reset_mbstring_encoding函数的典型用法代码示例。如果您正苦于以下问题:PHP reset_mbstring_encoding函数的具体用法?PHP reset_mbstring_encoding怎么用?PHP reset_mbstring_encoding使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了reset_mbstring_encoding函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: seems_utf8

function seems_utf8($str)
{
    mbstring_binary_safe_encoding();
    $length = strlen($str);
    reset_mbstring_encoding();
    for ($i = 0; $i < $length; $i++) {
        $c = ord($str[$i]);
        if ($c < 0x80) {
            $n = 0;
        } elseif (($c & 0xe0) == 0xc0) {
            $n = 1;
        } elseif (($c & 0xf0) == 0xe0) {
            $n = 2;
        } elseif (($c & 0xf8) == 0xf0) {
            $n = 3;
        } elseif (($c & 0xfc) == 0xf8) {
            $n = 4;
        } elseif (($c & 0xfe) == 0xfc) {
            $n = 5;
        } else {
            return false;
        }
        // Does not match any model
        for ($j = 0; $j < $n; $j++) {
            // n bytes matching 10bbbbbb follow ?
            if (++$i == $length || (ord($str[$i]) & 0xc0) != 0x80) {
                return false;
            }
        }
    }
    return true;
}
开发者ID:RafaRuiz,项目名称:geocode_checker,代码行数:32,代码来源:geocode.php

示例2: read

 /**
  * array (size=23)
  * 0 =>
  * array (size=11)
  * 'filename' => string 'akismet/' (length=8)
  * 'stored_filename' => string 'akismet/' (length=8)
  * 'size' => int 0
  * 'compressed_size' => int 0
  * 'mtime' => int 1443138698
  * 'comment' => string '' (length=0)
  * 'folder' => boolean true
  * 'index' => int 0
  * 'status' => string 'ok' (length=2)
  * 'crc' => int 0
  * 'content' => string '' (length=0)
  * 1 =>
  * array (size=11)
  * 'filename' => string 'akismet/akismet.php' (length=19)
  * 'stored_filename' => string 'akismet/akismet.php' (length=19)
  * 'size' => int 2438
  * 'compressed_size' => int 1184
  * 'mtime' => int 1443138698
  * 'comment' => string '' (length=0)
  * 'folder' => boolean false
  * 'index' => int 1
  * 'status' => string 'ok' (length=2)
  * 'crc' => int 1640791883
  * 'content' => string ''
  */
 public static function read($filePath)
 {
     if (function_exists('mbstring_binary_safe_encoding')) {
         mbstring_binary_safe_encoding();
     }
     $archive = new PclZip($filePath);
     $archive_files = $archive->extract(PCLZIP_OPT_EXTRACT_AS_STRING);
     if (function_exists('reset_mbstring_encoding')) {
         reset_mbstring_encoding();
     }
     return $archive_files;
 }
开发者ID:vicpril,项目名称:rep_bidqa,代码行数:41,代码来源:read.php

示例3: put_contents

 /**
  * Write a string to a file
  *
  * @param string $file Remote path to the file where to write the data.
  * @param string $contents The data to write.
  * @param int $mode (optional) The file permissions as octal number, usually 0644.
  * @return bool False upon failure.
  */
 function put_contents($file, $contents, $mode = false)
 {
     $fp = @fopen($file, 'wb');
     if (!$fp) {
         return false;
     }
     mbstring_binary_safe_encoding();
     $data_length = strlen($contents);
     $bytes_written = fwrite($fp, $contents);
     reset_mbstring_encoding();
     fclose($fp);
     if ($data_length !== $bytes_written) {
         return false;
     }
     $this->chmod($file, $mode);
     return true;
 }
开发者ID:Nancers,项目名称:Snancy-Website-Files,代码行数:25,代码来源:class-wp-filesystem-direct.php

示例4: bwg_wp_read_image_metadata

 private function bwg_wp_read_image_metadata($file)
 {
     if (!file_exists($file)) {
         return false;
     }
     list(, , $sourceImageType) = getimagesize($file);
     $meta = array('aperture' => 0, 'credit' => '', 'camera' => '', 'caption' => '', 'created_timestamp' => 0, 'copyright' => '', 'focal_length' => 0, 'iso' => 0, 'shutter_speed' => 0, 'title' => '', 'orientation' => 0);
     if (is_callable('iptcparse')) {
         getimagesize($file, $info);
         if (!empty($info['APP13'])) {
             $iptc = iptcparse($info['APP13']);
             if (!empty($iptc['2#105'][0])) {
                 $meta['title'] = trim($iptc['2#105'][0]);
             } elseif (!empty($iptc['2#005'][0])) {
                 $meta['title'] = trim($iptc['2#005'][0]);
             }
             if (!empty($iptc['2#120'][0])) {
                 $caption = trim($iptc['2#120'][0]);
                 if (empty($meta['title'])) {
                     mbstring_binary_safe_encoding();
                     $caption_length = strlen($caption);
                     reset_mbstring_encoding();
                     if ($caption_length < 80) {
                         $meta['title'] = $caption;
                     } else {
                         $meta['caption'] = $caption;
                     }
                 } elseif ($caption != $meta['title']) {
                     $meta['caption'] = $caption;
                 }
             }
             if (!empty($iptc['2#110'][0])) {
                 $meta['credit'] = trim($iptc['2#110'][0]);
             } elseif (!empty($iptc['2#080'][0])) {
                 $meta['credit'] = trim($iptc['2#080'][0]);
             }
             if (!empty($iptc['2#055'][0]) and !empty($iptc['2#060'][0])) {
                 $meta['created_timestamp'] = strtotime($iptc['2#055'][0] . ' ' . $iptc['2#060'][0]);
             }
             if (!empty($iptc['2#116'][0])) {
                 $meta['copyright'] = trim($iptc['2#116'][0]);
             }
         }
     }
     if (is_callable('exif_read_data') && in_array($sourceImageType, apply_filters('wp_read_image_metadata_types', array(IMAGETYPE_JPEG, IMAGETYPE_TIFF_II, IMAGETYPE_TIFF_MM)))) {
         $exif = @exif_read_data($file);
         if (empty($meta['title']) && !empty($exif['Title'])) {
             $meta['title'] = trim($exif['Title']);
         }
         if (!empty($exif['ImageDescription'])) {
             mbstring_binary_safe_encoding();
             $description_length = strlen($exif['ImageDescription']);
             reset_mbstring_encoding();
             if (empty($meta['title']) && $description_length < 80) {
                 $meta['title'] = trim($exif['ImageDescription']);
                 if (empty($meta['caption']) && !empty($exif['COMPUTED']['UserComment']) && trim($exif['COMPUTED']['UserComment']) != $meta['title']) {
                     $meta['caption'] = trim($exif['COMPUTED']['UserComment']);
                 }
             } elseif (empty($meta['caption']) && trim($exif['ImageDescription']) != $meta['title']) {
                 $meta['caption'] = trim($exif['ImageDescription']);
             }
         } elseif (empty($meta['caption']) && !empty($exif['Comments']) && trim($exif['Comments']) != $meta['title']) {
             $meta['caption'] = trim($exif['Comments']);
         }
         if (empty($meta['credit'])) {
             if (!empty($exif['Artist'])) {
                 $meta['credit'] = trim($exif['Artist']);
             } elseif (!empty($exif['Author'])) {
                 $meta['credit'] = trim($exif['Author']);
             }
         }
         if (empty($meta['copyright']) && !empty($exif['Copyright'])) {
             $meta['copyright'] = trim($exif['Copyright']);
         }
         if (!empty($exif['FNumber'])) {
             $meta['aperture'] = round(wp_exif_frac2dec($exif['FNumber']), 2);
         }
         if (!empty($exif['Model'])) {
             $meta['camera'] = trim($exif['Model']);
         }
         if (empty($meta['created_timestamp']) && !empty($exif['DateTimeDigitized'])) {
             $meta['created_timestamp'] = wp_exif_date2ts($exif['DateTimeDigitized']);
         }
         if (!empty($exif['FocalLength'])) {
             $meta['focal_length'] = (string) wp_exif_frac2dec($exif['FocalLength']);
         }
         if (!empty($exif['ISOSpeedRatings'])) {
             $meta['iso'] = is_array($exif['ISOSpeedRatings']) ? reset($exif['ISOSpeedRatings']) : $exif['ISOSpeedRatings'];
             $meta['iso'] = trim($meta['iso']);
         }
         if (!empty($exif['ExposureTime'])) {
             $meta['shutter_speed'] = (string) wp_exif_frac2dec($exif['ExposureTime']);
         }
         if (!empty($exif['Orientation'])) {
             $meta['orientation'] = $exif['Orientation'];
         }
     }
     foreach (array('title', 'caption', 'credit', 'copyright', 'camera', 'iso') as $key) {
         if ($meta[$key] && !seems_utf8($meta[$key])) {
             $meta[$key] = utf8_encode($meta[$key]);
//.........这里部分代码省略.........
开发者ID:jun200,项目名称:wordpress,代码行数:101,代码来源:model.php

示例5: dirlist

 /**
  * @param string $path
  * @param bool $include_hidden
  * @param bool $recursive
  * @return bool|array
  */
 public function dirlist($path = '.', $include_hidden = true, $recursive = false)
 {
     if ($this->is_file($path)) {
         $limit_file = basename($path);
         $path = dirname($path) . '/';
     } else {
         $limit_file = false;
     }
     mbstring_binary_safe_encoding();
     $list = $this->ftp->dirlist($path);
     if (empty($list) && !$this->exists($path)) {
         reset_mbstring_encoding();
         return false;
     }
     $ret = array();
     foreach ($list as $struc) {
         if ('.' == $struc['name'] || '..' == $struc['name']) {
             continue;
         }
         if (!$include_hidden && '.' == $struc['name'][0]) {
             continue;
         }
         if ($limit_file && $struc['name'] != $limit_file) {
             continue;
         }
         if ('d' == $struc['type']) {
             if ($recursive) {
                 $struc['files'] = $this->dirlist($path . '/' . $struc['name'], $include_hidden, $recursive);
             } else {
                 $struc['files'] = array();
             }
         }
         // Replace symlinks formatted as "source -> target" with just the source name
         if ($struc['islink']) {
             $struc['name'] = preg_replace('/(\\s*->\\s*.*)$/', '', $struc['name']);
         }
         $ret[$struc['name']] = $struc;
     }
     reset_mbstring_encoding();
     return $ret;
 }
开发者ID:hachi4,项目名称:WordPress,代码行数:47,代码来源:class-wp-filesystem-ftpsockets.php

示例6: write

 /**
  * Update or append the requested file with the supplied contents.
  *
  * @since 1.15.0
  *
  * @param string $file     Full path to config file to update.
  * @param string $contents Contents to write to the file.
  * @param bool   $append   Optional. Set to true to append contents to the file. Defaults to false.
  * @return bool|WP_Error Boolean true on success, WP_Error object otherwise.
  */
 public static function write($file, $contents, $append = false)
 {
     $callable = array();
     if (ITSEC_Lib_Utility::is_callable_function('fopen') && ITSEC_Lib_Utility::is_callable_function('fwrite') && ITSEC_Lib_Utility::is_callable_function('flock')) {
         $callable[] = 'fopen';
     }
     if (ITSEC_Lib_Utility::is_callable_function('file_put_contents')) {
         $callable[] = 'file_put_contents';
     }
     if (empty($callable)) {
         return new WP_Error('itsec-lib-file-write-no-callable-functions', sprintf(__('%s could not be written. Both the fopen/fwrite/flock and file_put_contents functions are disabled on the server. This is a server configuration issue that must be resolved before iThemes Security can write files.', 'it-l10n-better-wp-security'), $file));
     }
     if (ITSEC_Lib_Directory::is_dir($file)) {
         return new WP_Error('itsec-lib-file-write-path-exists-as-directory', sprintf(__('%s could not be written as a file. The requested path already exists as a directory. The directory must be removed or a new file name must be chosen before the file can be written.', 'it-l10n-better-wp-security'), $file));
     }
     if (!ITSEC_Lib_Directory::is_dir(dirname($file))) {
         $result = ITSEC_Lib_Directory::create(dirname($file));
         if (is_wp_error($result)) {
             return $result;
         }
     }
     $file_existed = self::is_file($file);
     $success = false;
     // Different permissions to try in case the starting set of permissions are prohibiting write.
     $trial_perms = array(false, 0644, 0664, 0666);
     foreach ($trial_perms as $perms) {
         if (false !== $perms) {
             if (!isset($original_file_perms)) {
                 $original_file_perms = self::get_permissions($file);
             }
             self::chmod($file, $perms);
         }
         if (in_array('fopen', $callable)) {
             if ($append) {
                 $mode = 'ab';
             } else {
                 $mode = 'wb';
             }
             if (false !== ($fh = @fopen($file, $mode))) {
                 flock($fh, LOCK_EX);
                 mbstring_binary_safe_encoding();
                 $data_length = strlen($contents);
                 $bytes_written = @fwrite($fh, $contents);
                 reset_mbstring_encoding();
                 @flock($fh, LOCK_UN);
                 @fclose($fh);
                 if ($data_length === $bytes_written) {
                     $success = true;
                 }
             }
         }
         if (!$success && in_array('file_put_contents', $callable)) {
             if ($append) {
                 $flags = FILE_APPEND;
             } else {
                 $flags = 0;
             }
             mbstring_binary_safe_encoding();
             $data_length = strlen($contents);
             $bytes_written = @file_put_contents($file, $contents, $flags);
             reset_mbstring_encoding();
             if ($data_length === $bytes_written) {
                 $success = true;
             }
         }
         if ($success) {
             if (!$file_existed) {
                 // Set default file permissions for the new file.
                 self::chmod($file, self::get_default_permissions());
             } else {
                 if (isset($original_file_perms) && !is_wp_error($original_file_perms)) {
                     // Reset the original file permissions if they were modified.
                     self::chmod($file, $original_file_perms);
                 }
             }
             return true;
         }
         if (!$file_existed) {
             // If the file is new, there is no point attempting different permissions.
             break;
         }
     }
     return new WP_Error('itsec-lib-file-write-file-put-contents-failed', sprintf(__('%s could not be written. This could be due to a permissions issue. Ensure that PHP runs as a user that has permission to write to this location.', 'it-l10n-better-wp-security'), $file));
 }
开发者ID:erikdukker,项目名称:medisom,代码行数:94,代码来源:class-itsec-lib-file.php

示例7: _unzip_file_pclzip

/**
 * This function should not be called directly, use unzip_file instead. Attempts to unzip an archive using the PclZip library.
 * Assumes that WP_Filesystem() has already been called and set up.
 *
 * @since 3.0.0
 * @see unzip_file
 * @access private
 *
 * @global WP_Filesystem_Base $wp_filesystem Subclass
 *
 * @param string $file Full path and filename of zip archive
 * @param string $to Full path on the filesystem to extract archive to
 * @param array $needed_dirs A partial list of required folders needed to be created.
 * @return mixed WP_Error on failure, True on success
 */
function _unzip_file_pclzip($file, $to, $needed_dirs = array()) {
	global $wp_filesystem;

	mbstring_binary_safe_encoding();

	require_once(ABSPATH . 'wp-admin/includes/class-pclzip.php');

	$archive = new PclZip($file);

	$archive_files = $archive->extract(PCLZIP_OPT_EXTRACT_AS_STRING);

	reset_mbstring_encoding();

	// Is the archive valid?
	if ( !is_array($archive_files) )
		return new WP_Error('incompatible_archive', __('Incompatible Archive.'), $archive->errorInfo(true));

	if ( 0 == count($archive_files) )
		return new WP_Error( 'empty_archive_pclzip', __( 'Empty archive.' ) );

	$uncompressed_size = 0;

	// Determine any children directories needed (From within the archive)
	foreach ( $archive_files as $file ) {
		if ( '__MACOSX/' === substr($file['filename'], 0, 9) ) // Skip the OS X-created __MACOSX directory
			continue;

		$uncompressed_size += $file['size'];

		$needed_dirs[] = $to . untrailingslashit( $file['folder'] ? $file['filename'] : dirname($file['filename']) );
	}

	/*
	 * disk_free_space() could return false. Assume that any falsey value is an error.
	 * A disk that has zero free bytes has bigger problems.
	 * Require we have enough space to unzip the file and copy its contents, with a 10% buffer.
	 */
	if ( defined( 'DOING_CRON' ) && DOING_CRON ) {
		$available_space = @disk_free_space( WP_CONTENT_DIR );
		if ( $available_space && ( $uncompressed_size * 2.1 ) > $available_space )
			return new WP_Error( 'disk_full_unzip_file', __( 'Could not copy files. You may have run out of disk space.' ), compact( 'uncompressed_size', 'available_space' ) );
	}

	$needed_dirs = array_unique($needed_dirs);
	foreach ( $needed_dirs as $dir ) {
		// Check the parent folders of the folders all exist within the creation array.
		if ( untrailingslashit($to) == $dir ) // Skip over the working directory, We know this exists (or will exist)
			continue;
		if ( strpos($dir, $to) === false ) // If the directory is not within the working directory, Skip it
			continue;

		$parent_folder = dirname($dir);
		while ( !empty($parent_folder) && untrailingslashit($to) != $parent_folder && !in_array($parent_folder, $needed_dirs) ) {
			$needed_dirs[] = $parent_folder;
			$parent_folder = dirname($parent_folder);
		}
	}
	asort($needed_dirs);

	// Create those directories if need be:
	foreach ( $needed_dirs as $_dir ) {
		// Only check to see if the dir exists upon creation failure. Less I/O this way.
		if ( ! $wp_filesystem->mkdir( $_dir, FS_CHMOD_DIR ) && ! $wp_filesystem->is_dir( $_dir ) )
			return new WP_Error( 'mkdir_failed_pclzip', __( 'Could not create directory.' ), substr( $_dir, strlen( $to ) ) );
	}
	unset($needed_dirs);

	// Extract the files from the zip
	foreach ( $archive_files as $file ) {
		if ( $file['folder'] )
			continue;

		if ( '__MACOSX/' === substr($file['filename'], 0, 9) ) // Don't extract the OS X-created __MACOSX directory files
			continue;

		if ( ! $wp_filesystem->put_contents( $to . $file['filename'], $file['content'], FS_CHMOD_FILE) )
			return new WP_Error( 'copy_failed_pclzip', __( 'Could not copy file.' ), $file['filename'] );
	}
	return true;
}
开发者ID:ShankarVellal,项目名称:WordPress,代码行数:95,代码来源:file.php

示例8: strip_invalid_text

    /**
     * Strips any invalid characters based on value/charset pairs.
     *
     * @since 4.2.0
     * @access protected
     *
     * @param array $data Array of value arrays. Each value array has the keys
     *                    'value' and 'charset'. An optional 'ascii' key can be
     *                    set to false to avoid redundant ASCII checks.
     * @return array|WP_Error The $data parameter, with invalid characters removed from
     *                        each value. This works as a passthrough: any additional keys
     *                        such as 'field' are retained in each value array. If we cannot
     *                        remove invalid characters, a WP_Error object is returned.
     */
    protected function strip_invalid_text($data)
    {
        $db_check_string = false;
        foreach ($data as &$value) {
            $charset = $value['charset'];
            if (is_array($value['length'])) {
                $length = $value['length']['length'];
                $truncate_by_byte_length = 'byte' === $value['length']['type'];
            } else {
                $length = false;
                // Since we have no length, we'll never truncate.
                // Initialize the variable to false. true would take us
                // through an unnecessary (for this case) codepath below.
                $truncate_by_byte_length = false;
            }
            // There's no charset to work with.
            if (false === $charset) {
                continue;
            }
            // Column isn't a string.
            if (!is_string($value['value'])) {
                continue;
            }
            $needs_validation = true;
            if ('latin1' === $charset || !isset($value['ascii']) && $this->check_ascii($value['value'])) {
                $truncate_by_byte_length = true;
                $needs_validation = false;
            }
            if ($truncate_by_byte_length) {
                mbstring_binary_safe_encoding();
                if (false !== $length && strlen($value['value']) > $length) {
                    $value['value'] = substr($value['value'], 0, $length);
                }
                reset_mbstring_encoding();
                if (!$needs_validation) {
                    continue;
                }
            }
            // utf8 can be handled by regex, which is a bunch faster than a DB lookup.
            if (('utf8' === $charset || 'utf8mb3' === $charset || 'utf8mb4' === $charset) && function_exists('mb_strlen')) {
                $regex = '/
					(
						(?: [\\x00-\\x7F]                  # single-byte sequences   0xxxxxxx
						|   [\\xC2-\\xDF][\\x80-\\xBF]       # double-byte sequences   110xxxxx 10xxxxxx
						|   \\xE0[\\xA0-\\xBF][\\x80-\\xBF]   # triple-byte sequences   1110xxxx 10xxxxxx * 2
						|   [\\xE1-\\xEC][\\x80-\\xBF]{2}
						|   \\xED[\\x80-\\x9F][\\x80-\\xBF]
						|   [\\xEE-\\xEF][\\x80-\\xBF]{2}';
                if ('utf8mb4' === $charset) {
                    $regex .= '
						|    \\xF0[\\x90-\\xBF][\\x80-\\xBF]{2} # four-byte sequences   11110xxx 10xxxxxx * 3
						|    [\\xF1-\\xF3][\\x80-\\xBF]{3}
						|    \\xF4[\\x80-\\x8F][\\x80-\\xBF]{2}
					';
                }
                $regex .= '){1,40}                          # ...one or more times
					)
					| .                                  # anything else
					/x';
                $value['value'] = preg_replace($regex, '$1', $value['value']);
                if (false !== $length && mb_strlen($value['value'], 'UTF-8') > $length) {
                    $value['value'] = mb_substr($value['value'], 0, $length, 'UTF-8');
                }
                continue;
            }
            // We couldn't use any local conversions, send it to the DB.
            $value['db'] = $db_check_string = true;
        }
        unset($value);
        // Remove by reference.
        if ($db_check_string) {
            $queries = array();
            foreach ($data as $col => $value) {
                if (!empty($value['db'])) {
                    // We're going to need to truncate by characters or bytes, depending on the length value we have.
                    if ('byte' === $value['length']['type']) {
                        // Using binary causes LEFT() to truncate by bytes.
                        $charset = 'binary';
                    } else {
                        $charset = $value['charset'];
                    }
                    if (is_array($value['length'])) {
                        $queries[$col] = $this->prepare("CONVERT( LEFT( CONVERT( %s USING {$charset} ), %.0f ) USING {$this->charset} )", $value['value'], $value['length']['length']);
                    } else {
                        if ('binary' !== $charset) {
                            // If we don't have a length, there's no need to convert binary - it will always return the same result.
//.........这里部分代码省略.........
开发者ID:renanvicente,项目名称:codedeploytest,代码行数:101,代码来源:wp-db.php

示例9: strip_invalid_text

    /**
     * Strips any invalid characters based on value/charset pairs.
     *
     * @since 4.2.0
     * @access protected
     *
     * @param array $data Array of value arrays. Each value array has the keys
     *                    'value' and 'charset'. An optional 'ascii' key can be
     *                    set to false to avoid redundant ASCII checks.
     * @return array|WP_Error The $data parameter, with invalid characters removed from
     *                        each value. This works as a passthrough: any additional keys
     *                        such as 'field' are retained in each value array. If we cannot
     *                        remove invalid characters, a WP_Error object is returned.
     */
    protected function strip_invalid_text($data)
    {
        $db_check_string = false;
        foreach ($data as &$value) {
            $charset = $value['charset'];
            if (is_array($value['length'])) {
                $length = $value['length']['length'];
            } else {
                $length = false;
            }
            // There's no charset to work with.
            if (false === $charset) {
                continue;
            }
            // Column isn't a string.
            if (!is_string($value['value'])) {
                continue;
            }
            $truncate_by_byte_length = 'byte' === $value['length']['type'];
            $needs_validation = true;
            if ('latin1' === $charset || !isset($value['ascii']) && $this->check_ascii($value['value'])) {
                $truncate_by_byte_length = true;
                $needs_validation = false;
            }
            if ($truncate_by_byte_length) {
                mbstring_binary_safe_encoding();
                if (false !== $length && strlen($value['value']) > $length) {
                    $value['value'] = substr($value['value'], 0, $length);
                }
                reset_mbstring_encoding();
                if (!$needs_validation) {
                    continue;
                }
            }
            // utf8 can be handled by regex, which is a bunch faster than a DB lookup.
            if (('utf8' === $charset || 'utf8mb3' === $charset || 'utf8mb4' === $charset) && function_exists('mb_strlen')) {
                $regex = '/
					(
						(?: [\\x00-\\x7F]                  # single-byte sequences   0xxxxxxx
						|   [\\xC2-\\xDF][\\x80-\\xBF]       # double-byte sequences   110xxxxx 10xxxxxx
						|   \\xE0[\\xA0-\\xBF][\\x80-\\xBF]   # triple-byte sequences   1110xxxx 10xxxxxx * 2
						|   [\\xE1-\\xEC][\\x80-\\xBF]{2}
						|   \\xED[\\x80-\\x9F][\\x80-\\xBF]
						|   [\\xEE-\\xEF][\\x80-\\xBF]{2}';
                if ('utf8mb4' === $charset) {
                    $regex .= '
						|    \\xF0[\\x90-\\xBF][\\x80-\\xBF]{2} # four-byte sequences   11110xxx 10xxxxxx * 3
						|    [\\xF1-\\xF3][\\x80-\\xBF]{3}
						|    \\xF4[\\x80-\\x8F][\\x80-\\xBF]{2}
					';
                }
                $regex .= '){1,40}                          # ...one or more times
					)
					| .                                  # anything else
					/x';
                $value['value'] = preg_replace($regex, '$1', $value['value']);
                if (false !== $length && mb_strlen($value['value'], 'UTF-8') > $length) {
                    $value['value'] = mb_substr($value['value'], 0, $length, 'UTF-8');
                }
                continue;
            }
            // We couldn't use any local conversions, send it to the DB.
            $value['db'] = $db_check_string = true;
        }
        unset($value);
        // Remove by reference.
        if ($db_check_string) {
            $queries = array();
            foreach ($data as $col => $value) {
                if (!empty($value['db'])) {
                    if (!isset($queries[$value['charset']])) {
                        $queries[$value['charset']] = array();
                    }
                    // We're going to need to truncate by characters or bytes, depending on the length value we have.
                    if ('byte' === $value['length']['type']) {
                        // Split the CONVERT() calls by charset, so we can make sure the connection is right
                        $queries[$value['charset']][$col] = $this->prepare("CONVERT( LEFT( CONVERT( %s USING binary ), %d ) USING {$value['charset']} )", $value['value'], $value['length']['length']);
                    } else {
                        $queries[$value['charset']][$col] = $this->prepare("LEFT( CONVERT( %s USING {$value['charset']} ), %d )", $value['value'], $value['length']['length']);
                    }
                    unset($data[$col]['db']);
                }
            }
            $connection_charset = $this->charset;
            foreach ($queries as $charset => $query) {
                if (!$query) {
//.........这里部分代码省略.........
开发者ID:dshkwnds,项目名称:Dockerfiles,代码行数:101,代码来源:wp-db.php

示例10: zip_export_data

 public function zip_export_data($is_backup = false)
 {
     $uploads_path = $this->get_wp_upload_dir();
     $zip_path = $this->get_upload_dir();
     if ($is_backup) {
         $zip_path = $uploads_path . 'tmm_backup/';
     }
     $tables = $this->get_wp_tables();
     $zip_filename = $zip_path . self::folder_key . '.zip';
     global $wpdb;
     file_put_contents($zip_path . 'wpdb.prfx', $wpdb->prefix);
     mbstring_binary_safe_encoding();
     require_once ABSPATH . 'wp-admin/includes/class-pclzip.php';
     $zip = new PclZip($zip_filename);
     if (!empty($tables)) {
         foreach ($tables as $table) {
             $file = $table . '.dat';
             $zip->add($zip_path . $file, PCLZIP_OPT_REMOVE_PATH, $zip_path);
             $file = $table . '.dsc';
             $zip->add($zip_path . $file, PCLZIP_OPT_REMOVE_PATH, $zip_path);
         }
     }
     $zip->add($zip_path . 'wpdb.prfx', PCLZIP_OPT_REMOVE_PATH, $zip_path);
     @$zip->create();
     reset_mbstring_encoding();
     foreach ($tables as $table) {
         if (file_exists($zip_path . $table . '.dsc')) {
             unlink($zip_path . $table . '.dsc');
         }
         if (file_exists($zip_path . $table . '.dat')) {
             unlink($zip_path . $table . '.dat');
         }
     }
     if (file_exists($zip_path . 'wpdb.prfx')) {
         unlink($zip_path . 'wpdb.prfx');
     }
     if (!$is_backup) {
         wp_die($this->get_zip_file_url());
     }
 }
开发者ID:ThemeMakers,项目名称:tmm_db_migrate,代码行数:40,代码来源:TMM_MigrateExport.php

示例11: utf8_uri_encode

/**
 * Encode the Unicode values to be used in the URI.
 *
 * @since 1.5.0
 *
 * @param string $utf8_string
 * @param int $length Max length of the string
 * @return string String with Unicode encoded for URI.
 */
function utf8_uri_encode( $utf8_string, $length = 0 ) {
	$unicode = '';
	$values = array();
	$num_octets = 1;
	$unicode_length = 0;

	mbstring_binary_safe_encoding();
	$string_length = strlen( $utf8_string );
	reset_mbstring_encoding();

	for ($i = 0; $i < $string_length; $i++ ) {

		$value = ord( $utf8_string[ $i ] );

		if ( $value < 128 ) {
			if ( $length && ( $unicode_length >= $length ) )
				break;
			$unicode .= chr($value);
			$unicode_length++;
		} else {
			if ( count( $values ) == 0 ) $num_octets = ( $value < 224 ) ? 2 : 3;

			$values[] = $value;

			if ( $length && ( $unicode_length + ($num_octets * 3) ) > $length )
				break;
			if ( count( $values ) == $num_octets ) {
				if ($num_octets == 3) {
					$unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]) . '%' . dechex($values[2]);
					$unicode_length += 9;
				} else {
					$unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]);
					$unicode_length += 6;
				}

				$values = array();
				$num_octets = 1;
			}
		}
	}

	return $unicode;
}
开发者ID:staylor,项目名称:develop.svn.wordpress.org,代码行数:52,代码来源:formatting.php

示例12: export_zip_file

 function export_zip_file($file, $source)
 {
     if (file_exists($file)) {
         unlink($file);
     }
     mbstring_binary_safe_encoding();
     // PclZip ships with WordPress
     require_once ABSPATH . 'wp-admin/includes/class-pclzip.php';
     $archive = new PclZip($file);
     if ($response = $archive->create($source, PCLZIP_OPT_REMOVE_PATH, dirname($source))) {
         reset_mbstring_encoding();
         header('Content-Description: File Transfer');
         header('Content-Type: application/octet-stream');
         header('Content-Length: ' . filesize($file));
         header('Content-Disposition: attachment; filename=' . basename($file));
         header('Expires: 0');
         header('Cache-Control: must-revalidate');
         header('Pragma: public');
         readfile($file);
         unlink($file);
         die;
     } else {
         $this->errors[] = __('PclZip returned zero bytes.', 'child-theme-configurator');
     }
 }
开发者ID:pacificano,项目名称:pacificano,代码行数:25,代码来源:class-ctc-admin.php

示例13: truncate_utf8

 /**
  * Truncate string as utf8
  *
  * @see http://jetpack.wp-a2z.org/oik_api/mbstring_binary_safe_encoding/
  * @link https://core.trac.wordpress.org/browser/trunk/src/wp-includes/formatting.php
  * @link https://core.trac.wordpress.org/browser/trunk/src/wp-includes/functions.php
  */
 private static function truncate_utf8($str, $regexp = NULL, $replace = '', $len = IP_GEO_BLOCK_MAX_STR_LEN)
 {
     // remove unnecessary characters
     $str = preg_replace('/[\\x00-\\x1f\\x7f]/', '', $str);
     if ($regexp) {
         $str = preg_replace($regexp, $replace, $str);
     }
     // limit the length of the string
     if (function_exists('mb_strcut')) {
         mbstring_binary_safe_encoding();
         // @since 3.7.0
         if (strlen($str) > $len) {
             $str = mb_strcut($str, 0, $len) . '…';
         }
         reset_mbstring_encoding();
         // @since 3.7.0
     } else {
         // https://core.trac.wordpress.org/ticket/25259
         mbstring_binary_safe_encoding();
         // @since 3.7.0
         $original = strlen($str);
         $str = substr($str, 0, $len);
         $length = strlen($str);
         reset_mbstring_encoding();
         // @since 3.7.0
         if ($length !== $original) {
             // bit pattern from seems_utf8() in wp-includes/formatting.php
             static $code = array(array(0x80, 0x0), array(0xe0, 0xc0), array(0xf0, 0xe0), array(0xf8, 0xf0), array(0xfc, 0xf8), array(0xfe, 0xfc));
             // truncate extra characters
             $len = min($length, 6);
             for ($i = 0; $i < $len; $i++) {
                 $c = ord($str[$length - 1 - $i]);
                 for ($j = $i; $j < 6; $j++) {
                     if (($c & $code[$j][0]) == $code[$j][1]) {
                         mbstring_binary_safe_encoding();
                         // @since 3.7.0
                         $str = substr($str, 0, $length - (int) ($j > 0) - $i);
                         reset_mbstring_encoding();
                         // @since 3.7.0
                         // validate whole characters
                         $str = self::validate_utf8($str);
                         return '…' !== $str ? "{$str}…" : '…';
                     }
                 }
             }
             // $str may not fit utf8
             return '…';
         }
     }
     // validate whole characters
     return self::validate_utf8($str);
 }
开发者ID:pemiu01,项目名称:WordPress-IP-Geo-Block,代码行数:59,代码来源:class-ip-geo-block-logs.php

示例14: _unzip_file_pclzip

/**
 * This function should not be called directly, use unzip_file instead. Attempts to unzip an archive using the PclZip library.
 * Assumes that WP_Filesystem() has already been called and set up.
 *
 * @since 3.0.0
 * @see unzip_file
 * @access private
 *
 * @param string $file Full path and filename of zip archive
 * @param string $to Full path on the filesystem to extract archive to
 * @param array $needed_dirs A partial list of required folders needed to be created.
 * @return mixed WP_Error on failure, True on success
 */
function _unzip_file_pclzip($file, $to, $needed_dirs = array())
{
    global $wp_filesystem;
    mbstring_binary_safe_encoding();
    require_once ABSPATH . 'wp-admin/includes/class-pclzip.php';
    $archive = new PclZip($file);
    $archive_files = $archive->extract(PCLZIP_OPT_EXTRACT_AS_STRING);
    reset_mbstring_encoding();
    // Is the archive valid?
    if (!is_array($archive_files)) {
        return new WP_Error('incompatible_archive', __('Incompatible Archive.'), $archive->errorInfo(true));
    }
    if (0 == count($archive_files)) {
        return new WP_Error('empty_archive', __('Empty archive.'));
    }
    // Determine any children directories needed (From within the archive)
    foreach ($archive_files as $file) {
        if ('__MACOSX/' === substr($file['filename'], 0, 9)) {
            // Skip the OS X-created __MACOSX directory
            continue;
        }
        $needed_dirs[] = $to . untrailingslashit($file['folder'] ? $file['filename'] : dirname($file['filename']));
    }
    $needed_dirs = array_unique($needed_dirs);
    foreach ($needed_dirs as $dir) {
        // Check the parent folders of the folders all exist within the creation array.
        if (untrailingslashit($to) == $dir) {
            // Skip over the working directory, We know this exists (or will exist)
            continue;
        }
        if (strpos($dir, $to) === false) {
            // If the directory is not within the working directory, Skip it
            continue;
        }
        $parent_folder = dirname($dir);
        while (!empty($parent_folder) && untrailingslashit($to) != $parent_folder && !in_array($parent_folder, $needed_dirs)) {
            $needed_dirs[] = $parent_folder;
            $parent_folder = dirname($parent_folder);
        }
    }
    asort($needed_dirs);
    // Create those directories if need be:
    foreach ($needed_dirs as $_dir) {
        if (!$wp_filesystem->mkdir($_dir, FS_CHMOD_DIR) && !$wp_filesystem->is_dir($_dir)) {
            // Only check to see if the dir exists upon creation failure. Less I/O this way.
            return new WP_Error('mkdir_failed', __('Could not create directory.'), $_dir);
        }
    }
    unset($needed_dirs);
    // Extract the files from the zip
    foreach ($archive_files as $file) {
        if ($file['folder']) {
            continue;
        }
        if ('__MACOSX/' === substr($file['filename'], 0, 9)) {
            // Don't extract the OS X-created __MACOSX directory files
            continue;
        }
        if (!$wp_filesystem->put_contents($to . $file['filename'], $file['content'], FS_CHMOD_FILE)) {
            return new WP_Error('copy_failed', __('Could not copy file.'), $to . $file['filename']);
        }
    }
    return true;
}
开发者ID:openify,项目名称:wordpress-composer,代码行数:77,代码来源:file.php

示例15: request


//.........这里部分代码省略.........
     }
     // WP allows passing in headers as a string, weirdly.
     if (!is_array($r['headers'])) {
         $processedHeaders = WP_Http::processHeaders($r['headers']);
         $r['headers'] = $processedHeaders['headers'];
     }
     // Setup arguments
     $headers = $r['headers'];
     $data = $r['body'];
     $type = $r['method'];
     $options = array('timeout' => $r['timeout'], 'useragent' => $r['user-agent'], 'blocking' => $r['blocking'], 'hooks' => new WP_HTTP_Requests_Hooks($url, $r));
     // Ensure redirects follow browser behaviour.
     $options['hooks']->register('requests.before_redirect', array(get_class(), 'browser_redirect_compatibility'));
     if ($r['stream']) {
         $options['filename'] = $r['filename'];
     }
     if (empty($r['redirection'])) {
         $options['follow_redirects'] = false;
     } else {
         $options['redirects'] = $r['redirection'];
     }
     // Use byte limit, if we can
     if (isset($r['limit_response_size'])) {
         $options['max_bytes'] = $r['limit_response_size'];
     }
     // If we've got cookies, use and convert them to Requests_Cookie.
     if (!empty($r['cookies'])) {
         $options['cookies'] = WP_Http::normalize_cookies($r['cookies']);
     }
     // SSL certificate handling
     if (!$r['sslverify']) {
         $options['verify'] = false;
         $options['verifyname'] = false;
     } else {
         $options['verify'] = $r['sslcertificates'];
     }
     // All non-GET/HEAD requests should put the arguments in the form body.
     if ('HEAD' !== $type && 'GET' !== $type) {
         $options['data_format'] = 'body';
     }
     /**
      * Filters whether SSL should be verified for non-local requests.
      *
      * @since 2.8.0
      *
      * @param bool $ssl_verify Whether to verify the SSL connection. Default true.
      */
     $options['verify'] = apply_filters('https_ssl_verify', $options['verify']);
     // Check for proxies.
     $proxy = new WP_HTTP_Proxy();
     if ($proxy->is_enabled() && $proxy->send_through_proxy($url)) {
         $options['proxy'] = new Requests_Proxy_HTTP($proxy->host() . ':' . $proxy->port());
         if ($proxy->use_authentication()) {
             $options['proxy']->use_authentication = true;
             $options['proxy']->user = $proxy->username();
             $options['proxy']->pass = $proxy->password();
         }
     }
     // Avoid issues where mbstring.func_overload is enabled
     mbstring_binary_safe_encoding();
     try {
         $requests_response = Requests::request($url, $headers, $data, $type, $options);
         // Convert the response into an array
         $http_response = new WP_HTTP_Requests_Response($requests_response, $r['filename']);
         $response = $http_response->to_array();
         // Add the original object to the array.
         $response['http_response'] = $http_response;
     } catch (Requests_Exception $e) {
         $response = new WP_Error('http_request_failed', $e->getMessage());
     }
     reset_mbstring_encoding();
     /**
      * Fires after an HTTP API response is received and before the response is returned.
      *
      * @since 2.8.0
      *
      * @param array|WP_Error $response HTTP response or WP_Error object.
      * @param string         $context  Context under which the hook is fired.
      * @param string         $class    HTTP transport used.
      * @param array          $args     HTTP request arguments.
      * @param string         $url      The request URL.
      */
     do_action('http_api_debug', $response, 'response', 'Requests', $r, $url);
     if (is_wp_error($response)) {
         return $response;
     }
     if (!$r['blocking']) {
         return array('headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array(), 'http_response' => null);
     }
     /**
      * Filters the HTTP API response immediately before the response is returned.
      *
      * @since 2.9.0
      *
      * @param array  $response HTTP response.
      * @param array  $r        HTTP request arguments.
      * @param string $url      The request URL.
      */
     return apply_filters('http_response', $response, $r, $url);
 }
开发者ID:aaemnnosttv,项目名称:develop.git.wordpress.org,代码行数:101,代码来源:class-http.php


注:本文中的reset_mbstring_encoding函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。