首页 > 代码库 > wordpress4.0.1源码学习和摘录--函数

wordpress4.0.1源码学习和摘录--函数

1.根据类型获取当前时间

function current_time( $type, $gmt = 0 ) {    switch ( $type ) {        case ‘mysql‘:            return ( $gmt ) ? gmdate( ‘Y-m-d H:i:s‘ ) : gmdate( ‘Y-m-d H:i:s‘, ( time() + ( get_option( ‘gmt_offset‘ ) * HOUR_IN_SECONDS ) ) );        case ‘timestamp‘:            return ( $gmt ) ? time() : time() + ( get_option( ‘gmt_offset‘ ) * HOUR_IN_SECONDS );        default:            return ( $gmt ) ? date( $type ) : date( $type, time() + ( get_option( ‘gmt_offset‘ ) * HOUR_IN_SECONDS ) );    }}

2.转换字节到对应单位

function size_format( $bytes, $decimals = 0 ) {    $quant = array(        // ========================= Origin ====        ‘TB‘ => 1099511627776,  // pow( 1024, 4)        ‘GB‘ => 1073741824,     // pow( 1024, 3)        ‘MB‘ => 1048576,        // pow( 1024, 2)        ‘kB‘ => 1024,           // pow( 1024, 1)        ‘B ‘ => 1,              // pow( 1024, 0)    );    foreach ( $quant as $unit => $mag )        if ( doubleval($bytes) >= $mag )            return number_format_i18n( $bytes / $mag, $decimals ) . ‘ ‘ . $unit;    return false;}function number_format_i18n( $number, $decimals = 0 ) {    global $wp_locale;    $formatted = number_format( $number, absint( $decimals ), $wp_locale->number_format[‘decimal_point‘], $wp_locale->number_format[‘thousands_sep‘] );    /**     * Filter the number formatted based on the locale.     *     * @since  2.8.0     *     * @param string $formatted Converted number in string format.     */    return apply_filters( ‘number_format_i18n‘, $formatted );}

3.转义引号

function add_magic_quotes( $array ) {    foreach ( (array) $array as $k => $v ) {        if ( is_array( $v ) ) {            $array[$k] = add_magic_quotes( $v );        } else {            $array[$k] = addslashes( $v );        }    }    return $array;}

4.缓存javascript

function cache_javascript_headers() {    $expiresOffset = 10 * DAY_IN_SECONDS;    header( "Content-Type: text/javascript; charset=" . get_bloginfo( ‘charset‘ ) );    header( "Vary: Accept-Encoding" ); // Handle proxies    header( "Expires: " . gmdate( "D, d M Y H:i:s", time() + $expiresOffset ) . " GMT" );}

5.创建绝对路径的目录

/** * Recursive directory creation based on full path. * * Will attempt to set permissions on folders. * * @since 2.0.1 * * @param string $target Full path to attempt to create. * @return bool Whether the path was created. True if path already exists. */function wp_mkdir_p( $target ) {    $wrapper = null;    // Strip the protocol.    if( wp_is_stream( $target ) ) {        list( $wrapper, $target ) = explode( ‘://‘, $target, 2 );    }    // From php.net/mkdir user contributed notes.    $target = str_replace( ‘//‘, ‘/‘, $target );    // Put the wrapper back on the target.    if( $wrapper !== null ) {        $target = $wrapper . ‘://‘ . $target;    }    /*     * Safe mode fails with a trailing slash under certain PHP versions.     * Use rtrim() instead of untrailingslashit to avoid formatting.php dependency.     */    $target = rtrim($target, ‘/‘);    if ( empty($target) )        $target = ‘/‘;    if ( file_exists( $target ) )        return @is_dir( $target );    // We need to find the permissions of the parent folder that exists and inherit that.    $target_parent = dirname( $target );    while ( ‘.‘ != $target_parent && ! is_dir( $target_parent ) ) {        $target_parent = dirname( $target_parent );    }    // Get the permission bits.    if ( $stat = @stat( $target_parent ) ) {        $dir_perms = $stat[‘mode‘] & 0007777;    } else {        $dir_perms = 0777;    }    if ( @mkdir( $target, $dir_perms, true ) ) {        /*         * If a umask is set that modifies $dir_perms, we‘ll have to re-set         * the $dir_perms correctly with chmod()         */        if ( $dir_perms != ( $dir_perms & ~umask() ) ) {            $folder_parts = explode( ‘/‘, substr( $target, strlen( $target_parent ) + 1 ) );            for ( $i = 1; $i <= count( $folder_parts ); $i++ ) {                @chmod( $target_parent . ‘/‘ . implode( ‘/‘, array_slice( $folder_parts, 0, $i ) ), $dir_perms );            }        }        return true;    }    return false;}

6.创建唯一的文件名

/** * Get a filename that is sanitized and unique for the given directory. * * If the filename is not unique, then a number will be added to the filename * before the extension, and will continue adding numbers until the filename is * unique. * * The callback is passed three parameters, the first one is the directory, the * second is the filename, and the third is the extension. * * @since 2.5.0 * * @param string   $dir                      Directory. * @param string   $filename                 File name. * @param callback $unique_filename_callback Callback. Default null. * @return string New filename, if given wasn‘t unique. */function wp_unique_filename( $dir, $filename, $unique_filename_callback = null ) {    // Sanitize the file name before we begin processing.    //$filename = sanitize_file_name($filename);    // Separate the filename into a name and extension.    $info = pathinfo($filename);    $ext = !empty($info[‘extension‘]) ? ‘.‘ . $info[‘extension‘] : ‘‘;    $name = basename($filename, $ext);    // Edge case: if file is named ‘.ext‘, treat as an empty name.    if ( $name === $ext )        $name = ‘‘;    /*     * Increment the file number until we have a unique file to save in $dir.     * Use callback if supplied.     */    if ( $unique_filename_callback && is_callable( $unique_filename_callback ) ) {        $filename = call_user_func( $unique_filename_callback, $dir, $name, $ext );    } else {        $number = ‘‘;        // Change ‘.ext‘ to lower case.        if ( $ext && strtolower($ext) != $ext ) {            $ext2 = strtolower($ext);            $filename2 = preg_replace( ‘|‘ . preg_quote($ext) . ‘$|‘, $ext2, $filename );            // Check for both lower and upper case extension or image sub-sizes may be overwritten.            while ( file_exists($dir . "/$filename") || file_exists($dir . "/$filename2") ) {                $new_number = $number + 1;                $filename = str_replace( "$number$ext", "$new_number$ext", $filename );                $filename2 = str_replace( "$number$ext2", "$new_number$ext2", $filename2 );                $number = $new_number;            }            return $filename2;        }        while ( file_exists( $dir . "/$filename" ) ) {            if ( ‘‘ == "$number$ext" )                $filename = $filename . ++$number . $ext;            else                $filename = str_replace( "$number$ext", ++$number . $ext, $filename );        }    }    return $filename;}

读到L2035==>待续

wordpress4.0.1源码学习和摘录--函数