code stringlengths 1 2.01M | language stringclasses 1 value |
|---|---|
<?php
/**
* Main WordPress Formatting API.
*
* Handles many functions for formatting output.
*
* @package WordPress
*/
/**
* Replaces common plain text characters into formatted entities
*
* As an example,
* <code>
* 'cause today's effort makes it worth tomorrow's "holiday"...
* </code>
* Becomes:
* <code>
* ’cause today’s effort makes it worth tomorrow’s “holiday”…
* </code>
* Code within certain html blocks are skipped.
*
* @since 0.71
* @uses $wp_cockneyreplace Array of formatted entities for certain common phrases
*
* @param string $text The text to be formatted
* @return string The string replaced with html entities
*/
function wptexturize($text) {
global $wp_cockneyreplace;
static $static_characters, $static_replacements, $dynamic_characters, $dynamic_replacements,
$default_no_texturize_tags, $default_no_texturize_shortcodes;
// No need to set up these static variables more than once
if ( ! isset( $static_characters ) ) {
/* translators: opening curly double quote */
$opening_quote = _x( '“', 'opening curly double quote' );
/* translators: closing curly double quote */
$closing_quote = _x( '”', 'closing curly double quote' );
/* translators: apostrophe, for example in 'cause or can't */
$apos = _x( '’', 'apostrophe' );
/* translators: prime, for example in 9' (nine feet) */
$prime = _x( '′', 'prime' );
/* translators: double prime, for example in 9" (nine inches) */
$double_prime = _x( '″', 'double prime' );
/* translators: opening curly single quote */
$opening_single_quote = _x( '‘', 'opening curly single quote' );
/* translators: closing curly single quote */
$closing_single_quote = _x( '’', 'closing curly single quote' );
/* translators: en dash */
$en_dash = _x( '–', 'en dash' );
/* translators: em dash */
$em_dash = _x( '—', 'em dash' );
$default_no_texturize_tags = array('pre', 'code', 'kbd', 'style', 'script', 'tt');
$default_no_texturize_shortcodes = array('code');
// if a plugin has provided an autocorrect array, use it
if ( isset($wp_cockneyreplace) ) {
$cockney = array_keys($wp_cockneyreplace);
$cockneyreplace = array_values($wp_cockneyreplace);
} elseif ( "'" != $apos ) { // Only bother if we're doing a replacement.
$cockney = array( "'tain't", "'twere", "'twas", "'tis", "'twill", "'til", "'bout", "'nuff", "'round", "'cause" );
$cockneyreplace = array( $apos . "tain" . $apos . "t", $apos . "twere", $apos . "twas", $apos . "tis", $apos . "twill", $apos . "til", $apos . "bout", $apos . "nuff", $apos . "round", $apos . "cause" );
} else {
$cockney = $cockneyreplace = array();
}
$static_characters = array_merge( array( '---', ' -- ', '--', ' - ', 'xn–', '...', '``', '\'\'', ' (tm)' ), $cockney );
$static_replacements = array_merge( array( $em_dash, ' ' . $em_dash . ' ', $en_dash, ' ' . $en_dash . ' ', 'xn--', '…', $opening_quote, $closing_quote, ' ™' ), $cockneyreplace );
/*
* Regex for common whitespace characters.
*
* By default, spaces include new lines, tabs, nbsp entities, and the UTF-8 nbsp.
* This is designed to replace the PCRE \s sequence. In #WP22692, that sequence
* was found to be unreliable due to random inclusion of the A0 byte.
*/
$spaces = '[\r\n\t ]|\xC2\xA0| ';
// Pattern-based replacements of characters.
$dynamic = array();
// '99 '99s '99's (apostrophe)
if ( "'" !== $apos ) {
$dynamic[ '/\'(?=\d)/' ] = $apos;
}
// Single quote at start, or preceded by (, {, <, [, ", or spaces.
if ( "'" !== $opening_single_quote ) {
$dynamic[ '/(?<=\A|[([{<"]|' . $spaces . ')\'/' ] = $opening_single_quote;
}
// 9" (double prime)
if ( '"' !== $double_prime ) {
$dynamic[ '/(?<=\d)"/' ] = $double_prime;
}
// 9' (prime)
if ( "'" !== $prime ) {
$dynamic[ '/(?<=\d)\'/' ] = $prime;
}
// Apostrophe in a word. No spaces or double primes.
if ( "'" !== $apos ) {
$dynamic[ '/(?<!' . $spaces . ')\'(?!\'|' . $spaces . ')/' ] = $apos;
}
// Double quote at start, or preceded by (, {, <, [, or spaces, and not followed by spaces.
if ( '"' !== $opening_quote ) {
$dynamic[ '/(?<=\A|[([{<]|' . $spaces . ')"(?!' . $spaces . ')/' ] = $opening_quote;
}
// Any remaining double quotes.
if ( '"' !== $closing_quote ) {
$dynamic[ '/"/' ] = $closing_quote;
}
// Single quotes followed by spaces or a period.
if ( "'" !== $closing_single_quote ) {
$dynamic[ '/\'(?=\Z|\.|' . $spaces . ')/' ] = $closing_single_quote;
}
$dynamic_characters = array_keys( $dynamic );
$dynamic_replacements = array_values( $dynamic );
}
// Transform into regexp sub-expression used in _wptexturize_pushpop_element
// Must do this every time in case plugins use these filters in a context sensitive manner
/**
* Filter the list of HTML elements not to texturize.
*
* @since 2.8.0
*
* @param array $default_no_texturize_tags An array of HTML element names.
*/
$no_texturize_tags = '(' . implode( '|', apply_filters( 'no_texturize_tags', $default_no_texturize_tags ) ) . ')';
/**
* Filter the list of shortcodes not to texturize.
*
* @since 2.8.0
*
* @param array $default_no_texturize_shortcodes An array of shortcode names.
*/
$no_texturize_shortcodes = '(' . implode( '|', apply_filters( 'no_texturize_shortcodes', $default_no_texturize_shortcodes ) ) . ')';
$no_texturize_tags_stack = array();
$no_texturize_shortcodes_stack = array();
$textarr = preg_split('/(<.*>|\[.*\])/Us', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
foreach ( $textarr as &$curl ) {
if ( empty( $curl ) ) {
continue;
}
// Only call _wptexturize_pushpop_element if first char is correct tag opening
$first = $curl[0];
if ( '<' === $first ) {
_wptexturize_pushpop_element($curl, $no_texturize_tags_stack, $no_texturize_tags, '<', '>');
} elseif ( '[' === $first ) {
_wptexturize_pushpop_element($curl, $no_texturize_shortcodes_stack, $no_texturize_shortcodes, '[', ']');
} elseif ( empty($no_texturize_shortcodes_stack) && empty($no_texturize_tags_stack) ) {
// This is not a tag, nor is the texturization disabled static strings
$curl = str_replace($static_characters, $static_replacements, $curl);
// regular expressions
$curl = preg_replace($dynamic_characters, $dynamic_replacements, $curl);
// 9x9 (times)
if ( 1 === preg_match( '/(?<=\d)x\d/', $text ) ) {
// Searching for a digit is 10 times more expensive than for the x, so we avoid doing this one!
$curl = preg_replace( '/\b(\d+)x(\d+)\b/', '$1×$2', $curl );
}
}
// Replace each & with & unless it already looks like an entity.
$curl = preg_replace('/&([^#])(?![a-zA-Z1-4]{1,8};)/', '&$1', $curl);
}
return implode( '', $textarr );
}
/**
* Search for disabled element tags. Push element to stack on tag open and pop
* on tag close. Assumes first character of $text is tag opening.
*
* @since 2.9.0
* @access private
*
* @param string $text Text to check. First character is assumed to be $opening
* @param array $stack Array used as stack of opened tag elements
* @param string $disabled_elements Tags to match against formatted as regexp sub-expression
* @param string $opening Tag opening character, assumed to be 1 character long
* @param string $closing Tag closing character
*/
function _wptexturize_pushpop_element($text, &$stack, $disabled_elements, $opening = '<', $closing = '>') {
// Check if it is a closing tag -- otherwise assume opening tag
if (strncmp($opening . '/', $text, 2)) {
// Opening? Check $text+1 against disabled elements
if (preg_match('/^' . $disabled_elements . '\b/', substr($text, 1), $matches)) {
/*
* This disables texturize until we find a closing tag of our type
* (e.g. <pre>) even if there was invalid nesting before that
*
* Example: in the case <pre>sadsadasd</code>"baba"</pre>
* "baba" won't be texturize
*/
array_push($stack, $matches[1]);
}
} else {
// Closing? Check $text+2 against disabled elements
$c = preg_quote($closing, '/');
if (preg_match('/^' . $disabled_elements . $c . '/', substr($text, 2), $matches)) {
$last = array_pop($stack);
// Make sure it matches the opening tag
if ( $last != $matches[1] ) {
array_push( $stack, $last );
}
}
}
}
/**
* Replaces double line-breaks with paragraph elements.
*
* A group of regex replaces used to identify text formatted with newlines and
* replace double line-breaks with HTML paragraph tags. The remaining
* line-breaks after conversion become <<br />> tags, unless $br is set to '0'
* or 'false'.
*
* @since 0.71
*
* @param string $pee The text which has to be formatted.
* @param bool $br Optional. If set, this will convert all remaining line-breaks after paragraphing. Default true.
* @return string Text which has been converted into correct paragraph tags.
*/
function wpautop($pee, $br = true) {
$pre_tags = array();
if ( trim($pee) === '' )
return '';
$pee = $pee . "\n"; // just to make things a little easier, pad the end
if ( strpos($pee, '<pre') !== false ) {
$pee_parts = explode( '</pre>', $pee );
$last_pee = array_pop($pee_parts);
$pee = '';
$i = 0;
foreach ( $pee_parts as $pee_part ) {
$start = strpos($pee_part, '<pre');
// Malformed html?
if ( $start === false ) {
$pee .= $pee_part;
continue;
}
$name = "<pre wp-pre-tag-$i></pre>";
$pre_tags[$name] = substr( $pee_part, $start ) . '</pre>';
$pee .= substr( $pee_part, 0, $start ) . $name;
$i++;
}
$pee .= $last_pee;
}
$pee = preg_replace('|<br />\s*<br />|', "\n\n", $pee);
// Space things out a little
$allblocks = '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|form|map|area|blockquote|address|math|style|p|h[1-6]|hr|fieldset|noscript|legend|section|article|aside|hgroup|header|footer|nav|figure|details|menu|summary)';
$pee = preg_replace('!(<' . $allblocks . '[^>]*>)!', "\n$1", $pee);
$pee = preg_replace('!(</' . $allblocks . '>)!', "$1\n\n", $pee);
$pee = str_replace(array("\r\n", "\r"), "\n", $pee); // cross-platform newlines
if ( strpos( $pee, '</object>' ) !== false ) {
// no P/BR around param and embed
$pee = preg_replace( '|(<object[^>]*>)\s*|', '$1', $pee );
$pee = preg_replace( '|\s*</object>|', '</object>', $pee );
$pee = preg_replace( '%\s*(</?(?:param|embed)[^>]*>)\s*%', '$1', $pee );
}
if ( strpos( $pee, '<source' ) !== false || strpos( $pee, '<track' ) !== false ) {
// no P/BR around source and track
$pee = preg_replace( '%([<\[](?:audio|video)[^>\]]*[>\]])\s*%', '$1', $pee );
$pee = preg_replace( '%\s*([<\[]/(?:audio|video)[>\]])%', '$1', $pee );
$pee = preg_replace( '%\s*(<(?:source|track)[^>]*>)\s*%', '$1', $pee );
}
$pee = preg_replace("/\n\n+/", "\n\n", $pee); // take care of duplicates
// make paragraphs, including one at the end
$pees = preg_split('/\n\s*\n/', $pee, -1, PREG_SPLIT_NO_EMPTY);
$pee = '';
foreach ( $pees as $tinkle ) {
$pee .= '<p>' . trim($tinkle, "\n") . "</p>\n";
}
$pee = preg_replace('|<p>\s*</p>|', '', $pee); // under certain strange conditions it could create a P of entirely whitespace
$pee = preg_replace('!<p>([^<]+)</(div|address|form)>!', "<p>$1</p></$2>", $pee);
$pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee); // don't pee all over a tag
$pee = preg_replace("|<p>(<li.+?)</p>|", "$1", $pee); // problem with nested lists
$pee = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $pee);
$pee = str_replace('</blockquote></p>', '</p></blockquote>', $pee);
$pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)!', "$1", $pee);
$pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee);
if ( $br ) {
$pee = preg_replace_callback('/<(script|style).*?<\/\\1>/s', '_autop_newline_preservation_helper', $pee);
$pee = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $pee); // optionally make line breaks
$pee = str_replace('<WPPreserveNewline />', "\n", $pee);
}
$pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*<br />!', "$1", $pee);
$pee = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $pee);
$pee = preg_replace( "|\n</p>$|", '</p>', $pee );
if ( !empty($pre_tags) )
$pee = str_replace(array_keys($pre_tags), array_values($pre_tags), $pee);
return $pee;
}
/**
* Newline preservation help function for wpautop
*
* @since 3.1.0
* @access private
*
* @param array $matches preg_replace_callback matches array
* @return string
*/
function _autop_newline_preservation_helper( $matches ) {
return str_replace("\n", "<WPPreserveNewline />", $matches[0]);
}
/**
* Don't auto-p wrap shortcodes that stand alone
*
* Ensures that shortcodes are not wrapped in <<p>>...<</p>>.
*
* @since 2.9.0
*
* @param string $pee The content.
* @return string The filtered content.
*/
function shortcode_unautop( $pee ) {
global $shortcode_tags;
if ( empty( $shortcode_tags ) || !is_array( $shortcode_tags ) ) {
return $pee;
}
$tagregexp = join( '|', array_map( 'preg_quote', array_keys( $shortcode_tags ) ) );
$pattern =
'/'
. '<p>' // Opening paragraph
. '\\s*+' // Optional leading whitespace
. '(' // 1: The shortcode
. '\\[' // Opening bracket
. "($tagregexp)" // 2: Shortcode name
. '(?![\\w-])' // Not followed by word character or hyphen
// Unroll the loop: Inside the opening shortcode tag
. '[^\\]\\/]*' // Not a closing bracket or forward slash
. '(?:'
. '\\/(?!\\])' // A forward slash not followed by a closing bracket
. '[^\\]\\/]*' // Not a closing bracket or forward slash
. ')*?'
. '(?:'
. '\\/\\]' // Self closing tag and closing bracket
. '|'
. '\\]' // Closing bracket
. '(?:' // Unroll the loop: Optionally, anything between the opening and closing shortcode tags
. '[^\\[]*+' // Not an opening bracket
. '(?:'
. '\\[(?!\\/\\2\\])' // An opening bracket not followed by the closing shortcode tag
. '[^\\[]*+' // Not an opening bracket
. ')*+'
. '\\[\\/\\2\\]' // Closing shortcode tag
. ')?'
. ')'
. ')'
. '\\s*+' // optional trailing whitespace
. '<\\/p>' // closing paragraph
. '/s';
return preg_replace( $pattern, '$1', $pee );
}
/**
* Checks to see if a string is utf8 encoded.
*
* NOTE: This function checks for 5-Byte sequences, UTF8
* has Bytes Sequences with a maximum length of 4.
*
* @author bmorel at ssi dot fr (modified)
* @since 1.2.1
*
* @param string $str The string to be checked
* @return bool True if $str fits a UTF-8 model, false otherwise.
*/
function seems_utf8($str) {
$length = strlen($str);
for ($i=0; $i < $length; $i++) {
$c = ord($str[$i]);
if ($c < 0x80) $n = 0; # 0bbbbbbb
elseif (($c & 0xE0) == 0xC0) $n=1; # 110bbbbb
elseif (($c & 0xF0) == 0xE0) $n=2; # 1110bbbb
elseif (($c & 0xF8) == 0xF0) $n=3; # 11110bbb
elseif (($c & 0xFC) == 0xF8) $n=4; # 111110bb
elseif (($c & 0xFE) == 0xFC) $n=5; # 1111110b
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;
}
/**
* Converts a number of special characters into their HTML entities.
*
* Specifically deals with: &, <, >, ", and '.
*
* $quote_style can be set to ENT_COMPAT to encode " to
* ", or ENT_QUOTES to do both. Default is ENT_NOQUOTES where no quotes are encoded.
*
* @since 1.2.2
* @access private
*
* @param string $string The text which is to be encoded.
* @param mixed $quote_style Optional. Converts double quotes if set to ENT_COMPAT, both single and double if set to ENT_QUOTES or none if set to ENT_NOQUOTES. Also compatible with old values; converting single quotes if set to 'single', double if set to 'double' or both if otherwise set. Default is ENT_NOQUOTES.
* @param string $charset Optional. The character encoding of the string. Default is false.
* @param boolean $double_encode Optional. Whether to encode existing html entities. Default is false.
* @return string The encoded text with HTML entities.
*/
function _wp_specialchars( $string, $quote_style = ENT_NOQUOTES, $charset = false, $double_encode = false ) {
$string = (string) $string;
if ( 0 === strlen( $string ) )
return '';
// Don't bother if there are no specialchars - saves some processing
if ( ! preg_match( '/[&<>"\']/', $string ) )
return $string;
// Account for the previous behaviour of the function when the $quote_style is not an accepted value
if ( empty( $quote_style ) )
$quote_style = ENT_NOQUOTES;
elseif ( ! in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) )
$quote_style = ENT_QUOTES;
// Store the site charset as a static to avoid multiple calls to wp_load_alloptions()
if ( ! $charset ) {
static $_charset;
if ( ! isset( $_charset ) ) {
$alloptions = wp_load_alloptions();
$_charset = isset( $alloptions['blog_charset'] ) ? $alloptions['blog_charset'] : '';
}
$charset = $_charset;
}
if ( in_array( $charset, array( 'utf8', 'utf-8', 'UTF8' ) ) )
$charset = 'UTF-8';
$_quote_style = $quote_style;
if ( $quote_style === 'double' ) {
$quote_style = ENT_COMPAT;
$_quote_style = ENT_COMPAT;
} elseif ( $quote_style === 'single' ) {
$quote_style = ENT_NOQUOTES;
}
// Handle double encoding ourselves
if ( $double_encode ) {
$string = @htmlspecialchars( $string, $quote_style, $charset );
} else {
// Decode & into &
$string = wp_specialchars_decode( $string, $_quote_style );
// Guarantee every &entity; is valid or re-encode the &
$string = wp_kses_normalize_entities( $string );
// Now re-encode everything except &entity;
$string = preg_split( '/(&#?x?[0-9a-z]+;)/i', $string, -1, PREG_SPLIT_DELIM_CAPTURE );
for ( $i = 0; $i < count( $string ); $i += 2 )
$string[$i] = @htmlspecialchars( $string[$i], $quote_style, $charset );
$string = implode( '', $string );
}
// Backwards compatibility
if ( 'single' === $_quote_style )
$string = str_replace( "'", ''', $string );
return $string;
}
/**
* Converts a number of HTML entities into their special characters.
*
* Specifically deals with: &, <, >, ", and '.
*
* $quote_style can be set to ENT_COMPAT to decode " entities,
* or ENT_QUOTES to do both " and '. Default is ENT_NOQUOTES where no quotes are decoded.
*
* @since 2.8.0
*
* @param string $string The text which is to be decoded.
* @param mixed $quote_style Optional. Converts double quotes if set to ENT_COMPAT, both single and double if set to ENT_QUOTES or none if set to ENT_NOQUOTES. Also compatible with old _wp_specialchars() values; converting single quotes if set to 'single', double if set to 'double' or both if otherwise set. Default is ENT_NOQUOTES.
* @return string The decoded text without HTML entities.
*/
function wp_specialchars_decode( $string, $quote_style = ENT_NOQUOTES ) {
$string = (string) $string;
if ( 0 === strlen( $string ) ) {
return '';
}
// Don't bother if there are no entities - saves a lot of processing
if ( strpos( $string, '&' ) === false ) {
return $string;
}
// Match the previous behaviour of _wp_specialchars() when the $quote_style is not an accepted value
if ( empty( $quote_style ) ) {
$quote_style = ENT_NOQUOTES;
} elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
$quote_style = ENT_QUOTES;
}
// More complete than get_html_translation_table( HTML_SPECIALCHARS )
$single = array( ''' => '\'', ''' => '\'' );
$single_preg = array( '/�*39;/' => ''', '/�*27;/i' => ''' );
$double = array( '"' => '"', '"' => '"', '"' => '"' );
$double_preg = array( '/�*34;/' => '"', '/�*22;/i' => '"' );
$others = array( '<' => '<', '<' => '<', '>' => '>', '>' => '>', '&' => '&', '&' => '&', '&' => '&' );
$others_preg = array( '/�*60;/' => '<', '/�*62;/' => '>', '/�*38;/' => '&', '/�*26;/i' => '&' );
if ( $quote_style === ENT_QUOTES ) {
$translation = array_merge( $single, $double, $others );
$translation_preg = array_merge( $single_preg, $double_preg, $others_preg );
} elseif ( $quote_style === ENT_COMPAT || $quote_style === 'double' ) {
$translation = array_merge( $double, $others );
$translation_preg = array_merge( $double_preg, $others_preg );
} elseif ( $quote_style === 'single' ) {
$translation = array_merge( $single, $others );
$translation_preg = array_merge( $single_preg, $others_preg );
} elseif ( $quote_style === ENT_NOQUOTES ) {
$translation = $others;
$translation_preg = $others_preg;
}
// Remove zero padding on numeric entities
$string = preg_replace( array_keys( $translation_preg ), array_values( $translation_preg ), $string );
// Replace characters according to translation table
return strtr( $string, $translation );
}
/**
* Checks for invalid UTF8 in a string.
*
* @since 2.8.0
*
* @param string $string The text which is to be checked.
* @param boolean $strip Optional. Whether to attempt to strip out invalid UTF8. Default is false.
* @return string The checked text.
*/
function wp_check_invalid_utf8( $string, $strip = false ) {
$string = (string) $string;
if ( 0 === strlen( $string ) ) {
return '';
}
// Store the site charset as a static to avoid multiple calls to get_option()
static $is_utf8;
if ( !isset( $is_utf8 ) ) {
$is_utf8 = in_array( get_option( 'blog_charset' ), array( 'utf8', 'utf-8', 'UTF8', 'UTF-8' ) );
}
if ( !$is_utf8 ) {
return $string;
}
// Check for support for utf8 in the installed PCRE library once and store the result in a static
static $utf8_pcre;
if ( !isset( $utf8_pcre ) ) {
$utf8_pcre = @preg_match( '/^./u', 'a' );
}
// We can't demand utf8 in the PCRE installation, so just return the string in those cases
if ( !$utf8_pcre ) {
return $string;
}
// preg_match fails when it encounters invalid UTF8 in $string
if ( 1 === @preg_match( '/^./us', $string ) ) {
return $string;
}
// Attempt to strip the bad chars if requested (not recommended)
if ( $strip && function_exists( 'iconv' ) ) {
return iconv( 'utf-8', 'utf-8', $string );
}
return '';
}
/**
* 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;
$string_length = strlen( $utf8_string );
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;
}
/**
* Converts all accent characters to ASCII characters.
*
* If there are no accent characters, then the string given is just returned.
*
* @since 1.2.1
*
* @param string $string Text that might have accent characters
* @return string Filtered string with replaced "nice" characters.
*/
function remove_accents($string) {
if ( !preg_match('/[\x80-\xff]/', $string) )
return $string;
if (seems_utf8($string)) {
$chars = array(
// Decompositions for Latin-1 Supplement
chr(194).chr(170) => 'a', chr(194).chr(186) => 'o',
chr(195).chr(128) => 'A', chr(195).chr(129) => 'A',
chr(195).chr(130) => 'A', chr(195).chr(131) => 'A',
chr(195).chr(132) => 'A', chr(195).chr(133) => 'A',
chr(195).chr(134) => 'AE',chr(195).chr(135) => 'C',
chr(195).chr(136) => 'E', chr(195).chr(137) => 'E',
chr(195).chr(138) => 'E', chr(195).chr(139) => 'E',
chr(195).chr(140) => 'I', chr(195).chr(141) => 'I',
chr(195).chr(142) => 'I', chr(195).chr(143) => 'I',
chr(195).chr(144) => 'D', chr(195).chr(145) => 'N',
chr(195).chr(146) => 'O', chr(195).chr(147) => 'O',
chr(195).chr(148) => 'O', chr(195).chr(149) => 'O',
chr(195).chr(150) => 'O', chr(195).chr(153) => 'U',
chr(195).chr(154) => 'U', chr(195).chr(155) => 'U',
chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y',
chr(195).chr(158) => 'TH',chr(195).chr(159) => 's',
chr(195).chr(160) => 'a', chr(195).chr(161) => 'a',
chr(195).chr(162) => 'a', chr(195).chr(163) => 'a',
chr(195).chr(164) => 'a', chr(195).chr(165) => 'a',
chr(195).chr(166) => 'ae',chr(195).chr(167) => 'c',
chr(195).chr(168) => 'e', chr(195).chr(169) => 'e',
chr(195).chr(170) => 'e', chr(195).chr(171) => 'e',
chr(195).chr(172) => 'i', chr(195).chr(173) => 'i',
chr(195).chr(174) => 'i', chr(195).chr(175) => 'i',
chr(195).chr(176) => 'd', chr(195).chr(177) => 'n',
chr(195).chr(178) => 'o', chr(195).chr(179) => 'o',
chr(195).chr(180) => 'o', chr(195).chr(181) => 'o',
chr(195).chr(182) => 'o', chr(195).chr(184) => 'o',
chr(195).chr(185) => 'u', chr(195).chr(186) => 'u',
chr(195).chr(187) => 'u', chr(195).chr(188) => 'u',
chr(195).chr(189) => 'y', chr(195).chr(190) => 'th',
chr(195).chr(191) => 'y', chr(195).chr(152) => 'O',
// Decompositions for Latin Extended-A
chr(196).chr(128) => 'A', chr(196).chr(129) => 'a',
chr(196).chr(130) => 'A', chr(196).chr(131) => 'a',
chr(196).chr(132) => 'A', chr(196).chr(133) => 'a',
chr(196).chr(134) => 'C', chr(196).chr(135) => 'c',
chr(196).chr(136) => 'C', chr(196).chr(137) => 'c',
chr(196).chr(138) => 'C', chr(196).chr(139) => 'c',
chr(196).chr(140) => 'C', chr(196).chr(141) => 'c',
chr(196).chr(142) => 'D', chr(196).chr(143) => 'd',
chr(196).chr(144) => 'D', chr(196).chr(145) => 'd',
chr(196).chr(146) => 'E', chr(196).chr(147) => 'e',
chr(196).chr(148) => 'E', chr(196).chr(149) => 'e',
chr(196).chr(150) => 'E', chr(196).chr(151) => 'e',
chr(196).chr(152) => 'E', chr(196).chr(153) => 'e',
chr(196).chr(154) => 'E', chr(196).chr(155) => 'e',
chr(196).chr(156) => 'G', chr(196).chr(157) => 'g',
chr(196).chr(158) => 'G', chr(196).chr(159) => 'g',
chr(196).chr(160) => 'G', chr(196).chr(161) => 'g',
chr(196).chr(162) => 'G', chr(196).chr(163) => 'g',
chr(196).chr(164) => 'H', chr(196).chr(165) => 'h',
chr(196).chr(166) => 'H', chr(196).chr(167) => 'h',
chr(196).chr(168) => 'I', chr(196).chr(169) => 'i',
chr(196).chr(170) => 'I', chr(196).chr(171) => 'i',
chr(196).chr(172) => 'I', chr(196).chr(173) => 'i',
chr(196).chr(174) => 'I', chr(196).chr(175) => 'i',
chr(196).chr(176) => 'I', chr(196).chr(177) => 'i',
chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij',
chr(196).chr(180) => 'J', chr(196).chr(181) => 'j',
chr(196).chr(182) => 'K', chr(196).chr(183) => 'k',
chr(196).chr(184) => 'k', chr(196).chr(185) => 'L',
chr(196).chr(186) => 'l', chr(196).chr(187) => 'L',
chr(196).chr(188) => 'l', chr(196).chr(189) => 'L',
chr(196).chr(190) => 'l', chr(196).chr(191) => 'L',
chr(197).chr(128) => 'l', chr(197).chr(129) => 'L',
chr(197).chr(130) => 'l', chr(197).chr(131) => 'N',
chr(197).chr(132) => 'n', chr(197).chr(133) => 'N',
chr(197).chr(134) => 'n', chr(197).chr(135) => 'N',
chr(197).chr(136) => 'n', chr(197).chr(137) => 'N',
chr(197).chr(138) => 'n', chr(197).chr(139) => 'N',
chr(197).chr(140) => 'O', chr(197).chr(141) => 'o',
chr(197).chr(142) => 'O', chr(197).chr(143) => 'o',
chr(197).chr(144) => 'O', chr(197).chr(145) => 'o',
chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe',
chr(197).chr(148) => 'R',chr(197).chr(149) => 'r',
chr(197).chr(150) => 'R',chr(197).chr(151) => 'r',
chr(197).chr(152) => 'R',chr(197).chr(153) => 'r',
chr(197).chr(154) => 'S',chr(197).chr(155) => 's',
chr(197).chr(156) => 'S',chr(197).chr(157) => 's',
chr(197).chr(158) => 'S',chr(197).chr(159) => 's',
chr(197).chr(160) => 'S', chr(197).chr(161) => 's',
chr(197).chr(162) => 'T', chr(197).chr(163) => 't',
chr(197).chr(164) => 'T', chr(197).chr(165) => 't',
chr(197).chr(166) => 'T', chr(197).chr(167) => 't',
chr(197).chr(168) => 'U', chr(197).chr(169) => 'u',
chr(197).chr(170) => 'U', chr(197).chr(171) => 'u',
chr(197).chr(172) => 'U', chr(197).chr(173) => 'u',
chr(197).chr(174) => 'U', chr(197).chr(175) => 'u',
chr(197).chr(176) => 'U', chr(197).chr(177) => 'u',
chr(197).chr(178) => 'U', chr(197).chr(179) => 'u',
chr(197).chr(180) => 'W', chr(197).chr(181) => 'w',
chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y',
chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z',
chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z',
chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z',
chr(197).chr(190) => 'z', chr(197).chr(191) => 's',
// Decompositions for Latin Extended-B
chr(200).chr(152) => 'S', chr(200).chr(153) => 's',
chr(200).chr(154) => 'T', chr(200).chr(155) => 't',
// Euro Sign
chr(226).chr(130).chr(172) => 'E',
// GBP (Pound) Sign
chr(194).chr(163) => '',
// Vowels with diacritic (Vietnamese)
// unmarked
chr(198).chr(160) => 'O', chr(198).chr(161) => 'o',
chr(198).chr(175) => 'U', chr(198).chr(176) => 'u',
// grave accent
chr(225).chr(186).chr(166) => 'A', chr(225).chr(186).chr(167) => 'a',
chr(225).chr(186).chr(176) => 'A', chr(225).chr(186).chr(177) => 'a',
chr(225).chr(187).chr(128) => 'E', chr(225).chr(187).chr(129) => 'e',
chr(225).chr(187).chr(146) => 'O', chr(225).chr(187).chr(147) => 'o',
chr(225).chr(187).chr(156) => 'O', chr(225).chr(187).chr(157) => 'o',
chr(225).chr(187).chr(170) => 'U', chr(225).chr(187).chr(171) => 'u',
chr(225).chr(187).chr(178) => 'Y', chr(225).chr(187).chr(179) => 'y',
// hook
chr(225).chr(186).chr(162) => 'A', chr(225).chr(186).chr(163) => 'a',
chr(225).chr(186).chr(168) => 'A', chr(225).chr(186).chr(169) => 'a',
chr(225).chr(186).chr(178) => 'A', chr(225).chr(186).chr(179) => 'a',
chr(225).chr(186).chr(186) => 'E', chr(225).chr(186).chr(187) => 'e',
chr(225).chr(187).chr(130) => 'E', chr(225).chr(187).chr(131) => 'e',
chr(225).chr(187).chr(136) => 'I', chr(225).chr(187).chr(137) => 'i',
chr(225).chr(187).chr(142) => 'O', chr(225).chr(187).chr(143) => 'o',
chr(225).chr(187).chr(148) => 'O', chr(225).chr(187).chr(149) => 'o',
chr(225).chr(187).chr(158) => 'O', chr(225).chr(187).chr(159) => 'o',
chr(225).chr(187).chr(166) => 'U', chr(225).chr(187).chr(167) => 'u',
chr(225).chr(187).chr(172) => 'U', chr(225).chr(187).chr(173) => 'u',
chr(225).chr(187).chr(182) => 'Y', chr(225).chr(187).chr(183) => 'y',
// tilde
chr(225).chr(186).chr(170) => 'A', chr(225).chr(186).chr(171) => 'a',
chr(225).chr(186).chr(180) => 'A', chr(225).chr(186).chr(181) => 'a',
chr(225).chr(186).chr(188) => 'E', chr(225).chr(186).chr(189) => 'e',
chr(225).chr(187).chr(132) => 'E', chr(225).chr(187).chr(133) => 'e',
chr(225).chr(187).chr(150) => 'O', chr(225).chr(187).chr(151) => 'o',
chr(225).chr(187).chr(160) => 'O', chr(225).chr(187).chr(161) => 'o',
chr(225).chr(187).chr(174) => 'U', chr(225).chr(187).chr(175) => 'u',
chr(225).chr(187).chr(184) => 'Y', chr(225).chr(187).chr(185) => 'y',
// acute accent
chr(225).chr(186).chr(164) => 'A', chr(225).chr(186).chr(165) => 'a',
chr(225).chr(186).chr(174) => 'A', chr(225).chr(186).chr(175) => 'a',
chr(225).chr(186).chr(190) => 'E', chr(225).chr(186).chr(191) => 'e',
chr(225).chr(187).chr(144) => 'O', chr(225).chr(187).chr(145) => 'o',
chr(225).chr(187).chr(154) => 'O', chr(225).chr(187).chr(155) => 'o',
chr(225).chr(187).chr(168) => 'U', chr(225).chr(187).chr(169) => 'u',
// dot below
chr(225).chr(186).chr(160) => 'A', chr(225).chr(186).chr(161) => 'a',
chr(225).chr(186).chr(172) => 'A', chr(225).chr(186).chr(173) => 'a',
chr(225).chr(186).chr(182) => 'A', chr(225).chr(186).chr(183) => 'a',
chr(225).chr(186).chr(184) => 'E', chr(225).chr(186).chr(185) => 'e',
chr(225).chr(187).chr(134) => 'E', chr(225).chr(187).chr(135) => 'e',
chr(225).chr(187).chr(138) => 'I', chr(225).chr(187).chr(139) => 'i',
chr(225).chr(187).chr(140) => 'O', chr(225).chr(187).chr(141) => 'o',
chr(225).chr(187).chr(152) => 'O', chr(225).chr(187).chr(153) => 'o',
chr(225).chr(187).chr(162) => 'O', chr(225).chr(187).chr(163) => 'o',
chr(225).chr(187).chr(164) => 'U', chr(225).chr(187).chr(165) => 'u',
chr(225).chr(187).chr(176) => 'U', chr(225).chr(187).chr(177) => 'u',
chr(225).chr(187).chr(180) => 'Y', chr(225).chr(187).chr(181) => 'y',
// Vowels with diacritic (Chinese, Hanyu Pinyin)
chr(201).chr(145) => 'a',
// macron
chr(199).chr(149) => 'U', chr(199).chr(150) => 'u',
// acute accent
chr(199).chr(151) => 'U', chr(199).chr(152) => 'u',
// caron
chr(199).chr(141) => 'A', chr(199).chr(142) => 'a',
chr(199).chr(143) => 'I', chr(199).chr(144) => 'i',
chr(199).chr(145) => 'O', chr(199).chr(146) => 'o',
chr(199).chr(147) => 'U', chr(199).chr(148) => 'u',
chr(199).chr(153) => 'U', chr(199).chr(154) => 'u',
// grave accent
chr(199).chr(155) => 'U', chr(199).chr(156) => 'u',
);
// Used for locale-specific rules
$locale = get_locale();
if ( 'de_DE' == $locale ) {
$chars[ chr(195).chr(132) ] = 'Ae';
$chars[ chr(195).chr(164) ] = 'ae';
$chars[ chr(195).chr(150) ] = 'Oe';
$chars[ chr(195).chr(182) ] = 'oe';
$chars[ chr(195).chr(156) ] = 'Ue';
$chars[ chr(195).chr(188) ] = 'ue';
$chars[ chr(195).chr(159) ] = 'ss';
} elseif ( 'da_DK' === $locale ) {
$chars[ chr(195).chr(134) ] = 'Ae';
$chars[ chr(195).chr(166) ] = 'ae';
$chars[ chr(195).chr(152) ] = 'Oe';
$chars[ chr(195).chr(184) ] = 'oe';
$chars[ chr(195).chr(133) ] = 'Aa';
$chars[ chr(195).chr(165) ] = 'aa';
}
$string = strtr($string, $chars);
} else {
// Assume ISO-8859-1 if not UTF-8
$chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158)
.chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194)
.chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202)
.chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210)
.chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218)
.chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227)
.chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235)
.chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243)
.chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251)
.chr(252).chr(253).chr(255);
$chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy";
$string = strtr($string, $chars['in'], $chars['out']);
$double_chars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254));
$double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
$string = str_replace($double_chars['in'], $double_chars['out'], $string);
}
return $string;
}
/**
* Sanitizes a filename, replacing whitespace with dashes.
*
* Removes special characters that are illegal in filenames on certain
* operating systems and special characters requiring special escaping
* to manipulate at the command line. Replaces spaces and consecutive
* dashes with a single dash. Trims period, dash and underscore from beginning
* and end of filename.
*
* @since 2.1.0
*
* @param string $filename The filename to be sanitized
* @return string The sanitized filename
*/
function sanitize_file_name( $filename ) {
$filename_raw = $filename;
$special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}", chr(0));
/**
* Filter the list of characters to remove from a filename.
*
* @since 2.8.0
*
* @param array $special_chars Characters to remove.
* @param string $filename_raw Filename as it was passed into sanitize_file_name().
*/
$special_chars = apply_filters( 'sanitize_file_name_chars', $special_chars, $filename_raw );
$filename = preg_replace( "#\x{00a0}#siu", ' ', $filename );
$filename = str_replace($special_chars, '', $filename);
$filename = preg_replace('/[\s-]+/', '-', $filename);
$filename = trim($filename, '.-_');
// Split the filename into a base and extension[s]
$parts = explode('.', $filename);
// Return if only one extension
if ( count( $parts ) <= 2 ) {
/**
* Filter a sanitized filename string.
*
* @since 2.8.0
*
* @param string $filename Sanitized filename.
* @param string $filename_raw The filename prior to sanitization.
*/
return apply_filters( 'sanitize_file_name', $filename, $filename_raw );
}
// Process multiple extensions
$filename = array_shift($parts);
$extension = array_pop($parts);
$mimes = get_allowed_mime_types();
/*
* Loop over any intermediate extensions. Postfix them with a trailing underscore
* if they are a 2 - 5 character long alpha string not in the extension whitelist.
*/
foreach ( (array) $parts as $part) {
$filename .= '.' . $part;
if ( preg_match("/^[a-zA-Z]{2,5}\d?$/", $part) ) {
$allowed = false;
foreach ( $mimes as $ext_preg => $mime_match ) {
$ext_preg = '!^(' . $ext_preg . ')$!i';
if ( preg_match( $ext_preg, $part ) ) {
$allowed = true;
break;
}
}
if ( !$allowed )
$filename .= '_';
}
}
$filename .= '.' . $extension;
/** This filter is documented in wp-includes/formatting.php */
return apply_filters('sanitize_file_name', $filename, $filename_raw);
}
/**
* Sanitizes a username, stripping out unsafe characters.
*
* Removes tags, octets, entities, and if strict is enabled, will only keep
* alphanumeric, _, space, ., -, @. After sanitizing, it passes the username,
* raw username (the username in the parameter), and the value of $strict as
* parameters for the 'sanitize_user' filter.
*
* @since 2.0.0
*
* @param string $username The username to be sanitized.
* @param bool $strict If set limits $username to specific characters. Default false.
* @return string The sanitized username, after passing through filters.
*/
function sanitize_user( $username, $strict = false ) {
$raw_username = $username;
$username = wp_strip_all_tags( $username );
$username = remove_accents( $username );
// Kill octets
$username = preg_replace( '|%([a-fA-F0-9][a-fA-F0-9])|', '', $username );
$username = preg_replace( '/&.+?;/', '', $username ); // Kill entities
// If strict, reduce to ASCII for max portability.
if ( $strict )
$username = preg_replace( '|[^a-z0-9 _.\-@]|i', '', $username );
$username = trim( $username );
// Consolidate contiguous whitespace
$username = preg_replace( '|\s+|', ' ', $username );
/**
* Filter a sanitized username string.
*
* @since 2.0.1
*
* @param string $username Sanitized username.
* @param string $raw_username The username prior to sanitization.
* @param bool $strict Whether to limit the sanitization to specific characters. Default false.
*/
return apply_filters( 'sanitize_user', $username, $raw_username, $strict );
}
/**
* Sanitizes a string key.
*
* Keys are used as internal identifiers. Lowercase alphanumeric characters, dashes and underscores are allowed.
*
* @since 3.0.0
*
* @param string $key String key
* @return string Sanitized key
*/
function sanitize_key( $key ) {
$raw_key = $key;
$key = strtolower( $key );
$key = preg_replace( '/[^a-z0-9_\-]/', '', $key );
/**
* Filter a sanitized key string.
*
* @since 3.0.0
*
* @param string $key Sanitized key.
* @param string $raw_key The key prior to sanitization.
*/
return apply_filters( 'sanitize_key', $key, $raw_key );
}
/**
* Sanitizes a title, or returns a fallback title.
*
* Specifically, HTML and PHP tags are stripped. Further actions can be added
* via the plugin API. If $title is empty and $fallback_title is set, the latter
* will be used.
*
* @since 1.0.0
*
* @param string $title The string to be sanitized.
* @param string $fallback_title Optional. A title to use if $title is empty.
* @param string $context Optional. The operation for which the string is sanitized
* @return string The sanitized string.
*/
function sanitize_title( $title, $fallback_title = '', $context = 'save' ) {
$raw_title = $title;
if ( 'save' == $context )
$title = remove_accents($title);
/**
* Filter a sanitized title string.
*
* @since 1.2.0
*
* @param string $title Sanitized title.
* @param string $raw_title The title prior to sanitization.
* @param string $context The context for which the title is being sanitized.
*/
$title = apply_filters( 'sanitize_title', $title, $raw_title, $context );
if ( '' === $title || false === $title )
$title = $fallback_title;
return $title;
}
/**
* Sanitizes a title with the 'query' context.
*
* Used for querying the database for a value from URL.
*
* @since 3.1.0
* @uses sanitize_title()
*
* @param string $title The string to be sanitized.
* @return string The sanitized string.
*/
function sanitize_title_for_query( $title ) {
return sanitize_title( $title, '', 'query' );
}
/**
* Sanitizes a title, replacing whitespace and a few other characters with dashes.
*
* Limits the output to alphanumeric characters, underscore (_) and dash (-).
* Whitespace becomes a dash.
*
* @since 1.2.0
*
* @param string $title The title to be sanitized.
* @param string $raw_title Optional. Not used.
* @param string $context Optional. The operation for which the string is sanitized.
* @return string The sanitized title.
*/
function sanitize_title_with_dashes( $title, $raw_title = '', $context = 'display' ) {
$title = strip_tags($title);
// Preserve escaped octets.
$title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
// Remove percent signs that are not part of an octet.
$title = str_replace('%', '', $title);
// Restore octets.
$title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
if (seems_utf8($title)) {
if (function_exists('mb_strtolower')) {
$title = mb_strtolower($title, 'UTF-8');
}
$title = utf8_uri_encode($title, 200);
}
$title = strtolower($title);
$title = preg_replace('/&.+?;/', '', $title); // kill entities
$title = str_replace('.', '-', $title);
if ( 'save' == $context ) {
// Convert nbsp, ndash and mdash to hyphens
$title = str_replace( array( '%c2%a0', '%e2%80%93', '%e2%80%94' ), '-', $title );
// Strip these characters entirely
$title = str_replace( array(
// iexcl and iquest
'%c2%a1', '%c2%bf',
// angle quotes
'%c2%ab', '%c2%bb', '%e2%80%b9', '%e2%80%ba',
// curly quotes
'%e2%80%98', '%e2%80%99', '%e2%80%9c', '%e2%80%9d',
'%e2%80%9a', '%e2%80%9b', '%e2%80%9e', '%e2%80%9f',
// copy, reg, deg, hellip and trade
'%c2%a9', '%c2%ae', '%c2%b0', '%e2%80%a6', '%e2%84%a2',
// acute accents
'%c2%b4', '%cb%8a', '%cc%81', '%cd%81',
// grave accent, macron, caron
'%cc%80', '%cc%84', '%cc%8c',
), '', $title );
// Convert times to x
$title = str_replace( '%c3%97', 'x', $title );
}
$title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
$title = preg_replace('/\s+/', '-', $title);
$title = preg_replace('|-+|', '-', $title);
$title = trim($title, '-');
return $title;
}
/**
* Ensures a string is a valid SQL order by clause.
*
* Accepts one or more columns, with or without ASC/DESC, and also accepts
* RAND().
*
* @since 2.5.1
*
* @param string $orderby Order by string to be checked.
* @return string|bool Returns the order by clause if it is a match, false otherwise.
*/
function sanitize_sql_orderby( $orderby ){
preg_match('/^\s*([a-z0-9_]+(\s+(ASC|DESC))?(\s*,\s*|\s*$))+|^\s*RAND\(\s*\)\s*$/i', $orderby, $obmatches);
if ( !$obmatches )
return false;
return $orderby;
}
/**
* Sanitizes an HTML classname to ensure it only contains valid characters.
*
* Strips the string down to A-Z,a-z,0-9,_,-. If this results in an empty
* string then it will return the alternative value supplied.
*
* @todo Expand to support the full range of CDATA that a class attribute can contain.
*
* @since 2.8.0
*
* @param string $class The classname to be sanitized
* @param string $fallback Optional. The value to return if the sanitization end's up as an empty string.
* Defaults to an empty string.
* @return string The sanitized value
*/
function sanitize_html_class( $class, $fallback = '' ) {
//Strip out any % encoded octets
$sanitized = preg_replace( '|%[a-fA-F0-9][a-fA-F0-9]|', '', $class );
//Limit to A-Z,a-z,0-9,_,-
$sanitized = preg_replace( '/[^A-Za-z0-9_-]/', '', $sanitized );
if ( '' == $sanitized )
$sanitized = $fallback;
/**
* Filter a sanitized HTML class string.
*
* @since 2.8.0
*
* @param string $sanitized The sanitized HTML class.
* @param string $class HTML class before sanitization.
* @param string $fallback The fallback string.
*/
return apply_filters( 'sanitize_html_class', $sanitized, $class, $fallback );
}
/**
* Converts a number of characters from a string.
*
* Metadata tags <<title>> and <<category>> are removed, <<br>> and <<hr>> are
* converted into correct XHTML and Unicode characters are converted to the
* valid range.
*
* @since 0.71
*
* @param string $content String of characters to be converted.
* @param string $deprecated Not used.
* @return string Converted string.
*/
function convert_chars($content, $deprecated = '') {
if ( !empty( $deprecated ) )
_deprecated_argument( __FUNCTION__, '0.71' );
// Translation of invalid Unicode references range to valid range
$wp_htmltranswinuni = array(
'€' => '€', // the Euro sign
'' => '',
'‚' => '‚', // these are Windows CP1252 specific characters
'ƒ' => 'ƒ', // they would look weird on non-Windows browsers
'„' => '„',
'…' => '…',
'†' => '†',
'‡' => '‡',
'ˆ' => 'ˆ',
'‰' => '‰',
'Š' => 'Š',
'‹' => '‹',
'Œ' => 'Œ',
'' => '',
'Ž' => 'Ž',
'' => '',
'' => '',
'‘' => '‘',
'’' => '’',
'“' => '“',
'”' => '”',
'•' => '•',
'–' => '–',
'—' => '—',
'˜' => '˜',
'™' => '™',
'š' => 'š',
'›' => '›',
'œ' => 'œ',
'' => '',
'ž' => 'ž',
'Ÿ' => 'Ÿ'
);
// Remove metadata tags
$content = preg_replace('/<title>(.+?)<\/title>/','',$content);
$content = preg_replace('/<category>(.+?)<\/category>/','',$content);
// Converts lone & characters into & (a.k.a. &)
$content = preg_replace('/&([^#])(?![a-z1-4]{1,8};)/i', '&$1', $content);
// Fix Word pasting
$content = strtr($content, $wp_htmltranswinuni);
// Just a little XHTML help
$content = str_replace('<br>', '<br />', $content);
$content = str_replace('<hr>', '<hr />', $content);
return $content;
}
/**
* Balances tags if forced to, or if the 'use_balanceTags' option is set to true.
*
* @since 0.71
*
* @param string $text Text to be balanced
* @param bool $force If true, forces balancing, ignoring the value of the option. Default false.
* @return string Balanced text
*/
function balanceTags( $text, $force = false ) {
if ( $force || get_option('use_balanceTags') == 1 ) {
return force_balance_tags( $text );
} else {
return $text;
}
}
/**
* Balances tags of string using a modified stack.
*
* @since 2.0.4
*
* @author Leonard Lin <leonard@acm.org>
* @license GPL
* @copyright November 4, 2001
* @version 1.1
* @todo Make better - change loop condition to $text in 1.2
* @internal Modified by Scott Reilly (coffee2code) 02 Aug 2004
* 1.1 Fixed handling of append/stack pop order of end text
* Added Cleaning Hooks
* 1.0 First Version
*
* @param string $text Text to be balanced.
* @return string Balanced text.
*/
function force_balance_tags( $text ) {
$tagstack = array();
$stacksize = 0;
$tagqueue = '';
$newtext = '';
// Known single-entity/self-closing tags
$single_tags = array( 'area', 'base', 'basefont', 'br', 'col', 'command', 'embed', 'frame', 'hr', 'img', 'input', 'isindex', 'link', 'meta', 'param', 'source' );
// Tags that can be immediately nested within themselves
$nestable_tags = array( 'blockquote', 'div', 'object', 'q', 'span' );
// WP bug fix for comments - in case you REALLY meant to type '< !--'
$text = str_replace('< !--', '< !--', $text);
// WP bug fix for LOVE <3 (and other situations with '<' before a number)
$text = preg_replace('#<([0-9]{1})#', '<$1', $text);
while ( preg_match("/<(\/?[\w:]*)\s*([^>]*)>/", $text, $regex) ) {
$newtext .= $tagqueue;
$i = strpos($text, $regex[0]);
$l = strlen($regex[0]);
// clear the shifter
$tagqueue = '';
// Pop or Push
if ( isset($regex[1][0]) && '/' == $regex[1][0] ) { // End Tag
$tag = strtolower(substr($regex[1],1));
// if too many closing tags
if( $stacksize <= 0 ) {
$tag = '';
// or close to be safe $tag = '/' . $tag;
}
// if stacktop value = tag close value then pop
else if ( $tagstack[$stacksize - 1] == $tag ) { // found closing tag
$tag = '</' . $tag . '>'; // Close Tag
// Pop
array_pop( $tagstack );
$stacksize--;
} else { // closing tag not at top, search for it
for ( $j = $stacksize-1; $j >= 0; $j-- ) {
if ( $tagstack[$j] == $tag ) {
// add tag to tagqueue
for ( $k = $stacksize-1; $k >= $j; $k--) {
$tagqueue .= '</' . array_pop( $tagstack ) . '>';
$stacksize--;
}
break;
}
}
$tag = '';
}
} else { // Begin Tag
$tag = strtolower($regex[1]);
// Tag Cleaning
// If it's an empty tag "< >", do nothing
if ( '' == $tag ) {
// do nothing
}
// ElseIf it presents itself as a self-closing tag...
elseif ( substr( $regex[2], -1 ) == '/' ) {
// ...but it isn't a known single-entity self-closing tag, then don't let it be treated as such and
// immediately close it with a closing tag (the tag will encapsulate no text as a result)
if ( ! in_array( $tag, $single_tags ) )
$regex[2] = trim( substr( $regex[2], 0, -1 ) ) . "></$tag";
}
// ElseIf it's a known single-entity tag but it doesn't close itself, do so
elseif ( in_array($tag, $single_tags) ) {
$regex[2] .= '/';
}
// Else it's not a single-entity tag
else {
// If the top of the stack is the same as the tag we want to push, close previous tag
if ( $stacksize > 0 && !in_array($tag, $nestable_tags) && $tagstack[$stacksize - 1] == $tag ) {
$tagqueue = '</' . array_pop( $tagstack ) . '>';
$stacksize--;
}
$stacksize = array_push( $tagstack, $tag );
}
// Attributes
$attributes = $regex[2];
if( ! empty( $attributes ) && $attributes[0] != '>' )
$attributes = ' ' . $attributes;
$tag = '<' . $tag . $attributes . '>';
//If already queuing a close tag, then put this tag on, too
if ( !empty($tagqueue) ) {
$tagqueue .= $tag;
$tag = '';
}
}
$newtext .= substr($text, 0, $i) . $tag;
$text = substr($text, $i + $l);
}
// Clear Tag Queue
$newtext .= $tagqueue;
// Add Remaining text
$newtext .= $text;
// Empty Stack
while( $x = array_pop($tagstack) )
$newtext .= '</' . $x . '>'; // Add remaining tags to close
// WP fix for the bug with HTML comments
$newtext = str_replace("< !--","<!--",$newtext);
$newtext = str_replace("< !--","< !--",$newtext);
return $newtext;
}
/**
* Acts on text which is about to be edited.
*
* The $content is run through esc_textarea(), which uses htmlspecialchars()
* to convert special characters to HTML entities. If $richedit is set to true,
* it is simply a holder for the 'format_to_edit' filter.
*
* @since 0.71
*
* @param string $content The text about to be edited.
* @param bool $richedit Whether the $content should not pass through htmlspecialchars(). Default false (meaning it will be passed).
* @return string The text after the filter (and possibly htmlspecialchars()) has been run.
*/
function format_to_edit( $content, $richedit = false ) {
/**
* Filter the text to be formatted for editing.
*
* @since 1.2.0
*
* @param string $content The text, prior to formatting for editing.
*/
$content = apply_filters( 'format_to_edit', $content );
if ( ! $richedit )
$content = esc_textarea( $content );
return $content;
}
/**
* Add leading zeros when necessary.
*
* If you set the threshold to '4' and the number is '10', then you will get
* back '0010'. If you set the threshold to '4' and the number is '5000', then you
* will get back '5000'.
*
* Uses sprintf to append the amount of zeros based on the $threshold parameter
* and the size of the number. If the number is large enough, then no zeros will
* be appended.
*
* @since 0.71
*
* @param mixed $number Number to append zeros to if not greater than threshold.
* @param int $threshold Digit places number needs to be to not have zeros added.
* @return string Adds leading zeros to number if needed.
*/
function zeroise($number, $threshold) {
return sprintf('%0'.$threshold.'s', $number);
}
/**
* Adds backslashes before letters and before a number at the start of a string.
*
* @since 0.71
*
* @param string $string Value to which backslashes will be added.
* @return string String with backslashes inserted.
*/
function backslashit($string) {
if ( isset( $string[0] ) && $string[0] >= '0' && $string[0] <= '9' )
$string = '\\\\' . $string;
return addcslashes( $string, 'A..Za..z' );
}
/**
* Appends a trailing slash.
*
* Will remove trailing forward and backslashes if it exists already before adding
* a trailing forward slash. This prevents double slashing a string or path.
*
* The primary use of this is for paths and thus should be used for paths. It is
* not restricted to paths and offers no specific path support.
*
* @since 1.2.0
*
* @param string $string What to add the trailing slash to.
* @return string String with trailing slash added.
*/
function trailingslashit( $string ) {
return untrailingslashit( $string ) . '/';
}
/**
* Removes trailing forward slashes and backslashes if they exist.
*
* The primary use of this is for paths and thus should be used for paths. It is
* not restricted to paths and offers no specific path support.
*
* @since 2.2.0
*
* @param string $string What to remove the trailing slashes from.
* @return string String without the trailing slashes.
*/
function untrailingslashit( $string ) {
return rtrim( $string, '/\\' );
}
/**
* Adds slashes to escape strings.
*
* Slashes will first be removed if magic_quotes_gpc is set, see {@link
* http://www.php.net/magic_quotes} for more details.
*
* @since 0.71
*
* @param string $gpc The string returned from HTTP request data.
* @return string Returns a string escaped with slashes.
*/
function addslashes_gpc($gpc) {
if ( get_magic_quotes_gpc() )
$gpc = stripslashes($gpc);
return wp_slash($gpc);
}
/**
* Navigates through an array and removes slashes from the values.
*
* If an array is passed, the array_map() function causes a callback to pass the
* value back to the function. The slashes from this value will removed.
*
* @since 2.0.0
*
* @param mixed $value The value to be stripped.
* @return mixed Stripped value.
*/
function stripslashes_deep($value) {
if ( is_array($value) ) {
$value = array_map('stripslashes_deep', $value);
} elseif ( is_object($value) ) {
$vars = get_object_vars( $value );
foreach ($vars as $key=>$data) {
$value->{$key} = stripslashes_deep( $data );
}
} elseif ( is_string( $value ) ) {
$value = stripslashes($value);
}
return $value;
}
/**
* Navigates through an array and encodes the values to be used in a URL.
*
*
* @since 2.2.0
*
* @param array|string $value The array or string to be encoded.
* @return array|string $value The encoded array (or string from the callback).
*/
function urlencode_deep($value) {
$value = is_array($value) ? array_map('urlencode_deep', $value) : urlencode($value);
return $value;
}
/**
* Navigates through an array and raw encodes the values to be used in a URL.
*
* @since 3.4.0
*
* @param array|string $value The array or string to be encoded.
* @return array|string $value The encoded array (or string from the callback).
*/
function rawurlencode_deep( $value ) {
return is_array( $value ) ? array_map( 'rawurlencode_deep', $value ) : rawurlencode( $value );
}
/**
* Converts email addresses characters to HTML entities to block spam bots.
*
* @since 0.71
*
* @param string $email_address Email address.
* @param int $hex_encoding Optional. Set to 1 to enable hex encoding.
* @return string Converted email address.
*/
function antispambot( $email_address, $hex_encoding = 0 ) {
$email_no_spam_address = '';
for ( $i = 0; $i < strlen( $email_address ); $i++ ) {
$j = rand( 0, 1 + $hex_encoding );
if ( $j == 0 ) {
$email_no_spam_address .= '&#' . ord( $email_address[$i] ) . ';';
} elseif ( $j == 1 ) {
$email_no_spam_address .= $email_address[$i];
} elseif ( $j == 2 ) {
$email_no_spam_address .= '%' . zeroise( dechex( ord( $email_address[$i] ) ), 2 );
}
}
$email_no_spam_address = str_replace( '@', '@', $email_no_spam_address );
return $email_no_spam_address;
}
/**
* Callback to convert URI match to HTML A element.
*
* This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
* make_clickable()}.
*
* @since 2.3.2
* @access private
*
* @param array $matches Single Regex Match.
* @return string HTML A element with URI address.
*/
function _make_url_clickable_cb($matches) {
$url = $matches[2];
if ( ')' == $matches[3] && strpos( $url, '(' ) ) {
// If the trailing character is a closing parethesis, and the URL has an opening parenthesis in it, add the closing parenthesis to the URL.
// Then we can let the parenthesis balancer do its thing below.
$url .= $matches[3];
$suffix = '';
} else {
$suffix = $matches[3];
}
// Include parentheses in the URL only if paired
while ( substr_count( $url, '(' ) < substr_count( $url, ')' ) ) {
$suffix = strrchr( $url, ')' ) . $suffix;
$url = substr( $url, 0, strrpos( $url, ')' ) );
}
$url = esc_url($url);
if ( empty($url) )
return $matches[0];
return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>" . $suffix;
}
/**
* Callback to convert URL match to HTML A element.
*
* This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
* make_clickable()}.
*
* @since 2.3.2
* @access private
*
* @param array $matches Single Regex Match.
* @return string HTML A element with URL address.
*/
function _make_web_ftp_clickable_cb($matches) {
$ret = '';
$dest = $matches[2];
$dest = 'http://' . $dest;
$dest = esc_url($dest);
if ( empty($dest) )
return $matches[0];
// removed trailing [.,;:)] from URL
if ( in_array( substr($dest, -1), array('.', ',', ';', ':', ')') ) === true ) {
$ret = substr($dest, -1);
$dest = substr($dest, 0, strlen($dest)-1);
}
return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>$ret";
}
/**
* Callback to convert email address match to HTML A element.
*
* This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
* make_clickable()}.
*
* @since 2.3.2
* @access private
*
* @param array $matches Single Regex Match.
* @return string HTML A element with email address.
*/
function _make_email_clickable_cb($matches) {
$email = $matches[2] . '@' . $matches[3];
return $matches[1] . "<a href=\"mailto:$email\">$email</a>";
}
/**
* Convert plaintext URI to HTML links.
*
* Converts URI, www and ftp, and email addresses. Finishes by fixing links
* within links.
*
* @since 0.71
*
* @param string $text Content to convert URIs.
* @return string Content with converted URIs.
*/
function make_clickable( $text ) {
$r = '';
$textarr = preg_split( '/(<[^<>]+>)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // split out HTML tags
$nested_code_pre = 0; // Keep track of how many levels link is nested inside <pre> or <code>
foreach ( $textarr as $piece ) {
if ( preg_match( '|^<code[\s>]|i', $piece ) || preg_match( '|^<pre[\s>]|i', $piece ) )
$nested_code_pre++;
elseif ( ( '</code>' === strtolower( $piece ) || '</pre>' === strtolower( $piece ) ) && $nested_code_pre )
$nested_code_pre--;
if ( $nested_code_pre || empty( $piece ) || ( $piece[0] === '<' && ! preg_match( '|^<\s*[\w]{1,20}+://|', $piece ) ) ) {
$r .= $piece;
continue;
}
// Long strings might contain expensive edge cases ...
if ( 10000 < strlen( $piece ) ) {
// ... break it up
foreach ( _split_str_by_whitespace( $piece, 2100 ) as $chunk ) { // 2100: Extra room for scheme and leading and trailing paretheses
if ( 2101 < strlen( $chunk ) ) {
$r .= $chunk; // Too big, no whitespace: bail.
} else {
$r .= make_clickable( $chunk );
}
}
} else {
$ret = " $piece "; // Pad with whitespace to simplify the regexes
$url_clickable = '~
([\\s(<.,;:!?]) # 1: Leading whitespace, or punctuation
( # 2: URL
[\\w]{1,20}+:// # Scheme and hier-part prefix
(?=\S{1,2000}\s) # Limit to URLs less than about 2000 characters long
[\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]*+ # Non-punctuation URL character
(?: # Unroll the Loop: Only allow puctuation URL character if followed by a non-punctuation URL character
[\'.,;:!?)] # Punctuation URL character
[\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]++ # Non-punctuation URL character
)*
)
(\)?) # 3: Trailing closing parenthesis (for parethesis balancing post processing)
~xS'; // The regex is a non-anchored pattern and does not have a single fixed starting character.
// Tell PCRE to spend more time optimizing since, when used on a page load, it will probably be used several times.
$ret = preg_replace_callback( $url_clickable, '_make_url_clickable_cb', $ret );
$ret = preg_replace_callback( '#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]+)#is', '_make_web_ftp_clickable_cb', $ret );
$ret = preg_replace_callback( '#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret );
$ret = substr( $ret, 1, -1 ); // Remove our whitespace padding.
$r .= $ret;
}
}
// Cleanup of accidental links within links
$r = preg_replace( '#(<a([ \r\n\t]+[^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i', "$1$3</a>", $r );
return $r;
}
/**
* Breaks a string into chunks by splitting at whitespace characters.
* The length of each returned chunk is as close to the specified length goal as possible,
* with the caveat that each chunk includes its trailing delimiter.
* Chunks longer than the goal are guaranteed to not have any inner whitespace.
*
* Joining the returned chunks with empty delimiters reconstructs the input string losslessly.
*
* Input string must have no null characters (or eventual transformations on output chunks must not care about null characters)
*
* <code>
* _split_str_by_whitespace( "1234 67890 1234 67890a cd 1234 890 123456789 1234567890a 45678 1 3 5 7 90 ", 10 ) ==
* array (
* 0 => '1234 67890 ', // 11 characters: Perfect split
* 1 => '1234 ', // 5 characters: '1234 67890a' was too long
* 2 => '67890a cd ', // 10 characters: '67890a cd 1234' was too long
* 3 => '1234 890 ', // 11 characters: Perfect split
* 4 => '123456789 ', // 10 characters: '123456789 1234567890a' was too long
* 5 => '1234567890a ', // 12 characters: Too long, but no inner whitespace on which to split
* 6 => ' 45678 ', // 11 characters: Perfect split
* 7 => '1 3 5 7 9', // 9 characters: End of $string
* );
* </code>
*
* @since 3.4.0
* @access private
*
* @param string $string The string to split.
* @param int $goal The desired chunk length.
* @return array Numeric array of chunks.
*/
function _split_str_by_whitespace( $string, $goal ) {
$chunks = array();
$string_nullspace = strtr( $string, "\r\n\t\v\f ", "\000\000\000\000\000\000" );
while ( $goal < strlen( $string_nullspace ) ) {
$pos = strrpos( substr( $string_nullspace, 0, $goal + 1 ), "\000" );
if ( false === $pos ) {
$pos = strpos( $string_nullspace, "\000", $goal + 1 );
if ( false === $pos ) {
break;
}
}
$chunks[] = substr( $string, 0, $pos + 1 );
$string = substr( $string, $pos + 1 );
$string_nullspace = substr( $string_nullspace, $pos + 1 );
}
if ( $string ) {
$chunks[] = $string;
}
return $chunks;
}
/**
* Adds rel nofollow string to all HTML A elements in content.
*
* @since 1.5.0
*
* @param string $text Content that may contain HTML A elements.
* @return string Converted content.
*/
function wp_rel_nofollow( $text ) {
// This is a pre save filter, so text is already escaped.
$text = stripslashes($text);
$text = preg_replace_callback('|<a (.+?)>|i', 'wp_rel_nofollow_callback', $text);
$text = wp_slash($text);
return $text;
}
/**
* Callback to add rel=nofollow string to HTML A element.
*
* Will remove already existing rel="nofollow" and rel='nofollow' from the
* string to prevent from invalidating (X)HTML.
*
* @since 2.3.0
*
* @param array $matches Single Match
* @return string HTML A Element with rel nofollow.
*/
function wp_rel_nofollow_callback( $matches ) {
$text = $matches[1];
$text = str_replace(array(' rel="nofollow"', " rel='nofollow'"), '', $text);
return "<a $text rel=\"nofollow\">";
}
/**
* Convert one smiley code to the icon graphic file equivalent.
*
* Callback handler for {@link convert_smilies()}.
* Looks up one smiley code in the $wpsmiliestrans global array and returns an
* <img> string for that smiley.
*
* @global array $wpsmiliestrans
* @since 2.8.0
*
* @param array $matches Single match. Smiley code to convert to image.
* @return string Image string for smiley.
*/
function translate_smiley( $matches ) {
global $wpsmiliestrans;
if ( count( $matches ) == 0 )
return '';
$smiley = trim( reset( $matches ) );
$img = $wpsmiliestrans[ $smiley ];
/**
* Filter the Smiley image URL before it's used in the image element.
*
* @since 2.9.0
*
* @param string $smiley_url URL for the smiley image.
* @param string $img Filename for the smiley image.
* @param string $site_url Site URL, as returned by site_url().
*/
$src_url = apply_filters( 'smilies_src', includes_url( "images/smilies/$img" ), $img, site_url() );
return sprintf( ' <img src="%s" alt="%s" class="wp-smiley" /> ', esc_url( $src_url ), esc_attr( $smiley ) );
}
/**
* Convert text equivalent of smilies to images.
*
* Will only convert smilies if the option 'use_smilies' is true and the global
* used in the function isn't empty.
*
* @since 0.71
* @uses $wp_smiliessearch
*
* @param string $text Content to convert smilies from text.
* @return string Converted content with text smilies replaced with images.
*/
function convert_smilies( $text ) {
global $wp_smiliessearch;
$output = '';
if ( get_option( 'use_smilies' ) && ! empty( $wp_smiliessearch ) ) {
// HTML loop taken from texturize function, could possible be consolidated
$textarr = preg_split( '/(<.*>)/U', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // capture the tags as well as in between
$stop = count( $textarr );// loop stuff
// Ignore proessing of specific tags
$tags_to_ignore = 'code|pre|style|script|textarea';
$ignore_block_element = '';
for ( $i = 0; $i < $stop; $i++ ) {
$content = $textarr[$i];
// If we're in an ignore block, wait until we find its closing tag
if ( '' == $ignore_block_element && preg_match( '/^<(' . $tags_to_ignore . ')>/', $content, $matches ) ) {
$ignore_block_element = $matches[1];
}
// If it's not a tag and not in ignore block
if ( '' == $ignore_block_element && strlen( $content ) > 0 && '<' != $content[0] ) {
$content = preg_replace_callback( $wp_smiliessearch, 'translate_smiley', $content );
}
// did we exit ignore block
if ( '' != $ignore_block_element && '</' . $ignore_block_element . '>' == $content ) {
$ignore_block_element = '';
}
$output .= $content;
}
} else {
// return default text.
$output = $text;
}
return $output;
}
/**
* Verifies that an email is valid.
*
* Does not grok i18n domains. Not RFC compliant.
*
* @since 0.71
*
* @param string $email Email address to verify.
* @param boolean $deprecated Deprecated.
* @return string|bool Either false or the valid email address.
*/
function is_email( $email, $deprecated = false ) {
if ( ! empty( $deprecated ) )
_deprecated_argument( __FUNCTION__, '3.0' );
// Test for the minimum length the email can be
if ( strlen( $email ) < 3 ) {
/**
* Filter whether an email address is valid.
*
* This filter is evaluated under several different contexts, such as 'email_too_short',
* 'email_no_at', 'local_invalid_chars', 'domain_period_sequence', 'domain_period_limits',
* 'domain_no_periods', 'sub_hyphen_limits', 'sub_invalid_chars', or no specific context.
*
* @since 2.8.0
*
* @param bool $is_email Whether the email address has passed the is_email() checks. Default false.
* @param string $email The email address being checked.
* @param string $message An explanatory message to the user.
* @param string $context Context under which the email was tested.
*/
return apply_filters( 'is_email', false, $email, 'email_too_short' );
}
// Test for an @ character after the first position
if ( strpos( $email, '@', 1 ) === false ) {
/** This filter is documented in wp-includes/formatting.php */
return apply_filters( 'is_email', false, $email, 'email_no_at' );
}
// Split out the local and domain parts
list( $local, $domain ) = explode( '@', $email, 2 );
// LOCAL PART
// Test for invalid characters
if ( !preg_match( '/^[a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]+$/', $local ) ) {
/** This filter is documented in wp-includes/formatting.php */
return apply_filters( 'is_email', false, $email, 'local_invalid_chars' );
}
// DOMAIN PART
// Test for sequences of periods
if ( preg_match( '/\.{2,}/', $domain ) ) {
/** This filter is documented in wp-includes/formatting.php */
return apply_filters( 'is_email', false, $email, 'domain_period_sequence' );
}
// Test for leading and trailing periods and whitespace
if ( trim( $domain, " \t\n\r\0\x0B." ) !== $domain ) {
/** This filter is documented in wp-includes/formatting.php */
return apply_filters( 'is_email', false, $email, 'domain_period_limits' );
}
// Split the domain into subs
$subs = explode( '.', $domain );
// Assume the domain will have at least two subs
if ( 2 > count( $subs ) ) {
/** This filter is documented in wp-includes/formatting.php */
return apply_filters( 'is_email', false, $email, 'domain_no_periods' );
}
// Loop through each sub
foreach ( $subs as $sub ) {
// Test for leading and trailing hyphens and whitespace
if ( trim( $sub, " \t\n\r\0\x0B-" ) !== $sub ) {
/** This filter is documented in wp-includes/formatting.php */
return apply_filters( 'is_email', false, $email, 'sub_hyphen_limits' );
}
// Test for invalid characters
if ( !preg_match('/^[a-z0-9-]+$/i', $sub ) ) {
/** This filter is documented in wp-includes/formatting.php */
return apply_filters( 'is_email', false, $email, 'sub_invalid_chars' );
}
}
// Congratulations your email made it!
/** This filter is documented in wp-includes/formatting.php */
return apply_filters( 'is_email', $email, $email, null );
}
/**
* Convert to ASCII from email subjects.
*
* @since 1.2.0
*
* @param string $string Subject line
* @return string Converted string to ASCII
*/
function wp_iso_descrambler($string) {
/* this may only work with iso-8859-1, I'm afraid */
if (!preg_match('#\=\?(.+)\?Q\?(.+)\?\=#i', $string, $matches)) {
return $string;
} else {
$subject = str_replace('_', ' ', $matches[2]);
$subject = preg_replace_callback('#\=([0-9a-f]{2})#i', '_wp_iso_convert', $subject);
return $subject;
}
}
/**
* Helper function to convert hex encoded chars to ASCII
*
* @since 3.1.0
* @access private
*
* @param array $match The preg_replace_callback matches array
* @return array Converted chars
*/
function _wp_iso_convert( $match ) {
return chr( hexdec( strtolower( $match[1] ) ) );
}
/**
* Returns a date in the GMT equivalent.
*
* Requires and returns a date in the Y-m-d H:i:s format. If there is a
* timezone_string available, the date is assumed to be in that timezone,
* otherwise it simply subtracts the value of the 'gmt_offset' option. Return
* format can be overridden using the $format parameter.
*
* @since 1.2.0
*
* @uses get_option() to retrieve the value of 'gmt_offset'.
* @param string $string The date to be converted.
* @param string $format The format string for the returned date (default is Y-m-d H:i:s)
* @return string GMT version of the date provided.
*/
function get_gmt_from_date( $string, $format = 'Y-m-d H:i:s' ) {
$tz = get_option( 'timezone_string' );
if ( $tz ) {
$datetime = date_create( $string, new DateTimeZone( $tz ) );
if ( ! $datetime )
return gmdate( $format, 0 );
$datetime->setTimezone( new DateTimeZone( 'UTC' ) );
$string_gmt = $datetime->format( $format );
} else {
if ( ! preg_match( '#([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})#', $string, $matches ) )
return gmdate( $format, 0 );
$string_time = gmmktime( $matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1] );
$string_gmt = gmdate( $format, $string_time - get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
}
return $string_gmt;
}
/**
* Converts a GMT date into the correct format for the blog.
*
* Requires and returns a date in the Y-m-d H:i:s format. If there is a
* timezone_string available, the returned date is in that timezone, otherwise
* it simply adds the value of gmt_offset. Return format can be overridden
* using the $format parameter
*
* @since 1.2.0
*
* @param string $string The date to be converted.
* @param string $format The format string for the returned date (default is Y-m-d H:i:s)
* @return string Formatted date relative to the timezone / GMT offset.
*/
function get_date_from_gmt( $string, $format = 'Y-m-d H:i:s' ) {
$tz = get_option( 'timezone_string' );
if ( $tz ) {
$datetime = date_create( $string, new DateTimeZone( 'UTC' ) );
if ( ! $datetime )
return date( $format, 0 );
$datetime->setTimezone( new DateTimeZone( $tz ) );
$string_localtime = $datetime->format( $format );
} else {
if ( ! preg_match('#([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})#', $string, $matches) )
return date( $format, 0 );
$string_time = gmmktime( $matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1] );
$string_localtime = gmdate( $format, $string_time + get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
}
return $string_localtime;
}
/**
* Computes an offset in seconds from an iso8601 timezone.
*
* @since 1.5.0
*
* @param string $timezone Either 'Z' for 0 offset or '±hhmm'.
* @return int|float The offset in seconds.
*/
function iso8601_timezone_to_offset($timezone) {
// $timezone is either 'Z' or '[+|-]hhmm'
if ($timezone == 'Z') {
$offset = 0;
} else {
$sign = (substr($timezone, 0, 1) == '+') ? 1 : -1;
$hours = intval(substr($timezone, 1, 2));
$minutes = intval(substr($timezone, 3, 4)) / 60;
$offset = $sign * HOUR_IN_SECONDS * ($hours + $minutes);
}
return $offset;
}
/**
* Converts an iso8601 date to MySQL DateTime format used by post_date[_gmt].
*
* @since 1.5.0
*
* @param string $date_string Date and time in ISO 8601 format {@link http://en.wikipedia.org/wiki/ISO_8601}.
* @param string $timezone Optional. If set to GMT returns the time minus gmt_offset. Default is 'user'.
* @return string The date and time in MySQL DateTime format - Y-m-d H:i:s.
*/
function iso8601_to_datetime($date_string, $timezone = 'user') {
$timezone = strtolower($timezone);
if ($timezone == 'gmt') {
preg_match('#([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(Z|[\+|\-][0-9]{2,4}){0,1}#', $date_string, $date_bits);
if (!empty($date_bits[7])) { // we have a timezone, so let's compute an offset
$offset = iso8601_timezone_to_offset($date_bits[7]);
} else { // we don't have a timezone, so we assume user local timezone (not server's!)
$offset = HOUR_IN_SECONDS * get_option('gmt_offset');
}
$timestamp = gmmktime($date_bits[4], $date_bits[5], $date_bits[6], $date_bits[2], $date_bits[3], $date_bits[1]);
$timestamp -= $offset;
return gmdate('Y-m-d H:i:s', $timestamp);
} else if ($timezone == 'user') {
return preg_replace('#([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(Z|[\+|\-][0-9]{2,4}){0,1}#', '$1-$2-$3 $4:$5:$6', $date_string);
}
}
/**
* Adds a element attributes to open links in new windows.
*
* Comment text in popup windows should be filtered through this. Right now it's
* a moderately dumb function, ideally it would detect whether a target or rel
* attribute was already there and adjust its actions accordingly.
*
* @since 0.71
*
* @param string $text Content to replace links to open in a new window.
* @return string Content that has filtered links.
*/
function popuplinks($text) {
$text = preg_replace('/<a (.+?)>/i', "<a $1 target='_blank' rel='external'>", $text);
return $text;
}
/**
* Strips out all characters that are not allowable in an email.
*
* @since 1.5.0
*
* @param string $email Email address to filter.
* @return string Filtered email address.
*/
function sanitize_email( $email ) {
// Test for the minimum length the email can be
if ( strlen( $email ) < 3 ) {
/**
* Filter a sanitized email address.
*
* This filter is evaluated under several contexts, including 'email_too_short',
* 'email_no_at', 'local_invalid_chars', 'domain_period_sequence', 'domain_period_limits',
* 'domain_no_periods', 'domain_no_valid_subs', or no context.
*
* @since 2.8.0
*
* @param string $email The sanitized email address.
* @param string $email The email address, as provided to sanitize_email().
* @param string $message A message to pass to the user.
*/
return apply_filters( 'sanitize_email', '', $email, 'email_too_short' );
}
// Test for an @ character after the first position
if ( strpos( $email, '@', 1 ) === false ) {
/** This filter is documented in wp-includes/formatting.php */
return apply_filters( 'sanitize_email', '', $email, 'email_no_at' );
}
// Split out the local and domain parts
list( $local, $domain ) = explode( '@', $email, 2 );
// LOCAL PART
// Test for invalid characters
$local = preg_replace( '/[^a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]/', '', $local );
if ( '' === $local ) {
/** This filter is documented in wp-includes/formatting.php */
return apply_filters( 'sanitize_email', '', $email, 'local_invalid_chars' );
}
// DOMAIN PART
// Test for sequences of periods
$domain = preg_replace( '/\.{2,}/', '', $domain );
if ( '' === $domain ) {
/** This filter is documented in wp-includes/formatting.php */
return apply_filters( 'sanitize_email', '', $email, 'domain_period_sequence' );
}
// Test for leading and trailing periods and whitespace
$domain = trim( $domain, " \t\n\r\0\x0B." );
if ( '' === $domain ) {
/** This filter is documented in wp-includes/formatting.php */
return apply_filters( 'sanitize_email', '', $email, 'domain_period_limits' );
}
// Split the domain into subs
$subs = explode( '.', $domain );
// Assume the domain will have at least two subs
if ( 2 > count( $subs ) ) {
/** This filter is documented in wp-includes/formatting.php */
return apply_filters( 'sanitize_email', '', $email, 'domain_no_periods' );
}
// Create an array that will contain valid subs
$new_subs = array();
// Loop through each sub
foreach ( $subs as $sub ) {
// Test for leading and trailing hyphens
$sub = trim( $sub, " \t\n\r\0\x0B-" );
// Test for invalid characters
$sub = preg_replace( '/[^a-z0-9-]+/i', '', $sub );
// If there's anything left, add it to the valid subs
if ( '' !== $sub ) {
$new_subs[] = $sub;
}
}
// If there aren't 2 or more valid subs
if ( 2 > count( $new_subs ) ) {
/** This filter is documented in wp-includes/formatting.php */
return apply_filters( 'sanitize_email', '', $email, 'domain_no_valid_subs' );
}
// Join valid subs into the new domain
$domain = join( '.', $new_subs );
// Put the email back together
$email = $local . '@' . $domain;
// Congratulations your email made it!
/** This filter is documented in wp-includes/formatting.php */
return apply_filters( 'sanitize_email', $email, $email, null );
}
/**
* Determines the difference between two timestamps.
*
* The difference is returned in a human readable format such as "1 hour",
* "5 mins", "2 days".
*
* @since 1.5.0
*
* @param int $from Unix timestamp from which the difference begins.
* @param int $to Optional. Unix timestamp to end the time difference. Default becomes time() if not set.
* @return string Human readable time difference.
*/
function human_time_diff( $from, $to = '' ) {
if ( empty( $to ) )
$to = time();
$diff = (int) abs( $to - $from );
if ( $diff < HOUR_IN_SECONDS ) {
$mins = round( $diff / MINUTE_IN_SECONDS );
if ( $mins <= 1 )
$mins = 1;
/* translators: min=minute */
$since = sprintf( _n( '%s min', '%s mins', $mins ), $mins );
} elseif ( $diff < DAY_IN_SECONDS && $diff >= HOUR_IN_SECONDS ) {
$hours = round( $diff / HOUR_IN_SECONDS );
if ( $hours <= 1 )
$hours = 1;
$since = sprintf( _n( '%s hour', '%s hours', $hours ), $hours );
} elseif ( $diff < WEEK_IN_SECONDS && $diff >= DAY_IN_SECONDS ) {
$days = round( $diff / DAY_IN_SECONDS );
if ( $days <= 1 )
$days = 1;
$since = sprintf( _n( '%s day', '%s days', $days ), $days );
} elseif ( $diff < 30 * DAY_IN_SECONDS && $diff >= WEEK_IN_SECONDS ) {
$weeks = round( $diff / WEEK_IN_SECONDS );
if ( $weeks <= 1 )
$weeks = 1;
$since = sprintf( _n( '%s week', '%s weeks', $weeks ), $weeks );
} elseif ( $diff < YEAR_IN_SECONDS && $diff >= 30 * DAY_IN_SECONDS ) {
$months = round( $diff / ( 30 * DAY_IN_SECONDS ) );
if ( $months <= 1 )
$months = 1;
$since = sprintf( _n( '%s month', '%s months', $months ), $months );
} elseif ( $diff >= YEAR_IN_SECONDS ) {
$years = round( $diff / YEAR_IN_SECONDS );
if ( $years <= 1 )
$years = 1;
$since = sprintf( _n( '%s year', '%s years', $years ), $years );
}
return $since;
}
/**
* Generates an excerpt from the content, if needed.
*
* The excerpt word amount will be 55 words and if the amount is greater than
* that, then the string ' […]' will be appended to the excerpt. If the string
* is less than 55 words, then the content will be returned as is.
*
* The 55 word limit can be modified by plugins/themes using the excerpt_length filter
* The ' […]' string can be modified by plugins/themes using the excerpt_more filter
*
* @since 1.5.0
*
* @param string $text Optional. The excerpt. If set to empty, an excerpt is generated.
* @return string The excerpt.
*/
function wp_trim_excerpt($text = '') {
$raw_excerpt = $text;
if ( '' == $text ) {
$text = get_the_content('');
$text = strip_shortcodes( $text );
/** This filter is documented in wp-includes/post-template.php */
$text = apply_filters( 'the_content', $text );
$text = str_replace(']]>', ']]>', $text);
/**
* Filter the number of words in an excerpt.
*
* @since 2.7.0
*
* @param int $number The number of words. Default 55.
*/
$excerpt_length = apply_filters( 'excerpt_length', 55 );
/**
* Filter the string in the "more" link displayed after a trimmed excerpt.
*
* @since 2.9.0
*
* @param string $more_string The string shown within the more link.
*/
$excerpt_more = apply_filters( 'excerpt_more', ' ' . '[…]' );
$text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
}
/**
* Filter the trimmed excerpt string.
*
* @since 2.8.0
*
* @param string $text The trimmed text.
* @param string $raw_excerpt The text prior to trimming.
*/
return apply_filters( 'wp_trim_excerpt', $text, $raw_excerpt );
}
/**
* Trims text to a certain number of words.
*
* This function is localized. For languages that count 'words' by the individual
* character (such as East Asian languages), the $num_words argument will apply
* to the number of individual characters.
*
* @since 3.3.0
*
* @param string $text Text to trim.
* @param int $num_words Number of words. Default 55.
* @param string $more Optional. What to append if $text needs to be trimmed. Default '…'.
* @return string Trimmed text.
*/
function wp_trim_words( $text, $num_words = 55, $more = null ) {
if ( null === $more )
$more = __( '…' );
$original_text = $text;
$text = wp_strip_all_tags( $text );
/* translators: If your word count is based on single characters (East Asian characters),
enter 'characters'. Otherwise, enter 'words'. Do not translate into your own language. */
if ( 'characters' == _x( 'words', 'word count: words or characters?' ) && preg_match( '/^utf\-?8$/i', get_option( 'blog_charset' ) ) ) {
$text = trim( preg_replace( "/[\n\r\t ]+/", ' ', $text ), ' ' );
preg_match_all( '/./u', $text, $words_array );
$words_array = array_slice( $words_array[0], 0, $num_words + 1 );
$sep = '';
} else {
$words_array = preg_split( "/[\n\r\t ]+/", $text, $num_words + 1, PREG_SPLIT_NO_EMPTY );
$sep = ' ';
}
if ( count( $words_array ) > $num_words ) {
array_pop( $words_array );
$text = implode( $sep, $words_array );
$text = $text . $more;
} else {
$text = implode( $sep, $words_array );
}
/**
* Filter the text content after words have been trimmed.
*
* @since 3.3.0
*
* @param string $text The trimmed text.
* @param int $num_words The number of words to trim the text to. Default 5.
* @param string $more An optional string to append to the end of the trimmed text, e.g. ….
* @param string $original_text The text before it was trimmed.
*/
return apply_filters( 'wp_trim_words', $text, $num_words, $more, $original_text );
}
/**
* Converts named entities into numbered entities.
*
* @since 1.5.1
*
* @param string $text The text within which entities will be converted.
* @return string Text with converted entities.
*/
function ent2ncr($text) {
/**
* Filter text before named entities are converted into numbered entities.
*
* A non-null string must be returned for the filter to be evaluated.
*
* @since 3.3.0
*
* @param null $converted_text The text to be converted. Default null.
* @param string $text The text prior to entity conversion.
*/
$filtered = apply_filters( 'pre_ent2ncr', null, $text );
if( null !== $filtered )
return $filtered;
$to_ncr = array(
'"' => '"',
'&' => '&',
'<' => '<',
'>' => '>',
'|' => '|',
' ' => ' ',
'¡' => '¡',
'¢' => '¢',
'£' => '£',
'¤' => '¤',
'¥' => '¥',
'¦' => '¦',
'&brkbar;' => '¦',
'§' => '§',
'¨' => '¨',
'¨' => '¨',
'©' => '©',
'ª' => 'ª',
'«' => '«',
'¬' => '¬',
'­' => '­',
'®' => '®',
'¯' => '¯',
'&hibar;' => '¯',
'°' => '°',
'±' => '±',
'²' => '²',
'³' => '³',
'´' => '´',
'µ' => 'µ',
'¶' => '¶',
'·' => '·',
'¸' => '¸',
'¹' => '¹',
'º' => 'º',
'»' => '»',
'¼' => '¼',
'½' => '½',
'¾' => '¾',
'¿' => '¿',
'À' => 'À',
'Á' => 'Á',
'Â' => 'Â',
'Ã' => 'Ã',
'Ä' => 'Ä',
'Å' => 'Å',
'Æ' => 'Æ',
'Ç' => 'Ç',
'È' => 'È',
'É' => 'É',
'Ê' => 'Ê',
'Ë' => 'Ë',
'Ì' => 'Ì',
'Í' => 'Í',
'Î' => 'Î',
'Ï' => 'Ï',
'Ð' => 'Ð',
'Ñ' => 'Ñ',
'Ò' => 'Ò',
'Ó' => 'Ó',
'Ô' => 'Ô',
'Õ' => 'Õ',
'Ö' => 'Ö',
'×' => '×',
'Ø' => 'Ø',
'Ù' => 'Ù',
'Ú' => 'Ú',
'Û' => 'Û',
'Ü' => 'Ü',
'Ý' => 'Ý',
'Þ' => 'Þ',
'ß' => 'ß',
'à' => 'à',
'á' => 'á',
'â' => 'â',
'ã' => 'ã',
'ä' => 'ä',
'å' => 'å',
'æ' => 'æ',
'ç' => 'ç',
'è' => 'è',
'é' => 'é',
'ê' => 'ê',
'ë' => 'ë',
'ì' => 'ì',
'í' => 'í',
'î' => 'î',
'ï' => 'ï',
'ð' => 'ð',
'ñ' => 'ñ',
'ò' => 'ò',
'ó' => 'ó',
'ô' => 'ô',
'õ' => 'õ',
'ö' => 'ö',
'÷' => '÷',
'ø' => 'ø',
'ù' => 'ù',
'ú' => 'ú',
'û' => 'û',
'ü' => 'ü',
'ý' => 'ý',
'þ' => 'þ',
'ÿ' => 'ÿ',
'Œ' => 'Œ',
'œ' => 'œ',
'Š' => 'Š',
'š' => 'š',
'Ÿ' => 'Ÿ',
'ƒ' => 'ƒ',
'ˆ' => 'ˆ',
'˜' => '˜',
'Α' => 'Α',
'Β' => 'Β',
'Γ' => 'Γ',
'Δ' => 'Δ',
'Ε' => 'Ε',
'Ζ' => 'Ζ',
'Η' => 'Η',
'Θ' => 'Θ',
'Ι' => 'Ι',
'Κ' => 'Κ',
'Λ' => 'Λ',
'Μ' => 'Μ',
'Ν' => 'Ν',
'Ξ' => 'Ξ',
'Ο' => 'Ο',
'Π' => 'Π',
'Ρ' => 'Ρ',
'Σ' => 'Σ',
'Τ' => 'Τ',
'Υ' => 'Υ',
'Φ' => 'Φ',
'Χ' => 'Χ',
'Ψ' => 'Ψ',
'Ω' => 'Ω',
'α' => 'α',
'β' => 'β',
'γ' => 'γ',
'δ' => 'δ',
'ε' => 'ε',
'ζ' => 'ζ',
'η' => 'η',
'θ' => 'θ',
'ι' => 'ι',
'κ' => 'κ',
'λ' => 'λ',
'μ' => 'μ',
'ν' => 'ν',
'ξ' => 'ξ',
'ο' => 'ο',
'π' => 'π',
'ρ' => 'ρ',
'ς' => 'ς',
'σ' => 'σ',
'τ' => 'τ',
'υ' => 'υ',
'φ' => 'φ',
'χ' => 'χ',
'ψ' => 'ψ',
'ω' => 'ω',
'ϑ' => 'ϑ',
'ϒ' => 'ϒ',
'ϖ' => 'ϖ',
' ' => ' ',
' ' => ' ',
' ' => ' ',
'‌' => '‌',
'‍' => '‍',
'‎' => '‎',
'‏' => '‏',
'–' => '–',
'—' => '—',
'‘' => '‘',
'’' => '’',
'‚' => '‚',
'“' => '“',
'”' => '”',
'„' => '„',
'†' => '†',
'‡' => '‡',
'•' => '•',
'…' => '…',
'‰' => '‰',
'′' => '′',
'″' => '″',
'‹' => '‹',
'›' => '›',
'‾' => '‾',
'⁄' => '⁄',
'€' => '€',
'ℑ' => 'ℑ',
'℘' => '℘',
'ℜ' => 'ℜ',
'™' => '™',
'ℵ' => 'ℵ',
'↵' => '↵',
'⇐' => '⇐',
'⇑' => '⇑',
'⇒' => '⇒',
'⇓' => '⇓',
'⇔' => '⇔',
'∀' => '∀',
'∂' => '∂',
'∃' => '∃',
'∅' => '∅',
'∇' => '∇',
'∈' => '∈',
'∉' => '∉',
'∋' => '∋',
'∏' => '∏',
'∑' => '∑',
'−' => '−',
'∗' => '∗',
'√' => '√',
'∝' => '∝',
'∞' => '∞',
'∠' => '∠',
'∧' => '∧',
'∨' => '∨',
'∩' => '∩',
'∪' => '∪',
'∫' => '∫',
'∴' => '∴',
'∼' => '∼',
'≅' => '≅',
'≈' => '≈',
'≠' => '≠',
'≡' => '≡',
'≤' => '≤',
'≥' => '≥',
'⊂' => '⊂',
'⊃' => '⊃',
'⊄' => '⊄',
'⊆' => '⊆',
'⊇' => '⊇',
'⊕' => '⊕',
'⊗' => '⊗',
'⊥' => '⊥',
'⋅' => '⋅',
'⌈' => '⌈',
'⌉' => '⌉',
'⌊' => '⌊',
'⌋' => '⌋',
'⟨' => '〈',
'⟩' => '〉',
'←' => '←',
'↑' => '↑',
'→' => '→',
'↓' => '↓',
'↔' => '↔',
'◊' => '◊',
'♠' => '♠',
'♣' => '♣',
'♥' => '♥',
'♦' => '♦'
);
return str_replace( array_keys($to_ncr), array_values($to_ncr), $text );
}
/**
* Formats text for the rich text editor.
*
* The filter 'richedit_pre' is applied here. If $text is empty the filter will
* be applied to an empty string.
*
* @since 2.0.0
*
* @param string $text The text to be formatted.
* @return string The formatted text after filter is applied.
*/
function wp_richedit_pre($text) {
if ( empty( $text ) ) {
/**
* Filter text returned for the rich text editor.
*
* This filter is first evaluated, and the value returned, if an empty string
* is passed to wp_richedit_pre(). If an empty string is passed, it results
* in a break tag and line feed.
*
* If a non-empty string is passed, the filter is evaluated on the wp_richedit_pre()
* return after being formatted.
*
* @since 2.0.0
*
* @param string $output Text for the rich text editor.
*/
return apply_filters( 'richedit_pre', '' );
}
$output = convert_chars($text);
$output = wpautop($output);
$output = htmlspecialchars($output, ENT_NOQUOTES, get_option( 'blog_charset' ) );
/** This filter is documented in wp-includes/formatting.php */
return apply_filters( 'richedit_pre', $output );
}
/**
* Formats text for the HTML editor.
*
* Unless $output is empty it will pass through htmlspecialchars before the
* 'htmledit_pre' filter is applied.
*
* @since 2.5.0
*
* @param string $output The text to be formatted.
* @return string Formatted text after filter applied.
*/
function wp_htmledit_pre($output) {
if ( !empty($output) )
$output = htmlspecialchars($output, ENT_NOQUOTES, get_option( 'blog_charset' ) ); // convert only < > &
/**
* Filter the text before it is formatted for the HTML editor.
*
* @since 2.5.0
*
* @param string $output The HTML-formatted text.
*/
return apply_filters( 'htmledit_pre', $output );
}
/**
* Perform a deep string replace operation to ensure the values in $search are no longer present
*
* Repeats the replacement operation until it no longer replaces anything so as to remove "nested" values
* e.g. $subject = '%0%0%0DDD', $search ='%0D', $result ='' rather than the '%0%0DD' that
* str_replace would return
*
* @since 2.8.1
* @access private
*
* @param string|array $search The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.
* @param string $subject The string being searched and replaced on, otherwise known as the haystack.
* @return string The string with the replaced svalues.
*/
function _deep_replace( $search, $subject ) {
$subject = (string) $subject;
$count = 1;
while ( $count ) {
$subject = str_replace( $search, '', $subject, $count );
}
return $subject;
}
/**
* Escapes data for use in a MySQL query.
*
* Usually you should prepare queries using wpdb::prepare().
* Sometimes, spot-escaping is required or useful. One example
* is preparing an array for use in an IN clause.
*
* @since 2.8.0
* @param string|array $data Unescaped data
* @return string|array Escaped data
*/
function esc_sql( $data ) {
global $wpdb;
return $wpdb->_escape( $data );
}
/**
* Checks and cleans a URL.
*
* A number of characters are removed from the URL. If the URL is for displaying
* (the default behaviour) ampersands are also replaced. The 'clean_url' filter
* is applied to the returned cleaned URL.
*
* @since 2.8.0
* @uses wp_kses_bad_protocol() To only permit protocols in the URL set
* via $protocols or the common ones set in the function.
*
* @param string $url The URL to be cleaned.
* @param array $protocols Optional. An array of acceptable protocols.
* Defaults to 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'svn' if not set.
* @param string $_context Private. Use esc_url_raw() for database usage.
* @return string The cleaned $url after the 'clean_url' filter is applied.
*/
function esc_url( $url, $protocols = null, $_context = 'display' ) {
$original_url = $url;
if ( '' == $url )
return $url;
$url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);
$strip = array('%0d', '%0a', '%0D', '%0A');
$url = _deep_replace($strip, $url);
$url = str_replace(';//', '://', $url);
/* If the URL doesn't appear to contain a scheme, we
* presume it needs http:// appended (unless a relative
* link starting with /, # or ? or a php file).
*/
if ( strpos($url, ':') === false && ! in_array( $url[0], array( '/', '#', '?' ) ) &&
! preg_match('/^[a-z0-9-]+?\.php/i', $url) )
$url = 'http://' . $url;
// Replace ampersands and single quotes only when displaying.
if ( 'display' == $_context ) {
$url = wp_kses_normalize_entities( $url );
$url = str_replace( '&', '&', $url );
$url = str_replace( "'", ''', $url );
}
if ( '/' === $url[0] ) {
$good_protocol_url = $url;
} else {
if ( ! is_array( $protocols ) )
$protocols = wp_allowed_protocols();
$good_protocol_url = wp_kses_bad_protocol( $url, $protocols );
if ( strtolower( $good_protocol_url ) != strtolower( $url ) )
return '';
}
/**
* Filter a string cleaned and escaped for output as a URL.
*
* @since 2.3.0
*
* @param string $good_protocol_url The cleaned URL to be returned.
* @param string $original_url The URL prior to cleaning.
* @param string $_context If 'display', replace ampersands and single quotes only.
*/
return apply_filters( 'clean_url', $good_protocol_url, $original_url, $_context );
}
/**
* Performs esc_url() for database usage.
*
* @since 2.8.0
* @uses esc_url()
*
* @param string $url The URL to be cleaned.
* @param array $protocols An array of acceptable protocols.
* @return string The cleaned URL.
*/
function esc_url_raw( $url, $protocols = null ) {
return esc_url( $url, $protocols, 'db' );
}
/**
* Convert entities, while preserving already-encoded entities.
*
* @link http://www.php.net/htmlentities Borrowed from the PHP Manual user notes.
*
* @since 1.2.2
*
* @param string $myHTML The text to be converted.
* @return string Converted text.
*/
function htmlentities2($myHTML) {
$translation_table = get_html_translation_table( HTML_ENTITIES, ENT_QUOTES );
$translation_table[chr(38)] = '&';
return preg_replace( "/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/", "&", strtr($myHTML, $translation_table) );
}
/**
* Escape single quotes, htmlspecialchar " < > &, and fix line endings.
*
* Escapes text strings for echoing in JS. It is intended to be used for inline JS
* (in a tag attribute, for example onclick="..."). Note that the strings have to
* be in single quotes. The filter 'js_escape' is also applied here.
*
* @since 2.8.0
*
* @param string $text The text to be escaped.
* @return string Escaped text.
*/
function esc_js( $text ) {
$safe_text = wp_check_invalid_utf8( $text );
$safe_text = _wp_specialchars( $safe_text, ENT_COMPAT );
$safe_text = preg_replace( '/&#(x)?0*(?(1)27|39);?/i', "'", stripslashes( $safe_text ) );
$safe_text = str_replace( "\r", '', $safe_text );
$safe_text = str_replace( "\n", '\\n', addslashes( $safe_text ) );
/**
* Filter a string cleaned and escaped for output in JavaScript.
*
* Text passed to esc_js() is stripped of invalid or special characters,
* and properly slashed for output.
*
* @since 2.0.6
*
* @param string $safe_text The text after it has been escaped.
* @param string $text The text prior to being escaped.
*/
return apply_filters( 'js_escape', $safe_text, $text );
}
/**
* Escaping for HTML blocks.
*
* @since 2.8.0
*
* @param string $text
* @return string
*/
function esc_html( $text ) {
$safe_text = wp_check_invalid_utf8( $text );
$safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
/**
* Filter a string cleaned and escaped for output in HTML.
*
* Text passed to esc_html() is stripped of invalid or special characters
* before output.
*
* @since 2.8.0
*
* @param string $safe_text The text after it has been escaped.
* @param string $text The text prior to being escaped.
*/
return apply_filters( 'esc_html', $safe_text, $text );
}
/**
* Escaping for HTML attributes.
*
* @since 2.8.0
*
* @param string $text
* @return string
*/
function esc_attr( $text ) {
$safe_text = wp_check_invalid_utf8( $text );
$safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
/**
* Filter a string cleaned and escaped for output in an HTML attribute.
*
* Text passed to esc_attr() is stripped of invalid or special characters
* before output.
*
* @since 2.0.6
*
* @param string $safe_text The text after it has been escaped.
* @param string $text The text prior to being escaped.
*/
return apply_filters( 'attribute_escape', $safe_text, $text );
}
/**
* Escaping for textarea values.
*
* @since 3.1.0
*
* @param string $text
* @return string
*/
function esc_textarea( $text ) {
$safe_text = htmlspecialchars( $text, ENT_QUOTES, get_option( 'blog_charset' ) );
/**
* Filter a string cleaned and escaped for output in a textarea element.
*
* @since 3.1.0
*
* @param string $safe_text The text after it has been escaped.
* @param string $text The text prior to being escaped.
*/
return apply_filters( 'esc_textarea', $safe_text, $text );
}
/**
* Escape an HTML tag name.
*
* @since 2.5.0
*
* @param string $tag_name
* @return string
*/
function tag_escape($tag_name) {
$safe_tag = strtolower( preg_replace('/[^a-zA-Z0-9_:]/', '', $tag_name) );
/**
* Filter a string cleaned and escaped for output as an HTML tag.
*
* @since 2.8.0
*
* @param string $safe_tag The tag name after it has been escaped.
* @param string $tag_name The text before it was escaped.
*/
return apply_filters( 'tag_escape', $safe_tag, $tag_name );
}
/**
* Escapes text for SQL LIKE special characters % and _.
*
* @since 2.5.0
*
* @param string $text The text to be escaped.
* @return string text, safe for inclusion in LIKE query.
*/
function like_escape($text) {
return str_replace(array("%", "_"), array("\\%", "\\_"), $text);
}
/**
* Convert full URL paths to absolute paths.
*
* Removes the http or https protocols and the domain. Keeps the path '/' at the
* beginning, so it isn't a true relative link, but from the web root base.
*
* @since 2.1.0
*
* @param string $link Full URL path.
* @return string Absolute path.
*/
function wp_make_link_relative( $link ) {
return preg_replace( '|https?://[^/]+(/.*)|i', '$1', $link );
}
/**
* Sanitises various option values based on the nature of the option.
*
* This is basically a switch statement which will pass $value through a number
* of functions depending on the $option.
*
* @since 2.0.5
*
* @param string $option The name of the option.
* @param string $value The unsanitised value.
* @return string Sanitized value.
*/
function sanitize_option($option, $value) {
switch ( $option ) {
case 'admin_email' :
case 'new_admin_email' :
$value = sanitize_email( $value );
if ( ! is_email( $value ) ) {
$value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
if ( function_exists( 'add_settings_error' ) )
add_settings_error( $option, 'invalid_admin_email', __( 'The email address entered did not appear to be a valid email address. Please enter a valid email address.' ) );
}
break;
case 'thumbnail_size_w':
case 'thumbnail_size_h':
case 'medium_size_w':
case 'medium_size_h':
case 'large_size_w':
case 'large_size_h':
case 'mailserver_port':
case 'comment_max_links':
case 'page_on_front':
case 'page_for_posts':
case 'rss_excerpt_length':
case 'default_category':
case 'default_email_category':
case 'default_link_category':
case 'close_comments_days_old':
case 'comments_per_page':
case 'thread_comments_depth':
case 'users_can_register':
case 'start_of_week':
$value = absint( $value );
break;
case 'posts_per_page':
case 'posts_per_rss':
$value = (int) $value;
if ( empty($value) )
$value = 1;
if ( $value < -1 )
$value = abs($value);
break;
case 'default_ping_status':
case 'default_comment_status':
// Options that if not there have 0 value but need to be something like "closed"
if ( $value == '0' || $value == '')
$value = 'closed';
break;
case 'blogdescription':
case 'blogname':
$value = wp_kses_post( $value );
$value = esc_html( $value );
break;
case 'blog_charset':
$value = preg_replace('/[^a-zA-Z0-9_-]/', '', $value); // strips slashes
break;
case 'blog_public':
// This is the value if the settings checkbox is not checked on POST. Don't rely on this.
if ( null === $value )
$value = 1;
else
$value = intval( $value );
break;
case 'date_format':
case 'time_format':
case 'mailserver_url':
case 'mailserver_login':
case 'mailserver_pass':
case 'upload_path':
$value = strip_tags( $value );
$value = wp_kses_data( $value );
break;
case 'ping_sites':
$value = explode( "\n", $value );
$value = array_filter( array_map( 'trim', $value ) );
$value = array_filter( array_map( 'esc_url_raw', $value ) );
$value = implode( "\n", $value );
break;
case 'gmt_offset':
$value = preg_replace('/[^0-9:.-]/', '', $value); // strips slashes
break;
case 'siteurl':
if ( (bool)preg_match( '#http(s?)://(.+)#i', $value) ) {
$value = esc_url_raw($value);
} else {
$value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
if ( function_exists('add_settings_error') )
add_settings_error('siteurl', 'invalid_siteurl', __('The WordPress address you entered did not appear to be a valid URL. Please enter a valid URL.'));
}
break;
case 'home':
if ( (bool)preg_match( '#http(s?)://(.+)#i', $value) ) {
$value = esc_url_raw($value);
} else {
$value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
if ( function_exists('add_settings_error') )
add_settings_error('home', 'invalid_home', __('The Site address you entered did not appear to be a valid URL. Please enter a valid URL.'));
}
break;
case 'WPLANG':
$allowed = get_available_languages();
if ( ! in_array( $value, $allowed ) && ! empty( $value ) )
$value = get_option( $option );
break;
case 'illegal_names':
if ( ! is_array( $value ) )
$value = explode( ' ', $value );
$value = array_values( array_filter( array_map( 'trim', $value ) ) );
if ( ! $value )
$value = '';
break;
case 'limited_email_domains':
case 'banned_email_domains':
if ( ! is_array( $value ) )
$value = explode( "\n", $value );
$domains = array_values( array_filter( array_map( 'trim', $value ) ) );
$value = array();
foreach ( $domains as $domain ) {
if ( ! preg_match( '/(--|\.\.)/', $domain ) && preg_match( '|^([a-zA-Z0-9-\.])+$|', $domain ) )
$value[] = $domain;
}
if ( ! $value )
$value = '';
break;
case 'timezone_string':
$allowed_zones = timezone_identifiers_list();
if ( ! in_array( $value, $allowed_zones ) && ! empty( $value ) ) {
$value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
if ( function_exists('add_settings_error') )
add_settings_error('timezone_string', 'invalid_timezone_string', __('The timezone you have entered is not valid. Please select a valid timezone.') );
}
break;
case 'permalink_structure':
case 'category_base':
case 'tag_base':
$value = esc_url_raw( $value );
$value = str_replace( 'http://', '', $value );
break;
case 'default_role' :
if ( ! get_role( $value ) && get_role( 'subscriber' ) )
$value = 'subscriber';
break;
}
/**
* Filter an option value following sanitization.
*
* @since 2.3.0
*
* @param string $value The sanitized option value.
* @param string $option The option name.
*/
$value = apply_filters( "sanitize_option_{$option}", $value, $option );
return $value;
}
/**
* Parses a string into variables to be stored in an array.
*
* Uses {@link http://www.php.net/parse_str parse_str()} and stripslashes if
* {@link http://www.php.net/magic_quotes magic_quotes_gpc} is on.
*
* @since 2.2.1
*
* @param string $string The string to be parsed.
* @param array $array Variables will be stored in this array.
*/
function wp_parse_str( $string, &$array ) {
parse_str( $string, $array );
if ( get_magic_quotes_gpc() )
$array = stripslashes_deep( $array );
/**
* Filter the array of variables derived from a parsed string.
*
* @since 2.3.0
*
* @param array $array The array populated with variables.
*/
$array = apply_filters( 'wp_parse_str', $array );
}
/**
* Convert lone less than signs.
*
* KSES already converts lone greater than signs.
*
* @uses wp_pre_kses_less_than_callback in the callback function.
* @since 2.3.0
*
* @param string $text Text to be converted.
* @return string Converted text.
*/
function wp_pre_kses_less_than( $text ) {
return preg_replace_callback('%<[^>]*?((?=<)|>|$)%', 'wp_pre_kses_less_than_callback', $text);
}
/**
* Callback function used by preg_replace.
*
* @uses esc_html to format the $matches text.
* @since 2.3.0
*
* @param array $matches Populated by matches to preg_replace.
* @return string The text returned after esc_html if needed.
*/
function wp_pre_kses_less_than_callback( $matches ) {
if ( false === strpos($matches[0], '>') )
return esc_html($matches[0]);
return $matches[0];
}
/**
* WordPress implementation of PHP sprintf() with filters.
*
* @since 2.5.0
* @link http://www.php.net/sprintf
*
* @param string $pattern The string which formatted args are inserted.
* @param mixed $args,... Arguments to be formatted into the $pattern string.
* @return string The formatted string.
*/
function wp_sprintf( $pattern ) {
$args = func_get_args();
$len = strlen($pattern);
$start = 0;
$result = '';
$arg_index = 0;
while ( $len > $start ) {
// Last character: append and break
if ( strlen($pattern) - 1 == $start ) {
$result .= substr($pattern, -1);
break;
}
// Literal %: append and continue
if ( substr($pattern, $start, 2) == '%%' ) {
$start += 2;
$result .= '%';
continue;
}
// Get fragment before next %
$end = strpos($pattern, '%', $start + 1);
if ( false === $end )
$end = $len;
$fragment = substr($pattern, $start, $end - $start);
// Fragment has a specifier
if ( $pattern[$start] == '%' ) {
// Find numbered arguments or take the next one in order
if ( preg_match('/^%(\d+)\$/', $fragment, $matches) ) {
$arg = isset($args[$matches[1]]) ? $args[$matches[1]] : '';
$fragment = str_replace("%{$matches[1]}$", '%', $fragment);
} else {
++$arg_index;
$arg = isset($args[$arg_index]) ? $args[$arg_index] : '';
}
/**
* Filter a fragment from the pattern passed to wp_sprintf().
*
* If the fragment is unchanged, then sprintf() will be run on the fragment.
*
* @since 2.5.0
*
* @param string $fragment A fragment from the pattern.
* @param string $arg The argument.
*/
$_fragment = apply_filters( 'wp_sprintf', $fragment, $arg );
if ( $_fragment != $fragment )
$fragment = $_fragment;
else
$fragment = sprintf($fragment, strval($arg) );
}
// Append to result and move to next fragment
$result .= $fragment;
$start = $end;
}
return $result;
}
/**
* Localize list items before the rest of the content.
*
* The '%l' must be at the first characters can then contain the rest of the
* content. The list items will have ', ', ', and', and ' and ' added depending
* on the amount of list items in the $args parameter.
*
* @since 2.5.0
*
* @param string $pattern Content containing '%l' at the beginning.
* @param array $args List items to prepend to the content and replace '%l'.
* @return string Localized list items and rest of the content.
*/
function wp_sprintf_l($pattern, $args) {
// Not a match
if ( substr($pattern, 0, 2) != '%l' )
return $pattern;
// Nothing to work with
if ( empty($args) )
return '';
/**
* Filter the translated delimiters used by wp_sprintf_l().
* Placeholders (%s) are included to assist translators and then
* removed before the array of strings reaches the filter.
*
* Please note: Ampersands and entities should be avoided here.
*
* @since 2.5.0
*
* @param array $delimiters An array of translated delimiters.
*/
$l = apply_filters( 'wp_sprintf_l', array(
/* translators: used to join items in a list with more than 2 items */
'between' => sprintf( __('%s, %s'), '', '' ),
/* translators: used to join last two items in a list with more than 2 times */
'between_last_two' => sprintf( __('%s, and %s'), '', '' ),
/* translators: used to join items in a list with only 2 items */
'between_only_two' => sprintf( __('%s and %s'), '', '' ),
) );
$args = (array) $args;
$result = array_shift($args);
if ( count($args) == 1 )
$result .= $l['between_only_two'] . array_shift($args);
// Loop when more than two args
$i = count($args);
while ( $i ) {
$arg = array_shift($args);
$i--;
if ( 0 == $i )
$result .= $l['between_last_two'] . $arg;
else
$result .= $l['between'] . $arg;
}
return $result . substr($pattern, 2);
}
/**
* Safely extracts not more than the first $count characters from html string.
*
* UTF-8, tags and entities safe prefix extraction. Entities inside will *NOT*
* be counted as one character. For example & will be counted as 4, < as
* 3, etc.
*
* @since 2.5.0
*
* @param string $str String to get the excerpt from.
* @param integer $count Maximum number of characters to take.
* @param string $more Optional. What to append if $str needs to be trimmed. Defaults to empty string.
* @return string The excerpt.
*/
function wp_html_excerpt( $str, $count, $more = null ) {
if ( null === $more )
$more = '';
$str = wp_strip_all_tags( $str, true );
$excerpt = mb_substr( $str, 0, $count );
// remove part of an entity at the end
$excerpt = preg_replace( '/&[^;\s]{0,6}$/', '', $excerpt );
if ( $str != $excerpt )
$excerpt = trim( $excerpt ) . $more;
return $excerpt;
}
/**
* Add a Base url to relative links in passed content.
*
* By default it supports the 'src' and 'href' attributes. However this can be
* changed via the 3rd param.
*
* @since 2.7.0
*
* @param string $content String to search for links in.
* @param string $base The base URL to prefix to links.
* @param array $attrs The attributes which should be processed.
* @return string The processed content.
*/
function links_add_base_url( $content, $base, $attrs = array('src', 'href') ) {
global $_links_add_base;
$_links_add_base = $base;
$attrs = implode('|', (array)$attrs);
return preg_replace_callback( "!($attrs)=(['\"])(.+?)\\2!i", '_links_add_base', $content );
}
/**
* Callback to add a base url to relative links in passed content.
*
* @since 2.7.0
* @access private
*
* @param string $m The matched link.
* @return string The processed link.
*/
function _links_add_base($m) {
global $_links_add_base;
//1 = attribute name 2 = quotation mark 3 = URL
return $m[1] . '=' . $m[2] .
( preg_match( '#^(\w{1,20}):#', $m[3], $protocol ) && in_array( $protocol[1], wp_allowed_protocols() ) ?
$m[3] :
path_join( $_links_add_base, $m[3] ) )
. $m[2];
}
/**
* Adds a Target attribute to all links in passed content.
*
* This function by default only applies to <a> tags, however this can be
* modified by the 3rd param.
*
* <b>NOTE:</b> Any current target attributed will be stripped and replaced.
*
* @since 2.7.0
*
* @param string $content String to search for links in.
* @param string $target The Target to add to the links.
* @param array $tags An array of tags to apply to.
* @return string The processed content.
*/
function links_add_target( $content, $target = '_blank', $tags = array('a') ) {
global $_links_add_target;
$_links_add_target = $target;
$tags = implode('|', (array)$tags);
return preg_replace_callback( "!<($tags)([^>]*)>!i", '_links_add_target', $content );
}
/**
* Callback to add a target attribute to all links in passed content.
*
* @since 2.7.0
* @access private
*
* @param string $m The matched link.
* @return string The processed link.
*/
function _links_add_target( $m ) {
global $_links_add_target;
$tag = $m[1];
$link = preg_replace('|( target=([\'"])(.*?)\2)|i', '', $m[2]);
return '<' . $tag . $link . ' target="' . esc_attr( $_links_add_target ) . '">';
}
/**
* Normalize EOL characters and strip duplicate whitespace.
*
* @since 2.7.0
*
* @param string $str The string to normalize.
* @return string The normalized string.
*/
function normalize_whitespace( $str ) {
$str = trim( $str );
$str = str_replace( "\r", "\n", $str );
$str = preg_replace( array( '/\n+/', '/[ \t]+/' ), array( "\n", ' ' ), $str );
return $str;
}
/**
* Properly strip all HTML tags including script and style
*
* This differs from strip_tags() because it removes the contents of
* the <script> and <style> tags. E.g. strip_tags( '<script>something</script>' )
* will return 'something'. wp_strip_all_tags will return ''
*
* @since 2.9.0
*
* @param string $string String containing HTML tags
* @param bool $remove_breaks optional Whether to remove left over line breaks and white space chars
* @return string The processed string.
*/
function wp_strip_all_tags($string, $remove_breaks = false) {
$string = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $string );
$string = strip_tags($string);
if ( $remove_breaks )
$string = preg_replace('/[\r\n\t ]+/', ' ', $string);
return trim( $string );
}
/**
* Sanitize a string from user input or from the db
*
* check for invalid UTF-8,
* Convert single < characters to entity,
* strip all tags,
* remove line breaks, tabs and extra white space,
* strip octets.
*
* @since 2.9.0
*
* @param string $str
* @return string
*/
function sanitize_text_field($str) {
$filtered = wp_check_invalid_utf8( $str );
if ( strpos($filtered, '<') !== false ) {
$filtered = wp_pre_kses_less_than( $filtered );
// This will strip extra whitespace for us.
$filtered = wp_strip_all_tags( $filtered, true );
} else {
$filtered = trim( preg_replace('/[\r\n\t ]+/', ' ', $filtered) );
}
$found = false;
while ( preg_match('/%[a-f0-9]{2}/i', $filtered, $match) ) {
$filtered = str_replace($match[0], '', $filtered);
$found = true;
}
if ( $found ) {
// Strip out the whitespace that may now exist after removing the octets.
$filtered = trim( preg_replace('/ +/', ' ', $filtered) );
}
/**
* Filter a sanitized text field string.
*
* @since 2.9.0
*
* @param string $filtered The sanitized string.
* @param string $str The string prior to being sanitized.
*/
return apply_filters( 'sanitize_text_field', $filtered, $str );
}
/**
* i18n friendly version of basename()
*
* @since 3.1.0
*
* @param string $path A path.
* @param string $suffix If the filename ends in suffix this will also be cut off.
* @return string
*/
function wp_basename( $path, $suffix = '' ) {
return urldecode( basename( str_replace( array( '%2F', '%5C' ), '/', urlencode( $path ) ), $suffix ) );
}
/**
* Forever eliminate "Wordpress" from the planet (or at least the little bit we can influence).
*
* Violating our coding standards for a good function name.
*
* @since 3.0.0
*/
function capital_P_dangit( $text ) {
// Simple replacement for titles
$current_filter = current_filter();
if ( 'the_title' === $current_filter || 'wp_title' === $current_filter )
return str_replace( 'Wordpress', 'WordPress', $text );
// Still here? Use the more judicious replacement
static $dblq = false;
if ( false === $dblq )
$dblq = _x( '“', 'opening curly double quote' );
return str_replace(
array( ' Wordpress', '‘Wordpress', $dblq . 'Wordpress', '>Wordpress', '(Wordpress' ),
array( ' WordPress', '‘WordPress', $dblq . 'WordPress', '>WordPress', '(WordPress' ),
$text );
}
/**
* Sanitize a mime type
*
* @since 3.1.3
*
* @param string $mime_type Mime type
* @return string Sanitized mime type
*/
function sanitize_mime_type( $mime_type ) {
$sani_mime_type = preg_replace( '/[^-+*.a-zA-Z0-9\/]/', '', $mime_type );
/**
* Filter a mime type following sanitization.
*
* @since 3.1.3
*
* @param string $sani_mime_type The sanitized mime type.
* @param string $mime_type The mime type prior to sanitization.
*/
return apply_filters( 'sanitize_mime_type', $sani_mime_type, $mime_type );
}
/**
* Sanitize space or carriage return separated URLs that are used to send trackbacks.
*
* @since 3.4.0
*
* @param string $to_ping Space or carriage return separated URLs
* @return string URLs starting with the http or https protocol, separated by a carriage return.
*/
function sanitize_trackback_urls( $to_ping ) {
$urls_to_ping = preg_split( '/[\r\n\t ]/', trim( $to_ping ), -1, PREG_SPLIT_NO_EMPTY );
foreach ( $urls_to_ping as $k => $url ) {
if ( !preg_match( '#^https?://.#i', $url ) )
unset( $urls_to_ping[$k] );
}
$urls_to_ping = array_map( 'esc_url_raw', $urls_to_ping );
$urls_to_ping = implode( "\n", $urls_to_ping );
/**
* Filter a list of trackback URLs following sanitization.
*
* The string returned here consists of a space or carriage return-delimited list
* of trackback URLs.
*
* @since 3.4.0
*
* @param string $urls_to_ping Sanitized space or carriage return separated URLs.
* @param string $to_ping Space or carriage return separated URLs before sanitization.
*/
return apply_filters( 'sanitize_trackback_urls', $urls_to_ping, $to_ping );
}
/**
* Add slashes to a string or array of strings.
*
* This should be used when preparing data for core API that expects slashed data.
* This should not be used to escape data going directly into an SQL query.
*
* @since 3.6.0
*
* @param string|array $value String or array of strings to slash.
* @return string|array Slashed $value
*/
function wp_slash( $value ) {
if ( is_array( $value ) ) {
foreach ( $value as $k => $v ) {
if ( is_array( $v ) ) {
$value[$k] = wp_slash( $v );
} else {
$value[$k] = addslashes( $v );
}
}
} else {
$value = addslashes( $value );
}
return $value;
}
/**
* Remove slashes from a string or array of strings.
*
* This should be used to remove slashes from data passed to core API that
* expects data to be unslashed.
*
* @since 3.6.0
*
* @param string|array $value String or array of strings to unslash.
* @return string|array Unslashed $value
*/
function wp_unslash( $value ) {
return stripslashes_deep( $value );
}
/**
* Extract and return the first URL from passed content.
*
* @since 3.6.0
*
* @param string $content A string which might contain a URL.
* @return string The found URL.
*/
function get_url_in_content( $content ) {
if ( empty( $content ) ) {
return false;
}
if ( preg_match( '/<a\s[^>]*?href=([\'"])(.+?)\1/is', $content, $matches ) ) {
return esc_url_raw( $matches[2] );
}
return false;
}
| PHP |
<?php
/**
* Defines constants and global variables that can be overridden, generally in wp-config.php.
*
* @package WordPress
*/
/**
* Defines initial WordPress constants
*
* @see wp_debug_mode()
*
* @since 3.0.0
*/
function wp_initial_constants() {
global $blog_id;
// set memory limits
if ( !defined('WP_MEMORY_LIMIT') ) {
if( is_multisite() ) {
define('WP_MEMORY_LIMIT', '64M');
} else {
define('WP_MEMORY_LIMIT', '40M');
}
}
if ( ! defined( 'WP_MAX_MEMORY_LIMIT' ) ) {
define( 'WP_MAX_MEMORY_LIMIT', '256M' );
}
/**
* The $blog_id global, which you can change in the config allows you to create a simple
* multiple blog installation using just one WordPress and changing $blog_id around.
*
* @global int $blog_id
* @since 2.0.0
*/
if ( ! isset($blog_id) )
$blog_id = 1;
// set memory limits.
if ( function_exists( 'memory_get_usage' ) ) {
$current_limit = @ini_get( 'memory_limit' );
$current_limit_int = intval( $current_limit );
if ( false !== strpos( $current_limit, 'G' ) )
$current_limit_int *= 1024;
$wp_limit_int = intval( WP_MEMORY_LIMIT );
if ( false !== strpos( WP_MEMORY_LIMIT, 'G' ) )
$wp_limit_int *= 1024;
if ( -1 != $current_limit && ( -1 == WP_MEMORY_LIMIT || $current_limit_int < $wp_limit_int ) )
@ini_set( 'memory_limit', WP_MEMORY_LIMIT );
}
if ( !defined('WP_CONTENT_DIR') )
define( 'WP_CONTENT_DIR', ABSPATH . 'wp-content' ); // no trailing slash, full paths only - WP_CONTENT_URL is defined further down
// Add define('WP_DEBUG', true); to wp-config.php to enable display of notices during development.
if ( !defined('WP_DEBUG') )
define( 'WP_DEBUG', false );
// Add define('WP_DEBUG_DISPLAY', null); to wp-config.php use the globally configured setting for
// display_errors and not force errors to be displayed. Use false to force display_errors off.
if ( !defined('WP_DEBUG_DISPLAY') )
define( 'WP_DEBUG_DISPLAY', true );
// Add define('WP_DEBUG_LOG', true); to enable error logging to wp-content/debug.log.
if ( !defined('WP_DEBUG_LOG') )
define('WP_DEBUG_LOG', false);
if ( !defined('WP_CACHE') )
define('WP_CACHE', false);
/**
* Private
*/
if ( !defined('MEDIA_TRASH') )
define('MEDIA_TRASH', false);
if ( !defined('SHORTINIT') )
define('SHORTINIT', false);
// Constants for expressing human-readable intervals
// in their respective number of seconds.
define( 'MINUTE_IN_SECONDS', 60 );
define( 'HOUR_IN_SECONDS', 60 * MINUTE_IN_SECONDS );
define( 'DAY_IN_SECONDS', 24 * HOUR_IN_SECONDS );
define( 'WEEK_IN_SECONDS', 7 * DAY_IN_SECONDS );
define( 'YEAR_IN_SECONDS', 365 * DAY_IN_SECONDS );
}
/**
* Defines plugin directory WordPress constants
*
* Defines must-use plugin directory constants, which may be overridden in the sunrise.php drop-in
*
* @since 3.0.0
*/
function wp_plugin_directory_constants() {
if ( !defined('WP_CONTENT_URL') )
define( 'WP_CONTENT_URL', get_option('siteurl') . '/wp-content'); // full url - WP_CONTENT_DIR is defined further up
/**
* Allows for the plugins directory to be moved from the default location.
*
* @since 2.6.0
*/
if ( !defined('WP_PLUGIN_DIR') )
define( 'WP_PLUGIN_DIR', WP_CONTENT_DIR . '/plugins' ); // full path, no trailing slash
/**
* Allows for the plugins directory to be moved from the default location.
*
* @since 2.6.0
*/
if ( !defined('WP_PLUGIN_URL') )
define( 'WP_PLUGIN_URL', WP_CONTENT_URL . '/plugins' ); // full url, no trailing slash
/**
* Allows for the plugins directory to be moved from the default location.
*
* @since 2.1.0
* @deprecated
*/
if ( !defined('PLUGINDIR') )
define( 'PLUGINDIR', 'wp-content/plugins' ); // Relative to ABSPATH. For back compat.
/**
* Allows for the mu-plugins directory to be moved from the default location.
*
* @since 2.8.0
*/
if ( !defined('WPMU_PLUGIN_DIR') )
define( 'WPMU_PLUGIN_DIR', WP_CONTENT_DIR . '/mu-plugins' ); // full path, no trailing slash
/**
* Allows for the mu-plugins directory to be moved from the default location.
*
* @since 2.8.0
*/
if ( !defined('WPMU_PLUGIN_URL') )
define( 'WPMU_PLUGIN_URL', WP_CONTENT_URL . '/mu-plugins' ); // full url, no trailing slash
/**
* Allows for the mu-plugins directory to be moved from the default location.
*
* @since 2.8.0
* @deprecated
*/
if ( !defined( 'MUPLUGINDIR' ) )
define( 'MUPLUGINDIR', 'wp-content/mu-plugins' ); // Relative to ABSPATH. For back compat.
}
/**
* Defines cookie related WordPress constants
*
* Defines constants after multisite is loaded. Cookie-related constants may be overridden in ms_network_cookies().
* @since 3.0.0
*/
function wp_cookie_constants() {
/**
* Used to guarantee unique hash cookies
*
* @since 1.5.0
*/
if ( !defined( 'COOKIEHASH' ) ) {
$siteurl = get_site_option( 'siteurl' );
if ( $siteurl )
define( 'COOKIEHASH', md5( $siteurl ) );
else
define( 'COOKIEHASH', '' );
}
/**
* @since 2.0.0
*/
if ( !defined('USER_COOKIE') )
define('USER_COOKIE', 'wordpressuser_' . COOKIEHASH);
/**
* @since 2.0.0
*/
if ( !defined('PASS_COOKIE') )
define('PASS_COOKIE', 'wordpresspass_' . COOKIEHASH);
/**
* @since 2.5.0
*/
if ( !defined('AUTH_COOKIE') )
define('AUTH_COOKIE', 'wordpress_' . COOKIEHASH);
/**
* @since 2.6.0
*/
if ( !defined('SECURE_AUTH_COOKIE') )
define('SECURE_AUTH_COOKIE', 'wordpress_sec_' . COOKIEHASH);
/**
* @since 2.6.0
*/
if ( !defined('LOGGED_IN_COOKIE') )
define('LOGGED_IN_COOKIE', 'wordpress_logged_in_' . COOKIEHASH);
/**
* @since 2.3.0
*/
if ( !defined('TEST_COOKIE') )
define('TEST_COOKIE', 'wordpress_test_cookie');
/**
* @since 1.2.0
*/
if ( !defined('COOKIEPATH') )
define('COOKIEPATH', preg_replace('|https?://[^/]+|i', '', get_option('home') . '/' ) );
/**
* @since 1.5.0
*/
if ( !defined('SITECOOKIEPATH') )
define('SITECOOKIEPATH', preg_replace('|https?://[^/]+|i', '', get_option('siteurl') . '/' ) );
/**
* @since 2.6.0
*/
if ( !defined('ADMIN_COOKIE_PATH') )
define( 'ADMIN_COOKIE_PATH', SITECOOKIEPATH . 'wp-admin' );
/**
* @since 2.6.0
*/
if ( !defined('PLUGINS_COOKIE_PATH') )
define( 'PLUGINS_COOKIE_PATH', preg_replace('|https?://[^/]+|i', '', WP_PLUGIN_URL) );
/**
* @since 2.0.0
*/
if ( !defined('COOKIE_DOMAIN') )
define('COOKIE_DOMAIN', false);
}
/**
* Defines cookie related WordPress constants
*
* @since 3.0.0
*/
function wp_ssl_constants() {
/**
* @since 2.6.0
*/
if ( !defined('FORCE_SSL_ADMIN') )
define('FORCE_SSL_ADMIN', false);
force_ssl_admin(FORCE_SSL_ADMIN);
/**
* @since 2.6.0
*/
if ( !defined('FORCE_SSL_LOGIN') )
define('FORCE_SSL_LOGIN', false);
force_ssl_login(FORCE_SSL_LOGIN);
}
/**
* Defines functionality related WordPress constants
*
* @since 3.0.0
*/
function wp_functionality_constants() {
/**
* @since 2.5.0
*/
if ( !defined( 'AUTOSAVE_INTERVAL' ) )
define( 'AUTOSAVE_INTERVAL', 60 );
/**
* @since 2.9.0
*/
if ( !defined( 'EMPTY_TRASH_DAYS' ) )
define( 'EMPTY_TRASH_DAYS', 30 );
if ( !defined('WP_POST_REVISIONS') )
define('WP_POST_REVISIONS', true);
/**
* @since 3.3.0
*/
if ( !defined( 'WP_CRON_LOCK_TIMEOUT' ) )
define('WP_CRON_LOCK_TIMEOUT', 60); // In seconds
}
/**
* Defines templating related WordPress constants
*
* @since 3.0.0
*/
function wp_templating_constants() {
/**
* Filesystem path to the current active template directory
* @since 1.5.0
*/
define('TEMPLATEPATH', get_template_directory());
/**
* Filesystem path to the current active template stylesheet directory
* @since 2.1.0
*/
define('STYLESHEETPATH', get_stylesheet_directory());
/**
* Slug of the default theme for this install.
* Used as the default theme when installing new sites.
* Will be used as the fallback if the current theme doesn't exist.
* @since 3.0.0
*/
if ( !defined('WP_DEFAULT_THEME') )
define( 'WP_DEFAULT_THEME', 'twentyfourteen' );
}
| PHP |
<?php
/**
* Date and Time Locale object
*
* @package WordPress
* @subpackage i18n
*/
/**
* Class that loads the calendar locale.
*
* @since 2.1.0
*/
class WP_Locale {
/**
* Stores the translated strings for the full weekday names.
*
* @since 2.1.0
* @var array
* @access private
*/
var $weekday;
/**
* Stores the translated strings for the one character weekday names.
*
* There is a hack to make sure that Tuesday and Thursday, as well
* as Sunday and Saturday, don't conflict. See init() method for more.
*
* @see WP_Locale::init() for how to handle the hack.
*
* @since 2.1.0
* @var array
* @access private
*/
var $weekday_initial;
/**
* Stores the translated strings for the abbreviated weekday names.
*
* @since 2.1.0
* @var array
* @access private
*/
var $weekday_abbrev;
/**
* Stores the translated strings for the full month names.
*
* @since 2.1.0
* @var array
* @access private
*/
var $month;
/**
* Stores the translated strings for the abbreviated month names.
*
* @since 2.1.0
* @var array
* @access private
*/
var $month_abbrev;
/**
* Stores the translated strings for 'am' and 'pm'.
*
* Also the capitalized versions.
*
* @since 2.1.0
* @var array
* @access private
*/
var $meridiem;
/**
* The text direction of the locale language.
*
* Default is left to right 'ltr'.
*
* @since 2.1.0
* @var string
* @access private
*/
var $text_direction = 'ltr';
/**
* Sets up the translated strings and object properties.
*
* The method creates the translatable strings for various
* calendar elements. Which allows for specifying locale
* specific calendar names and text direction.
*
* @since 2.1.0
* @access private
*/
function init() {
// The Weekdays
$this->weekday[0] = /* translators: weekday */ __('Sunday');
$this->weekday[1] = /* translators: weekday */ __('Monday');
$this->weekday[2] = /* translators: weekday */ __('Tuesday');
$this->weekday[3] = /* translators: weekday */ __('Wednesday');
$this->weekday[4] = /* translators: weekday */ __('Thursday');
$this->weekday[5] = /* translators: weekday */ __('Friday');
$this->weekday[6] = /* translators: weekday */ __('Saturday');
// The first letter of each day. The _%day%_initial suffix is a hack to make
// sure the day initials are unique.
$this->weekday_initial[__('Sunday')] = /* translators: one-letter abbreviation of the weekday */ __('S_Sunday_initial');
$this->weekday_initial[__('Monday')] = /* translators: one-letter abbreviation of the weekday */ __('M_Monday_initial');
$this->weekday_initial[__('Tuesday')] = /* translators: one-letter abbreviation of the weekday */ __('T_Tuesday_initial');
$this->weekday_initial[__('Wednesday')] = /* translators: one-letter abbreviation of the weekday */ __('W_Wednesday_initial');
$this->weekday_initial[__('Thursday')] = /* translators: one-letter abbreviation of the weekday */ __('T_Thursday_initial');
$this->weekday_initial[__('Friday')] = /* translators: one-letter abbreviation of the weekday */ __('F_Friday_initial');
$this->weekday_initial[__('Saturday')] = /* translators: one-letter abbreviation of the weekday */ __('S_Saturday_initial');
foreach ($this->weekday_initial as $weekday_ => $weekday_initial_) {
$this->weekday_initial[$weekday_] = preg_replace('/_.+_initial$/', '', $weekday_initial_);
}
// Abbreviations for each day.
$this->weekday_abbrev[__('Sunday')] = /* translators: three-letter abbreviation of the weekday */ __('Sun');
$this->weekday_abbrev[__('Monday')] = /* translators: three-letter abbreviation of the weekday */ __('Mon');
$this->weekday_abbrev[__('Tuesday')] = /* translators: three-letter abbreviation of the weekday */ __('Tue');
$this->weekday_abbrev[__('Wednesday')] = /* translators: three-letter abbreviation of the weekday */ __('Wed');
$this->weekday_abbrev[__('Thursday')] = /* translators: three-letter abbreviation of the weekday */ __('Thu');
$this->weekday_abbrev[__('Friday')] = /* translators: three-letter abbreviation of the weekday */ __('Fri');
$this->weekday_abbrev[__('Saturday')] = /* translators: three-letter abbreviation of the weekday */ __('Sat');
// The Months
$this->month['01'] = /* translators: month name */ __('January');
$this->month['02'] = /* translators: month name */ __('February');
$this->month['03'] = /* translators: month name */ __('March');
$this->month['04'] = /* translators: month name */ __('April');
$this->month['05'] = /* translators: month name */ __('May');
$this->month['06'] = /* translators: month name */ __('June');
$this->month['07'] = /* translators: month name */ __('July');
$this->month['08'] = /* translators: month name */ __('August');
$this->month['09'] = /* translators: month name */ __('September');
$this->month['10'] = /* translators: month name */ __('October');
$this->month['11'] = /* translators: month name */ __('November');
$this->month['12'] = /* translators: month name */ __('December');
// Abbreviations for each month. Uses the same hack as above to get around the
// 'May' duplication.
$this->month_abbrev[__('January')] = /* translators: three-letter abbreviation of the month */ __('Jan_January_abbreviation');
$this->month_abbrev[__('February')] = /* translators: three-letter abbreviation of the month */ __('Feb_February_abbreviation');
$this->month_abbrev[__('March')] = /* translators: three-letter abbreviation of the month */ __('Mar_March_abbreviation');
$this->month_abbrev[__('April')] = /* translators: three-letter abbreviation of the month */ __('Apr_April_abbreviation');
$this->month_abbrev[__('May')] = /* translators: three-letter abbreviation of the month */ __('May_May_abbreviation');
$this->month_abbrev[__('June')] = /* translators: three-letter abbreviation of the month */ __('Jun_June_abbreviation');
$this->month_abbrev[__('July')] = /* translators: three-letter abbreviation of the month */ __('Jul_July_abbreviation');
$this->month_abbrev[__('August')] = /* translators: three-letter abbreviation of the month */ __('Aug_August_abbreviation');
$this->month_abbrev[__('September')] = /* translators: three-letter abbreviation of the month */ __('Sep_September_abbreviation');
$this->month_abbrev[__('October')] = /* translators: three-letter abbreviation of the month */ __('Oct_October_abbreviation');
$this->month_abbrev[__('November')] = /* translators: three-letter abbreviation of the month */ __('Nov_November_abbreviation');
$this->month_abbrev[__('December')] = /* translators: three-letter abbreviation of the month */ __('Dec_December_abbreviation');
foreach ($this->month_abbrev as $month_ => $month_abbrev_) {
$this->month_abbrev[$month_] = preg_replace('/_.+_abbreviation$/', '', $month_abbrev_);
}
// The Meridiems
$this->meridiem['am'] = __('am');
$this->meridiem['pm'] = __('pm');
$this->meridiem['AM'] = __('AM');
$this->meridiem['PM'] = __('PM');
// Numbers formatting
// See http://php.net/number_format
/* translators: $thousands_sep argument for http://php.net/number_format, default is , */
$trans = __('number_format_thousands_sep');
$this->number_format['thousands_sep'] = ('number_format_thousands_sep' == $trans) ? ',' : $trans;
/* translators: $dec_point argument for http://php.net/number_format, default is . */
$trans = __('number_format_decimal_point');
$this->number_format['decimal_point'] = ('number_format_decimal_point' == $trans) ? '.' : $trans;
// Set text direction.
if ( isset( $GLOBALS['text_direction'] ) )
$this->text_direction = $GLOBALS['text_direction'];
/* translators: 'rtl' or 'ltr'. This sets the text direction for WordPress. */
elseif ( 'rtl' == _x( 'ltr', 'text direction' ) )
$this->text_direction = 'rtl';
if ( 'rtl' === $this->text_direction && strpos( $GLOBALS['wp_version'], '-src' ) ) {
$this->text_direction = 'ltr';
add_action( 'all_admin_notices', array( $this, 'rtl_src_admin_notice' ) );
}
}
function rtl_src_admin_notice() {
echo '<div class="error"><p>' . 'The <code>build</code> directory of the develop repository must be used for RTL.' . '</p></div>';
}
/**
* Retrieve the full translated weekday word.
*
* Week starts on translated Sunday and can be fetched
* by using 0 (zero). So the week starts with 0 (zero)
* and ends on Saturday with is fetched by using 6 (six).
*
* @since 2.1.0
* @access public
*
* @param int $weekday_number 0 for Sunday through 6 Saturday
* @return string Full translated weekday
*/
function get_weekday($weekday_number) {
return $this->weekday[$weekday_number];
}
/**
* Retrieve the translated weekday initial.
*
* The weekday initial is retrieved by the translated
* full weekday word. When translating the weekday initial
* pay attention to make sure that the starting letter does
* not conflict.
*
* @since 2.1.0
* @access public
*
* @param string $weekday_name
* @return string
*/
function get_weekday_initial($weekday_name) {
return $this->weekday_initial[$weekday_name];
}
/**
* Retrieve the translated weekday abbreviation.
*
* The weekday abbreviation is retrieved by the translated
* full weekday word.
*
* @since 2.1.0
* @access public
*
* @param string $weekday_name Full translated weekday word
* @return string Translated weekday abbreviation
*/
function get_weekday_abbrev($weekday_name) {
return $this->weekday_abbrev[$weekday_name];
}
/**
* Retrieve the full translated month by month number.
*
* The $month_number parameter has to be a string
* because it must have the '0' in front of any number
* that is less than 10. Starts from '01' and ends at
* '12'.
*
* You can use an integer instead and it will add the
* '0' before the numbers less than 10 for you.
*
* @since 2.1.0
* @access public
*
* @param string|int $month_number '01' through '12'
* @return string Translated full month name
*/
function get_month($month_number) {
return $this->month[zeroise($month_number, 2)];
}
/**
* Retrieve translated version of month abbreviation string.
*
* The $month_name parameter is expected to be the translated or
* translatable version of the month.
*
* @since 2.1.0
* @access public
*
* @param string $month_name Translated month to get abbreviated version
* @return string Translated abbreviated month
*/
function get_month_abbrev($month_name) {
return $this->month_abbrev[$month_name];
}
/**
* Retrieve translated version of meridiem string.
*
* The $meridiem parameter is expected to not be translated.
*
* @since 2.1.0
* @access public
*
* @param string $meridiem Either 'am', 'pm', 'AM', or 'PM'. Not translated version.
* @return string Translated version
*/
function get_meridiem($meridiem) {
return $this->meridiem[$meridiem];
}
/**
* Global variables are deprecated. For backwards compatibility only.
*
* @deprecated For backwards compatibility only.
* @access private
*
* @since 2.1.0
*/
function register_globals() {
$GLOBALS['weekday'] = $this->weekday;
$GLOBALS['weekday_initial'] = $this->weekday_initial;
$GLOBALS['weekday_abbrev'] = $this->weekday_abbrev;
$GLOBALS['month'] = $this->month;
$GLOBALS['month_abbrev'] = $this->month_abbrev;
}
/**
* Constructor which calls helper methods to set up object variables
*
* @uses WP_Locale::init()
* @uses WP_Locale::register_globals()
* @since 2.1.0
*
* @return WP_Locale
*/
function __construct() {
$this->init();
$this->register_globals();
}
/**
* Checks if current locale is RTL.
*
* @since 3.0.0
* @return bool Whether locale is RTL.
*/
function is_rtl() {
return 'rtl' == $this->text_direction;
}
/**
* Register date/time format strings for general POT.
*
* Private, unused method to add some date/time formats translated
* on wp-admin/options-general.php to the general POT that would
* otherwise be added to the admin POT.
*
* @since 3.6.0
*/
function _strings_for_pot() {
/* translators: localized date format, see http://php.net/date */
__( 'F j, Y' );
/* translators: localized time format, see http://php.net/date */
__( 'g:i a' );
/* translators: localized date and time format, see http://php.net/date */
__( 'F j, Y g:i a' );
}
}
/**
* Checks if current locale is RTL.
*
* @since 3.0.0
* @return bool Whether locale is RTL.
*/
function is_rtl() {
global $wp_locale;
return $wp_locale->is_rtl();
}
| PHP |
<?php
/**
* WordPress environment setup class.
*
* @package WordPress
* @since 2.0.0
*/
class WP {
/**
* Public query variables.
*
* Long list of public query variables.
*
* @since 2.0.0
* @access public
* @var array
*/
var $public_query_vars = array('m', 'p', 'posts', 'w', 'cat', 'withcomments', 'withoutcomments', 's', 'search', 'exact', 'sentence', 'calendar', 'page', 'paged', 'more', 'tb', 'pb', 'author', 'order', 'orderby', 'year', 'monthnum', 'day', 'hour', 'minute', 'second', 'name', 'category_name', 'tag', 'feed', 'author_name', 'static', 'pagename', 'page_id', 'error', 'comments_popup', 'attachment', 'attachment_id', 'subpost', 'subpost_id', 'preview', 'robots', 'taxonomy', 'term', 'cpage', 'post_type');
/**
* Private query variables.
*
* Long list of private query variables.
*
* @since 2.0.0
* @var array
*/
var $private_query_vars = array( 'offset', 'posts_per_page', 'posts_per_archive_page', 'showposts', 'nopaging', 'post_type', 'post_status', 'category__in', 'category__not_in', 'category__and', 'tag__in', 'tag__not_in', 'tag__and', 'tag_slug__in', 'tag_slug__and', 'tag_id', 'post_mime_type', 'perm', 'comments_per_page', 'post__in', 'post__not_in', 'post_parent', 'post_parent__in', 'post_parent__not_in' );
/**
* Extra query variables set by the user.
*
* @since 2.1.0
* @var array
*/
var $extra_query_vars = array();
/**
* Query variables for setting up the WordPress Query Loop.
*
* @since 2.0.0
* @var array
*/
var $query_vars;
/**
* String parsed to set the query variables.
*
* @since 2.0.0
* @var string
*/
var $query_string;
/**
* Permalink or requested URI.
*
* @since 2.0.0
* @var string
*/
var $request;
/**
* Rewrite rule the request matched.
*
* @since 2.0.0
* @var string
*/
var $matched_rule;
/**
* Rewrite query the request matched.
*
* @since 2.0.0
* @var string
*/
var $matched_query;
/**
* Whether already did the permalink.
*
* @since 2.0.0
* @var bool
*/
var $did_permalink = false;
/**
* Add name to list of public query variables.
*
* @since 2.1.0
*
* @param string $qv Query variable name.
*/
function add_query_var($qv) {
if ( !in_array($qv, $this->public_query_vars) )
$this->public_query_vars[] = $qv;
}
/**
* Set the value of a query variable.
*
* @since 2.3.0
*
* @param string $key Query variable name.
* @param mixed $value Query variable value.
*/
function set_query_var($key, $value) {
$this->query_vars[$key] = $value;
}
/**
* Parse request to find correct WordPress query.
*
* Sets up the query variables based on the request. There are also many
* filters and actions that can be used to further manipulate the result.
*
* @since 2.0.0
*
* @param array|string $extra_query_vars Set the extra query variables.
*/
function parse_request($extra_query_vars = '') {
global $wp_rewrite;
/**
* Filter whether to parse the request.
*
* @since 3.5.0
*
* @param bool $bool Whether or not to parse the request. Default true.
* @param WP $this Current WordPress environment instance.
* @param array|string $extra_query_vars Extra passed query variables.
*/
if ( ! apply_filters( 'do_parse_request', true, $this, $extra_query_vars ) )
return;
$this->query_vars = array();
$post_type_query_vars = array();
if ( is_array($extra_query_vars) )
$this->extra_query_vars = & $extra_query_vars;
else if (! empty($extra_query_vars))
parse_str($extra_query_vars, $this->extra_query_vars);
// Process PATH_INFO, REQUEST_URI, and 404 for permalinks.
// Fetch the rewrite rules.
$rewrite = $wp_rewrite->wp_rewrite_rules();
if ( ! empty($rewrite) ) {
// If we match a rewrite rule, this will be cleared.
$error = '404';
$this->did_permalink = true;
$pathinfo = isset( $_SERVER['PATH_INFO'] ) ? $_SERVER['PATH_INFO'] : '';
list( $pathinfo ) = explode( '?', $pathinfo );
$pathinfo = str_replace( "%", "%25", $pathinfo );
list( $req_uri ) = explode( '?', $_SERVER['REQUEST_URI'] );
$self = $_SERVER['PHP_SELF'];
$home_path = trim( parse_url( home_url(), PHP_URL_PATH ), '/' );
// Trim path info from the end and the leading home path from the
// front. For path info requests, this leaves us with the requesting
// filename, if any. For 404 requests, this leaves us with the
// requested permalink.
$req_uri = str_replace($pathinfo, '', $req_uri);
$req_uri = trim($req_uri, '/');
$req_uri = preg_replace("|^$home_path|i", '', $req_uri);
$req_uri = trim($req_uri, '/');
$pathinfo = trim($pathinfo, '/');
$pathinfo = preg_replace("|^$home_path|i", '', $pathinfo);
$pathinfo = trim($pathinfo, '/');
$self = trim($self, '/');
$self = preg_replace("|^$home_path|i", '', $self);
$self = trim($self, '/');
// The requested permalink is in $pathinfo for path info requests and
// $req_uri for other requests.
if ( ! empty($pathinfo) && !preg_match('|^.*' . $wp_rewrite->index . '$|', $pathinfo) ) {
$request = $pathinfo;
} else {
// If the request uri is the index, blank it out so that we don't try to match it against a rule.
if ( $req_uri == $wp_rewrite->index )
$req_uri = '';
$request = $req_uri;
}
$this->request = $request;
// Look for matches.
$request_match = $request;
if ( empty( $request_match ) ) {
// An empty request could only match against ^$ regex
if ( isset( $rewrite['$'] ) ) {
$this->matched_rule = '$';
$query = $rewrite['$'];
$matches = array('');
}
} else {
foreach ( (array) $rewrite as $match => $query ) {
// If the requesting file is the anchor of the match, prepend it to the path info.
if ( ! empty($req_uri) && strpos($match, $req_uri) === 0 && $req_uri != $request )
$request_match = $req_uri . '/' . $request;
if ( preg_match("#^$match#", $request_match, $matches) ||
preg_match("#^$match#", urldecode($request_match), $matches) ) {
if ( $wp_rewrite->use_verbose_page_rules && preg_match( '/pagename=\$matches\[([0-9]+)\]/', $query, $varmatch ) ) {
// this is a verbose page match, lets check to be sure about it
if ( ! get_page_by_path( $matches[ $varmatch[1] ] ) )
continue;
}
// Got a match.
$this->matched_rule = $match;
break;
}
}
}
if ( isset( $this->matched_rule ) ) {
// Trim the query of everything up to the '?'.
$query = preg_replace("!^.+\?!", '', $query);
// Substitute the substring matches into the query.
$query = addslashes(WP_MatchesMapRegex::apply($query, $matches));
$this->matched_query = $query;
// Parse the query.
parse_str($query, $perma_query_vars);
// If we're processing a 404 request, clear the error var since we found something.
if ( '404' == $error )
unset( $error, $_GET['error'] );
}
// If req_uri is empty or if it is a request for ourself, unset error.
if ( empty($request) || $req_uri == $self || strpos($_SERVER['PHP_SELF'], 'wp-admin/') !== false ) {
unset( $error, $_GET['error'] );
if ( isset($perma_query_vars) && strpos($_SERVER['PHP_SELF'], 'wp-admin/') !== false )
unset( $perma_query_vars );
$this->did_permalink = false;
}
}
/**
* Filter the query variables whitelist before processing.
*
* Allows (publicly allowed) query vars to be added, removed, or changed prior
* to executing the query. Needed to allow custom rewrite rules using your own arguments
* to work, or any other custom query variables you want to be publicly available.
*
* @since 1.5.0
*
* @param array $public_query_vars The array of whitelisted query variables.
*/
$this->public_query_vars = apply_filters( 'query_vars', $this->public_query_vars );
foreach ( get_post_types( array(), 'objects' ) as $post_type => $t )
if ( $t->query_var )
$post_type_query_vars[$t->query_var] = $post_type;
foreach ( $this->public_query_vars as $wpvar ) {
if ( isset( $this->extra_query_vars[$wpvar] ) )
$this->query_vars[$wpvar] = $this->extra_query_vars[$wpvar];
elseif ( isset( $_POST[$wpvar] ) )
$this->query_vars[$wpvar] = $_POST[$wpvar];
elseif ( isset( $_GET[$wpvar] ) )
$this->query_vars[$wpvar] = $_GET[$wpvar];
elseif ( isset( $perma_query_vars[$wpvar] ) )
$this->query_vars[$wpvar] = $perma_query_vars[$wpvar];
if ( !empty( $this->query_vars[$wpvar] ) ) {
if ( ! is_array( $this->query_vars[$wpvar] ) ) {
$this->query_vars[$wpvar] = (string) $this->query_vars[$wpvar];
} else {
foreach ( $this->query_vars[$wpvar] as $vkey => $v ) {
if ( !is_object( $v ) ) {
$this->query_vars[$wpvar][$vkey] = (string) $v;
}
}
}
if ( isset($post_type_query_vars[$wpvar] ) ) {
$this->query_vars['post_type'] = $post_type_query_vars[$wpvar];
$this->query_vars['name'] = $this->query_vars[$wpvar];
}
}
}
// Convert urldecoded spaces back into +
foreach ( get_taxonomies( array() , 'objects' ) as $taxonomy => $t )
if ( $t->query_var && isset( $this->query_vars[$t->query_var] ) )
$this->query_vars[$t->query_var] = str_replace( ' ', '+', $this->query_vars[$t->query_var] );
// Limit publicly queried post_types to those that are publicly_queryable
if ( isset( $this->query_vars['post_type']) ) {
$queryable_post_types = get_post_types( array('publicly_queryable' => true) );
if ( ! is_array( $this->query_vars['post_type'] ) ) {
if ( ! in_array( $this->query_vars['post_type'], $queryable_post_types ) )
unset( $this->query_vars['post_type'] );
} else {
$this->query_vars['post_type'] = array_intersect( $this->query_vars['post_type'], $queryable_post_types );
}
}
foreach ( (array) $this->private_query_vars as $var) {
if ( isset($this->extra_query_vars[$var]) )
$this->query_vars[$var] = $this->extra_query_vars[$var];
}
if ( isset($error) )
$this->query_vars['error'] = $error;
/**
* Filter the array of parsed query variables.
*
* @since 2.1.0
*
* @param array $query_vars The array of requested query variables.
*/
$this->query_vars = apply_filters( 'request', $this->query_vars );
/**
* Fires once all query variables for the current request have been parsed.
*
* @since 2.1.0
*
* @param WP &$this Current WordPress environment instance (passed by reference).
*/
do_action_ref_array( 'parse_request', array( &$this ) );
}
/**
* Send additional HTTP headers for caching, content type, etc.
*
* Sets the X-Pingback header, 404 status (if 404), Content-type. If showing
* a feed, it will also send last-modified, etag, and 304 status if needed.
*
* @since 2.0.0
*/
function send_headers() {
$headers = array('X-Pingback' => get_bloginfo('pingback_url'));
$status = null;
$exit_required = false;
if ( is_user_logged_in() )
$headers = array_merge($headers, wp_get_nocache_headers());
if ( ! empty( $this->query_vars['error'] ) ) {
$status = (int) $this->query_vars['error'];
if ( 404 === $status ) {
if ( ! is_user_logged_in() )
$headers = array_merge($headers, wp_get_nocache_headers());
$headers['Content-Type'] = get_option('html_type') . '; charset=' . get_option('blog_charset');
} elseif ( in_array( $status, array( 403, 500, 502, 503 ) ) ) {
$exit_required = true;
}
} else if ( empty($this->query_vars['feed']) ) {
$headers['Content-Type'] = get_option('html_type') . '; charset=' . get_option('blog_charset');
} else {
// We're showing a feed, so WP is indeed the only thing that last changed
if ( !empty($this->query_vars['withcomments'])
|| false !== strpos( $this->query_vars['feed'], 'comments-' )
|| ( empty($this->query_vars['withoutcomments'])
&& ( !empty($this->query_vars['p'])
|| !empty($this->query_vars['name'])
|| !empty($this->query_vars['page_id'])
|| !empty($this->query_vars['pagename'])
|| !empty($this->query_vars['attachment'])
|| !empty($this->query_vars['attachment_id'])
)
)
)
$wp_last_modified = mysql2date('D, d M Y H:i:s', get_lastcommentmodified('GMT'), 0).' GMT';
else
$wp_last_modified = mysql2date('D, d M Y H:i:s', get_lastpostmodified('GMT'), 0).' GMT';
$wp_etag = '"' . md5($wp_last_modified) . '"';
$headers['Last-Modified'] = $wp_last_modified;
$headers['ETag'] = $wp_etag;
// Support for Conditional GET
if (isset($_SERVER['HTTP_IF_NONE_MATCH']))
$client_etag = wp_unslash( $_SERVER['HTTP_IF_NONE_MATCH'] );
else $client_etag = false;
$client_last_modified = empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? '' : trim($_SERVER['HTTP_IF_MODIFIED_SINCE']);
// If string is empty, return 0. If not, attempt to parse into a timestamp
$client_modified_timestamp = $client_last_modified ? strtotime($client_last_modified) : 0;
// Make a timestamp for our most recent modification...
$wp_modified_timestamp = strtotime($wp_last_modified);
if ( ($client_last_modified && $client_etag) ?
(($client_modified_timestamp >= $wp_modified_timestamp) && ($client_etag == $wp_etag)) :
(($client_modified_timestamp >= $wp_modified_timestamp) || ($client_etag == $wp_etag)) ) {
$status = 304;
$exit_required = true;
}
}
/**
* Filter the HTTP headers before they're sent to the browser.
*
* @since 2.8.0
*
* @param array $headers The list of headers to be sent.
* @param WP $this Current WordPress environment instance.
*/
$headers = apply_filters( 'wp_headers', $headers, $this );
if ( ! empty( $status ) )
status_header( $status );
// If Last-Modified is set to false, it should not be sent (no-cache situation).
if ( isset( $headers['Last-Modified'] ) && false === $headers['Last-Modified'] ) {
unset( $headers['Last-Modified'] );
// In PHP 5.3+, make sure we are not sending a Last-Modified header.
if ( function_exists( 'header_remove' ) ) {
@header_remove( 'Last-Modified' );
} else {
// In PHP 5.2, send an empty Last-Modified header, but only as a
// last resort to override a header already sent. #WP23021
foreach ( headers_list() as $header ) {
if ( 0 === stripos( $header, 'Last-Modified' ) ) {
$headers['Last-Modified'] = '';
break;
}
}
}
}
foreach( (array) $headers as $name => $field_value )
@header("{$name}: {$field_value}");
if ( $exit_required )
exit();
/**
* Fires once the requested HTTP headers for caching, content type, etc. have been sent.
*
* @since 2.1.0
*
* @param WP &$this Current WordPress environment instance (passed by reference).
*/
do_action_ref_array( 'send_headers', array( &$this ) );
}
/**
* Sets the query string property based off of the query variable property.
*
* The 'query_string' filter is deprecated, but still works. Plugins should
* use the 'request' filter instead.
*
* @since 2.0.0
*/
function build_query_string() {
$this->query_string = '';
foreach ( (array) array_keys($this->query_vars) as $wpvar) {
if ( '' != $this->query_vars[$wpvar] ) {
$this->query_string .= (strlen($this->query_string) < 1) ? '' : '&';
if ( !is_scalar($this->query_vars[$wpvar]) ) // Discard non-scalars.
continue;
$this->query_string .= $wpvar . '=' . rawurlencode($this->query_vars[$wpvar]);
}
}
if ( has_filter( 'query_string' ) ) { // Don't bother filtering and parsing if no plugins are hooked in.
/**
* Filter the query string before parsing.
*
* @since 1.5.0
* @deprecated 2.1.0 Use 'query_vars' or 'request' filters instead.
*
* @param string $query_string The query string to modify.
*/
$this->query_string = apply_filters( 'query_string', $this->query_string );
parse_str($this->query_string, $this->query_vars);
}
}
/**
* Set up the WordPress Globals.
*
* The query_vars property will be extracted to the GLOBALS. So care should
* be taken when naming global variables that might interfere with the
* WordPress environment.
*
* @global string $query_string Query string for the loop.
* @global array $posts The found posts.
* @global WP_Post|null $post The current post, if available.
* @global string $request The SQL statement for the request.
* @global int $more Only set, if single page or post.
* @global int $single If single page or post. Only set, if single page or post.
* @global WP_User $authordata Only set, if author archive.
*
* @since 2.0.0
*/
function register_globals() {
global $wp_query;
// Extract updated query vars back into global namespace.
foreach ( (array) $wp_query->query_vars as $key => $value ) {
$GLOBALS[ $key ] = $value;
}
$GLOBALS['query_string'] = $this->query_string;
$GLOBALS['posts'] = & $wp_query->posts;
$GLOBALS['post'] = isset( $wp_query->post ) ? $wp_query->post : null;
$GLOBALS['request'] = $wp_query->request;
if ( $wp_query->is_single() || $wp_query->is_page() ) {
$GLOBALS['more'] = 1;
$GLOBALS['single'] = 1;
}
if ( $wp_query->is_author() && isset( $wp_query->post ) )
$GLOBALS['authordata'] = get_userdata( $wp_query->post->post_author );
}
/**
* Set up the current user.
*
* @since 2.0.0
*/
function init() {
wp_get_current_user();
}
/**
* Set up the Loop based on the query variables.
*
* @uses WP::$query_vars
* @since 2.0.0
*/
function query_posts() {
global $wp_the_query;
$this->build_query_string();
$wp_the_query->query($this->query_vars);
}
/**
* Set the Headers for 404, if nothing is found for requested URL.
*
* Issue a 404 if a request doesn't match any posts and doesn't match
* any object (e.g. an existing-but-empty category, tag, author) and a 404 was not already
* issued, and if the request was not a search or the homepage.
*
* Otherwise, issue a 200.
*
* @since 2.0.0
*/
function handle_404() {
global $wp_query;
// If we've already issued a 404, bail.
if ( is_404() )
return;
// Never 404 for the admin, robots, or if we found posts.
if ( is_admin() || is_robots() || $wp_query->posts ) {
status_header( 200 );
return;
}
// We will 404 for paged queries, as no posts were found.
if ( ! is_paged() ) {
// Don't 404 for authors without posts as long as they matched an author on this site.
$author = get_query_var( 'author' );
if ( is_author() && is_numeric( $author ) && $author > 0 && is_user_member_of_blog( $author ) ) {
status_header( 200 );
return;
}
// Don't 404 for these queries if they matched an object.
if ( ( is_tag() || is_category() || is_tax() || is_post_type_archive() ) && get_queried_object() ) {
status_header( 200 );
return;
}
// Don't 404 for these queries either.
if ( is_home() || is_search() ) {
status_header( 200 );
return;
}
}
// Guess it's time to 404.
$wp_query->set_404();
status_header( 404 );
nocache_headers();
}
/**
* Sets up all of the variables required by the WordPress environment.
*
* The action 'wp' has one parameter that references the WP object. It
* allows for accessing the properties and methods to further manipulate the
* object.
*
* @since 2.0.0
*
* @param string|array $query_args Passed to {@link parse_request()}
*/
function main($query_args = '') {
$this->init();
$this->parse_request($query_args);
$this->send_headers();
$this->query_posts();
$this->handle_404();
$this->register_globals();
/**
* Fires once the WordPress environment has been set up.
*
* @since 2.1.0
*
* @param WP &$this Current WordPress environment instance (passed by reference).
*/
do_action_ref_array( 'wp', array( &$this ) );
}
}
/**
* Helper class to remove the need to use eval to replace $matches[] in query strings.
*
* @since 2.9.0
*/
class WP_MatchesMapRegex {
/**
* store for matches
*
* @access private
* @var array
*/
var $_matches;
/**
* store for mapping result
*
* @access public
* @var string
*/
var $output;
/**
* subject to perform mapping on (query string containing $matches[] references
*
* @access private
* @var string
*/
var $_subject;
/**
* regexp pattern to match $matches[] references
*
* @var string
*/
var $_pattern = '(\$matches\[[1-9]+[0-9]*\])'; // magic number
/**
* constructor
*
* @param string $subject subject if regex
* @param array $matches data to use in map
* @return self
*/
function WP_MatchesMapRegex($subject, $matches) {
$this->_subject = $subject;
$this->_matches = $matches;
$this->output = $this->_map();
}
/**
* Substitute substring matches in subject.
*
* static helper function to ease use
*
* @access public
* @param string $subject subject
* @param array $matches data used for substitution
* @return string
*/
public static function apply($subject, $matches) {
$oSelf = new WP_MatchesMapRegex($subject, $matches);
return $oSelf->output;
}
/**
* do the actual mapping
*
* @access private
* @return string
*/
function _map() {
$callback = array($this, 'callback');
return preg_replace_callback($this->_pattern, $callback, $this->_subject);
}
/**
* preg_replace_callback hook
*
* @access public
* @param array $matches preg_replace regexp matches
* @return string
*/
function callback($matches) {
$index = intval(substr($matches[0], 9, -1));
return ( isset( $this->_matches[$index] ) ? urlencode($this->_matches[$index]) : '' );
}
}
| PHP |
<?php
/**
* Comment template functions
*
* These functions are meant to live inside of the WordPress loop.
*
* @package WordPress
* @subpackage Template
*/
/**
* Retrieve the author of the current comment.
*
* If the comment has an empty comment_author field, then 'Anonymous' person is
* assumed.
*
* @since 1.5.0
*
* @param int $comment_ID Optional. The ID of the comment for which to retrieve the author. Default current comment.
* @return string The comment author
*/
function get_comment_author( $comment_ID = 0 ) {
$comment = get_comment( $comment_ID );
if ( empty( $comment->comment_author ) ) {
if ( $comment->user_id && $user = get_userdata( $comment->user_id ) )
$author = $user->display_name;
else
$author = __('Anonymous');
} else {
$author = $comment->comment_author;
}
/**
* Filter the returned comment author name.
*
* @since 1.5.0
*
* @param string $author The comment author's username.
*/
return apply_filters( 'get_comment_author', $author );
}
/**
* Displays the author of the current comment.
*
* @since 0.71
*
* @param int $comment_ID Optional. The ID of the comment for which to print the author. Default current comment.
*/
function comment_author( $comment_ID = 0 ) {
$author = get_comment_author( $comment_ID );
/**
* Filter the comment author's name for display.
*
* @since 1.2.0
*
* @param string $author The comment author's username.
*/
$author = apply_filters( 'comment_author', $author );
echo $author;
}
/**
* Retrieve the email of the author of the current comment.
*
* @since 1.5.0
*
* @param int $comment_ID Optional. The ID of the comment for which to get the author's email. Default current comment.
* @return string The current comment author's email
*/
function get_comment_author_email( $comment_ID = 0 ) {
$comment = get_comment( $comment_ID );
/**
* Filter the comment author's returned email address.
*
* @since 1.5.0
*
* @param string $comment_author_email The comment author's email address.
*/
return apply_filters( 'get_comment_author_email', $comment->comment_author_email );
}
/**
* Display the email of the author of the current global $comment.
*
* Care should be taken to protect the email address and assure that email
* harvesters do not capture your commentors' email address. Most assume that
* their email address will not appear in raw form on the blog. Doing so will
* enable anyone, including those that people don't want to get the email
* address and use it for their own means good and bad.
*
* @since 0.71
*
* @param int $comment_ID Optional. The ID of the comment for which to print the author's email. Default current comment.
*/
function comment_author_email( $comment_ID = 0 ) {
$author_email = get_comment_author_email( $comment_ID );
/**
* Filter the comment author's email for display.
*
* @since 1.2.0
*
* @param string $author_email The comment author's email address.
*/
echo apply_filters( 'author_email', $author_email );
}
/**
* Display the html email link to the author of the current comment.
*
* Care should be taken to protect the email address and assure that email
* harvesters do not capture your commentors' email address. Most assume that
* their email address will not appear in raw form on the blog. Doing so will
* enable anyone, including those that people don't want to get the email
* address and use it for their own means good and bad.
*
* @since 0.71
*
* @param string $linktext Optional. Text to display instead of the comment author's email address.
* Default empty.
* @param string $before Optional. Text or HTML to display before the email link. Default empty.
* @param string $after Optional. Text or HTML to display after the email link. Default empty.
*/
function comment_author_email_link( $linktext = '', $before = '', $after = '' ) {
if ( $link = get_comment_author_email_link( $linktext, $before, $after ) )
echo $link;
}
/**
* Return the html email link to the author of the current comment.
*
* Care should be taken to protect the email address and assure that email
* harvesters do not capture your commentors' email address. Most assume that
* their email address will not appear in raw form on the blog. Doing so will
* enable anyone, including those that people don't want to get the email
* address and use it for their own means good and bad.
*
* @global object $comment The current Comment row object.
*
* @since 2.7.0
*
* @param string $linktext Optional. Text to display instead of the comment author's email address.
* Default empty.
* @param string $before Optional. Text or HTML to display before the email link. Default empty.
* @param string $after Optional. Text or HTML to display after the email link. Default empty.
*/
function get_comment_author_email_link( $linktext = '', $before = '', $after = '' ) {
global $comment;
/**
* Filter the comment author's email for display.
*
* Care should be taken to protect the email address and assure that email
* harvesters do not capture your commenters' email address.
*
* @since 1.2.0
*
* @param string $comment_author_email The comment author's email address.
*/
$email = apply_filters( 'comment_email', $comment->comment_author_email );
if ((!empty($email)) && ($email != '@')) {
$display = ($linktext != '') ? $linktext : $email;
$return = $before;
$return .= "<a href='mailto:$email'>$display</a>";
$return .= $after;
return $return;
} else {
return '';
}
}
/**
* Retrieve the HTML link to the URL of the author of the current comment.
*
* Both get_comment_author_url() and get_comment_author() rely on get_comment(),
* which falls back to the global comment variable if the $comment_ID argument is empty.
*
* @since 1.5.0
*
* @param int $comment_ID ID of the comment for which to get the author's link.
* Default current comment.
* @return string The comment author name or HTML link for author's URL.
*/
function get_comment_author_link( $comment_ID = 0 ) {
$url = get_comment_author_url( $comment_ID );
$author = get_comment_author( $comment_ID );
if ( empty( $url ) || 'http://' == $url )
$return = $author;
else
$return = "<a href='$url' rel='external nofollow' class='url'>$author</a>";
/**
* Filter the comment author's link for display.
*
* @since 1.5.0
*
* @param string $return The HTML-formatted comment author link.
* Empty for an invalid URL.
*/
return apply_filters( 'get_comment_author_link', $return );
}
/**
* Display the html link to the url of the author of the current comment.
*
* @since 0.71
*
* @see get_comment_author_link() Echoes result
*
* @param int $comment_ID ID of the comment for which to print the author's
* link. Default current comment.
*/
function comment_author_link( $comment_ID = 0 ) {
echo get_comment_author_link( $comment_ID );
}
/**
* Retrieve the IP address of the author of the current comment.
*
* @since 1.5.0
*
* @param int $comment_ID ID of the comment for which to get the author's IP
* address. Default current comment.
* @return string Comment author's IP address.
*/
function get_comment_author_IP( $comment_ID = 0 ) {
$comment = get_comment( $comment_ID );
/**
* Filter the comment author's returned IP address.
*
* @since 1.5.0
*
* @param string $comment_author_IP The comment author's IP address.
*/
return apply_filters( 'get_comment_author_IP', $comment->comment_author_IP );
}
/**
* Display the IP address of the author of the current comment.
*
* @since 0.71
*
* @param int $comment_ID ID of the comment for which to print the author's IP
* address. Default current comment.
*/
function comment_author_IP( $comment_ID = 0 ) {
echo get_comment_author_IP( $comment_ID );
}
/**
* Retrieve the url of the author of the current comment.
*
* @since 1.5.0
*
* @param int $comment_ID ID of the comment for which to get the author's URL.
* Default current comment.
* @return string
*/
function get_comment_author_url( $comment_ID = 0 ) {
$comment = get_comment( $comment_ID );
$url = ('http://' == $comment->comment_author_url) ? '' : $comment->comment_author_url;
$url = esc_url( $url, array('http', 'https') );
/**
* Filter the comment author's URL.
*
* @since 1.5.0
*
* @param string $url The comment author's URL.
*/
return apply_filters( 'get_comment_author_url', $url );
}
/**
* Display the url of the author of the current comment.
*
* @since 0.71
*
* @param int $comment_ID ID of the comment for which to print the author's URL.
* Default current comment.
*/
function comment_author_url( $comment_ID = 0 ) {
$author_url = get_comment_author_url( $comment_ID );
/**
* Filter the comment author's URL for display.
*
* @since 1.2.0
*
* @param string $author_url The comment author's URL.
*/
echo apply_filters( 'comment_url', $author_url );
}
/**
* Retrieves the HTML link of the url of the author of the current comment.
*
* $linktext parameter is only used if the URL does not exist for the comment
* author. If the URL does exist then the URL will be used and the $linktext
* will be ignored.
*
* Encapsulate the HTML link between the $before and $after. So it will appear
* in the order of $before, link, and finally $after.
*
* @since 1.5.0
*
* @param string $linktext Optional. The text to display instead of the comment
* author's email address. Default empty.
* @param string $before Optional. The text or HTML to display before the email link.
* Default empty.
* @param string $after Optional. The text or HTML to display after the email link.
* Default empty.
* @return string The HTML link between the $before and $after parameters.
*/
function get_comment_author_url_link( $linktext = '', $before = '', $after = '' ) {
$url = get_comment_author_url();
$display = ($linktext != '') ? $linktext : $url;
$display = str_replace( 'http://www.', '', $display );
$display = str_replace( 'http://', '', $display );
if ( '/' == substr($display, -1) )
$display = substr($display, 0, -1);
$return = "$before<a href='$url' rel='external'>$display</a>$after";
/**
* Filter the comment author's returned URL link.
*
* @since 1.5.0
*
* @param string $return The HTML-formatted comment author URL link.
*/
return apply_filters( 'get_comment_author_url_link', $return );
}
/**
* Displays the HTML link of the url of the author of the current comment.
*
* @since 0.71
*
* @param string $linktext Optional. Text to display instead of the comment author's
* email address. Default empty.
* @param string $before Optional. Text or HTML to display before the email link.
* Default empty.
* @param string $after Optional. Text or HTML to display after the email link.
* Default empty.
*/
function comment_author_url_link( $linktext = '', $before = '', $after = '' ) {
echo get_comment_author_url_link( $linktext, $before, $after );
}
/**
* Generates semantic classes for each comment element.
*
* @since 2.7.0
*
* @param string|array $class Optional. One or more classes to add to the class list.
* Default empty.
* @param int $comment_id Comment ID. Default current comment.
* @param int|WP_Post $post_id Post ID or WP_Post object. Default current post.
* @param bool $echo Optional. Whether to cho or return the output.
* Default true.
*/
function comment_class( $class = '', $comment_id = null, $post_id = null, $echo = true ) {
// Separates classes with a single space, collates classes for comment DIV
$class = 'class="' . join( ' ', get_comment_class( $class, $comment_id, $post_id ) ) . '"';
if ( $echo)
echo $class;
else
return $class;
}
/**
* Returns the classes for the comment div as an array.
*
* @since 2.7.0
*
* @param string|array $class Optional. One or more classes to add to the class list. Default empty.
* @param int $comment_id Comment ID. Default current comment.
* @param int|WP_Post $post_id Post ID or WP_Post object. Default current post.
* @return array An array of classes.
*/
function get_comment_class( $class = '', $comment_id = null, $post_id = null ) {
global $comment_alt, $comment_depth, $comment_thread_alt;
$comment = get_comment($comment_id);
$classes = array();
// Get the comment type (comment, trackback),
$classes[] = ( empty( $comment->comment_type ) ) ? 'comment' : $comment->comment_type;
// If the comment author has an id (registered), then print the log in name
if ( $comment->user_id > 0 && $user = get_userdata($comment->user_id) ) {
// For all registered users, 'byuser'
$classes[] = 'byuser';
$classes[] = 'comment-author-' . sanitize_html_class($user->user_nicename, $comment->user_id);
// For comment authors who are the author of the post
if ( $post = get_post($post_id) ) {
if ( $comment->user_id === $post->post_author )
$classes[] = 'bypostauthor';
}
}
if ( empty($comment_alt) )
$comment_alt = 0;
if ( empty($comment_depth) )
$comment_depth = 1;
if ( empty($comment_thread_alt) )
$comment_thread_alt = 0;
if ( $comment_alt % 2 ) {
$classes[] = 'odd';
$classes[] = 'alt';
} else {
$classes[] = 'even';
}
$comment_alt++;
// Alt for top-level comments
if ( 1 == $comment_depth ) {
if ( $comment_thread_alt % 2 ) {
$classes[] = 'thread-odd';
$classes[] = 'thread-alt';
} else {
$classes[] = 'thread-even';
}
$comment_thread_alt++;
}
$classes[] = "depth-$comment_depth";
if ( !empty($class) ) {
if ( !is_array( $class ) )
$class = preg_split('#\s+#', $class);
$classes = array_merge($classes, $class);
}
$classes = array_map('esc_attr', $classes);
/**
* Filter the returned CSS classes for the current comment.
*
* @since 2.7.0
*
* @param array $classes An array of comment classes.
* @param string $class A comma-separated list of additional classes added to the list.
* @param int $comment_id The comment id.
* @param int|WP_Post $post_id The post ID or WP_Post object.
*/
return apply_filters( 'comment_class', $classes, $class, $comment_id, $post_id );
}
/**
* Retrieve the comment date of the current comment.
*
* @since 1.5.0
*
* @param string $d Optional. The format of the date. Default user's setting.
* @param int $comment_ID ID of the comment for which to get the date. Default current comment.
* @return string The comment's date.
*/
function get_comment_date( $d = '', $comment_ID = 0 ) {
$comment = get_comment( $comment_ID );
if ( '' == $d )
$date = mysql2date(get_option('date_format'), $comment->comment_date);
else
$date = mysql2date($d, $comment->comment_date);
/**
* Filter the returned comment date.
*
* @since 1.5.0
*
* @param string|int $date Formatted date string or Unix timestamp.
* @param string $d The format of the date.
* @param object $comment The comment object.
*/
return apply_filters( 'get_comment_date', $date, $d, $comment );
}
/**
* Display the comment date of the current comment.
*
* @since 0.71
*
* @param string $d Optional. The format of the date. Default user's settings.
* @param int $comment_ID ID of the comment for which to print the date. Default current comment.
*/
function comment_date( $d = '', $comment_ID = 0 ) {
echo get_comment_date( $d, $comment_ID );
}
/**
* Retrieve the excerpt of the current comment.
*
* Will cut each word and only output the first 20 words with '…' at the end.
* If the word count is less than 20, then no truncating is done and no '…'
* will appear.
*
* @since 1.5.0
*
* @param int $comment_ID ID of the comment for which to get the excerpt.
* Default current comment.
* @return string The maybe truncated comment with 20 words or less.
*/
function get_comment_excerpt( $comment_ID = 0 ) {
$comment = get_comment( $comment_ID );
$comment_text = strip_tags($comment->comment_content);
$blah = explode(' ', $comment_text);
if (count($blah) > 20) {
$k = 20;
$use_dotdotdot = 1;
} else {
$k = count($blah);
$use_dotdotdot = 0;
}
$excerpt = '';
for ($i=0; $i<$k; $i++) {
$excerpt .= $blah[$i] . ' ';
}
$excerpt .= ($use_dotdotdot) ? '…' : '';
/**
* Filter the retrieved comment excerpt.
*
* @since 1.5.0
*
* @param string $excerpt The comment excerpt text.
*/
return apply_filters( 'get_comment_excerpt', $excerpt );
}
/**
* Display the excerpt of the current comment.
*
* @since 1.2.0
*
* @param int $comment_ID ID of the comment for which to print the excerpt.
* Default current comment.
*/
function comment_excerpt( $comment_ID = 0 ) {
$comment_excerpt = get_comment_excerpt($comment_ID);
/**
* Filter the comment excerpt for display.
*
* @since 1.2.0
*
* @param string $comment_excerpt The comment excerpt text.
*/
echo apply_filters( 'comment_excerpt', $comment_excerpt );
}
/**
* Retrieve the comment id of the current comment.
*
* @since 1.5.0
*
* @return int The comment ID.
*/
function get_comment_ID() {
global $comment;
/**
* Filter the returned comment ID.
*
* @since 1.5.0
*
* @param int $comment_ID The current comment ID.
*/
return apply_filters( 'get_comment_ID', $comment->comment_ID );
}
/**
* Display the comment id of the current comment.
*
* @since 0.71
*/
function comment_ID() {
echo get_comment_ID();
}
/**
* Retrieve the link to a given comment.
*
* @since 1.5.0
*
* @see get_page_of_comment()
*
* @param mixed $comment Comment to retrieve. Default current comment.
* @param array $args Optional. An array of arguments to override the defaults.
* @return string The permalink to the given comment.
*/
function get_comment_link( $comment = null, $args = array() ) {
global $wp_rewrite, $in_comment_loop;
$comment = get_comment($comment);
// Backwards compat
if ( ! is_array( $args ) ) {
$args = array( 'page' => $args );
}
$defaults = array( 'type' => 'all', 'page' => '', 'per_page' => '', 'max_depth' => '' );
$args = wp_parse_args( $args, $defaults );
if ( '' === $args['per_page'] && get_option('page_comments') )
$args['per_page'] = get_option('comments_per_page');
if ( empty($args['per_page']) ) {
$args['per_page'] = 0;
$args['page'] = 0;
}
if ( $args['per_page'] ) {
if ( '' == $args['page'] )
$args['page'] = ( !empty($in_comment_loop) ) ? get_query_var('cpage') : get_page_of_comment( $comment->comment_ID, $args );
if ( $wp_rewrite->using_permalinks() )
$link = user_trailingslashit( trailingslashit( get_permalink( $comment->comment_post_ID ) ) . 'comment-page-' . $args['page'], 'comment' );
else
$link = add_query_arg( 'cpage', $args['page'], get_permalink( $comment->comment_post_ID ) );
} else {
$link = get_permalink( $comment->comment_post_ID );
}
$link = $link . '#comment-' . $comment->comment_ID;
/**
* Filter the returned single comment permalink.
*
* @since 2.8.0
*
* @see get_page_of_comment()
*
* @param string $link The comment permalink with '#comment-$id' appended.
* @param object $comment The current comment object.
* @param array $args An array of arguments to override the defaults.
*/
return apply_filters( 'get_comment_link', $link, $comment, $args );
}
/**
* Retrieve the link to the current post comments.
*
* @since 1.5.0
*
* @param int|WP_Post $post_id Post ID or WP_Post object. Default current post.
* @return string The link to the comments.
*/
function get_comments_link( $post_id = 0 ) {
$comments_link = get_permalink( $post_id ) . '#comments';
/**
* Filter the returned post comments permalink.
*
* @since 3.6.0
*
* @param string $comments_link Post comments permalink with '#comments' appended.
* @param int|WP_Post $post_id Post ID or WP_Post object.
*/
return apply_filters( 'get_comments_link', $comments_link, $post_id );
}
/**
* Display the link to the current post comments.
*
* @since 0.71
*
* @param string $deprecated Not Used.
* @param bool $deprecated_2 Not Used.
*/
function comments_link( $deprecated = '', $deprecated_2 = '' ) {
if ( !empty( $deprecated ) )
_deprecated_argument( __FUNCTION__, '0.72' );
if ( !empty( $deprecated_2 ) )
_deprecated_argument( __FUNCTION__, '1.3' );
echo esc_url( get_comments_link() );
}
/**
* Retrieve the amount of comments a post has.
*
* @since 1.5.0
*
* @param int|WP_Post $post_id Post ID or WP_Post object. Default current post.
* @return int The number of comments a post has.
*/
function get_comments_number( $post_id = 0 ) {
$post_id = absint( $post_id );
if ( !$post_id )
$post_id = get_the_ID();
$post = get_post($post_id);
if ( ! isset($post->comment_count) )
$count = 0;
else
$count = $post->comment_count;
/**
* Filter the returned comment count for a post.
*
* @since 1.5.0
*
* @param int $count Nnumber of comments a post has.
* @param int|WP_Post $post_id Post ID or WP_Post object.
*/
return apply_filters( 'get_comments_number', $count, $post_id );
}
/**
* Display the language string for the number of comments the current post has.
*
* @since 0.71
*
* @param string $zero Optional. Text for no comments. Default false.
* @param string $one Optional. Text for one comment. Default false.
* @param string $more Optional. Text for more than one comment. Default false.
* @param string $deprecated Not used.
*/
function comments_number( $zero = false, $one = false, $more = false, $deprecated = '' ) {
if ( !empty( $deprecated ) )
_deprecated_argument( __FUNCTION__, '1.3' );
$number = get_comments_number();
if ( $number > 1 )
$output = str_replace('%', number_format_i18n($number), ( false === $more ) ? __('% Comments') : $more);
elseif ( $number == 0 )
$output = ( false === $zero ) ? __('No Comments') : $zero;
else // must be one
$output = ( false === $one ) ? __('1 Comment') : $one;
/**
* Filter the comments count for display.
*
* @since 1.5.0
*
* @see _n()
*
* @param string $output A translatable string formatted based on whether the count
* is equal to 0, 1, or 1+.
* @param int $number The number of post comments.
*/
echo apply_filters( 'comments_number', $output, $number );
}
/**
* Retrieve the text of the current comment.
*
* @since 1.5.0
*
* @see Walker_Comment::comment()
*
* @param int $comment_ID ID of the comment for which to get the text. Default current comment.
* @param array $args Optional. An array of arguments. Default empty.
* @return string The comment content.
*/
function get_comment_text( $comment_ID = 0, $args = array() ) {
$comment = get_comment( $comment_ID );
/**
* Filter the text of a comment.
*
* @since 1.5.0
*
* @see Walker_Comment::comment()
*
* @param string $comment_content Text of the comment.
* @param object $comment The comment object.
* @param array $args An array of arguments.
*/
return apply_filters( 'get_comment_text', $comment->comment_content, $comment, $args );
}
/**
* Display the text of the current comment.
*
* @since 0.71
*
* @see Walker_Comment::comment()
*
* @param int $comment_ID ID of the comment for which to print the text. Default 0.
* @param array $args Optional. An array of arguments. Default empty array. Default empty.
*/
function comment_text( $comment_ID = 0, $args = array() ) {
$comment = get_comment( $comment_ID );
$comment_text = get_comment_text( $comment_ID , $args );
/**
* Filter the text of a comment to be displayed.
*
* @since 1.2.0
*
* @see Walker_Comment::comment()
*
* @param string $comment_text Text of the current comment.
* @param object $comment The comment object.
* @param array $args An array of arguments.
*/
echo apply_filters( 'comment_text', $comment_text, $comment, $args );
}
/**
* Retrieve the comment time of the current comment.
*
* @since 1.5.0
*
* @param string $d Optional. The format of the time. Default user's settings.
* @param bool $gmt Optional. Whether to use the GMT date. Default false.
* @param bool $translate Optional. Whether to translate the time (for use in feeds).
* Default true.
* @return string The formatted time.
*/
function get_comment_time( $d = '', $gmt = false, $translate = true ) {
global $comment;
$comment_date = $gmt ? $comment->comment_date_gmt : $comment->comment_date;
if ( '' == $d )
$date = mysql2date(get_option('time_format'), $comment_date, $translate);
else
$date = mysql2date($d, $comment_date, $translate);
/**
* Filter the returned comment time.
*
* @since 1.5.0
*
* @param string|int $date The comment time, formatted as a date string or Unix timestamp.
* @param string $d Date format.
* @param bool $gmt Whether the GMT date is in use.
* @param bool $translate Whether the time is translated.
* @param object $comment The comment object.
*/
return apply_filters( 'get_comment_time', $date, $d, $gmt, $translate, $comment );
}
/**
* Display the comment time of the current comment.
*
* @since 0.71
*
* @param string $d Optional. The format of the time. Default user's settings.
*/
function comment_time( $d = '' ) {
echo get_comment_time($d);
}
/**
* Retrieve the comment type of the current comment.
*
* @since 1.5.0
*
* @param int $comment_ID ID of the comment for which to get the type. Default current comment.
* @return string The comment type.
*/
function get_comment_type( $comment_ID = 0 ) {
$comment = get_comment( $comment_ID );
if ( '' == $comment->comment_type )
$comment->comment_type = 'comment';
/**
* Filter the returned comment type.
*
* @since 1.5.0
*
* @param string $comment_type The type of comment, such as 'comment', 'pingback', or 'trackback'.
*/
return apply_filters( 'get_comment_type', $comment->comment_type );
}
/**
* Display the comment type of the current comment.
*
* @since 0.71
*
* @param string $commenttxt Optional. String to display for comment type. Default false.
* @param string $trackbacktxt Optional. String to display for trackback type. Default false.
* @param string $pingbacktxt Optional. String to display for pingback type. Default false.
*/
function comment_type( $commenttxt = false, $trackbacktxt = false, $pingbacktxt = false ) {
if ( false === $commenttxt ) $commenttxt = _x( 'Comment', 'noun' );
if ( false === $trackbacktxt ) $trackbacktxt = __( 'Trackback' );
if ( false === $pingbacktxt ) $pingbacktxt = __( 'Pingback' );
$type = get_comment_type();
switch( $type ) {
case 'trackback' :
echo $trackbacktxt;
break;
case 'pingback' :
echo $pingbacktxt;
break;
default :
echo $commenttxt;
}
}
/**
* Retrieve The current post's trackback URL.
*
* There is a check to see if permalink's have been enabled and if so, will
* retrieve the pretty path. If permalinks weren't enabled, the ID of the
* current post is used and appended to the correct page to go to.
*
* @since 1.5.0
*
* @return string The trackback URL after being filtered.
*/
function get_trackback_url() {
if ( '' != get_option('permalink_structure') )
$tb_url = trailingslashit(get_permalink()) . user_trailingslashit('trackback', 'single_trackback');
else
$tb_url = get_option('siteurl') . '/wp-trackback.php?p=' . get_the_ID();
/**
* Filter the returned trackback URL.
*
* @since 2.2.0
*
* @param string $tb_url The trackback URL.
*/
return apply_filters( 'trackback_url', $tb_url );
}
/**
* Display the current post's trackback URL.
*
* @since 0.71
*
* @param bool $deprecated_echo Not used.
* @return void|string Should only be used to echo the trackback URL, use get_trackback_url()
* for the result instead.
*/
function trackback_url( $deprecated_echo = true ) {
if ( $deprecated_echo !== true )
_deprecated_argument( __FUNCTION__, '2.5', __('Use <code>get_trackback_url()</code> instead if you do not want the value echoed.') );
if ( $deprecated_echo )
echo get_trackback_url();
else
return get_trackback_url();
}
/**
* Generate and display the RDF for the trackback information of current post.
*
* Deprecated in 3.0.0, and restored in 3.0.1.
*
* @since 0.71
*
* @param int $deprecated Not used (Was $timezone = 0).
*/
function trackback_rdf( $deprecated = '' ) {
if ( ! empty( $deprecated ) ) {
_deprecated_argument( __FUNCTION__, '2.5' );
}
if ( isset( $_SERVER['HTTP_USER_AGENT'] ) && false !== stripos( $_SERVER['HTTP_USER_AGENT'], 'W3C_Validator' ) ) {
return;
}
echo '<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">
<rdf:Description rdf:about="';
the_permalink();
echo '"'."\n";
echo ' dc:identifier="';
the_permalink();
echo '"'."\n";
echo ' dc:title="'.str_replace('--', '--', wptexturize(strip_tags(get_the_title()))).'"'."\n";
echo ' trackback:ping="'.get_trackback_url().'"'." />\n";
echo '</rdf:RDF>';
}
/**
* Whether the current post is open for comments.
*
* @since 1.5.0
*
* @param int|WP_Post $post_id Post ID or WP_Post object. Default current post.
* @return bool True if the comments are open.
*/
function comments_open( $post_id = null ) {
$_post = get_post($post_id);
$open = ( 'open' == $_post->comment_status );
/**
* Filter whether the current post is open for comments.
*
* @since 2.5.0
*
* @param bool $open Whether the current post is open for comments.
* @param int|WP_Post $post_id The post ID or WP_Post object.
*/
return apply_filters( 'comments_open', $open, $post_id );
}
/**
* Whether the current post is open for pings.
*
* @since 1.5.0
*
* @param int|WP_Post $post_id Post ID or WP_Post object. Default current post.
* @return bool True if pings are accepted
*/
function pings_open( $post_id = null ) {
$_post = get_post($post_id);
$open = ( 'open' == $_post->ping_status );
/**
* Filter whether the current post is open for pings.
*
* @since 2.5.0
*
* @param bool $open Whether the current post is open for pings.
* @param int|WP_Post $post_id The post ID or WP_Post object.
*/
return apply_filters( 'pings_open', $open, $post_id );
}
/**
* Display form token for unfiltered comments.
*
* Will only display nonce token if the current user has permissions for
* unfiltered html. Won't display the token for other users.
*
* The function was backported to 2.0.10 and was added to versions 2.1.3 and
* above. Does not exist in versions prior to 2.0.10 in the 2.0 branch and in
* the 2.1 branch, prior to 2.1.3. Technically added in 2.2.0.
*
* Backported to 2.0.10.
*
* @since 2.1.3
*/
function wp_comment_form_unfiltered_html_nonce() {
$post = get_post();
$post_id = $post ? $post->ID : 0;
if ( current_user_can( 'unfiltered_html' ) ) {
wp_nonce_field( 'unfiltered-html-comment_' . $post_id, '_wp_unfiltered_html_comment_disabled', false );
echo "<script>(function(){if(window===window.parent){document.getElementById('_wp_unfiltered_html_comment_disabled').name='_wp_unfiltered_html_comment';}})();</script>\n";
}
}
/**
* Load the comment template specified in $file.
*
* Will not display the comments template if not on single post or page, or if
* the post does not have comments.
*
* Uses the WordPress database object to query for the comments. The comments
* are passed through the 'comments_array' filter hook with the list of comments
* and the post ID respectively.
*
* The $file path is passed through a filter hook called, 'comments_template'
* which includes the TEMPLATEPATH and $file combined. Tries the $filtered path
* first and if it fails it will require the default comment template from the
* default theme. If either does not exist, then the WordPress process will be
* halted. It is advised for that reason, that the default theme is not deleted.
*
* @todo Document globals
* @uses $withcomments Will not try to get the comments if the post has none.
*
* @since 1.5.0
*
* @param string $file Optional. The file to load. Default '/comments.php'.
* @param bool $separate_comments Optional. Whether to separate the comments by comment type.
* Default false.
* @return null Returns null if no comments appear.
*/
function comments_template( $file = '/comments.php', $separate_comments = false ) {
global $wp_query, $withcomments, $post, $wpdb, $id, $comment, $user_login, $user_ID, $user_identity, $overridden_cpage;
if ( !(is_single() || is_page() || $withcomments) || empty($post) )
return;
if ( empty($file) )
$file = '/comments.php';
$req = get_option('require_name_email');
/*
* Comment author information fetched from the comment cookies.
* Uuses wp_get_current_commenter().
*/
$commenter = wp_get_current_commenter();
/*
* The name of the current comment author escaped for use in attributes.
* Escaped by sanitize_comment_cookies().
*/
$comment_author = $commenter['comment_author'];
/*
* The email address of the current comment author escaped for use in attributes.
* Escaped by sanitize_comment_cookies().
*/
$comment_author_email = $commenter['comment_author_email'];
/*
* The url of the current comment author escaped for use in attributes.
*/
$comment_author_url = esc_url($commenter['comment_author_url']);
/** @todo Use API instead of SELECTs. */
if ( $user_ID) {
$comments = $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND (comment_approved = '1' OR ( user_id = %d AND comment_approved = '0' ) ) ORDER BY comment_date_gmt", $post->ID, $user_ID));
} else if ( empty($comment_author) ) {
$comments = get_comments( array('post_id' => $post->ID, 'status' => 'approve', 'order' => 'ASC') );
} else {
$comments = $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND ( comment_approved = '1' OR ( comment_author = %s AND comment_author_email = %s AND comment_approved = '0' ) ) ORDER BY comment_date_gmt", $post->ID, wp_specialchars_decode($comment_author,ENT_QUOTES), $comment_author_email));
}
/**
* Filter the comments array.
*
* @since 2.1.0
*
* @param array $comments Array of comments supplied to the comments template.
* @param int $post_ID Post ID.
*/
$wp_query->comments = apply_filters( 'comments_array', $comments, $post->ID );
$comments = &$wp_query->comments;
$wp_query->comment_count = count($wp_query->comments);
update_comment_cache($wp_query->comments);
if ( $separate_comments ) {
$wp_query->comments_by_type = separate_comments($comments);
$comments_by_type = &$wp_query->comments_by_type;
}
$overridden_cpage = false;
if ( '' == get_query_var('cpage') && get_option('page_comments') ) {
set_query_var( 'cpage', 'newest' == get_option('default_comments_page') ? get_comment_pages_count() : 1 );
$overridden_cpage = true;
}
if ( !defined('COMMENTS_TEMPLATE') )
define('COMMENTS_TEMPLATE', true);
$theme_template = STYLESHEETPATH . $file;
/**
* Filter the path to the theme template file used for the comments template.
*
* @since 1.5.1
*
* @param string $theme_template The path to the theme template file.
*/
$include = apply_filters( 'comments_template', $theme_template );
if ( file_exists( $include ) )
require( $include );
elseif ( file_exists( TEMPLATEPATH . $file ) )
require( TEMPLATEPATH . $file );
else // Backward compat code will be removed in a future release
require( ABSPATH . WPINC . '/theme-compat/comments.php');
}
/**
* Display the JS popup script to show a comment.
*
* If the $file parameter is empty, then the home page is assumed. The defaults
* for the window are 400px by 400px.
*
* For the comment link popup to work, this function has to be called or the
* normal comment link will be assumed.
*
* @global string $wpcommentspopupfile The URL to use for the popup window.
* @global int $wpcommentsjavascript Whether to use JavaScript. Set when function is called.
*
* @since 0.71
*
* @param int $width Optional. The width of the popup window. Default 400.
* @param int $height Optional. The height of the popup window. Default 400.
* @param string $file Optional. Sets the location of the popup window.
*/
function comments_popup_script( $width = 400, $height = 400, $file = '' ) {
global $wpcommentspopupfile, $wpcommentsjavascript;
if (empty ($file)) {
$wpcommentspopupfile = ''; // Use the index.
} else {
$wpcommentspopupfile = $file;
}
$wpcommentsjavascript = 1;
$javascript = "<script type='text/javascript'>\nfunction wpopen (macagna) {\n window.open(macagna, '_blank', 'width=$width,height=$height,scrollbars=yes,status=yes');\n}\n</script>\n";
echo $javascript;
}
/**
* Displays the link to the comments popup window for the current post ID.
*
* Is not meant to be displayed on single posts and pages. Should be used
* on the lists of posts
*
* @global string $wpcommentspopupfile The URL to use for the popup window.
* @global int $wpcommentsjavascript Whether to use JavaScript. Set when function is called.
*
* @since 0.71
*
* @param string $zero Optional. String to display when no comments. Default false.
* @param string $one Optional. String to display when only one comment is available.
* Default false.
* @param string $more Optional. String to display when there are more than one comment.
* Default false.
* @param string $css_class Optional. CSS class to use for comments. Default empty.
* @param string $none Optional. String to display when comments have been turned off.
* Default false.
* @return null Returns null on single posts and pages.
*/
function comments_popup_link( $zero = false, $one = false, $more = false, $css_class = '', $none = false ) {
global $wpcommentspopupfile, $wpcommentsjavascript;
$id = get_the_ID();
if ( false === $zero ) $zero = __( 'No Comments' );
if ( false === $one ) $one = __( '1 Comment' );
if ( false === $more ) $more = __( '% Comments' );
if ( false === $none ) $none = __( 'Comments Off' );
$number = get_comments_number( $id );
if ( 0 == $number && !comments_open() && !pings_open() ) {
echo '<span' . ((!empty($css_class)) ? ' class="' . esc_attr( $css_class ) . '"' : '') . '>' . $none . '</span>';
return;
}
if ( post_password_required() ) {
echo __('Enter your password to view comments.');
return;
}
echo '<a href="';
if ( $wpcommentsjavascript ) {
if ( empty( $wpcommentspopupfile ) )
$home = home_url();
else
$home = get_option('siteurl');
echo $home . '/' . $wpcommentspopupfile . '?comments_popup=' . $id;
echo '" onclick="wpopen(this.href); return false"';
} else { // if comments_popup_script() is not in the template, display simple comment link
if ( 0 == $number )
echo get_permalink() . '#respond';
else
comments_link();
echo '"';
}
if ( !empty( $css_class ) ) {
echo ' class="'.$css_class.'" ';
}
$title = the_title_attribute( array('echo' => 0 ) );
$attributes = '';
/**
* Filter the comments popup link attributes for display.
*
* @since 2.5.0
*
* @param string $attributes The comments popup link attributes. Default empty.
*/
echo apply_filters( 'comments_popup_link_attributes', $attributes );
echo ' title="' . esc_attr( sprintf( __('Comment on %s'), $title ) ) . '">';
comments_number( $zero, $one, $more );
echo '</a>';
}
/**
* Retrieve HTML content for reply to comment link.
*
* @since 2.7.0
*
* @param array $args {
* Optional. Override default arguments.
*
* @type string $add_below The first part of the selector used to identify the comment to respond below.
* The resulting value is passed as the first parameter to addComment.moveForm(),
* concatenated as $add_below-$comment->comment_ID. Default 'comment'.
* @type string $respond_id The selector identifying the responding comment. Passed as the third parameter
* to addComment.moveForm(), and appended to the link URL as a hash value.
* Default 'respond'.
* @type string $reply_text The text of the Reply link. Default 'Reply'.
* @type string $login_text The text of the link to reply if logged out. Default 'Log in to Reply'.
* @type int $depth' The depth of the new comment. Must be greater than 0 and less than the value
* of the 'thread_comments_depth' option set in Settings > Discussion. Default 0.
* @type string $before The text or HTML to add before the reply link. Default empty.
* @type string $after The text or HTML to add after the reply link. Default empty.
* }
* @param int $comment Comment being replied to. Default current comment.
* @param int|WP_Post $post Post ID or WP_Post object the comment is going to be displayed on.
* Default current post.
* @return mixed Link to show comment form, if successful. False, if comments are closed.
*/
function get_comment_reply_link($args = array(), $comment = null, $post = null) {
$defaults = array(
'add_below' => 'comment',
'respond_id' => 'respond',
'reply_text' => __('Reply'),
'login_text' => __('Log in to Reply'),
'depth' => 0,
'before' => '',
'after' => ''
);
$args = wp_parse_args($args, $defaults);
if ( 0 == $args['depth'] || $args['max_depth'] <= $args['depth'] )
return;
extract($args, EXTR_SKIP);
$comment = get_comment($comment);
if ( empty($post) )
$post = $comment->comment_post_ID;
$post = get_post($post);
if ( !comments_open($post->ID) )
return false;
$link = '';
if ( get_option('comment_registration') && ! is_user_logged_in() )
$link = '<a rel="nofollow" class="comment-reply-login" href="' . esc_url( wp_login_url( get_permalink() ) ) . '">' . $login_text . '</a>';
else
$link = "<a class='comment-reply-link' href='" . esc_url( add_query_arg( 'replytocom', $comment->comment_ID ) ) . "#" . $respond_id . "' onclick='return addComment.moveForm(\"$add_below-$comment->comment_ID\", \"$comment->comment_ID\", \"$respond_id\", \"$post->ID\")'>$reply_text</a>";
/**
* Filter the comment reply link.
*
* @since 2.7.0
*
* @param string $link The HTML markup for the comment reply link.
* @param array $args An array of arguments overriding the defaults.
* @param object $comment The object of the comment being replied.
* @param WP_Post $post The WP_Post object.
*/
return apply_filters( 'comment_reply_link', $before . $link . $after, $args, $comment, $post );
}
/**
* Displays the HTML content for reply to comment link.
*
* @since 2.7.0
*
* @see get_comment_reply_link()
*
* @param array $args Optional. Override default options.
* @param int $comment Comment being replied to. Default current comment.
* @param int|WP_Post $post Post ID or WP_Post object the comment is going to be displayed on.
* Default current post.
* @return mixed Link to show comment form, if successful. False, if comments are closed.
*/
function comment_reply_link($args = array(), $comment = null, $post = null) {
echo get_comment_reply_link($args, $comment, $post);
}
/**
* Retrieve HTML content for reply to post link.
*
* @since 2.7.0
*
* @param array $args {
* Optional. Override default arguments.
*
* @type string $add_below The first part of the selector used to identify the comment to respond below.
* The resulting value is passed as the first parameter to addComment.moveForm(),
* concatenated as $add_below-$comment->comment_ID. Default is 'post'.
* @type string $respond_id The selector identifying the responding comment. Passed as the third parameter
* to addComment.moveForm(), and appended to the link URL as a hash value.
* Default 'respond'.
* @type string $reply_text Text of the Reply link. Default is 'Leave a Comment'.
* @type string $login_text Text of the link to reply if logged out. Default is 'Log in to leave a Comment'.
* @type string $before Text or HTML to add before the reply link. Default empty.
* @type string $after Text or HTML to add after the reply link. Default empty.
* }
* @param int|WP_Post $post Optional. Post ID or WP_Post object the comment is going to be displayed on.
* Default current post.
* @return string|bool|null Link to show comment form, if successful. False, if comments are closed.
*/
function get_post_reply_link($args = array(), $post = null) {
$defaults = array(
'add_below' => 'post',
'respond_id' => 'respond',
'reply_text' => __('Leave a Comment'),
'login_text' => __('Log in to leave a Comment'),
'before' => '',
'after' => '',
);
$args = wp_parse_args($args, $defaults);
extract($args, EXTR_SKIP);
$post = get_post($post);
if ( !comments_open($post->ID) )
return false;
if ( get_option('comment_registration') && ! is_user_logged_in() )
$link = '<a rel="nofollow" href="' . wp_login_url( get_permalink() ) . '">' . $login_text . '</a>';
else
$link = "<a rel='nofollow' class='comment-reply-link' href='" . get_permalink($post->ID) . "#$respond_id' onclick='return addComment.moveForm(\"$add_below-$post->ID\", \"0\", \"$respond_id\", \"$post->ID\")'>$reply_text</a>";
$formatted_link = $before . $link . $after;
/**
* Filter the formatted post comments link HTML.
*
* @since 2.7.0
*
* @param string $formatted The HTML-formatted post comments link.
* @param int|WP_Post $post The post ID or WP_Post object.
*/
return apply_filters( 'post_comments_link', $formatted_link, $post );
}
/**
* Displays the HTML content for reply to post link.
*
* @since 2.7.0
*
* @see get_post_reply_link()
*
* @param array $args Optional. Override default options,
* @param int|WP_Post $post Post ID or WP_Post object the comment is going to be displayed on.
* Default current post.
* @return string|bool|null Link to show comment form, if successful. False, if comments are closed.
*/
function post_reply_link($args = array(), $post = null) {
echo get_post_reply_link($args, $post);
}
/**
* Retrieve HTML content for cancel comment reply link.
*
* @since 2.7.0
*
* @param string $text Optional. Text to display for cancel reply link. Default empty.
*/
function get_cancel_comment_reply_link( $text = '' ) {
if ( empty($text) )
$text = __('Click here to cancel reply.');
$style = isset($_GET['replytocom']) ? '' : ' style="display:none;"';
$link = esc_html( remove_query_arg('replytocom') ) . '#respond';
$formatted_link = '<a rel="nofollow" id="cancel-comment-reply-link" href="' . $link . '"' . $style . '>' . $text . '</a>';
/**
* Filter the cancel comment reply link HTML.
*
* @since 2.7.0
*
* @param string $formatted_link The HTML-formatted cancel comment reply link.
* @param string $link Cancel comment reply link URL.
* @param string $text Cancel comment reply link text.
*/
return apply_filters( 'cancel_comment_reply_link', $formatted_link, $link, $text );
}
/**
* Display HTML content for cancel comment reply link.
*
* @since 2.7.0
*
* @param string $text Optional. Text to display for cancel reply link. Default empty.
*/
function cancel_comment_reply_link( $text = '' ) {
echo get_cancel_comment_reply_link($text);
}
/**
* Retrieve hidden input HTML for replying to comments.
*
* @since 3.0.0
*
* @param int $id Optional. Post ID. Default current post ID.
* @return string Hidden input HTML for replying to comments
*/
function get_comment_id_fields( $id = 0 ) {
if ( empty( $id ) )
$id = get_the_ID();
$replytoid = isset($_GET['replytocom']) ? (int) $_GET['replytocom'] : 0;
$result = "<input type='hidden' name='comment_post_ID' value='$id' id='comment_post_ID' />\n";
$result .= "<input type='hidden' name='comment_parent' id='comment_parent' value='$replytoid' />\n";
/**
* Filter the returned comment id fields.
*
* @since 3.0.0
*
* @param string $result The HTML-formatted hidden id field comment elements.
* @param int $id The post ID.
* @param int $replytoid The id of the comment being replied to.
*/
return apply_filters( 'comment_id_fields', $result, $id, $replytoid );
}
/**
* Output hidden input HTML for replying to comments.
*
* @since 2.7.0
*
* @param int $id Optional. Post ID. Default current post ID.
*/
function comment_id_fields( $id = 0 ) {
echo get_comment_id_fields( $id );
}
/**
* Display text based on comment reply status.
*
* Only affects users with Javascript disabled.
*
* @since 2.7.0
*
* @param string $noreplytext Optional. Text to display when not replying to a comment.
* Default false.
* @param string $replytext Optional. Text to display when replying to a comment.
* Default false. Accepts "%s" for the author of the comment
* being replied to.
* @param string $linktoparent Optional. Boolean to control making the author's name a link
* to their comment. Default true.
*/
function comment_form_title( $noreplytext = false, $replytext = false, $linktoparent = true ) {
global $comment;
if ( false === $noreplytext ) $noreplytext = __( 'Leave a Reply' );
if ( false === $replytext ) $replytext = __( 'Leave a Reply to %s' );
$replytoid = isset($_GET['replytocom']) ? (int) $_GET['replytocom'] : 0;
if ( 0 == $replytoid )
echo $noreplytext;
else {
$comment = get_comment($replytoid);
$author = ( $linktoparent ) ? '<a href="#comment-' . get_comment_ID() . '">' . get_comment_author() . '</a>' : get_comment_author();
printf( $replytext, $author );
}
}
/**
* HTML comment list class.
*
* @uses Walker
* @since 2.7.0
*/
class Walker_Comment extends Walker {
/**
* What the class handles.
*
* @see Walker::$tree_type
*
* @since 2.7.0
* @var string
*/
var $tree_type = 'comment';
/**
* DB fields to use.
*
* @see Walker::$db_fields
*
* @since 2.7.0
* @var array
*/
var $db_fields = array ('parent' => 'comment_parent', 'id' => 'comment_ID');
/**
* Start the list before the elements are added.
*
* @see Walker::start_lvl()
*
* @since 2.7.0
*
* @param string $output Passed by reference. Used to append additional content.
* @param int $depth Depth of comment.
* @param array $args Uses 'style' argument for type of HTML list.
*/
function start_lvl( &$output, $depth = 0, $args = array() ) {
$GLOBALS['comment_depth'] = $depth + 1;
switch ( $args['style'] ) {
case 'div':
break;
case 'ol':
$output .= '<ol class="children">' . "\n";
break;
default:
case 'ul':
$output .= '<ul class="children">' . "\n";
break;
}
}
/**
* End the list of items after the elements are added.
*
* @see Walker::end_lvl()
*
* @since 2.7.0
*
* @param string $output Passed by reference. Used to append additional content.
* @param int $depth Depth of comment.
* @param array $args Will only append content if style argument value is 'ol' or 'ul'.
*/
function end_lvl( &$output, $depth = 0, $args = array() ) {
$GLOBALS['comment_depth'] = $depth + 1;
switch ( $args['style'] ) {
case 'div':
break;
case 'ol':
$output .= "</ol><!-- .children -->\n";
break;
default:
case 'ul':
$output .= "</ul><!-- .children -->\n";
break;
}
}
/**
* Traverse elements to create list from elements.
*
* This function is designed to enhance Walker::display_element() to
* display children of higher nesting levels than selected inline on
* the highest depth level displayed. This prevents them being orphaned
* at the end of the comment list.
*
* Example: max_depth = 2, with 5 levels of nested content.
* 1
* 1.1
* 1.1.1
* 1.1.1.1
* 1.1.1.1.1
* 1.1.2
* 1.1.2.1
* 2
* 2.2
*
* @see Walker::display_element()
* @see wp_list_comments()
*
* @since 2.7.0
*
* @param object $element Data object.
* @param array $children_elements List of elements to continue traversing.
* @param int $max_depth Max depth to traverse.
* @param int $depth Depth of current element.
* @param array $args An array of arguments.
* @param string $output Passed by reference. Used to append additional content.
* @return null Null on failure with no changes to parameters.
*/
function display_element( $element, &$children_elements, $max_depth, $depth, $args, &$output ) {
if ( !$element )
return;
$id_field = $this->db_fields['id'];
$id = $element->$id_field;
parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );
// If we're at the max depth, and the current element still has children, loop over those and display them at this level
// This is to prevent them being orphaned to the end of the list.
if ( $max_depth <= $depth + 1 && isset( $children_elements[$id]) ) {
foreach ( $children_elements[ $id ] as $child )
$this->display_element( $child, $children_elements, $max_depth, $depth, $args, $output );
unset( $children_elements[ $id ] );
}
}
/**
* Start the element output.
*
* @since 2.7.0
*
* @see Walker::start_el()
* @see wp_list_comments()
*
* @param string $output Passed by reference. Used to append additional content.
* @param object $comment Comment data object.
* @param int $depth Depth of comment in reference to parents.
* @param array $args An array of arguments.
*/
function start_el( &$output, $comment, $depth = 0, $args = array(), $id = 0 ) {
$depth++;
$GLOBALS['comment_depth'] = $depth;
$GLOBALS['comment'] = $comment;
if ( !empty( $args['callback'] ) ) {
ob_start();
call_user_func( $args['callback'], $comment, $args, $depth );
$output .= ob_get_clean();
return;
}
if ( ( 'pingback' == $comment->comment_type || 'trackback' == $comment->comment_type ) && $args['short_ping'] ) {
ob_start();
$this->ping( $comment, $depth, $args );
$output .= ob_get_clean();
} elseif ( 'html5' === $args['format'] ) {
ob_start();
$this->html5_comment( $comment, $depth, $args );
$output .= ob_get_clean();
} else {
ob_start();
$this->comment( $comment, $depth, $args );
$output .= ob_get_clean();
}
}
/**
* Ends the element output, if needed.
*
* @since 2.7.0
*
* @see Walker::end_el()
* @see wp_list_comments()
*
* @param string $output Passed by reference. Used to append additional content.
* @param object $comment The comment object. Default current comment.
* @param int $depth Depth of comment.
* @param array $args An array of arguments.
*/
function end_el( &$output, $comment, $depth = 0, $args = array() ) {
if ( !empty( $args['end-callback'] ) ) {
ob_start();
call_user_func( $args['end-callback'], $comment, $args, $depth );
$output .= ob_get_clean();
return;
}
if ( 'div' == $args['style'] )
$output .= "</div><!-- #comment-## -->\n";
else
$output .= "</li><!-- #comment-## -->\n";
}
/**
* Output a pingback comment.
*
* @access protected
* @since 3.6.0
*
* @see wp_list_comments()
*
* @param object $comment The comment object.
* @param int $depth Depth of comment.
* @param array $args An array of arguments.
*/
protected function ping( $comment, $depth, $args ) {
$tag = ( 'div' == $args['style'] ) ? 'div' : 'li';
?>
<<?php echo $tag; ?> id="comment-<?php comment_ID(); ?>" <?php comment_class(); ?>>
<div class="comment-body">
<?php _e( 'Pingback:' ); ?> <?php comment_author_link(); ?> <?php edit_comment_link( __( 'Edit' ), '<span class="edit-link">', '</span>' ); ?>
</div>
<?php
}
/**
* Output a single comment.
*
* @access protected
* @since 3.6.0
*
* @see wp_list_comments()
*
* @param object $comment Comment to display.
* @param int $depth Depth of comment.
* @param array $args An array of arguments.
*/
protected function comment( $comment, $depth, $args ) {
if ( 'div' == $args['style'] ) {
$tag = 'div';
$add_below = 'comment';
} else {
$tag = 'li';
$add_below = 'div-comment';
}
?>
<<?php echo $tag; ?> <?php comment_class( empty( $args['has_children'] ) ? '' : 'parent' ); ?> id="comment-<?php comment_ID(); ?>">
<?php if ( 'div' != $args['style'] ) : ?>
<div id="div-comment-<?php comment_ID(); ?>" class="comment-body">
<?php endif; ?>
<div class="comment-author vcard">
<?php if ( 0 != $args['avatar_size'] ) echo get_avatar( $comment, $args['avatar_size'] ); ?>
<?php printf( __( '<cite class="fn">%s</cite> <span class="says">says:</span>' ), get_comment_author_link() ); ?>
</div>
<?php if ( '0' == $comment->comment_approved ) : ?>
<em class="comment-awaiting-moderation"><?php _e( 'Your comment is awaiting moderation.' ) ?></em>
<br />
<?php endif; ?>
<div class="comment-meta commentmetadata"><a href="<?php echo esc_url( get_comment_link( $comment->comment_ID, $args ) ); ?>">
<?php
/* translators: 1: date, 2: time */
printf( __( '%1$s at %2$s' ), get_comment_date(), get_comment_time() ); ?></a><?php edit_comment_link( __( '(Edit)' ), ' ', '' );
?>
</div>
<?php comment_text( get_comment_id(), array_merge( $args, array( 'add_below' => $add_below, 'depth' => $depth, 'max_depth' => $args['max_depth'] ) ) ); ?>
<div class="reply">
<?php comment_reply_link( array_merge( $args, array( 'add_below' => $add_below, 'depth' => $depth, 'max_depth' => $args['max_depth'] ) ) ); ?>
</div>
<?php if ( 'div' != $args['style'] ) : ?>
</div>
<?php endif; ?>
<?php
}
/**
* Output a comment in the HTML5 format.
*
* @access protected
* @since 3.6.0
*
* @see wp_list_comments()
*
* @param object $comment Comment to display.
* @param int $depth Depth of comment.
* @param array $args An array of arguments.
*/
protected function html5_comment( $comment, $depth, $args ) {
$tag = ( 'div' === $args['style'] ) ? 'div' : 'li';
?>
<<?php echo $tag; ?> id="comment-<?php comment_ID(); ?>" <?php comment_class( empty( $args['has_children'] ) ? '' : 'parent' ); ?>>
<article id="div-comment-<?php comment_ID(); ?>" class="comment-body">
<footer class="comment-meta">
<div class="comment-author vcard">
<?php if ( 0 != $args['avatar_size'] ) echo get_avatar( $comment, $args['avatar_size'] ); ?>
<?php printf( __( '%s <span class="says">says:</span>' ), sprintf( '<b class="fn">%s</b>', get_comment_author_link() ) ); ?>
</div><!-- .comment-author -->
<div class="comment-metadata">
<a href="<?php echo esc_url( get_comment_link( $comment->comment_ID, $args ) ); ?>">
<time datetime="<?php comment_time( 'c' ); ?>">
<?php printf( _x( '%1$s at %2$s', '1: date, 2: time' ), get_comment_date(), get_comment_time() ); ?>
</time>
</a>
<?php edit_comment_link( __( 'Edit' ), '<span class="edit-link">', '</span>' ); ?>
</div><!-- .comment-metadata -->
<?php if ( '0' == $comment->comment_approved ) : ?>
<p class="comment-awaiting-moderation"><?php _e( 'Your comment is awaiting moderation.' ); ?></p>
<?php endif; ?>
</footer><!-- .comment-meta -->
<div class="comment-content">
<?php comment_text(); ?>
</div><!-- .comment-content -->
<div class="reply">
<?php comment_reply_link( array_merge( $args, array( 'add_below' => 'div-comment', 'depth' => $depth, 'max_depth' => $args['max_depth'] ) ) ); ?>
</div><!-- .reply -->
</article><!-- .comment-body -->
<?php
}
}
/**
* List comments.
*
* Used in the comments.php template to list comments for a particular post.
*
* @since 2.7.0
*
* @see WP_Query->comments
*
* @param string|array $args {
* Optional. Formatting options.
*
* @type string $walker The Walker class used to list comments. Default null.
* @type int $max_depth The maximum comments depth. Default empty.
* @type string $style The style of list ordering. Default 'ul'. Accepts 'ul', 'ol'.
* @type string $callback Callback function to use. Default null.
* @type string $end-callback Callback function to use at the end. Default null.
* @type string $type Type of comments to list.
* Default 'all'. Accepts 'all', 'comment', 'pingback', 'trackback', 'pings'.
* @type int $page Page ID to list comments for. Default empty.
* @type int $per_page Number of comments to list per page. Default empty.
* @type int $avatar_size Height and width dimensions of the avatar size. Default 32.
* @type string $reverse_top_level Ordering of the listed comments. Default null. Accepts 'desc', 'asc'.
* @type bool $reverse_children Whether to reverse child comments in the list. Default null.
* @type string $format How to format the comments list.
* Default 'html5' if the theme supports it. Accepts 'html5', 'xhtml'.
* @type bool $short_ping Whether to output short pings. Default false.
* @type bool $echo Whether to echo the output or return it. Default true.
* }
* @param array $comments Optional. Array of comment objects.
*/
function wp_list_comments( $args = array(), $comments = null ) {
global $wp_query, $comment_alt, $comment_depth, $comment_thread_alt, $overridden_cpage, $in_comment_loop;
$in_comment_loop = true;
$comment_alt = $comment_thread_alt = 0;
$comment_depth = 1;
$defaults = array(
'walker' => null,
'max_depth' => '',
'style' => 'ul',
'callback' => null,
'end-callback' => null,
'type' => 'all',
'page' => '',
'per_page' => '',
'avatar_size' => 32,
'reverse_top_level' => null,
'reverse_children' => '',
'format' => current_theme_supports( 'html5', 'comment-list' ) ? 'html5' : 'xhtml',
'short_ping' => false,
'echo' => true,
);
$r = wp_parse_args( $args, $defaults );
// Figure out what comments we'll be looping through ($_comments)
if ( null !== $comments ) {
$comments = (array) $comments;
if ( empty($comments) )
return;
if ( 'all' != $r['type'] ) {
$comments_by_type = separate_comments($comments);
if ( empty($comments_by_type[$r['type']]) )
return;
$_comments = $comments_by_type[$r['type']];
} else {
$_comments = $comments;
}
} else {
if ( empty($wp_query->comments) )
return;
if ( 'all' != $r['type'] ) {
if ( empty($wp_query->comments_by_type) )
$wp_query->comments_by_type = separate_comments($wp_query->comments);
if ( empty($wp_query->comments_by_type[$r['type']]) )
return;
$_comments = $wp_query->comments_by_type[$r['type']];
} else {
$_comments = $wp_query->comments;
}
}
if ( '' === $r['per_page'] && get_option('page_comments') )
$r['per_page'] = get_query_var('comments_per_page');
if ( empty($r['per_page']) ) {
$r['per_page'] = 0;
$r['page'] = 0;
}
if ( '' === $r['max_depth'] ) {
if ( get_option('thread_comments') )
$r['max_depth'] = get_option('thread_comments_depth');
else
$r['max_depth'] = -1;
}
if ( '' === $r['page'] ) {
if ( empty($overridden_cpage) ) {
$r['page'] = get_query_var('cpage');
} else {
$threaded = ( -1 != $r['max_depth'] );
$r['page'] = ( 'newest' == get_option('default_comments_page') ) ? get_comment_pages_count($_comments, $r['per_page'], $threaded) : 1;
set_query_var( 'cpage', $r['page'] );
}
}
// Validation check
$r['page'] = intval($r['page']);
if ( 0 == $r['page'] && 0 != $r['per_page'] )
$r['page'] = 1;
if ( null === $r['reverse_top_level'] )
$r['reverse_top_level'] = ( 'desc' == get_option('comment_order') );
extract( $r, EXTR_SKIP );
if ( empty($walker) )
$walker = new Walker_Comment;
$output = $walker->paged_walk($_comments, $max_depth, $page, $per_page, $r);
$wp_query->max_num_comment_pages = $walker->max_pages;
$in_comment_loop = false;
if ( $r['echo'] )
echo $output;
else
return $output;
}
/**
* Output a complete commenting form for use within a template.
*
* Most strings and form fields may be controlled through the $args array passed
* into the function, while you may also choose to use the comment_form_default_fields
* filter to modify the array of default fields if you'd just like to add a new
* one or remove a single field. All fields are also individually passed through
* a filter of the form comment_form_field_$name where $name is the key used
* in the array of fields.
*
* @since 3.0.0
*
* @param array $args {
* Optional. Default arguments and form fields to override.
*
* @type array $fields {
* Default comment fields, filterable by default via the 'comment_form_default_fields' hook.
*
* @type string $author Comment author field HTML.
* @type string $email Comment author email field HTML.
* @type string $url Comment author URL field HTML.
* }
* @type string $comment_field The comment textarea field HTML.
* @type string $must_log_in HTML element for a 'must be logged in to comment' message.
* @type string $logged_in_as HTML element for a 'logged in as <user>' message.
* @type string $comment_notes_before HTML element for a message displayed before the comment form.
* Default 'Your email address will not be published.'.
* @type string $comment_notes_after HTML element for a message displayed after the comment form.
* Default 'You may use these HTML tags and attributes ...'.
* @type string $id_form The comment form element id attribute. Default 'commentform'.
* @type string $id_submit The comment submit element id attribute. Default 'submit'.
* @type string $title_reply The translatable 'reply' button label. Default 'Leave a Reply'.
* @type string $title_reply_to The translatable 'reply-to' button label. Default 'Leave a Reply to %s',
* where %s is the author of the comment being replied to.
* @type string $cancel_reply_link The translatable 'cancel reply' button label. Default 'Cancel reply'.
* @type string $label_submit The translatable 'submit' button label. Default 'Post a comment'.
* @type string $format The comment form format. Default 'xhtml'. Accepts 'xhtml', 'html5'.
* }
* @param int|WP_Post $post_id Post ID or WP_Post object to generate the form for. Default current post.
*/
function comment_form( $args = array(), $post_id = null ) {
if ( null === $post_id )
$post_id = get_the_ID();
else
$id = $post_id;
$commenter = wp_get_current_commenter();
$user = wp_get_current_user();
$user_identity = $user->exists() ? $user->display_name : '';
$args = wp_parse_args( $args );
if ( ! isset( $args['format'] ) )
$args['format'] = current_theme_supports( 'html5', 'comment-form' ) ? 'html5' : 'xhtml';
$req = get_option( 'require_name_email' );
$aria_req = ( $req ? " aria-required='true'" : '' );
$html5 = 'html5' === $args['format'];
$fields = array(
'author' => '<p class="comment-form-author">' . '<label for="author">' . __( 'Name' ) . ( $req ? ' <span class="required">*</span>' : '' ) . '</label> ' .
'<input id="author" name="author" type="text" value="' . esc_attr( $commenter['comment_author'] ) . '" size="30"' . $aria_req . ' /></p>',
'email' => '<p class="comment-form-email"><label for="email">' . __( 'Email' ) . ( $req ? ' <span class="required">*</span>' : '' ) . '</label> ' .
'<input id="email" name="email" ' . ( $html5 ? 'type="email"' : 'type="text"' ) . ' value="' . esc_attr( $commenter['comment_author_email'] ) . '" size="30"' . $aria_req . ' /></p>',
'url' => '<p class="comment-form-url"><label for="url">' . __( 'Website' ) . '</label> ' .
'<input id="url" name="url" ' . ( $html5 ? 'type="url"' : 'type="text"' ) . ' value="' . esc_attr( $commenter['comment_author_url'] ) . '" size="30" /></p>',
);
$required_text = sprintf( ' ' . __('Required fields are marked %s'), '<span class="required">*</span>' );
/**
* Filter the default comment form fields.
*
* @since 3.0.0
*
* @param array $fields The default comment fields.
*/
$fields = apply_filters( 'comment_form_default_fields', $fields );
$defaults = array(
'fields' => $fields,
'comment_field' => '<p class="comment-form-comment"><label for="comment">' . _x( 'Comment', 'noun' ) . '</label> <textarea id="comment" name="comment" cols="45" rows="8" aria-required="true"></textarea></p>',
/** This filter is documented in wp-includes/link-template.php */
'must_log_in' => '<p class="must-log-in">' . sprintf( __( 'You must be <a href="%s">logged in</a> to post a comment.' ), wp_login_url( apply_filters( 'the_permalink', get_permalink( $post_id ) ) ) ) . '</p>',
/** This filter is documented in wp-includes/link-template.php */
'logged_in_as' => '<p class="logged-in-as">' . sprintf( __( 'Logged in as <a href="%1$s">%2$s</a>. <a href="%3$s" title="Log out of this account">Log out?</a>' ), get_edit_user_link(), $user_identity, wp_logout_url( apply_filters( 'the_permalink', get_permalink( $post_id ) ) ) ) . '</p>',
'comment_notes_before' => '<p class="comment-notes">' . __( 'Your email address will not be published.' ) . ( $req ? $required_text : '' ) . '</p>',
'comment_notes_after' => '<p class="form-allowed-tags">' . sprintf( __( 'You may use these <abbr title="HyperText Markup Language">HTML</abbr> tags and attributes: %s' ), ' <code>' . allowed_tags() . '</code>' ) . '</p>',
'id_form' => 'commentform',
'id_submit' => 'submit',
'title_reply' => __( 'Leave a Reply' ),
'title_reply_to' => __( 'Leave a Reply to %s' ),
'cancel_reply_link' => __( 'Cancel reply' ),
'label_submit' => __( 'Post Comment' ),
'format' => 'xhtml',
);
/**
* Filter the comment form default arguments.
*
* Use 'comment_form_default_fields' to filter the comment fields.
*
* @since 3.0.0
*
* @param array $defaults The default comment form arguments.
*/
$args = wp_parse_args( $args, apply_filters( 'comment_form_defaults', $defaults ) );
?>
<?php if ( comments_open( $post_id ) ) : ?>
<?php
/**
* Fires before the comment form.
*
* @since 3.0.0
*/
do_action( 'comment_form_before' );
?>
<div id="respond" class="comment-respond">
<h3 id="reply-title" class="comment-reply-title"><?php comment_form_title( $args['title_reply'], $args['title_reply_to'] ); ?> <small><?php cancel_comment_reply_link( $args['cancel_reply_link'] ); ?></small></h3>
<?php if ( get_option( 'comment_registration' ) && !is_user_logged_in() ) : ?>
<?php echo $args['must_log_in']; ?>
<?php
/**
* Fires after the HTML-formatted 'must log in after' message in the comment form.
*
* @since 3.0.0
*/
do_action( 'comment_form_must_log_in_after' );
?>
<?php else : ?>
<form action="<?php echo site_url( '/wp-comments-post.php' ); ?>" method="post" id="<?php echo esc_attr( $args['id_form'] ); ?>" class="comment-form"<?php echo $html5 ? ' novalidate' : ''; ?>>
<?php
/**
* Fires at the top of the comment form, inside the <form> tag.
*
* @since 3.0.0
*/
do_action( 'comment_form_top' );
?>
<?php if ( is_user_logged_in() ) : ?>
<?php
/**
* Filter the 'logged in' message for the comment form for display.
*
* @since 3.0.0
*
* @param string $args_logged_in The logged-in-as HTML-formatted message.
* @param array $commenter An array containing the comment author's
* username, email, and URL.
* @param string $user_identity If the commenter is a registered user,
* the display name, blank otherwise.
*/
echo apply_filters( 'comment_form_logged_in', $args['logged_in_as'], $commenter, $user_identity );
?>
<?php
/**
* Fires after the is_user_logged_in() check in the comment form.
*
* @since 3.0.0
*
* @param array $commenter An array containing the comment author's
* username, email, and URL.
* @param string $user_identity If the commenter is a registered user,
* the display name, blank otherwise.
*/
do_action( 'comment_form_logged_in_after', $commenter, $user_identity );
?>
<?php else : ?>
<?php echo $args['comment_notes_before']; ?>
<?php
/**
* Fires before the comment fields in the comment form.
*
* @since 3.0.0
*/
do_action( 'comment_form_before_fields' );
foreach ( (array) $args['fields'] as $name => $field ) {
/**
* Filter a comment form field for display.
*
* The dynamic portion of the filter hook, $name, refers to the name
* of the comment form field. Such as 'author', 'email', or 'url'.
*
* @since 3.0.0
*
* @param string $field The HTML-formatted output of the comment form field.
*/
echo apply_filters( "comment_form_field_{$name}", $field ) . "\n";
}
/**
* Fires after the comment fields in the comment form.
*
* @since 3.0.0
*/
do_action( 'comment_form_after_fields' );
?>
<?php endif; ?>
<?php
/**
* Filter the content of the comment textarea field for display.
*
* @since 3.0.0
*
* @param string $args_comment_field The content of the comment textarea field.
*/
echo apply_filters( 'comment_form_field_comment', $args['comment_field'] );
?>
<?php echo $args['comment_notes_after']; ?>
<p class="form-submit">
<input name="submit" type="submit" id="<?php echo esc_attr( $args['id_submit'] ); ?>" value="<?php echo esc_attr( $args['label_submit'] ); ?>" />
<?php comment_id_fields( $post_id ); ?>
</p>
<?php
/**
* Fires at the bottom of the comment form, inside the closing </form> tag.
*
* @since 1.5.0
*
* @param int $post_id The post ID.
*/
do_action( 'comment_form', $post_id );
?>
</form>
<?php endif; ?>
</div><!-- #respond -->
<?php
/**
* Fires after the comment form.
*
* @since 3.0.0
*/
do_action( 'comment_form_after' );
else :
/**
* Fires after the comment form if comments are closed.
*
* @since 3.0.0
*/
do_action( 'comment_form_comments_closed' );
endif;
}
| PHP |
<?php
/**
* BackPress Scripts Procedural API
*
* @since 2.6.0
*
* @package WordPress
* @subpackage BackPress
*/
/**
* Print scripts in document head that are in the $handles queue.
*
* Called by admin-header.php and wp_head hook. Since it is called by wp_head on every page load,
* the function does not instantiate the WP_Scripts object unless script names are explicitly passed.
* Makes use of already-instantiated $wp_scripts global if present. Use provided wp_print_scripts
* hook to register/enqueue new scripts.
*
* @see WP_Scripts::do_items()
* @global WP_Scripts $wp_scripts The WP_Scripts object for printing scripts.
*
* @since 2.6.0
*
* @param array|bool $handles Optional. Scripts to be printed. Default 'false'.
* @return array On success, a processed array of WP_Dependencies items; otherwise, an empty array.
*/
function wp_print_scripts( $handles = false ) {
/**
* Fires before scripts in the $handles queue are printed.
*
* @since 2.1.0
*/
do_action( 'wp_print_scripts' );
if ( '' === $handles ) // for wp_head
$handles = false;
global $wp_scripts;
if ( ! is_a( $wp_scripts, 'WP_Scripts' ) ) {
if ( ! did_action( 'init' ) )
_doing_it_wrong( __FUNCTION__, sprintf( __( 'Scripts and styles should not be registered or enqueued until the %1$s, %2$s, or %3$s hooks.' ),
'<code>wp_enqueue_scripts</code>', '<code>admin_enqueue_scripts</code>', '<code>login_enqueue_scripts</code>' ), '3.3' );
if ( !$handles )
return array(); // No need to instantiate if nothing is there.
else
$wp_scripts = new WP_Scripts();
}
return $wp_scripts->do_items( $handles );
}
/**
* Register a new script.
*
* Registers a script to be linked later using the wp_enqueue_script() function.
*
* @see WP_Dependencies::add(), WP_Dependencies::add_data()
* @global WP_Scripts $wp_scripts The WP_Scripts object for printing scripts.
*
* @since 2.6.0
*
* @param string $handle Name of the script. Should be unique.
* @param string $src Path to the script from the WordPress root directory. Example: '/js/myscript.js'.
* @param array $deps Optional. An array of registered script handles this script depends on. Set to false if there
* are no dependencies. Default empty array.
* @param string|bool $ver Optional. String specifying script version number, if it has one, which is concatenated
* to end of path as a query string. If no version is specified or set to false, a version
* number is automatically added equal to current installed WordPress version.
* If set to null, no version is added. Default 'false'. Accepts 'false', 'null', or 'string'.
* @param bool $in_footer Optional. Whether to enqueue the script before </head> or before </body>.
* Default 'false'. Accepts 'false' or 'true'.
*/
function wp_register_script( $handle, $src, $deps = array(), $ver = false, $in_footer = false ) {
global $wp_scripts;
if ( ! is_a( $wp_scripts, 'WP_Scripts' ) ) {
if ( ! did_action( 'init' ) )
_doing_it_wrong( __FUNCTION__, sprintf( __( 'Scripts and styles should not be registered or enqueued until the %1$s, %2$s, or %3$s hooks.' ),
'<code>wp_enqueue_scripts</code>', '<code>admin_enqueue_scripts</code>', '<code>login_enqueue_scripts</code>' ), '3.3' );
$wp_scripts = new WP_Scripts();
}
$wp_scripts->add( $handle, $src, $deps, $ver );
if ( $in_footer )
$wp_scripts->add_data( $handle, 'group', 1 );
}
/**
* Localize a script.
*
* Works only if the script has already been added.
*
* Accepts an associative array $l10n and creates a JavaScript object:
* <code>
* "$object_name" = {
* key: value,
* key: value,
* ...
* }
* </code>
*
* @see WP_Dependencies::localize()
* @link http://core.trac.wordpress.org/ticket/11520
* @global WP_Scripts $wp_scripts The WP_Scripts object for printing scripts.
*
* @since 2.6.0
*
* @param string $handle Script handle the data will be attached to.
* @param string $object_name Name for the JavaScript object. Passed directly, so it should be qualified JS variable.
* Example: '/[a-zA-Z0-9_]+/'.
* @param array $l10n The data itself. The data can be either a single or multi-dimensional array.
* @return bool True if the script was successfully localized, false otherwise.
*/
function wp_localize_script( $handle, $object_name, $l10n ) {
global $wp_scripts;
if ( ! is_a( $wp_scripts, 'WP_Scripts' ) ) {
if ( ! did_action( 'init' ) )
_doing_it_wrong( __FUNCTION__, sprintf( __( 'Scripts and styles should not be registered or enqueued until the %1$s, %2$s, or %3$s hooks.' ),
'<code>wp_enqueue_scripts</code>', '<code>admin_enqueue_scripts</code>', '<code>login_enqueue_scripts</code>' ), '3.3' );
return false;
}
return $wp_scripts->localize( $handle, $object_name, $l10n );
}
/**
* Remove a registered script.
*
* Note: there are intentional safeguards in place to prevent critical admin scripts,
* such as jQuery core, from being unregistered.
*
* @see WP_Dependencies::remove()
* @global WP_Scripts $wp_scripts The WP_Scripts object for printing scripts.
*
* @since 2.6.0
*
* @param string $handle Name of the script to be removed.
*/
function wp_deregister_script( $handle ) {
global $wp_scripts;
if ( ! is_a( $wp_scripts, 'WP_Scripts' ) ) {
if ( ! did_action( 'init' ) )
_doing_it_wrong( __FUNCTION__, sprintf( __( 'Scripts and styles should not be registered or enqueued until the %1$s, %2$s, or %3$s hooks.' ),
'<code>wp_enqueue_scripts</code>', '<code>admin_enqueue_scripts</code>', '<code>login_enqueue_scripts</code>' ), '3.3' );
$wp_scripts = new WP_Scripts();
}
/**
* Do not allow accidental or negligent de-registering of critical scripts in the admin.
* Show minimal remorse if the correct hook is used.
*/
$current_filter = current_filter();
if ( ( is_admin() && 'admin_enqueue_scripts' !== $current_filter ) ||
( 'wp-login.php' === $GLOBALS['pagenow'] && 'login_enqueue_scripts' !== $current_filter )
) {
$no = array(
'jquery', 'jquery-core', 'jquery-migrate', 'jquery-ui-core', 'jquery-ui-accordion',
'jquery-ui-autocomplete', 'jquery-ui-button', 'jquery-ui-datepicker', 'jquery-ui-dialog',
'jquery-ui-draggable', 'jquery-ui-droppable', 'jquery-ui-menu', 'jquery-ui-mouse',
'jquery-ui-position', 'jquery-ui-progressbar', 'jquery-ui-resizable', 'jquery-ui-selectable',
'jquery-ui-slider', 'jquery-ui-sortable', 'jquery-ui-spinner', 'jquery-ui-tabs',
'jquery-ui-tooltip', 'jquery-ui-widget', 'underscore', 'backbone',
);
if ( in_array( $handle, $no ) ) {
$message = sprintf( __( 'Do not deregister the %1$s script in the administration area. To target the frontend theme, use the %2$s hook.' ),
"<code>$handle</code>", '<code>wp_enqueue_scripts</code>' );
_doing_it_wrong( __FUNCTION__, $message, '3.6' );
return;
}
}
$wp_scripts->remove( $handle );
}
/**
* Enqueue a script.
*
* Registers the script if $src provided (does NOT overwrite), and enqueues it.
*
* @see WP_Dependencies::add(), WP_Dependencies::add_data(), WP_Dependencies::enqueue()
* @global WP_Scripts $wp_scripts The WP_Scripts object for printing scripts.
*
* @since 2.6.0
* @param string $handle Name of the script.
* @param string|bool $src Path to the script from the root directory of WordPress. Example: '/js/myscript.js'.
* @param array $deps An array of registered handles this script depends on. Default empty array.
* @param string|bool $ver Optional. String specifying the script version number, if it has one. This parameter
* is used to ensure that the correct version is sent to the client regardless of caching,
* and so should be included if a version number is available and makes sense for the script.
* @param bool $in_footer Optional. Whether to enqueue the script before </head> or before </body>.
* Default 'false'. Accepts 'false' or 'true'.
*/
function wp_enqueue_script( $handle, $src = false, $deps = array(), $ver = false, $in_footer = false ) {
global $wp_scripts;
if ( ! is_a( $wp_scripts, 'WP_Scripts' ) ) {
if ( ! did_action( 'init' ) )
_doing_it_wrong( __FUNCTION__, sprintf( __( 'Scripts and styles should not be registered or enqueued until the %1$s, %2$s, or %3$s hooks.' ),
'<code>wp_enqueue_scripts</code>', '<code>admin_enqueue_scripts</code>', '<code>login_enqueue_scripts</code>' ), '3.3' );
$wp_scripts = new WP_Scripts();
}
if ( $src ) {
$_handle = explode('?', $handle);
$wp_scripts->add( $_handle[0], $src, $deps, $ver );
if ( $in_footer )
$wp_scripts->add_data( $_handle[0], 'group', 1 );
}
$wp_scripts->enqueue( $handle );
}
/**
* Remove a previously enqueued script.
*
* @see WP_Dependencies::dequeue()
* @global WP_Scripts $wp_scripts The WP_Scripts object for printing scripts.
*
* @since 3.1.0
*
* @param string $handle Name of the script to be removed.
*/
function wp_dequeue_script( $handle ) {
global $wp_scripts;
if ( ! is_a( $wp_scripts, 'WP_Scripts' ) ) {
if ( ! did_action( 'init' ) )
_doing_it_wrong( __FUNCTION__, sprintf( __( 'Scripts and styles should not be registered or enqueued until the %1$s, %2$s, or %3$s hooks.' ),
'<code>wp_enqueue_scripts</code>', '<code>admin_enqueue_scripts</code>', '<code>login_enqueue_scripts</code>' ), '3.3' );
$wp_scripts = new WP_Scripts();
}
$wp_scripts->dequeue( $handle );
}
/**
* Check whether a script has been added to the queue.
*
* @global WP_Scripts $wp_scripts The WP_Scripts object for printing scripts.
*
* @since 2.8.0
* @since 3.5.0 'enqueued' added as an alias of the 'queue' list.
*
* @param string $handle Name of the script.
* @param string $list Optional. Status of the script to check. Default 'enqueued'.
* Accepts 'enqueued', 'registered', 'queue', 'to_do', and 'done'.
* @return bool Whether the script script is queued.
*/
function wp_script_is( $handle, $list = 'enqueued' ) {
global $wp_scripts;
if ( ! is_a( $wp_scripts, 'WP_Scripts' ) ) {
if ( ! did_action( 'init' ) )
_doing_it_wrong( __FUNCTION__, sprintf( __( 'Scripts and styles should not be registered or enqueued until the %1$s, %2$s, or %3$s hooks.' ),
'<code>wp_enqueue_scripts</code>', '<code>admin_enqueue_scripts</code>', '<code>login_enqueue_scripts</code>' ), '3.3' );
$wp_scripts = new WP_Scripts();
}
return (bool) $wp_scripts->query( $handle, $list );
}
| PHP |
<?php
/**
* Template loading functions.
*
* @package WordPress
* @subpackage Template
*/
/**
* Retrieve path to a template
*
* Used to quickly retrieve the path of a template without including the file
* extension. It will also check the parent theme, if the file exists, with
* the use of {@link locate_template()}. Allows for more generic template location
* without the use of the other get_*_template() functions.
*
* @since 1.5.0
*
* @param string $type Filename without extension.
* @param array $templates An optional list of template candidates
* @return string Full path to template file.
*/
function get_query_template( $type, $templates = array() ) {
$type = preg_replace( '|[^a-z0-9-]+|', '', $type );
if ( empty( $templates ) )
$templates = array("{$type}.php");
$template = locate_template( $templates );
/**
* Filter the path of the queried template by type.
*
* The dynamic portion of the hook name, $type, refers to the filename
* -- minus the extension -- of the file to load. This hook also applies
* to various types of files loaded as part of the Template Hierarchy.
*
* @since 1.5.0
*
* @param string $template Path to the template. @see locate_template()
*/
return apply_filters( "{$type}_template", $template );
}
/**
* Retrieve path of index template in current or parent template.
*
* The template path is filterable via the 'index_template' hook.
*
* @since 3.0.0
*
* @see get_query_template()
*
* @return string Full path to index template file.
*/
function get_index_template() {
return get_query_template('index');
}
/**
* Retrieve path of 404 template in current or parent template.
*
* The template path is filterable via the '404_template' hook.
*
* @since 1.5.0
*
* @see get_query_template()
*
* @return string Full path to 404 template file.
*/
function get_404_template() {
return get_query_template('404');
}
/**
* Retrieve path of archive template in current or parent template.
*
* The template path is filterable via the 'archive_template' hook.
*
* @since 1.5.0
*
* @see get_query_template()
*
* @return string Full path to archive template file.
*/
function get_archive_template() {
$post_types = array_filter( (array) get_query_var( 'post_type' ) );
$templates = array();
if ( count( $post_types ) == 1 ) {
$post_type = reset( $post_types );
$templates[] = "archive-{$post_type}.php";
}
$templates[] = 'archive.php';
return get_query_template( 'archive', $templates );
}
/**
* Retrieve path of post type archive template in current or parent template.
*
* The template path is filterable via the 'archive_template' hook.
*
* @since 3.7.0
*
* @see get_archive_template()
*
* @return string Full path to archive template file.
*/
function get_post_type_archive_template() {
$post_type = get_query_var( 'post_type' );
if ( is_array( $post_type ) )
$post_type = reset( $post_type );
$obj = get_post_type_object( $post_type );
if ( ! $obj->has_archive )
return '';
return get_archive_template();
}
/**
* Retrieve path of author template in current or parent template.
*
* The template path is filterable via the 'author_template' hook.
*
* @since 1.5.0
*
* @see get_query_template()
*
* @return string Full path to author template file.
*/
function get_author_template() {
$author = get_queried_object();
$templates = array();
if ( is_a( $author, 'WP_User' ) ) {
$templates[] = "author-{$author->user_nicename}.php";
$templates[] = "author-{$author->ID}.php";
}
$templates[] = 'author.php';
return get_query_template( 'author', $templates );
}
/**
* Retrieve path of category template in current or parent template.
*
* Works by first retrieving the current slug, for example 'category-default.php', and then
* trying category ID, for example 'category-1.php', and will finally fall back to category.php
* template, if those files don't exist.
*
* The template path is filterable via the 'category_template' hook.
*
* @since 1.5.0
*
* @see get_query_template()
*
* @return string Full path to category template file.
*/
function get_category_template() {
$category = get_queried_object();
$templates = array();
if ( ! empty( $category->slug ) ) {
$templates[] = "category-{$category->slug}.php";
$templates[] = "category-{$category->term_id}.php";
}
$templates[] = 'category.php';
return get_query_template( 'category', $templates );
}
/**
* Retrieve path of tag template in current or parent template.
*
* Works by first retrieving the current tag name, for example 'tag-wordpress.php', and then
* trying tag ID, for example 'tag-1.php', and will finally fall back to tag.php
* template, if those files don't exist.
*
* The template path is filterable via the 'tag_template' hook.
*
* @since 2.3.0
*
* @see get_query_template()
*
* @return string Full path to tag template file.
*/
function get_tag_template() {
$tag = get_queried_object();
$templates = array();
if ( ! empty( $tag->slug ) ) {
$templates[] = "tag-{$tag->slug}.php";
$templates[] = "tag-{$tag->term_id}.php";
}
$templates[] = 'tag.php';
return get_query_template( 'tag', $templates );
}
/**
* Retrieve path of taxonomy template in current or parent template.
*
* Retrieves the taxonomy and term, if term is available. The template is
* prepended with 'taxonomy-' and followed by both the taxonomy string and
* the taxonomy string followed by a dash and then followed by the term.
*
* The taxonomy and term template is checked and used first, if it exists.
* Second, just the taxonomy template is checked, and then finally, taxonomy.php
* template is used. If none of the files exist, then it will fall back on to
* index.php.
*
* The template path is filterable via the 'taxonomy_template' hook.
*
* @since 2.5.0
*
* @see get_query_template()
*
* @return string Full path to taxonomy template file.
*/
function get_taxonomy_template() {
$term = get_queried_object();
$templates = array();
if ( ! empty( $term->slug ) ) {
$taxonomy = $term->taxonomy;
$templates[] = "taxonomy-$taxonomy-{$term->slug}.php";
$templates[] = "taxonomy-$taxonomy.php";
}
$templates[] = 'taxonomy.php';
return get_query_template( 'taxonomy', $templates );
}
/**
* Retrieve path of date template in current or parent template.
*
* The template path is filterable via the 'date_template' hook.
*
* @since 1.5.0
*
* @see get_query_template()
*
* @return string Full path to date template file.
*/
function get_date_template() {
return get_query_template('date');
}
/**
* Retrieve path of home template in current or parent template.
*
* This is the template used for the page containing the blog posts.
* Attempts to locate 'home.php' first before falling back to 'index.php'.
*
* The template path is filterable via the 'home_template' hook.
*
* @since 1.5.0
*
* @see get_query_template()
*
* @return string Full path to home template file.
*/
function get_home_template() {
$templates = array( 'home.php', 'index.php' );
return get_query_template( 'home', $templates );
}
/**
* Retrieve path of front-page template in current or parent template.
*
* Looks for 'front-page.php'. The template path is filterable via the
* 'front_page_template' hook.
*
* @since 3.0.0
*
* @see get_query_template()
*
* @return string Full path to front page template file.
*/
function get_front_page_template() {
$templates = array('front-page.php');
return get_query_template( 'front_page', $templates );
}
/**
* Retrieve path of page template in current or parent template.
*
* Will first look for the specifically assigned page template.
* Then will search for 'page-{slug}.php', followed by 'page-{id}.php',
* and finally 'page.php'.
*
* The template path is filterable via the 'page_template' hook.
*
* @since 1.5.0
*
* @see get_query_template()
*
* @return string Full path to page template file.
*/
function get_page_template() {
$id = get_queried_object_id();
$template = get_page_template_slug();
$pagename = get_query_var('pagename');
if ( ! $pagename && $id ) {
// If a static page is set as the front page, $pagename will not be set. Retrieve it from the queried object
$post = get_queried_object();
if ( $post )
$pagename = $post->post_name;
}
$templates = array();
if ( $template && 0 === validate_file( $template ) )
$templates[] = $template;
if ( $pagename )
$templates[] = "page-$pagename.php";
if ( $id )
$templates[] = "page-$id.php";
$templates[] = 'page.php';
return get_query_template( 'page', $templates );
}
/**
* Retrieve path of paged template in current or parent template.
*
* The template path is filterable via the 'paged_template' hook.
*
* @since 1.5.0
*
* @see get_query_template()
*
* @return string Full path to paged template file.
*/
function get_paged_template() {
return get_query_template('paged');
}
/**
* Retrieve path of search template in current or parent template.
*
* The template path is filterable via the 'search_template' hook.
*
* @since 1.5.0
*
* @see get_query_template()
*
* @return string Full path to search template file.
*/
function get_search_template() {
return get_query_template('search');
}
/**
* Retrieve path of single template in current or parent template.
*
* The template path is filterable via the 'single_template' hook.
*
* @since 1.5.0
*
* @see get_query_template()
*
* @return string Full path to single template file.
*/
function get_single_template() {
$object = get_queried_object();
$templates = array();
if ( ! empty( $object->post_type ) )
$templates[] = "single-{$object->post_type}.php";
$templates[] = "single.php";
return get_query_template( 'single', $templates );
}
/**
* Retrieve path of attachment template in current or parent template.
*
* The attachment path first checks if the first part of the mime type exists.
* The second check is for the second part of the mime type. The last check is
* for both types separated by an underscore. If neither are found then the file
* 'attachment.php' is checked and returned.
*
* Some examples for the 'text/plain' mime type are 'text.php', 'plain.php', and
* finally 'text_plain.php'.
*
* The template path is filterable via the 'attachment_template' hook.
*
* @since 2.0.0
*
* @see get_query_template()
*
* @return string Full path to attachment template file.
*/
function get_attachment_template() {
global $posts;
if ( ! empty( $posts ) && isset( $posts[0]->post_mime_type ) ) {
$type = explode( '/', $posts[0]->post_mime_type );
if ( ! empty( $type ) ) {
if ( $template = get_query_template( $type[0] ) )
return $template;
elseif ( ! empty( $type[1] ) ) {
if ( $template = get_query_template( $type[1] ) )
return $template;
elseif ( $template = get_query_template( "$type[0]_$type[1]" ) )
return $template;
}
}
}
return get_query_template( 'attachment' );
}
/**
* Retrieve path of comment popup template in current or parent template.
*
* Checks for comment popup template in current template, if it exists or in the
* parent template.
*
* The template path is filterable via the 'comments_popup_template' hook.
*
* @since 1.5.0
*
* @see get_query_template()
*
* @return string Full path to comments popup template file.
*/
function get_comments_popup_template() {
$template = get_query_template( 'comments_popup', array( 'comments-popup.php' ) );
// Backward compat code will be removed in a future release
if ('' == $template)
$template = ABSPATH . WPINC . '/theme-compat/comments-popup.php';
return $template;
}
/**
* Retrieve the name of the highest priority template file that exists.
*
* Searches in the STYLESHEETPATH before TEMPLATEPATH so that themes which
* inherit from a parent theme can just overload one file.
*
* @since 2.7.0
*
* @param string|array $template_names Template file(s) to search for, in order.
* @param bool $load If true the template file will be loaded if it is found.
* @param bool $require_once Whether to require_once or require. Default true. Has no effect if $load is false.
* @return string The template filename if one is located.
*/
function locate_template($template_names, $load = false, $require_once = true ) {
$located = '';
foreach ( (array) $template_names as $template_name ) {
if ( !$template_name )
continue;
if ( file_exists(STYLESHEETPATH . '/' . $template_name)) {
$located = STYLESHEETPATH . '/' . $template_name;
break;
} else if ( file_exists(TEMPLATEPATH . '/' . $template_name) ) {
$located = TEMPLATEPATH . '/' . $template_name;
break;
}
}
if ( $load && '' != $located )
load_template( $located, $require_once );
return $located;
}
/**
* Require the template file with WordPress environment.
*
* The globals are set up for the template file to ensure that the WordPress
* environment is available from within the function. The query variables are
* also available.
*
* @since 1.5.0
*
* @param string $_template_file Path to template file.
* @param bool $require_once Whether to require_once or require. Default true.
*/
function load_template( $_template_file, $require_once = true ) {
global $posts, $post, $wp_did_header, $wp_query, $wp_rewrite, $wpdb, $wp_version, $wp, $id, $comment, $user_ID;
if ( is_array( $wp_query->query_vars ) )
extract( $wp_query->query_vars, EXTR_SKIP );
if ( $require_once )
require_once( $_template_file );
else
require( $_template_file );
}
| PHP |
<?php
/**
* These functions can be replaced via plugins. If plugins do not redefine these
* functions, then these will be used instead.
*
* @package WordPress
*/
if ( !function_exists('wp_set_current_user') ) :
/**
* Changes the current user by ID or name.
*
* Set $id to null and specify a name if you do not know a user's ID.
*
* Some WordPress functionality is based on the current user and not based on
* the signed in user. Therefore, it opens the ability to edit and perform
* actions on users who aren't signed in.
*
* @since 2.0.3
* @global object $current_user The current user object which holds the user data.
*
* @param int $id User ID
* @param string $name User's username
* @return WP_User Current user User object
*/
function wp_set_current_user($id, $name = '') {
global $current_user;
if ( isset( $current_user ) && ( $current_user instanceof WP_User ) && ( $id == $current_user->ID ) )
return $current_user;
$current_user = new WP_User( $id, $name );
setup_userdata( $current_user->ID );
/**
* Fires after the current user is set.
*
* @since 2.0.1
*/
do_action( 'set_current_user' );
return $current_user;
}
endif;
if ( !function_exists('wp_get_current_user') ) :
/**
* Retrieve the current user object.
*
* @since 2.0.3
*
* @return WP_User Current user WP_User object
*/
function wp_get_current_user() {
global $current_user;
get_currentuserinfo();
return $current_user;
}
endif;
if ( !function_exists('get_currentuserinfo') ) :
/**
* Populate global variables with information about the currently logged in user.
*
* Will set the current user, if the current user is not set. The current user
* will be set to the logged-in person. If no user is logged-in, then it will
* set the current user to 0, which is invalid and won't have any permissions.
*
* @since 0.71
*
* @uses $current_user Checks if the current user is set
* @uses wp_validate_auth_cookie() Retrieves current logged in user.
*
* @return bool|null False on XML-RPC Request and invalid auth cookie. Null when current user set.
*/
function get_currentuserinfo() {
global $current_user;
if ( ! empty( $current_user ) ) {
if ( $current_user instanceof WP_User )
return;
// Upgrade stdClass to WP_User
if ( is_object( $current_user ) && isset( $current_user->ID ) ) {
$cur_id = $current_user->ID;
$current_user = null;
wp_set_current_user( $cur_id );
return;
}
// $current_user has a junk value. Force to WP_User with ID 0.
$current_user = null;
wp_set_current_user( 0 );
return false;
}
if ( defined('XMLRPC_REQUEST') && XMLRPC_REQUEST ) {
wp_set_current_user( 0 );
return false;
}
/**
* Filter the current user.
*
* The default filters use this to determine the current user from the
* request's cookies, if available.
*
* Returning a value of false will effectively short-circuit setting
* the current user.
*
* @since 3.9.0
*
* @param int|bool $user_id User ID if one has been determined, false otherwise.
*/
$user_id = apply_filters( 'determine_current_user', false );
if ( ! $user_id ) {
wp_set_current_user( 0 );
return false;
}
wp_set_current_user( $user_id );
}
endif;
if ( !function_exists('get_userdata') ) :
/**
* Retrieve user info by user ID.
*
* @since 0.71
*
* @param int $user_id User ID
* @return WP_User|bool WP_User object on success, false on failure.
*/
function get_userdata( $user_id ) {
return get_user_by( 'id', $user_id );
}
endif;
if ( !function_exists('get_user_by') ) :
/**
* Retrieve user info by a given field
*
* @since 2.8.0
*
* @param string $field The field to retrieve the user with. id | slug | email | login
* @param int|string $value A value for $field. A user ID, slug, email address, or login name.
* @return WP_User|bool WP_User object on success, false on failure.
*/
function get_user_by( $field, $value ) {
$userdata = WP_User::get_data_by( $field, $value );
if ( !$userdata )
return false;
$user = new WP_User;
$user->init( $userdata );
return $user;
}
endif;
if ( !function_exists('cache_users') ) :
/**
* Retrieve info for user lists to prevent multiple queries by get_userdata()
*
* @since 3.0.0
*
* @param array $user_ids User ID numbers list
*/
function cache_users( $user_ids ) {
global $wpdb;
$clean = _get_non_cached_ids( $user_ids, 'users' );
if ( empty( $clean ) )
return;
$list = implode( ',', $clean );
$users = $wpdb->get_results( "SELECT * FROM $wpdb->users WHERE ID IN ($list)" );
$ids = array();
foreach ( $users as $user ) {
update_user_caches( $user );
$ids[] = $user->ID;
}
update_meta_cache( 'user', $ids );
}
endif;
if ( !function_exists( 'wp_mail' ) ) :
/**
* Send mail, similar to PHP's mail
*
* A true return value does not automatically mean that the user received the
* email successfully. It just only means that the method used was able to
* process the request without any errors.
*
* Using the two 'wp_mail_from' and 'wp_mail_from_name' hooks allow from
* creating a from address like 'Name <email@address.com>' when both are set. If
* just 'wp_mail_from' is set, then just the email address will be used with no
* name.
*
* The default content type is 'text/plain' which does not allow using HTML.
* However, you can set the content type of the email by using the
* 'wp_mail_content_type' filter.
*
* The default charset is based on the charset used on the blog. The charset can
* be set using the 'wp_mail_charset' filter.
*
* @since 1.2.1
*
* @uses PHPMailer
*
* @param string|array $to Array or comma-separated list of email addresses to send message.
* @param string $subject Email subject
* @param string $message Message contents
* @param string|array $headers Optional. Additional headers.
* @param string|array $attachments Optional. Files to attach.
* @return bool Whether the email contents were sent successfully.
*/
function wp_mail( $to, $subject, $message, $headers = '', $attachments = array() ) {
// Compact the input, apply the filters, and extract them back out
/**
* Filter the wp_mail() arguments.
*
* @since 2.2.0
*
* @param array $args A compacted array of wp_mail() arguments, including the "to" email,
* subject, message, headers, and attachments values.
*/
extract( apply_filters( 'wp_mail', compact( 'to', 'subject', 'message', 'headers', 'attachments' ) ) );
if ( !is_array($attachments) )
$attachments = explode( "\n", str_replace( "\r\n", "\n", $attachments ) );
global $phpmailer;
// (Re)create it, if it's gone missing
if ( !is_object( $phpmailer ) || !is_a( $phpmailer, 'PHPMailer' ) ) {
require_once ABSPATH . WPINC . '/class-phpmailer.php';
require_once ABSPATH . WPINC . '/class-smtp.php';
$phpmailer = new PHPMailer( true );
}
// Headers
if ( empty( $headers ) ) {
$headers = array();
} else {
if ( !is_array( $headers ) ) {
// Explode the headers out, so this function can take both
// string headers and an array of headers.
$tempheaders = explode( "\n", str_replace( "\r\n", "\n", $headers ) );
} else {
$tempheaders = $headers;
}
$headers = array();
$cc = array();
$bcc = array();
// If it's actually got contents
if ( !empty( $tempheaders ) ) {
// Iterate through the raw headers
foreach ( (array) $tempheaders as $header ) {
if ( strpos($header, ':') === false ) {
if ( false !== stripos( $header, 'boundary=' ) ) {
$parts = preg_split('/boundary=/i', trim( $header ) );
$boundary = trim( str_replace( array( "'", '"' ), '', $parts[1] ) );
}
continue;
}
// Explode them out
list( $name, $content ) = explode( ':', trim( $header ), 2 );
// Cleanup crew
$name = trim( $name );
$content = trim( $content );
switch ( strtolower( $name ) ) {
// Mainly for legacy -- process a From: header if it's there
case 'from':
if ( strpos($content, '<' ) !== false ) {
// So... making my life hard again?
$from_name = substr( $content, 0, strpos( $content, '<' ) - 1 );
$from_name = str_replace( '"', '', $from_name );
$from_name = trim( $from_name );
$from_email = substr( $content, strpos( $content, '<' ) + 1 );
$from_email = str_replace( '>', '', $from_email );
$from_email = trim( $from_email );
} else {
$from_email = trim( $content );
}
break;
case 'content-type':
if ( strpos( $content, ';' ) !== false ) {
list( $type, $charset ) = explode( ';', $content );
$content_type = trim( $type );
if ( false !== stripos( $charset, 'charset=' ) ) {
$charset = trim( str_replace( array( 'charset=', '"' ), '', $charset ) );
} elseif ( false !== stripos( $charset, 'boundary=' ) ) {
$boundary = trim( str_replace( array( 'BOUNDARY=', 'boundary=', '"' ), '', $charset ) );
$charset = '';
}
} else {
$content_type = trim( $content );
}
break;
case 'cc':
$cc = array_merge( (array) $cc, explode( ',', $content ) );
break;
case 'bcc':
$bcc = array_merge( (array) $bcc, explode( ',', $content ) );
break;
default:
// Add it to our grand headers array
$headers[trim( $name )] = trim( $content );
break;
}
}
}
}
// Empty out the values that may be set
$phpmailer->ClearAllRecipients();
$phpmailer->ClearAttachments();
$phpmailer->ClearCustomHeaders();
$phpmailer->ClearReplyTos();
// From email and name
// If we don't have a name from the input headers
if ( !isset( $from_name ) )
$from_name = 'WordPress';
/* If we don't have an email from the input headers default to wordpress@$sitename
* Some hosts will block outgoing mail from this address if it doesn't exist but
* there's no easy alternative. Defaulting to admin_email might appear to be another
* option but some hosts may refuse to relay mail from an unknown domain. See
* http://trac.wordpress.org/ticket/5007.
*/
if ( !isset( $from_email ) ) {
// Get the site domain and get rid of www.
$sitename = strtolower( $_SERVER['SERVER_NAME'] );
if ( substr( $sitename, 0, 4 ) == 'www.' ) {
$sitename = substr( $sitename, 4 );
}
$from_email = 'wordpress@' . $sitename;
}
/**
* Filter the email address to send from.
*
* @since 2.2.0
*
* @param string $from_email Email address to send from.
*/
$phpmailer->From = apply_filters( 'wp_mail_from', $from_email );
/**
* Filter the name to associate with the "from" email address.
*
* @since 2.3.0
*
* @param string $from_name Name associated with the "from" email address.
*/
$phpmailer->FromName = apply_filters( 'wp_mail_from_name', $from_name );
// Set destination addresses
if ( !is_array( $to ) )
$to = explode( ',', $to );
foreach ( (array) $to as $recipient ) {
try {
// Break $recipient into name and address parts if in the format "Foo <bar@baz.com>"
$recipient_name = '';
if( preg_match( '/(.*)<(.+)>/', $recipient, $matches ) ) {
if ( count( $matches ) == 3 ) {
$recipient_name = $matches[1];
$recipient = $matches[2];
}
}
$phpmailer->AddAddress( $recipient, $recipient_name);
} catch ( phpmailerException $e ) {
continue;
}
}
// Set mail's subject and body
$phpmailer->Subject = $subject;
$phpmailer->Body = $message;
// Add any CC and BCC recipients
if ( !empty( $cc ) ) {
foreach ( (array) $cc as $recipient ) {
try {
// Break $recipient into name and address parts if in the format "Foo <bar@baz.com>"
$recipient_name = '';
if( preg_match( '/(.*)<(.+)>/', $recipient, $matches ) ) {
if ( count( $matches ) == 3 ) {
$recipient_name = $matches[1];
$recipient = $matches[2];
}
}
$phpmailer->AddCc( $recipient, $recipient_name );
} catch ( phpmailerException $e ) {
continue;
}
}
}
if ( !empty( $bcc ) ) {
foreach ( (array) $bcc as $recipient) {
try {
// Break $recipient into name and address parts if in the format "Foo <bar@baz.com>"
$recipient_name = '';
if( preg_match( '/(.*)<(.+)>/', $recipient, $matches ) ) {
if ( count( $matches ) == 3 ) {
$recipient_name = $matches[1];
$recipient = $matches[2];
}
}
$phpmailer->AddBcc( $recipient, $recipient_name );
} catch ( phpmailerException $e ) {
continue;
}
}
}
// Set to use PHP's mail()
$phpmailer->IsMail();
// Set Content-Type and charset
// If we don't have a content-type from the input headers
if ( !isset( $content_type ) )
$content_type = 'text/plain';
/**
* Filter the wp_mail() content type.
*
* @since 2.3.0
*
* @param string $content_type Default wp_mail() content type.
*/
$content_type = apply_filters( 'wp_mail_content_type', $content_type );
$phpmailer->ContentType = $content_type;
// Set whether it's plaintext, depending on $content_type
if ( 'text/html' == $content_type )
$phpmailer->IsHTML( true );
// If we don't have a charset from the input headers
if ( !isset( $charset ) )
$charset = get_bloginfo( 'charset' );
// Set the content-type and charset
/**
* Filter the default wp_mail() charset.
*
* @since 2.3.0
*
* @param string $charset Default email charset.
*/
$phpmailer->CharSet = apply_filters( 'wp_mail_charset', $charset );
// Set custom headers
if ( !empty( $headers ) ) {
foreach( (array) $headers as $name => $content ) {
$phpmailer->AddCustomHeader( sprintf( '%1$s: %2$s', $name, $content ) );
}
if ( false !== stripos( $content_type, 'multipart' ) && ! empty($boundary) )
$phpmailer->AddCustomHeader( sprintf( "Content-Type: %s;\n\t boundary=\"%s\"", $content_type, $boundary ) );
}
if ( !empty( $attachments ) ) {
foreach ( $attachments as $attachment ) {
try {
$phpmailer->AddAttachment($attachment);
} catch ( phpmailerException $e ) {
continue;
}
}
}
/**
* Fires after PHPMailer is initialized.
*
* @since 2.2.0
*
* @param PHPMailer &$phpmailer The PHPMailer instance, passed by reference.
*/
do_action_ref_array( 'phpmailer_init', array( &$phpmailer ) );
// Send!
try {
return $phpmailer->Send();
} catch ( phpmailerException $e ) {
return false;
}
}
endif;
if ( !function_exists('wp_authenticate') ) :
/**
* Checks a user's login information and logs them in if it checks out.
*
* @since 2.5.0
*
* @param string $username User's username
* @param string $password User's password
* @return WP_User|WP_Error WP_User object if login successful, otherwise WP_Error object.
*/
function wp_authenticate($username, $password) {
$username = sanitize_user($username);
$password = trim($password);
/**
* Filter the user to authenticate.
*
* If a non-null value is passed, the filter will effectively short-circuit
* authentication, returning an error instead.
*
* @since 2.8.0
*
* @param null|WP_User $user User to authenticate.
* @param string $username User login.
* @param string $password User password
*/
$user = apply_filters( 'authenticate', null, $username, $password );
if ( $user == null ) {
// TODO what should the error message be? (Or would these even happen?)
// Only needed if all authentication handlers fail to return anything.
$user = new WP_Error('authentication_failed', __('<strong>ERROR</strong>: Invalid username or incorrect password.'));
}
$ignore_codes = array('empty_username', 'empty_password');
if (is_wp_error($user) && !in_array($user->get_error_code(), $ignore_codes) ) {
/**
* Fires after a user login has failed.
*
* @since 2.5.0
*
* @param string $username User login.
*/
do_action( 'wp_login_failed', $username );
}
return $user;
}
endif;
if ( !function_exists('wp_logout') ) :
/**
* Log the current user out.
*
* @since 2.5.0
*/
function wp_logout() {
wp_clear_auth_cookie();
/**
* Fires after a user is logged-out.
*
* @since 1.5.0
*/
do_action( 'wp_logout' );
}
endif;
if ( !function_exists('wp_validate_auth_cookie') ) :
/**
* Validates authentication cookie.
*
* The checks include making sure that the authentication cookie is set and
* pulling in the contents (if $cookie is not used).
*
* Makes sure the cookie is not expired. Verifies the hash in cookie is what is
* should be and compares the two.
*
* @since 2.5.0
*
* @param string $cookie Optional. If used, will validate contents instead of cookie's
* @param string $scheme Optional. The cookie scheme to use: auth, secure_auth, or logged_in
* @return bool|int False if invalid cookie, User ID if valid.
*/
function wp_validate_auth_cookie($cookie = '', $scheme = '') {
if ( ! $cookie_elements = wp_parse_auth_cookie($cookie, $scheme) ) {
/**
* Fires if an authentication cookie is malformed.
*
* @since 2.7.0
*
* @param string $cookie Malformed auth cookie.
* @param string $scheme Authentication scheme. Values include 'auth', 'secure_auth',
* or 'logged_in'.
*/
do_action( 'auth_cookie_malformed', $cookie, $scheme );
return false;
}
extract($cookie_elements, EXTR_OVERWRITE);
$expired = $expiration;
// Allow a grace period for POST and AJAX requests
if ( defined('DOING_AJAX') || 'POST' == $_SERVER['REQUEST_METHOD'] )
$expired += HOUR_IN_SECONDS;
// Quick check to see if an honest cookie has expired
if ( $expired < time() ) {
/**
* Fires once an authentication cookie has expired.
*
* @since 2.7.0
*
* @param array $cookie_elements An array of data for the authentication cookie.
*/
do_action( 'auth_cookie_expired', $cookie_elements );
return false;
}
$user = get_user_by('login', $username);
if ( ! $user ) {
/**
* Fires if a bad username is entered in the user authentication process.
*
* @since 2.7.0
*
* @param array $cookie_elements An array of data for the authentication cookie.
*/
do_action( 'auth_cookie_bad_username', $cookie_elements );
return false;
}
$pass_frag = substr($user->user_pass, 8, 4);
$key = wp_hash($username . $pass_frag . '|' . $expiration, $scheme);
$hash = hash_hmac('md5', $username . '|' . $expiration, $key);
if ( ! hash_equals( $hash, $hmac ) ) {
/**
* Fires if a bad authentication cookie hash is encountered.
*
* @since 2.7.0
*
* @param array $cookie_elements An array of data for the authentication cookie.
*/
do_action( 'auth_cookie_bad_hash', $cookie_elements );
return false;
}
if ( $expiration < time() ) // AJAX/POST grace period set above
$GLOBALS['login_grace_period'] = 1;
/**
* Fires once an authentication cookie has been validated.
*
* @since 2.7.0
*
* @param array $cookie_elements An array of data for the authentication cookie.
* @param WP_User $user User object.
*/
do_action( 'auth_cookie_valid', $cookie_elements, $user );
return $user->ID;
}
endif;
if ( !function_exists('wp_generate_auth_cookie') ) :
/**
* Generate authentication cookie contents.
*
* @since 2.5.0
*
* @param int $user_id User ID
* @param int $expiration Cookie expiration in seconds
* @param string $scheme Optional. The cookie scheme to use: auth, secure_auth, or logged_in
* @return string Authentication cookie contents
*/
function wp_generate_auth_cookie($user_id, $expiration, $scheme = 'auth') {
$user = get_userdata($user_id);
$pass_frag = substr($user->user_pass, 8, 4);
$key = wp_hash($user->user_login . $pass_frag . '|' . $expiration, $scheme);
$hash = hash_hmac('md5', $user->user_login . '|' . $expiration, $key);
$cookie = $user->user_login . '|' . $expiration . '|' . $hash;
/**
* Filter the authentication cookie.
*
* @since 2.5.0
*
* @param string $cookie Authentication cookie.
* @param int $user_id User ID.
* @param int $expiration Authentication cookie expiration in seconds.
* @param string $scheme Cookie scheme used. Accepts 'auth', 'secure_auth', or 'logged_in'.
*/
return apply_filters( 'auth_cookie', $cookie, $user_id, $expiration, $scheme );
}
endif;
if ( !function_exists('wp_parse_auth_cookie') ) :
/**
* Parse a cookie into its components
*
* @since 2.7.0
*
* @param string $cookie
* @param string $scheme Optional. The cookie scheme to use: auth, secure_auth, or logged_in
* @return array Authentication cookie components
*/
function wp_parse_auth_cookie($cookie = '', $scheme = '') {
if ( empty($cookie) ) {
switch ($scheme){
case 'auth':
$cookie_name = AUTH_COOKIE;
break;
case 'secure_auth':
$cookie_name = SECURE_AUTH_COOKIE;
break;
case "logged_in":
$cookie_name = LOGGED_IN_COOKIE;
break;
default:
if ( is_ssl() ) {
$cookie_name = SECURE_AUTH_COOKIE;
$scheme = 'secure_auth';
} else {
$cookie_name = AUTH_COOKIE;
$scheme = 'auth';
}
}
if ( empty($_COOKIE[$cookie_name]) )
return false;
$cookie = $_COOKIE[$cookie_name];
}
$cookie_elements = explode('|', $cookie);
if ( count($cookie_elements) != 3 )
return false;
list($username, $expiration, $hmac) = $cookie_elements;
return compact('username', 'expiration', 'hmac', 'scheme');
}
endif;
if ( !function_exists('wp_set_auth_cookie') ) :
/**
* Sets the authentication cookies based on user ID.
*
* The $remember parameter increases the time that the cookie will be kept. The
* default the cookie is kept without remembering is two days. When $remember is
* set, the cookies will be kept for 14 days or two weeks.
*
* @since 2.5.0
*
* @param int $user_id User ID
* @param bool $remember Whether to remember the user
*/
function wp_set_auth_cookie($user_id, $remember = false, $secure = '') {
if ( $remember ) {
/**
* Filter the duration of the authentication cookie expiration period.
*
* @since 2.8.0
*
* @param int $length Duration of the expiration period in seconds.
* @param int $user_id User ID.
* @param bool $remember Whether to remember the user login. Default false.
*/
$expiration = time() + apply_filters( 'auth_cookie_expiration', 14 * DAY_IN_SECONDS, $user_id, $remember );
/*
* Ensure the browser will continue to send the cookie after the expiration time is reached.
* Needed for the login grace period in wp_validate_auth_cookie().
*/
$expire = $expiration + ( 12 * HOUR_IN_SECONDS );
} else {
/** This filter is documented in wp-includes/pluggable.php */
$expiration = time() + apply_filters( 'auth_cookie_expiration', 2 * DAY_IN_SECONDS, $user_id, $remember );
$expire = 0;
}
if ( '' === $secure )
$secure = is_ssl();
/**
* Filter whether the connection is secure.
*
* @since 3.1.0
*
* @param bool $secure Whether the connection is secure.
* @param int $user_id User ID.
*/
$secure = apply_filters( 'secure_auth_cookie', $secure, $user_id );
/**
* Filter whether to use a secure cookie when logged-in.
*
* @since 3.1.0
*
* @param bool $cookie Whether to use a secure cookie when logged-in.
* @param int $user_id User ID.
* @param bool $secure Whether the connection is secure.
*/
$secure_logged_in_cookie = apply_filters( 'secure_logged_in_cookie', false, $user_id, $secure );
if ( $secure ) {
$auth_cookie_name = SECURE_AUTH_COOKIE;
$scheme = 'secure_auth';
} else {
$auth_cookie_name = AUTH_COOKIE;
$scheme = 'auth';
}
$auth_cookie = wp_generate_auth_cookie($user_id, $expiration, $scheme);
$logged_in_cookie = wp_generate_auth_cookie($user_id, $expiration, 'logged_in');
/**
* Fires immediately before the authentication cookie is set.
*
* @since 2.5.0
*
* @param string $auth_cookie Authentication cookie.
* @param int $expire Login grace period in seconds. Default 43,200 seconds, or 12 hours.
* @param int $expiration Duration in seconds the authentication cookie should be valid.
* Default 1,209,600 seconds, or 14 days.
* @param int $user_id User ID.
* @param string $scheme Authentication scheme. Values include 'auth', 'secure_auth', or 'logged_in'.
*/
do_action( 'set_auth_cookie', $auth_cookie, $expire, $expiration, $user_id, $scheme );
/**
* Fires immediately before the secure authentication cookie is set.
*
* @since 2.6.0
*
* @param string $logged_in_cookie The logged-in cookie.
* @param int $expire Login grace period in seconds. Default 43,200 seconds, or 12 hours.
* @param int $expiration Duration in seconds the authentication cookie should be valid.
* Default 1,209,600 seconds, or 14 days.
* @param int $user_id User ID.
* @param string $scheme Authentication scheme. Default 'logged_in'.
*/
do_action( 'set_logged_in_cookie', $logged_in_cookie, $expire, $expiration, $user_id, 'logged_in' );
setcookie($auth_cookie_name, $auth_cookie, $expire, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN, $secure, true);
setcookie($auth_cookie_name, $auth_cookie, $expire, ADMIN_COOKIE_PATH, COOKIE_DOMAIN, $secure, true);
setcookie(LOGGED_IN_COOKIE, $logged_in_cookie, $expire, COOKIEPATH, COOKIE_DOMAIN, $secure_logged_in_cookie, true);
if ( COOKIEPATH != SITECOOKIEPATH )
setcookie(LOGGED_IN_COOKIE, $logged_in_cookie, $expire, SITECOOKIEPATH, COOKIE_DOMAIN, $secure_logged_in_cookie, true);
}
endif;
if ( !function_exists('wp_clear_auth_cookie') ) :
/**
* Removes all of the cookies associated with authentication.
*
* @since 2.5.0
*/
function wp_clear_auth_cookie() {
/**
* Fires just before the authentication cookies are cleared.
*
* @since 2.7.0
*/
do_action( 'clear_auth_cookie' );
setcookie( AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, ADMIN_COOKIE_PATH, COOKIE_DOMAIN );
setcookie( SECURE_AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, ADMIN_COOKIE_PATH, COOKIE_DOMAIN );
setcookie( AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN );
setcookie( SECURE_AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN );
setcookie( LOGGED_IN_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
setcookie( LOGGED_IN_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN );
// Old cookies
setcookie( AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
setcookie( AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN );
setcookie( SECURE_AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
setcookie( SECURE_AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN );
// Even older cookies
setcookie( USER_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
setcookie( PASS_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
setcookie( USER_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN );
setcookie( PASS_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN );
}
endif;
if ( !function_exists('is_user_logged_in') ) :
/**
* Checks if the current visitor is a logged in user.
*
* @since 2.0.0
*
* @return bool True if user is logged in, false if not logged in.
*/
function is_user_logged_in() {
$user = wp_get_current_user();
if ( ! $user->exists() )
return false;
return true;
}
endif;
if ( !function_exists('auth_redirect') ) :
/**
* Checks if a user is logged in, if not it redirects them to the login page.
*
* @since 1.5.0
*/
function auth_redirect() {
// Checks if a user is logged in, if not redirects them to the login page
$secure = ( is_ssl() || force_ssl_admin() );
/**
* Filter whether to use a secure authentication redirect.
*
* @since 3.1.0
*
* @param bool $secure Whether to use a secure authentication redirect. Default false.
*/
$secure = apply_filters( 'secure_auth_redirect', $secure );
// If https is required and request is http, redirect
if ( $secure && !is_ssl() && false !== strpos($_SERVER['REQUEST_URI'], 'wp-admin') ) {
if ( 0 === strpos( $_SERVER['REQUEST_URI'], 'http' ) ) {
wp_redirect( set_url_scheme( $_SERVER['REQUEST_URI'], 'https' ) );
exit();
} else {
wp_redirect( 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
exit();
}
}
if ( is_user_admin() ) {
$scheme = 'logged_in';
} else {
/**
* Filter the authentication redirect scheme.
*
* @since 2.9.0
*
* @param string $scheme Authentication redirect scheme. Default empty.
*/
$scheme = apply_filters( 'auth_redirect_scheme', '' );
}
if ( $user_id = wp_validate_auth_cookie( '', $scheme) ) {
/**
* Fires before the authentication redirect.
*
* @since 2.8.0
*
* @param int $user_id User ID.
*/
do_action( 'auth_redirect', $user_id );
// If the user wants ssl but the session is not ssl, redirect.
if ( !$secure && get_user_option('use_ssl', $user_id) && false !== strpos($_SERVER['REQUEST_URI'], 'wp-admin') ) {
if ( 0 === strpos( $_SERVER['REQUEST_URI'], 'http' ) ) {
wp_redirect( set_url_scheme( $_SERVER['REQUEST_URI'], 'https' ) );
exit();
} else {
wp_redirect( 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
exit();
}
}
return; // The cookie is good so we're done
}
// The cookie is no good so force login
nocache_headers();
$redirect = ( strpos( $_SERVER['REQUEST_URI'], '/options.php' ) && wp_get_referer() ) ? wp_get_referer() : set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
$login_url = wp_login_url($redirect, true);
wp_redirect($login_url);
exit();
}
endif;
if ( !function_exists('check_admin_referer') ) :
/**
* Makes sure that a user was referred from another admin page.
*
* To avoid security exploits.
*
* @since 1.2.0
*
* @param string $action Action nonce
* @param string $query_arg where to look for nonce in $_REQUEST (since 2.5)
*/
function check_admin_referer($action = -1, $query_arg = '_wpnonce') {
if ( -1 == $action )
_doing_it_wrong( __FUNCTION__, __( 'You should specify a nonce action to be verified by using the first parameter.' ), '3.2' );
$adminurl = strtolower(admin_url());
$referer = strtolower(wp_get_referer());
$result = isset($_REQUEST[$query_arg]) ? wp_verify_nonce($_REQUEST[$query_arg], $action) : false;
if ( !$result && !(-1 == $action && strpos($referer, $adminurl) === 0) ) {
wp_nonce_ays($action);
die();
}
/**
* Fires once the admin request has been validated or not.
*
* @since 1.5.1
*
* @param string $action The nonce action.
* @param bool $result Whether the admin request nonce was validated.
*/
do_action( 'check_admin_referer', $action, $result );
return $result;
}
endif;
if ( !function_exists('check_ajax_referer') ) :
/**
* Verifies the AJAX request to prevent processing requests external of the blog.
*
* @since 2.0.3
*
* @param string $action Action nonce
* @param string $query_arg where to look for nonce in $_REQUEST (since 2.5)
*/
function check_ajax_referer( $action = -1, $query_arg = false, $die = true ) {
$nonce = '';
if ( $query_arg && isset( $_REQUEST[ $query_arg ] ) )
$nonce = $_REQUEST[ $query_arg ];
elseif ( isset( $_REQUEST['_ajax_nonce'] ) )
$nonce = $_REQUEST['_ajax_nonce'];
elseif ( isset( $_REQUEST['_wpnonce'] ) )
$nonce = $_REQUEST['_wpnonce'];
$result = wp_verify_nonce( $nonce, $action );
if ( $die && false == $result ) {
if ( defined( 'DOING_AJAX' ) && DOING_AJAX )
wp_die( -1 );
else
die( '-1' );
}
/**
* Fires once the AJAX request has been validated or not.
*
* @since 2.1.0
*
* @param string $action The AJAX nonce action.
* @param bool $result Whether the AJAX request nonce was validated.
*/
do_action( 'check_ajax_referer', $action, $result );
return $result;
}
endif;
if ( !function_exists('wp_redirect') ) :
/**
* Redirects to another page.
*
* @since 1.5.1
*
* @param string $location The path to redirect to.
* @param int $status Status code to use.
* @return bool False if $location is not provided, true otherwise.
*/
function wp_redirect($location, $status = 302) {
global $is_IIS;
/**
* Filter the redirect location.
*
* @since 2.1.0
*
* @param string $location The path to redirect to.
* @param int $status Status code to use.
*/
$location = apply_filters( 'wp_redirect', $location, $status );
/**
* Filter the redirect status code.
*
* @since 2.3.0
*
* @param int $status Status code to use.
* @param string $location The path to redirect to.
*/
$status = apply_filters( 'wp_redirect_status', $status, $location );
if ( ! $location )
return false;
$location = wp_sanitize_redirect($location);
if ( !$is_IIS && php_sapi_name() != 'cgi-fcgi' )
status_header($status); // This causes problems on IIS and some FastCGI setups
header("Location: $location", true, $status);
return true;
}
endif;
if ( !function_exists('wp_sanitize_redirect') ) :
/**
* Sanitizes a URL for use in a redirect.
*
* @since 2.3.0
*
* @return string redirect-sanitized URL
**/
function wp_sanitize_redirect($location) {
$location = preg_replace('|[^a-z0-9-~+_.?#=&;,/:%!]|i', '', $location);
$location = wp_kses_no_null($location);
// remove %0d and %0a from location
$strip = array('%0d', '%0a', '%0D', '%0A');
$location = _deep_replace($strip, $location);
return $location;
}
endif;
if ( !function_exists('wp_safe_redirect') ) :
/**
* Performs a safe (local) redirect, using wp_redirect().
*
* Checks whether the $location is using an allowed host, if it has an absolute
* path. A plugin can therefore set or remove allowed host(s) to or from the
* list.
*
* If the host is not allowed, then the redirect is to wp-admin on the siteurl
* instead. This prevents malicious redirects which redirect to another host,
* but only used in a few places.
*
* @since 2.3.0
*
* @uses wp_validate_redirect() To validate the redirect is to an allowed host.
*
* @return void Does not return anything
**/
function wp_safe_redirect($location, $status = 302) {
// Need to look at the URL the way it will end up in wp_redirect()
$location = wp_sanitize_redirect($location);
$location = wp_validate_redirect($location, admin_url());
wp_redirect($location, $status);
}
endif;
if ( !function_exists('wp_validate_redirect') ) :
/**
* Validates a URL for use in a redirect.
*
* Checks whether the $location is using an allowed host, if it has an absolute
* path. A plugin can therefore set or remove allowed host(s) to or from the
* list.
*
* If the host is not allowed, then the redirect is to $default supplied
*
* @since 2.8.1
*
* @param string $location The redirect to validate
* @param string $default The value to return if $location is not allowed
* @return string redirect-sanitized URL
**/
function wp_validate_redirect($location, $default = '') {
$location = trim( $location );
// browsers will assume 'http' is your protocol, and will obey a redirect to a URL starting with '//'
if ( substr($location, 0, 2) == '//' )
$location = 'http:' . $location;
// In php 5 parse_url may fail if the URL query part contains http://, bug #38143
$test = ( $cut = strpos($location, '?') ) ? substr( $location, 0, $cut ) : $location;
$lp = parse_url($test);
// Give up if malformed URL
if ( false === $lp )
return $default;
// Allow only http and https schemes. No data:, etc.
if ( isset($lp['scheme']) && !('http' == $lp['scheme'] || 'https' == $lp['scheme']) )
return $default;
// Reject if scheme is set but host is not. This catches urls like https:host.com for which parse_url does not set the host field.
if ( isset($lp['scheme']) && !isset($lp['host']) )
return $default;
$wpp = parse_url(home_url());
/**
* Filter the whitelist of hosts to redirect to.
*
* @since 2.3.0
*
* @param array $hosts An array of allowed hosts.
* @param bool|string $host The parsed host; empty if not isset.
*/
$allowed_hosts = (array) apply_filters( 'allowed_redirect_hosts', array($wpp['host']), isset($lp['host']) ? $lp['host'] : '' );
if ( isset($lp['host']) && ( !in_array($lp['host'], $allowed_hosts) && $lp['host'] != strtolower($wpp['host'])) )
$location = $default;
return $location;
}
endif;
if ( ! function_exists('wp_notify_postauthor') ) :
/**
* Notify an author (and/or others) of a comment/trackback/pingback on a post.
*
* @since 1.0.0
*
* @param int $comment_id Comment ID
* @param string $deprecated Not used
* @return bool True on completion. False if no email addresses were specified.
*/
function wp_notify_postauthor( $comment_id, $deprecated = null ) {
if ( null !== $deprecated ) {
_deprecated_argument( __FUNCTION__, '3.8' );
}
$comment = get_comment( $comment_id );
if ( empty( $comment ) )
return false;
$post = get_post( $comment->comment_post_ID );
$author = get_userdata( $post->post_author );
// Who to notify? By default, just the post author, but others can be added.
$emails = array();
if ( $author ) {
$emails[] = $author->user_email;
}
/**
* Filter the list of email addresses to receive a comment notification.
*
* By default, only post authors are notified of comments. This filter allows
* others to be added.
*
* @since 3.7.0
*
* @param array $emails An array of email addresses to receive a comment notification.
* @param int $comment_id The comment ID.
*/
$emails = apply_filters( 'comment_notification_recipients', $emails, $comment_id );
$emails = array_filter( $emails );
// If there are no addresses to send the comment to, bail.
if ( ! count( $emails ) ) {
return false;
}
// Facilitate unsetting below without knowing the keys.
$emails = array_flip( $emails );
/**
* Filter whether to notify comment authors of their comments on their own posts.
*
* By default, comment authors aren't notified of their comments on their own
* posts. This filter allows you to override that.
*
* @since 3.8.0
*
* @param bool $notify Whether to notify the post author of their own comment.
* Default false.
* @param int $comment_id The comment ID.
*/
$notify_author = apply_filters( 'comment_notification_notify_author', false, $comment_id );
// The comment was left by the author
if ( $author && ! $notify_author && $comment->user_id == $post->post_author ) {
unset( $emails[ $author->user_email ] );
}
// The author moderated a comment on their own post
if ( $author && ! $notify_author && $post->post_author == get_current_user_id() ) {
unset( $emails[ $author->user_email ] );
}
// The post author is no longer a member of the blog
if ( $author && ! $notify_author && ! user_can( $post->post_author, 'read_post', $post->ID ) ) {
unset( $emails[ $author->user_email ] );
}
// If there's no email to send the comment to, bail, otherwise flip array back around for use below
if ( ! count( $emails ) ) {
return false;
} else {
$emails = array_flip( $emails );
}
$comment_author_domain = @gethostbyaddr($comment->comment_author_IP);
// The blogname option is escaped with esc_html on the way into the database in sanitize_option
// we want to reverse this for the plain text arena of emails.
$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
switch ( $comment->comment_type ) {
case 'trackback':
$notify_message = sprintf( __( 'New trackback on your post "%s"' ), $post->post_title ) . "\r\n";
/* translators: 1: website name, 2: author IP, 3: author domain */
$notify_message .= sprintf( __('Website: %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
$notify_message .= sprintf( __('URL : %s'), $comment->comment_author_url ) . "\r\n";
$notify_message .= __('Excerpt: ') . "\r\n" . $comment->comment_content . "\r\n\r\n";
$notify_message .= __('You can see all trackbacks on this post here: ') . "\r\n";
/* translators: 1: blog name, 2: post title */
$subject = sprintf( __('[%1$s] Trackback: "%2$s"'), $blogname, $post->post_title );
break;
case 'pingback':
$notify_message = sprintf( __( 'New pingback on your post "%s"' ), $post->post_title ) . "\r\n";
/* translators: 1: comment author, 2: author IP, 3: author domain */
$notify_message .= sprintf( __('Website: %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
$notify_message .= sprintf( __('URL : %s'), $comment->comment_author_url ) . "\r\n";
$notify_message .= __('Excerpt: ') . "\r\n" . sprintf('[...] %s [...]', $comment->comment_content ) . "\r\n\r\n";
$notify_message .= __('You can see all pingbacks on this post here: ') . "\r\n";
/* translators: 1: blog name, 2: post title */
$subject = sprintf( __('[%1$s] Pingback: "%2$s"'), $blogname, $post->post_title );
break;
default: // Comments
$notify_message = sprintf( __( 'New comment on your post "%s"' ), $post->post_title ) . "\r\n";
/* translators: 1: comment author, 2: author IP, 3: author domain */
$notify_message .= sprintf( __('Author : %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
$notify_message .= sprintf( __('E-mail : %s'), $comment->comment_author_email ) . "\r\n";
$notify_message .= sprintf( __('URL : %s'), $comment->comment_author_url ) . "\r\n";
$notify_message .= sprintf( __('Whois : http://whois.arin.net/rest/ip/%s'), $comment->comment_author_IP ) . "\r\n";
$notify_message .= __('Comment: ') . "\r\n" . $comment->comment_content . "\r\n\r\n";
$notify_message .= __('You can see all comments on this post here: ') . "\r\n";
/* translators: 1: blog name, 2: post title */
$subject = sprintf( __('[%1$s] Comment: "%2$s"'), $blogname, $post->post_title );
break;
}
$notify_message .= get_permalink($comment->comment_post_ID) . "#comments\r\n\r\n";
$notify_message .= sprintf( __('Permalink: %s'), get_comment_link( $comment_id ) ) . "\r\n";
if ( user_can( $post->post_author, 'edit_comment', $comment_id ) ) {
if ( EMPTY_TRASH_DAYS )
$notify_message .= sprintf( __('Trash it: %s'), admin_url("comment.php?action=trash&c=$comment_id") ) . "\r\n";
else
$notify_message .= sprintf( __('Delete it: %s'), admin_url("comment.php?action=delete&c=$comment_id") ) . "\r\n";
$notify_message .= sprintf( __('Spam it: %s'), admin_url("comment.php?action=spam&c=$comment_id") ) . "\r\n";
}
$wp_email = 'wordpress@' . preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME']));
if ( '' == $comment->comment_author ) {
$from = "From: \"$blogname\" <$wp_email>";
if ( '' != $comment->comment_author_email )
$reply_to = "Reply-To: $comment->comment_author_email";
} else {
$from = "From: \"$comment->comment_author\" <$wp_email>";
if ( '' != $comment->comment_author_email )
$reply_to = "Reply-To: \"$comment->comment_author_email\" <$comment->comment_author_email>";
}
$message_headers = "$from\n"
. "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";
if ( isset($reply_to) )
$message_headers .= $reply_to . "\n";
/**
* Filter the comment notification email text.
*
* @since 1.5.2
*
* @param string $notify_message The comment notification email text.
* @param int $comment_id Comment ID.
*/
$notify_message = apply_filters( 'comment_notification_text', $notify_message, $comment_id );
/**
* Filter the comment notification email subject.
*
* @since 1.5.2
*
* @param string $subject The comment notification email subject.
* @param int $comment_id Comment ID.
*/
$subject = apply_filters( 'comment_notification_subject', $subject, $comment_id );
/**
* Filter the comment notification email headers.
*
* @since 1.5.2
*
* @param string $message_headers Headers for the comment notification email.
* @param int $comment_id Comment ID.
*/
$message_headers = apply_filters( 'comment_notification_headers', $message_headers, $comment_id );
foreach ( $emails as $email ) {
@wp_mail( $email, wp_specialchars_decode( $subject ), $notify_message, $message_headers );
}
return true;
}
endif;
if ( !function_exists('wp_notify_moderator') ) :
/**
* Notifies the moderator of the blog about a new comment that is awaiting approval.
*
* @since 1.0.0
*
* @uses $wpdb
*
* @param int $comment_id Comment ID
* @return bool Always returns true
*/
function wp_notify_moderator($comment_id) {
global $wpdb;
if ( 0 == get_option( 'moderation_notify' ) )
return true;
$comment = get_comment($comment_id);
$post = get_post($comment->comment_post_ID);
$user = get_userdata( $post->post_author );
// Send to the administration and to the post author if the author can modify the comment.
$emails = array( get_option( 'admin_email' ) );
if ( user_can( $user->ID, 'edit_comment', $comment_id ) && ! empty( $user->user_email ) ) {
if ( 0 !== strcasecmp( $user->user_email, get_option( 'admin_email' ) ) )
$emails[] = $user->user_email;
}
$comment_author_domain = @gethostbyaddr($comment->comment_author_IP);
$comments_waiting = $wpdb->get_var("SELECT count(comment_ID) FROM $wpdb->comments WHERE comment_approved = '0'");
// The blogname option is escaped with esc_html on the way into the database in sanitize_option
// we want to reverse this for the plain text arena of emails.
$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
switch ( $comment->comment_type ) {
case 'trackback':
$notify_message = sprintf( __('A new trackback on the post "%s" is waiting for your approval'), $post->post_title ) . "\r\n";
$notify_message .= get_permalink($comment->comment_post_ID) . "\r\n\r\n";
$notify_message .= sprintf( __('Website : %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
$notify_message .= sprintf( __('URL : %s'), $comment->comment_author_url ) . "\r\n";
$notify_message .= __('Trackback excerpt: ') . "\r\n" . $comment->comment_content . "\r\n\r\n";
break;
case 'pingback':
$notify_message = sprintf( __('A new pingback on the post "%s" is waiting for your approval'), $post->post_title ) . "\r\n";
$notify_message .= get_permalink($comment->comment_post_ID) . "\r\n\r\n";
$notify_message .= sprintf( __('Website : %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
$notify_message .= sprintf( __('URL : %s'), $comment->comment_author_url ) . "\r\n";
$notify_message .= __('Pingback excerpt: ') . "\r\n" . $comment->comment_content . "\r\n\r\n";
break;
default: // Comments
$notify_message = sprintf( __('A new comment on the post "%s" is waiting for your approval'), $post->post_title ) . "\r\n";
$notify_message .= get_permalink($comment->comment_post_ID) . "\r\n\r\n";
$notify_message .= sprintf( __('Author : %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
$notify_message .= sprintf( __('E-mail : %s'), $comment->comment_author_email ) . "\r\n";
$notify_message .= sprintf( __('URL : %s'), $comment->comment_author_url ) . "\r\n";
$notify_message .= sprintf( __('Whois : http://whois.arin.net/rest/ip/%s'), $comment->comment_author_IP ) . "\r\n";
$notify_message .= __('Comment: ') . "\r\n" . $comment->comment_content . "\r\n\r\n";
break;
}
$notify_message .= sprintf( __('Approve it: %s'), admin_url("comment.php?action=approve&c=$comment_id") ) . "\r\n";
if ( EMPTY_TRASH_DAYS )
$notify_message .= sprintf( __('Trash it: %s'), admin_url("comment.php?action=trash&c=$comment_id") ) . "\r\n";
else
$notify_message .= sprintf( __('Delete it: %s'), admin_url("comment.php?action=delete&c=$comment_id") ) . "\r\n";
$notify_message .= sprintf( __('Spam it: %s'), admin_url("comment.php?action=spam&c=$comment_id") ) . "\r\n";
$notify_message .= sprintf( _n('Currently %s comment is waiting for approval. Please visit the moderation panel:',
'Currently %s comments are waiting for approval. Please visit the moderation panel:', $comments_waiting), number_format_i18n($comments_waiting) ) . "\r\n";
$notify_message .= admin_url("edit-comments.php?comment_status=moderated") . "\r\n";
$subject = sprintf( __('[%1$s] Please moderate: "%2$s"'), $blogname, $post->post_title );
$message_headers = '';
/**
* Filter the list of recipients for comment moderation emails.
*
* @since 3.7.0
*
* @param array $emails List of email addresses to notify for comment moderation.
* @param int $comment_id Comment ID.
*/
$emails = apply_filters( 'comment_moderation_recipients', $emails, $comment_id );
/**
* Filter the comment moderation email text.
*
* @since 1.5.2
*
* @param string $notify_message Text of the comment moderation email.
* @param int $comment_id Comment ID.
*/
$notify_message = apply_filters( 'comment_moderation_text', $notify_message, $comment_id );
/**
* Filter the comment moderation email subject.
*
* @since 1.5.2
*
* @param string $subject Subject of the comment moderation email.
* @param int $comment_id Comment ID.
*/
$subject = apply_filters( 'comment_moderation_subject', $subject, $comment_id );
/**
* Filter the comment moderation email headers.
*
* @since 2.8.0
*
* @param string $message_headers Headers for the comment moderation email.
* @param int $comment_id Comment ID.
*/
$message_headers = apply_filters( 'comment_moderation_headers', $message_headers, $comment_id );
foreach ( $emails as $email ) {
@wp_mail( $email, wp_specialchars_decode( $subject ), $notify_message, $message_headers );
}
return true;
}
endif;
if ( !function_exists('wp_password_change_notification') ) :
/**
* Notify the blog admin of a user changing password, normally via email.
*
* @since 2.7.0
*
* @param object $user User Object
*/
function wp_password_change_notification(&$user) {
// send a copy of password change notification to the admin
// but check to see if it's the admin whose password we're changing, and skip this
if ( 0 !== strcasecmp( $user->user_email, get_option( 'admin_email' ) ) ) {
$message = sprintf(__('Password Lost and Changed for user: %s'), $user->user_login) . "\r\n";
// The blogname option is escaped with esc_html on the way into the database in sanitize_option
// we want to reverse this for the plain text arena of emails.
$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
wp_mail(get_option('admin_email'), sprintf(__('[%s] Password Lost/Changed'), $blogname), $message);
}
}
endif;
if ( !function_exists('wp_new_user_notification') ) :
/**
* Email login credentials to a newly-registered user.
*
* A new user registration notification is also sent to admin email.
*
* @since 2.0.0
*
* @param int $user_id User ID.
* @param string $plaintext_pass Optional. The user's plaintext password. Default empty.
*/
function wp_new_user_notification($user_id, $plaintext_pass = '') {
$user = get_userdata( $user_id );
// The blogname option is escaped with esc_html on the way into the database in sanitize_option
// we want to reverse this for the plain text arena of emails.
$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
$message = sprintf(__('New user registration on your site %s:'), $blogname) . "\r\n\r\n";
$message .= sprintf(__('Username: %s'), $user->user_login) . "\r\n\r\n";
$message .= sprintf(__('E-mail: %s'), $user->user_email) . "\r\n";
@wp_mail(get_option('admin_email'), sprintf(__('[%s] New User Registration'), $blogname), $message);
if ( empty($plaintext_pass) )
return;
$message = sprintf(__('Username: %s'), $user->user_login) . "\r\n";
$message .= sprintf(__('Password: %s'), $plaintext_pass) . "\r\n";
$message .= wp_login_url() . "\r\n";
wp_mail($user->user_email, sprintf(__('[%s] Your username and password'), $blogname), $message);
}
endif;
if ( !function_exists('wp_nonce_tick') ) :
/**
* Get the time-dependent variable for nonce creation.
*
* A nonce has a lifespan of two ticks. Nonces in their second tick may be
* updated, e.g. by autosave.
*
* @since 2.5.0
*
* @return int
*/
function wp_nonce_tick() {
/**
* Filter the lifespan of nonces in seconds.
*
* @since 2.5.0
*
* @param int $lifespan Lifespan of nonces in seconds. Default 86,400 seconds, or one day.
*/
$nonce_life = apply_filters( 'nonce_life', DAY_IN_SECONDS );
return ceil(time() / ( $nonce_life / 2 ));
}
endif;
if ( !function_exists('wp_verify_nonce') ) :
/**
* Verify that correct nonce was used with time limit.
*
* The user is given an amount of time to use the token, so therefore, since the
* UID and $action remain the same, the independent variable is the time.
*
* @since 2.0.3
*
* @param string $nonce Nonce that was used in the form to verify
* @param string|int $action Should give context to what is taking place and be the same when nonce was created.
* @return bool Whether the nonce check passed or failed.
*/
function wp_verify_nonce($nonce, $action = -1) {
$user = wp_get_current_user();
$uid = (int) $user->ID;
if ( ! $uid ) {
/**
* Filter whether the user who generated the nonce is logged out.
*
* @since 3.5.0
*
* @param int $uid ID of the nonce-owning user.
* @param string $action The nonce action.
*/
$uid = apply_filters( 'nonce_user_logged_out', $uid, $action );
}
$i = wp_nonce_tick();
// Nonce generated 0-12 hours ago
$expected = substr( wp_hash( $i . '|' . $action . '|' . $uid, 'nonce'), -12, 10 );
if ( hash_equals( $expected, $nonce ) ) {
return 1;
}
// Nonce generated 12-24 hours ago
$expected = substr( wp_hash( ( $i - 1 ) . '|' . $action . '|' . $uid, 'nonce' ), -12, 10 );
if ( hash_equals( $expected, $nonce ) ) {
return 2;
}
// Invalid nonce
return false;
}
endif;
if ( !function_exists('wp_create_nonce') ) :
/**
* Creates a random, one time use token.
*
* @since 2.0.3
*
* @param string|int $action Scalar value to add context to the nonce.
* @return string The one use form token
*/
function wp_create_nonce($action = -1) {
$user = wp_get_current_user();
$uid = (int) $user->ID;
if ( ! $uid ) {
/** This filter is documented in wp-includes/pluggable.php */
$uid = apply_filters( 'nonce_user_logged_out', $uid, $action );
}
$i = wp_nonce_tick();
return substr(wp_hash($i . '|' . $action . '|' . $uid, 'nonce'), -12, 10);
}
endif;
if ( !function_exists('wp_salt') ) :
/**
* Get salt to add to hashes.
*
* Salts are created using secret keys. Secret keys are located in two places:
* in the database and in the wp-config.php file. The secret key in the database
* is randomly generated and will be appended to the secret keys in wp-config.php.
*
* The secret keys in wp-config.php should be updated to strong, random keys to maximize
* security. Below is an example of how the secret key constants are defined.
* Do not paste this example directly into wp-config.php. Instead, have a
* {@link https://api.wordpress.org/secret-key/1.1/salt/ secret key created} just
* for you.
*
* <code>
* define('AUTH_KEY', ' Xakm<o xQy rw4EMsLKM-?!T+,PFF})H4lzcW57AF0U@N@< >M%G4Yt>f`z]MON');
* define('SECURE_AUTH_KEY', 'LzJ}op]mr|6+![P}Ak:uNdJCJZd>(Hx.-Mh#Tz)pCIU#uGEnfFz|f ;;eU%/U^O~');
* define('LOGGED_IN_KEY', '|i|Ux`9<p-h$aFf(qnT:sDO:D1P^wZ$$/Ra@miTJi9G;ddp_<q}6H1)o|a +&JCM');
* define('NONCE_KEY', '%:R{[P|,s.KuMltH5}cI;/k<Gx~j!f0I)m_sIyu+&NJZ)-iO>z7X>QYR0Z_XnZ@|');
* define('AUTH_SALT', 'eZyT)-Naw]F8CwA*VaW#q*|.)g@o}||wf~@C-YSt}(dh_r6EbI#A,y|nU2{B#JBW');
* define('SECURE_AUTH_SALT', '!=oLUTXh,QW=H `}`L|9/^4-3 STz},T(w}W<I`.JjPi)<Bmf1v,HpGe}T1:Xt7n');
* define('LOGGED_IN_SALT', '+XSqHc;@Q*K_b|Z?NC[3H!!EONbh.n<+=uKR:>*c(u`g~EJBf#8u#R{mUEZrozmm');
* define('NONCE_SALT', 'h`GXHhD>SLWVfg1(1(N{;.V!MoE(SfbA_ksP@&`+AycHcAV$+?@3q+rxV{%^VyKT');
* </code>
*
* Salting passwords helps against tools which has stored hashed values of
* common dictionary strings. The added values makes it harder to crack.
*
* @since 2.5.0
*
* @link https://api.wordpress.org/secret-key/1.1/salt/ Create secrets for wp-config.php
*
* @param string $scheme Authentication scheme (auth, secure_auth, logged_in, nonce)
* @return string Salt value
*/
function wp_salt( $scheme = 'auth' ) {
static $cached_salts = array();
if ( isset( $cached_salts[ $scheme ] ) ) {
/**
* Filter the WordPress salt.
*
* @since 2.5.0
*
* @param string $cached_salt Cached salt for the given scheme.
* @param string $scheme Authentication scheme. Values include 'auth',
* 'secure_auth', 'logged_in', and 'nonce'.
*/
return apply_filters( 'salt', $cached_salts[ $scheme ], $scheme );
}
static $duplicated_keys;
if ( null === $duplicated_keys ) {
$duplicated_keys = array( 'put your unique phrase here' => true );
foreach ( array( 'AUTH', 'SECURE_AUTH', 'LOGGED_IN', 'NONCE', 'SECRET' ) as $first ) {
foreach ( array( 'KEY', 'SALT' ) as $second ) {
if ( ! defined( "{$first}_{$second}" ) )
continue;
$value = constant( "{$first}_{$second}" );
$duplicated_keys[ $value ] = isset( $duplicated_keys[ $value ] );
}
}
}
$key = $salt = '';
if ( defined( 'SECRET_KEY' ) && SECRET_KEY && empty( $duplicated_keys[ SECRET_KEY ] ) )
$key = SECRET_KEY;
if ( 'auth' == $scheme && defined( 'SECRET_SALT' ) && SECRET_SALT && empty( $duplicated_keys[ SECRET_SALT ] ) )
$salt = SECRET_SALT;
if ( in_array( $scheme, array( 'auth', 'secure_auth', 'logged_in', 'nonce' ) ) ) {
foreach ( array( 'key', 'salt' ) as $type ) {
$const = strtoupper( "{$scheme}_{$type}" );
if ( defined( $const ) && constant( $const ) && empty( $duplicated_keys[ constant( $const ) ] ) ) {
$$type = constant( $const );
} elseif ( ! $$type ) {
$$type = get_site_option( "{$scheme}_{$type}" );
if ( ! $$type ) {
$$type = wp_generate_password( 64, true, true );
update_site_option( "{$scheme}_{$type}", $$type );
}
}
}
} else {
if ( ! $key ) {
$key = get_site_option( 'secret_key' );
if ( ! $key ) {
$key = wp_generate_password( 64, true, true );
update_site_option( 'secret_key', $key );
}
}
$salt = hash_hmac( 'md5', $scheme, $key );
}
$cached_salts[ $scheme ] = $key . $salt;
/** This filter is documented in wp-includes/pluggable.php */
return apply_filters( 'salt', $cached_salts[ $scheme ], $scheme );
}
endif;
if ( !function_exists('wp_hash') ) :
/**
* Get hash of given string.
*
* @since 2.0.3
* @uses wp_salt() Get WordPress salt
*
* @param string $data Plain text to hash
* @return string Hash of $data
*/
function wp_hash($data, $scheme = 'auth') {
$salt = wp_salt($scheme);
return hash_hmac('md5', $data, $salt);
}
endif;
if ( !function_exists('wp_hash_password') ) :
/**
* Create a hash (encrypt) of a plain text password.
*
* For integration with other applications, this function can be overwritten to
* instead use the other package password checking algorithm.
*
* @since 2.5.0
*
* @global object $wp_hasher PHPass object
* @uses PasswordHash::HashPassword
*
* @param string $password Plain text user password to hash
* @return string The hash string of the password
*/
function wp_hash_password($password) {
global $wp_hasher;
if ( empty($wp_hasher) ) {
require_once( ABSPATH . 'wp-includes/class-phpass.php');
// By default, use the portable hash from phpass
$wp_hasher = new PasswordHash(8, true);
}
return $wp_hasher->HashPassword( trim( $password ) );
}
endif;
if ( !function_exists('wp_check_password') ) :
/**
* Checks the plaintext password against the encrypted Password.
*
* Maintains compatibility between old version and the new cookie authentication
* protocol using PHPass library. The $hash parameter is the encrypted password
* and the function compares the plain text password when encrypted similarly
* against the already encrypted password to see if they match.
*
* For integration with other applications, this function can be overwritten to
* instead use the other package password checking algorithm.
*
* @since 2.5.0
*
* @global object $wp_hasher PHPass object used for checking the password
* against the $hash + $password
* @uses PasswordHash::CheckPassword
*
* @param string $password Plaintext user's password
* @param string $hash Hash of the user's password to check against.
* @return bool False, if the $password does not match the hashed password
*/
function wp_check_password($password, $hash, $user_id = '') {
global $wp_hasher;
// If the hash is still md5...
if ( strlen($hash) <= 32 ) {
$check = ( $hash == md5($password) );
if ( $check && $user_id ) {
// Rehash using new hash.
wp_set_password($password, $user_id);
$hash = wp_hash_password($password);
}
/**
* Filter whether the plaintext password matches the encrypted password.
*
* @since 2.5.0
*
* @param bool $check Whether the passwords match.
* @param string $hash The hashed password.
* @param int $user_id User ID.
*/
return apply_filters( 'check_password', $check, $password, $hash, $user_id );
}
// If the stored hash is longer than an MD5, presume the
// new style phpass portable hash.
if ( empty($wp_hasher) ) {
require_once( ABSPATH . 'wp-includes/class-phpass.php');
// By default, use the portable hash from phpass
$wp_hasher = new PasswordHash(8, true);
}
$check = $wp_hasher->CheckPassword($password, $hash);
/** This filter is documented in wp-includes/pluggable.php */
return apply_filters( 'check_password', $check, $password, $hash, $user_id );
}
endif;
if ( !function_exists('wp_generate_password') ) :
/**
* Generates a random password drawn from the defined set of characters.
*
* @since 2.5.0
*
* @param int $length The length of password to generate
* @param bool $special_chars Whether to include standard special characters. Default true.
* @param bool $extra_special_chars Whether to include other special characters. Used when
* generating secret keys and salts. Default false.
* @return string The random password
**/
function wp_generate_password( $length = 12, $special_chars = true, $extra_special_chars = false ) {
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
if ( $special_chars )
$chars .= '!@#$%^&*()';
if ( $extra_special_chars )
$chars .= '-_ []{}<>~`+=,.;:/?|';
$password = '';
for ( $i = 0; $i < $length; $i++ ) {
$password .= substr($chars, wp_rand(0, strlen($chars) - 1), 1);
}
/**
* Filter the randomly-generated password.
*
* @since 3.0.0
*
* @param string $password The generated password.
*/
return apply_filters( 'random_password', $password );
}
endif;
if ( !function_exists('wp_rand') ) :
/**
* Generates a random number
*
* @since 2.6.2
*
* @param int $min Lower limit for the generated number
* @param int $max Upper limit for the generated number
* @return int A random number between min and max
*/
function wp_rand( $min = 0, $max = 0 ) {
global $rnd_value;
// Reset $rnd_value after 14 uses
// 32(md5) + 40(sha1) + 40(sha1) / 8 = 14 random numbers from $rnd_value
if ( strlen($rnd_value) < 8 ) {
if ( defined( 'WP_SETUP_CONFIG' ) )
static $seed = '';
else
$seed = get_transient('random_seed');
$rnd_value = md5( uniqid(microtime() . mt_rand(), true ) . $seed );
$rnd_value .= sha1($rnd_value);
$rnd_value .= sha1($rnd_value . $seed);
$seed = md5($seed . $rnd_value);
if ( ! defined( 'WP_SETUP_CONFIG' ) )
set_transient('random_seed', $seed);
}
// Take the first 8 digits for our value
$value = substr($rnd_value, 0, 8);
// Strip the first eight, leaving the remainder for the next call to wp_rand().
$rnd_value = substr($rnd_value, 8);
$value = abs(hexdec($value));
// Some misconfigured 32bit environments (Entropy PHP, for example) truncate integers larger than PHP_INT_MAX to PHP_INT_MAX rather than overflowing them to floats.
$max_random_number = 3000000000 === 2147483647 ? (float) "4294967295" : 4294967295; // 4294967295 = 0xffffffff
// Reduce the value to be within the min - max range
if ( $max != 0 )
$value = $min + ( $max - $min + 1 ) * $value / ( $max_random_number + 1 );
return abs(intval($value));
}
endif;
if ( !function_exists('wp_set_password') ) :
/**
* Updates the user's password with a new encrypted one.
*
* For integration with other applications, this function can be overwritten to
* instead use the other package password checking algorithm.
*
* @since 2.5.0
*
* @uses $wpdb WordPress database object for queries
* @uses wp_hash_password() Used to encrypt the user's password before passing to the database
*
* @param string $password The plaintext new user password
* @param int $user_id User ID
*/
function wp_set_password( $password, $user_id ) {
global $wpdb;
$hash = wp_hash_password( $password );
$wpdb->update($wpdb->users, array('user_pass' => $hash, 'user_activation_key' => ''), array('ID' => $user_id) );
wp_cache_delete($user_id, 'users');
}
endif;
if ( !function_exists( 'get_avatar' ) ) :
/**
* Retrieve the avatar for a user who provided a user ID or email address.
*
* @since 2.5.0
*
* @param int|string|object $id_or_email A user ID, email address, or comment object
* @param int $size Size of the avatar image
* @param string $default URL to a default image to use if no avatar is available
* @param string $alt Alternative text to use in image tag. Defaults to blank
* @return string <img> tag for the user's avatar
*/
function get_avatar( $id_or_email, $size = '96', $default = '', $alt = false ) {
if ( ! get_option('show_avatars') )
return false;
if ( false === $alt)
$safe_alt = '';
else
$safe_alt = esc_attr( $alt );
if ( !is_numeric($size) )
$size = '96';
$email = '';
if ( is_numeric($id_or_email) ) {
$id = (int) $id_or_email;
$user = get_userdata($id);
if ( $user )
$email = $user->user_email;
} elseif ( is_object($id_or_email) ) {
// No avatar for pingbacks or trackbacks
/**
* Filter the list of allowed comment types for retrieving avatars.
*
* @since 3.0.0
*
* @param array $types An array of content types. Default only contains 'comment'.
*/
$allowed_comment_types = apply_filters( 'get_avatar_comment_types', array( 'comment' ) );
if ( ! empty( $id_or_email->comment_type ) && ! in_array( $id_or_email->comment_type, (array) $allowed_comment_types ) )
return false;
if ( ! empty( $id_or_email->user_id ) ) {
$id = (int) $id_or_email->user_id;
$user = get_userdata($id);
if ( $user )
$email = $user->user_email;
}
if ( ! $email && ! empty( $id_or_email->comment_author_email ) )
$email = $id_or_email->comment_author_email;
} else {
$email = $id_or_email;
}
if ( empty($default) ) {
$avatar_default = get_option('avatar_default');
if ( empty($avatar_default) )
$default = 'mystery';
else
$default = $avatar_default;
}
if ( !empty($email) )
$email_hash = md5( strtolower( trim( $email ) ) );
if ( is_ssl() ) {
$host = 'https://secure.gravatar.com';
} else {
if ( !empty($email) )
$host = sprintf( "http://%d.gravatar.com", ( hexdec( $email_hash[0] ) % 2 ) );
else
$host = 'http://0.gravatar.com';
}
if ( 'mystery' == $default )
$default = "$host/avatar/ad516503a11cd5ca435acc9bb6523536?s={$size}"; // ad516503a11cd5ca435acc9bb6523536 == md5('unknown@gravatar.com')
elseif ( 'blank' == $default )
$default = $email ? 'blank' : includes_url( 'images/blank.gif' );
elseif ( !empty($email) && 'gravatar_default' == $default )
$default = '';
elseif ( 'gravatar_default' == $default )
$default = "$host/avatar/?s={$size}";
elseif ( empty($email) )
$default = "$host/avatar/?d=$default&s={$size}";
elseif ( strpos($default, 'http://') === 0 )
$default = add_query_arg( 's', $size, $default );
if ( !empty($email) ) {
$out = "$host/avatar/";
$out .= $email_hash;
$out .= '?s='.$size;
$out .= '&d=' . urlencode( $default );
$rating = get_option('avatar_rating');
if ( !empty( $rating ) )
$out .= "&r={$rating}";
$out = str_replace( '&', '&', esc_url( $out ) );
$avatar = "<img alt='{$safe_alt}' src='{$out}' class='avatar avatar-{$size} photo' height='{$size}' width='{$size}' />";
} else {
$out = esc_url( $default );
$avatar = "<img alt='{$safe_alt}' src='{$out}' class='avatar avatar-{$size} photo avatar-default' height='{$size}' width='{$size}' />";
}
/**
* Filter the avatar to retrieve.
*
* @since 2.5.0
*
* @param string $avatar Image tag for the user's avatar.
* @param int|object|string $id_or_email A user ID, email address, or comment object.
* @param int $size Square avatar width and height in pixels to retrieve.
* @param string $alt Alternative text to use in the avatar image tag.
* Default empty.
*/
return apply_filters( 'get_avatar', $avatar, $id_or_email, $size, $default, $alt );
}
endif;
if ( !function_exists( 'wp_text_diff' ) ) :
/**
* Displays a human readable HTML representation of the difference between two strings.
*
* The Diff is available for getting the changes between versions. The output is
* HTML, so the primary use is for displaying the changes. If the two strings
* are equivalent, then an empty string will be returned.
*
* The arguments supported and can be changed are listed below.
*
* 'title' : Default is an empty string. Titles the diff in a manner compatible
* with the output.
* 'title_left' : Default is an empty string. Change the HTML to the left of the
* title.
* 'title_right' : Default is an empty string. Change the HTML to the right of
* the title.
*
* @since 2.6.0
*
* @see wp_parse_args() Used to change defaults to user defined settings.
* @uses Text_Diff
* @uses WP_Text_Diff_Renderer_Table
*
* @param string $left_string "old" (left) version of string
* @param string $right_string "new" (right) version of string
* @param string|array $args Optional. Change 'title', 'title_left', and 'title_right' defaults.
* @return string Empty string if strings are equivalent or HTML with differences.
*/
function wp_text_diff( $left_string, $right_string, $args = null ) {
$defaults = array( 'title' => '', 'title_left' => '', 'title_right' => '' );
$args = wp_parse_args( $args, $defaults );
if ( !class_exists( 'WP_Text_Diff_Renderer_Table' ) )
require( ABSPATH . WPINC . '/wp-diff.php' );
$left_string = normalize_whitespace($left_string);
$right_string = normalize_whitespace($right_string);
$left_lines = explode("\n", $left_string);
$right_lines = explode("\n", $right_string);
$text_diff = new Text_Diff($left_lines, $right_lines);
$renderer = new WP_Text_Diff_Renderer_Table( $args );
$diff = $renderer->render($text_diff);
if ( !$diff )
return '';
$r = "<table class='diff'>\n";
if ( ! empty( $args[ 'show_split_view' ] ) ) {
$r .= "<col class='content diffsplit left' /><col class='content diffsplit middle' /><col class='content diffsplit right' />";
} else {
$r .= "<col class='content' />";
}
if ( $args['title'] || $args['title_left'] || $args['title_right'] )
$r .= "<thead>";
if ( $args['title'] )
$r .= "<tr class='diff-title'><th colspan='4'>$args[title]</th></tr>\n";
if ( $args['title_left'] || $args['title_right'] ) {
$r .= "<tr class='diff-sub-title'>\n";
$r .= "\t<td></td><th>$args[title_left]</th>\n";
$r .= "\t<td></td><th>$args[title_right]</th>\n";
$r .= "</tr>\n";
}
if ( $args['title'] || $args['title_left'] || $args['title_right'] )
$r .= "</thead>\n";
$r .= "<tbody>\n$diff\n</tbody>\n";
$r .= "</table>";
return $r;
}
endif;
if ( ! function_exists( 'hash_equals' ) ) :
/**
* Compare two strings in constant time.
*
* This function is NOT pluggable. It is in this file (in addition to
* compat.php) to prevent errors if, during an update, pluggable.php
* copies over but compat.php does not.
*
* This function was added in PHP 5.6.
* It can leak the length of a string.
*
* @since 3.9.2
*
* @param string $a Expected string.
* @param string $b Actual string.
* @return bool Whether strings are equal.
*/
function hash_equals( $a, $b ) {
$a_length = strlen( $a );
if ( $a_length !== strlen( $b ) ) {
return false;
}
$result = 0;
// Do not attempt to "optimize" this.
for ( $i = 0; $i < $a_length; $i++ ) {
$result |= ord( $a[ $i ] ) ^ ord( $b[ $i ] );
}
return $result === 0;
}
endif;
| PHP |
<?php
/**
* Deprecated pluggable functions from past WordPress versions. You shouldn't use these
* functions and look for the alternatives instead. The functions will be removed in a
* later version.
*
* Deprecated warnings are also thrown if one of these functions is being defined by a plugin.
*
* @package WordPress
* @subpackage Deprecated
* @see pluggable.php
*/
/*
* Deprecated functions come here to die.
*/
if ( !function_exists('set_current_user') ) :
/**
* Changes the current user by ID or name.
*
* Set $id to null and specify a name if you do not know a user's ID.
*
* @since 2.0.1
* @see wp_set_current_user() An alias of wp_set_current_user()
* @deprecated 3.0.0
* @deprecated Use wp_set_current_user()
*
* @param int|null $id User ID.
* @param string $name Optional. The user's username
* @return object returns wp_set_current_user()
*/
function set_current_user($id, $name = '') {
_deprecated_function( __FUNCTION__, '3.0', 'wp_set_current_user()' );
return wp_set_current_user($id, $name);
}
endif;
if ( !function_exists('get_userdatabylogin') ) :
/**
* Retrieve user info by login name.
*
* @since 0.71
* @deprecated 3.3.0
* @deprecated Use get_user_by('login')
*
* @param string $user_login User's username
* @return bool|object False on failure, User DB row object
*/
function get_userdatabylogin($user_login) {
_deprecated_function( __FUNCTION__, '3.3', "get_user_by('login')" );
return get_user_by('login', $user_login);
}
endif;
if ( !function_exists('get_user_by_email') ) :
/**
* Retrieve user info by email.
*
* @since 2.5.0
* @deprecated 3.3.0
* @deprecated Use get_user_by('email')
*
* @param string $email User's email address
* @return bool|object False on failure, User DB row object
*/
function get_user_by_email($email) {
_deprecated_function( __FUNCTION__, '3.3', "get_user_by('email')" );
return get_user_by('email', $email);
}
endif;
if ( !function_exists('wp_setcookie') ) :
/**
* Sets a cookie for a user who just logged in. This function is deprecated.
*
* @since 1.5.0
* @deprecated 2.5.0
* @deprecated Use wp_set_auth_cookie()
* @see wp_set_auth_cookie()
*
* @param string $username The user's username
* @param string $password Optional. The user's password
* @param bool $already_md5 Optional. Whether the password has already been through MD5
* @param string $home Optional. Will be used instead of COOKIEPATH if set
* @param string $siteurl Optional. Will be used instead of SITECOOKIEPATH if set
* @param bool $remember Optional. Remember that the user is logged in
*/
function wp_setcookie($username, $password = '', $already_md5 = false, $home = '', $siteurl = '', $remember = false) {
_deprecated_function( __FUNCTION__, '2.5', 'wp_set_auth_cookie()' );
$user = get_user_by('login', $username);
wp_set_auth_cookie($user->ID, $remember);
}
else :
_deprecated_function( 'wp_setcookie', '2.5', 'wp_set_auth_cookie()' );
endif;
if ( !function_exists('wp_clearcookie') ) :
/**
* Clears the authentication cookie, logging the user out. This function is deprecated.
*
* @since 1.5.0
* @deprecated 2.5.0
* @deprecated Use wp_clear_auth_cookie()
* @see wp_clear_auth_cookie()
*/
function wp_clearcookie() {
_deprecated_function( __FUNCTION__, '2.5', 'wp_clear_auth_cookie()' );
wp_clear_auth_cookie();
}
else :
_deprecated_function( 'wp_clearcookie', '2.5', 'wp_clear_auth_cookie()' );
endif;
if ( !function_exists('wp_get_cookie_login') ):
/**
* Gets the user cookie login. This function is deprecated.
*
* This function is deprecated and should no longer be extended as it won't be
* used anywhere in WordPress. Also, plugins shouldn't use it either.
*
* @since 2.0.3
* @deprecated 2.5.0
* @deprecated No alternative
*
* @return bool Always returns false
*/
function wp_get_cookie_login() {
_deprecated_function( __FUNCTION__, '2.5' );
return false;
}
else :
_deprecated_function( 'wp_get_cookie_login', '2.5' );
endif;
if ( !function_exists('wp_login') ) :
/**
* Checks a users login information and logs them in if it checks out. This function is deprecated.
*
* Use the global $error to get the reason why the login failed. If the username
* is blank, no error will be set, so assume blank username on that case.
*
* Plugins extending this function should also provide the global $error and set
* what the error is, so that those checking the global for why there was a
* failure can utilize it later.
*
* @since 1.2.2
* @deprecated Use wp_signon()
* @global string $error Error when false is returned
*
* @param string $username User's username
* @param string $password User's password
* @param bool $deprecated Not used
* @return bool False on login failure, true on successful check
*/
function wp_login($username, $password, $deprecated = '') {
_deprecated_function( __FUNCTION__, '2.5', 'wp_signon()' );
global $error;
$user = wp_authenticate($username, $password);
if ( ! is_wp_error($user) )
return true;
$error = $user->get_error_message();
return false;
}
else :
_deprecated_function( 'wp_login', '2.5', 'wp_signon()' );
endif;
/**
* WordPress AtomPub API implementation.
*
* Originally stored in wp-app.php, and later wp-includes/class-wp-atom-server.php.
* It is kept here in case a plugin directly referred to the class.
*
* @since 2.2.0
* @deprecated 3.5.0
* @link https://wordpress.org/plugins/atom-publishing-protocol/
*/
if ( ! class_exists( 'wp_atom_server' ) ) {
class wp_atom_server {
public function __call( $name, $arguments ) {
_deprecated_function( __CLASS__ . '::' . $name, '3.5', 'the Atom Publishing Protocol plugin' );
}
public static function __callStatic( $name, $arguments ) {
_deprecated_function( __CLASS__ . '::' . $name, '3.5', 'the Atom Publishing Protocol plugin' );
}
}
} | PHP |
<?php
/**
* Canonical API to handle WordPress Redirecting
*
* Based on "Permalink Redirect" from Scott Yang and "Enforce www. Preference"
* by Mark Jaquith
*
* @package WordPress
* @since 2.3.0
*/
/**
* Redirects incoming links to the proper URL based on the site url.
*
* Search engines consider www.somedomain.com and somedomain.com to be two
* different URLs when they both go to the same location. This SEO enhancement
* prevents penalty for duplicate content by redirecting all incoming links to
* one or the other.
*
* Prevents redirection for feeds, trackbacks, searches, comment popup, and
* admin URLs. Does not redirect on non-pretty-permalink-supporting IIS 7+,
* page/post previews, WP admin, Trackbacks, robots.txt, searches, or on POST
* requests.
*
* Will also attempt to find the correct link when a user enters a URL that does
* not exist based on exact WordPress query. Will instead try to parse the URL
* or query in an attempt to figure the correct page to go to.
*
* @since 2.3.0
* @uses $wp_rewrite
* @uses $is_IIS
*
* @param string $requested_url Optional. The URL that was requested, used to
* figure if redirect is needed.
* @param bool $do_redirect Optional. Redirect to the new URL.
* @return null|false|string Null, if redirect not needed. False, if redirect
* not needed or the string of the URL
*/
function redirect_canonical( $requested_url = null, $do_redirect = true ) {
global $wp_rewrite, $is_IIS, $wp_query, $wpdb;
if ( is_trackback() || is_search() || is_comments_popup() || is_admin() || !empty($_POST) || is_preview() || is_robots() || ( $is_IIS && !iis7_supports_permalinks() ) )
return;
if ( !$requested_url ) {
// build the URL in the address bar
$requested_url = is_ssl() ? 'https://' : 'http://';
$requested_url .= $_SERVER['HTTP_HOST'];
$requested_url .= $_SERVER['REQUEST_URI'];
}
$original = @parse_url($requested_url);
if ( false === $original )
return;
// Some PHP setups turn requests for / into /index.php in REQUEST_URI
// See: http://trac.wordpress.org/ticket/5017
// See: http://trac.wordpress.org/ticket/7173
// Disabled, for now:
// $original['path'] = preg_replace('|/index\.php$|', '/', $original['path']);
$redirect = $original;
$redirect_url = false;
// Notice fixing
if ( !isset($redirect['path']) )
$redirect['path'] = '';
if ( !isset($redirect['query']) )
$redirect['query'] = '';
if ( is_feed() && ( $id = get_query_var( 'p' ) ) ) {
if ( $redirect_url = get_post_comments_feed_link( $id, get_query_var( 'feed' ) ) ) {
$redirect['query'] = _remove_qs_args_if_not_in_url( $redirect['query'], array( 'p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type', 'feed'), $redirect_url );
$redirect['path'] = parse_url( $redirect_url, PHP_URL_PATH );
}
}
if ( is_singular() && 1 > $wp_query->post_count && ($id = get_query_var('p')) ) {
$vars = $wpdb->get_results( $wpdb->prepare("SELECT post_type, post_parent FROM $wpdb->posts WHERE ID = %d", $id) );
if ( isset($vars[0]) && $vars = $vars[0] ) {
if ( 'revision' == $vars->post_type && $vars->post_parent > 0 )
$id = $vars->post_parent;
if ( $redirect_url = get_permalink($id) )
$redirect['query'] = _remove_qs_args_if_not_in_url( $redirect['query'], array( 'p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type' ), $redirect_url );
}
}
// These tests give us a WP-generated permalink
if ( is_404() ) {
// Redirect ?page_id, ?p=, ?attachment_id= to their respective url's
$id = max( get_query_var('p'), get_query_var('page_id'), get_query_var('attachment_id') );
if ( $id && $redirect_post = get_post($id) ) {
$post_type_obj = get_post_type_object($redirect_post->post_type);
if ( $post_type_obj->public ) {
$redirect_url = get_permalink($redirect_post);
$redirect['query'] = _remove_qs_args_if_not_in_url( $redirect['query'], array( 'p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type' ), $redirect_url );
}
}
if ( get_query_var( 'day' ) && get_query_var( 'monthnum' ) && get_query_var( 'year' ) ) {
$year = get_query_var( 'year' );
$month = get_query_var( 'monthnum' );
$day = get_query_var( 'day' );
$date = sprintf( '%04d-%02d-%02d', $year, $month, $day );
if ( ! wp_checkdate( $month, $day, $year, $date ) ) {
$redirect_url = get_month_link( $year, $month );
$redirect['query'] = _remove_qs_args_if_not_in_url( $redirect['query'], array( 'year', 'monthnum', 'day' ), $redirect_url );
}
} elseif ( get_query_var( 'monthnum' ) && get_query_var( 'year' ) && 12 < get_query_var( 'monthnum' ) ) {
$redirect_url = get_year_link( get_query_var( 'year' ) );
$redirect['query'] = _remove_qs_args_if_not_in_url( $redirect['query'], array( 'year', 'monthnum' ), $redirect_url );
}
if ( ! $redirect_url ) {
if ( $redirect_url = redirect_guess_404_permalink() ) {
$redirect['query'] = _remove_qs_args_if_not_in_url( $redirect['query'], array( 'page', 'feed', 'p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type' ), $redirect_url );
}
}
} elseif ( is_object($wp_rewrite) && $wp_rewrite->using_permalinks() ) {
// rewriting of old ?p=X, ?m=2004, ?m=200401, ?m=20040101
if ( is_attachment() && !empty($_GET['attachment_id']) && ! $redirect_url ) {
if ( $redirect_url = get_attachment_link(get_query_var('attachment_id')) )
$redirect['query'] = remove_query_arg('attachment_id', $redirect['query']);
} elseif ( is_single() && !empty($_GET['p']) && ! $redirect_url ) {
if ( $redirect_url = get_permalink(get_query_var('p')) )
$redirect['query'] = remove_query_arg(array('p', 'post_type'), $redirect['query']);
} elseif ( is_single() && !empty($_GET['name']) && ! $redirect_url ) {
if ( $redirect_url = get_permalink( $wp_query->get_queried_object_id() ) )
$redirect['query'] = remove_query_arg('name', $redirect['query']);
} elseif ( is_page() && !empty($_GET['page_id']) && ! $redirect_url ) {
if ( $redirect_url = get_permalink(get_query_var('page_id')) )
$redirect['query'] = remove_query_arg('page_id', $redirect['query']);
} elseif ( is_page() && !is_feed() && isset($wp_query->queried_object) && 'page' == get_option('show_on_front') && $wp_query->queried_object->ID == get_option('page_on_front') && ! $redirect_url ) {
$redirect_url = home_url('/');
} elseif ( is_home() && !empty($_GET['page_id']) && 'page' == get_option('show_on_front') && get_query_var('page_id') == get_option('page_for_posts') && ! $redirect_url ) {
if ( $redirect_url = get_permalink(get_option('page_for_posts')) )
$redirect['query'] = remove_query_arg('page_id', $redirect['query']);
} elseif ( !empty($_GET['m']) && ( is_year() || is_month() || is_day() ) ) {
$m = get_query_var('m');
switch ( strlen($m) ) {
case 4: // Yearly
$redirect_url = get_year_link($m);
break;
case 6: // Monthly
$redirect_url = get_month_link( substr($m, 0, 4), substr($m, 4, 2) );
break;
case 8: // Daily
$redirect_url = get_day_link(substr($m, 0, 4), substr($m, 4, 2), substr($m, 6, 2));
break;
}
if ( $redirect_url )
$redirect['query'] = remove_query_arg('m', $redirect['query']);
// now moving on to non ?m=X year/month/day links
} elseif ( is_day() && get_query_var('year') && get_query_var('monthnum') && !empty($_GET['day']) ) {
if ( $redirect_url = get_day_link(get_query_var('year'), get_query_var('monthnum'), get_query_var('day')) )
$redirect['query'] = remove_query_arg(array('year', 'monthnum', 'day'), $redirect['query']);
} elseif ( is_month() && get_query_var('year') && !empty($_GET['monthnum']) ) {
if ( $redirect_url = get_month_link(get_query_var('year'), get_query_var('monthnum')) )
$redirect['query'] = remove_query_arg(array('year', 'monthnum'), $redirect['query']);
} elseif ( is_year() && !empty($_GET['year']) ) {
if ( $redirect_url = get_year_link(get_query_var('year')) )
$redirect['query'] = remove_query_arg('year', $redirect['query']);
} elseif ( is_author() && !empty($_GET['author']) && preg_match( '|^[0-9]+$|', $_GET['author'] ) ) {
$author = get_userdata(get_query_var('author'));
if ( ( false !== $author ) && $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE $wpdb->posts.post_author = %d AND $wpdb->posts.post_status = 'publish' LIMIT 1", $author->ID ) ) ) {
if ( $redirect_url = get_author_posts_url($author->ID, $author->user_nicename) )
$redirect['query'] = remove_query_arg('author', $redirect['query']);
}
} elseif ( is_category() || is_tag() || is_tax() ) { // Terms (Tags/categories)
$term_count = 0;
foreach ( $wp_query->tax_query->queries as $tax_query )
$term_count += count( $tax_query['terms'] );
$obj = $wp_query->get_queried_object();
if ( $term_count <= 1 && !empty($obj->term_id) && ( $tax_url = get_term_link((int)$obj->term_id, $obj->taxonomy) ) && !is_wp_error($tax_url) ) {
if ( !empty($redirect['query']) ) {
// Strip taxonomy query vars off the url.
$qv_remove = array( 'term', 'taxonomy');
if ( is_category() ) {
$qv_remove[] = 'category_name';
$qv_remove[] = 'cat';
} elseif ( is_tag() ) {
$qv_remove[] = 'tag';
$qv_remove[] = 'tag_id';
} else { // Custom taxonomies will have a custom query var, remove those too:
$tax_obj = get_taxonomy( $obj->taxonomy );
if ( false !== $tax_obj->query_var )
$qv_remove[] = $tax_obj->query_var;
}
$rewrite_vars = array_diff( array_keys($wp_query->query), array_keys($_GET) );
if ( !array_diff($rewrite_vars, array_keys($_GET)) ) { // Check to see if all the Query vars are coming from the rewrite, none are set via $_GET
$redirect['query'] = remove_query_arg($qv_remove, $redirect['query']); //Remove all of the per-tax qv's
// Create the destination url for this taxonomy
$tax_url = parse_url($tax_url);
if ( ! empty($tax_url['query']) ) { // Taxonomy accessible via ?taxonomy=..&term=.. or any custom qv..
parse_str($tax_url['query'], $query_vars);
$redirect['query'] = add_query_arg($query_vars, $redirect['query']);
} else { // Taxonomy is accessible via a "pretty-URL"
$redirect['path'] = $tax_url['path'];
}
} else { // Some query vars are set via $_GET. Unset those from $_GET that exist via the rewrite
foreach ( $qv_remove as $_qv ) {
if ( isset($rewrite_vars[$_qv]) )
$redirect['query'] = remove_query_arg($_qv, $redirect['query']);
}
}
}
}
} elseif ( is_single() && strpos($wp_rewrite->permalink_structure, '%category%') !== false && $cat = get_query_var( 'category_name' ) ) {
$category = get_category_by_path( $cat );
$post_terms = wp_get_object_terms($wp_query->get_queried_object_id(), 'category', array('fields' => 'tt_ids'));
if ( (!$category || is_wp_error($category)) || ( !is_wp_error($post_terms) && !empty($post_terms) && !in_array($category->term_taxonomy_id, $post_terms) ) )
$redirect_url = get_permalink($wp_query->get_queried_object_id());
}
// Post Paging
if ( is_singular() && ! is_front_page() && get_query_var('page') ) {
if ( !$redirect_url )
$redirect_url = get_permalink( get_queried_object_id() );
$redirect_url = trailingslashit( $redirect_url ) . user_trailingslashit( get_query_var( 'page' ), 'single_paged' );
$redirect['query'] = remove_query_arg( 'page', $redirect['query'] );
}
// paging and feeds
if ( get_query_var('paged') || is_feed() || get_query_var('cpage') ) {
while ( preg_match( "#/$wp_rewrite->pagination_base/?[0-9]+?(/+)?$#", $redirect['path'] ) || preg_match( '#/(comments/?)?(feed|rss|rdf|atom|rss2)(/+)?$#', $redirect['path'] ) || preg_match( '#/comment-page-[0-9]+(/+)?$#', $redirect['path'] ) ) {
// Strip off paging and feed
$redirect['path'] = preg_replace("#/$wp_rewrite->pagination_base/?[0-9]+?(/+)?$#", '/', $redirect['path']); // strip off any existing paging
$redirect['path'] = preg_replace('#/(comments/?)?(feed|rss2?|rdf|atom)(/+|$)#', '/', $redirect['path']); // strip off feed endings
$redirect['path'] = preg_replace('#/comment-page-[0-9]+?(/+)?$#', '/', $redirect['path']); // strip off any existing comment paging
}
$addl_path = '';
if ( is_feed() && in_array( get_query_var('feed'), $wp_rewrite->feeds ) ) {
$addl_path = !empty( $addl_path ) ? trailingslashit($addl_path) : '';
if ( !is_singular() && get_query_var( 'withcomments' ) )
$addl_path .= 'comments/';
if ( ( 'rss' == get_default_feed() && 'feed' == get_query_var('feed') ) || 'rss' == get_query_var('feed') )
$addl_path .= user_trailingslashit( 'feed/' . ( ( get_default_feed() == 'rss2' ) ? '' : 'rss2' ), 'feed' );
else
$addl_path .= user_trailingslashit( 'feed/' . ( ( get_default_feed() == get_query_var('feed') || 'feed' == get_query_var('feed') ) ? '' : get_query_var('feed') ), 'feed' );
$redirect['query'] = remove_query_arg( 'feed', $redirect['query'] );
} elseif ( is_feed() && 'old' == get_query_var('feed') ) {
$old_feed_files = array(
'wp-atom.php' => 'atom',
'wp-commentsrss2.php' => 'comments_rss2',
'wp-feed.php' => get_default_feed(),
'wp-rdf.php' => 'rdf',
'wp-rss.php' => 'rss2',
'wp-rss2.php' => 'rss2',
);
if ( isset( $old_feed_files[ basename( $redirect['path'] ) ] ) ) {
$redirect_url = get_feed_link( $old_feed_files[ basename( $redirect['path'] ) ] );
wp_redirect( $redirect_url, 301 );
die();
}
}
if ( get_query_var('paged') > 0 ) {
$paged = get_query_var('paged');
$redirect['query'] = remove_query_arg( 'paged', $redirect['query'] );
if ( !is_feed() ) {
if ( $paged > 1 && !is_single() ) {
$addl_path = ( !empty( $addl_path ) ? trailingslashit($addl_path) : '' ) . user_trailingslashit("$wp_rewrite->pagination_base/$paged", 'paged');
} elseif ( !is_single() ) {
$addl_path = !empty( $addl_path ) ? trailingslashit($addl_path) : '';
}
} elseif ( $paged > 1 ) {
$redirect['query'] = add_query_arg( 'paged', $paged, $redirect['query'] );
}
}
if ( get_option('page_comments') && ( ( 'newest' == get_option('default_comments_page') && get_query_var('cpage') > 0 ) || ( 'newest' != get_option('default_comments_page') && get_query_var('cpage') > 1 ) ) ) {
$addl_path = ( !empty( $addl_path ) ? trailingslashit($addl_path) : '' ) . user_trailingslashit( 'comment-page-' . get_query_var('cpage'), 'commentpaged' );
$redirect['query'] = remove_query_arg( 'cpage', $redirect['query'] );
}
$redirect['path'] = user_trailingslashit( preg_replace('|/' . preg_quote( $wp_rewrite->index, '|' ) . '/?$|', '/', $redirect['path']) ); // strip off trailing /index.php/
if ( !empty( $addl_path ) && $wp_rewrite->using_index_permalinks() && strpos($redirect['path'], '/' . $wp_rewrite->index . '/') === false )
$redirect['path'] = trailingslashit($redirect['path']) . $wp_rewrite->index . '/';
if ( !empty( $addl_path ) )
$redirect['path'] = trailingslashit($redirect['path']) . $addl_path;
$redirect_url = $redirect['scheme'] . '://' . $redirect['host'] . $redirect['path'];
}
if ( 'wp-register.php' == basename( $redirect['path'] ) ) {
if ( is_multisite() )
/** This filter is documented in wp-login.php */
$redirect_url = apply_filters( 'wp_signup_location', network_site_url( 'wp-signup.php' ) );
else
$redirect_url = site_url( 'wp-login.php?action=register' );
wp_redirect( $redirect_url, 301 );
die();
}
}
// tack on any additional query vars
$redirect['query'] = preg_replace( '#^\??&*?#', '', $redirect['query'] );
if ( $redirect_url && !empty($redirect['query']) ) {
parse_str( $redirect['query'], $_parsed_query );
$redirect = @parse_url($redirect_url);
if ( ! empty( $_parsed_query['name'] ) && ! empty( $redirect['query'] ) ) {
parse_str( $redirect['query'], $_parsed_redirect_query );
if ( empty( $_parsed_redirect_query['name'] ) )
unset( $_parsed_query['name'] );
}
$_parsed_query = rawurlencode_deep( $_parsed_query );
$redirect_url = add_query_arg( $_parsed_query, $redirect_url );
}
if ( $redirect_url )
$redirect = @parse_url($redirect_url);
// www.example.com vs example.com
$user_home = @parse_url(home_url());
if ( !empty($user_home['host']) )
$redirect['host'] = $user_home['host'];
if ( empty($user_home['path']) )
$user_home['path'] = '/';
// Handle ports
if ( !empty($user_home['port']) )
$redirect['port'] = $user_home['port'];
else
unset($redirect['port']);
// trailing /index.php
$redirect['path'] = preg_replace('|/' . preg_quote( $wp_rewrite->index, '|' ) . '/*?$|', '/', $redirect['path']);
// Remove trailing spaces from the path
$redirect['path'] = preg_replace( '#(%20| )+$#', '', $redirect['path'] );
if ( !empty( $redirect['query'] ) ) {
// Remove trailing spaces from certain terminating query string args
$redirect['query'] = preg_replace( '#((p|page_id|cat|tag)=[^&]*?)(%20| )+$#', '$1', $redirect['query'] );
// Clean up empty query strings
$redirect['query'] = trim(preg_replace( '#(^|&)(p|page_id|cat|tag)=?(&|$)#', '&', $redirect['query']), '&');
// Redirect obsolete feeds
$redirect['query'] = preg_replace( '#(^|&)feed=rss(&|$)#', '$1feed=rss2$2', $redirect['query'] );
// Remove redundant leading ampersands
$redirect['query'] = preg_replace( '#^\??&*?#', '', $redirect['query'] );
}
// strip /index.php/ when we're not using PATHINFO permalinks
if ( !$wp_rewrite->using_index_permalinks() )
$redirect['path'] = str_replace( '/' . $wp_rewrite->index . '/', '/', $redirect['path'] );
// trailing slashes
if ( is_object($wp_rewrite) && $wp_rewrite->using_permalinks() && !is_404() && (!is_front_page() || ( is_front_page() && (get_query_var('paged') > 1) ) ) ) {
$user_ts_type = '';
if ( get_query_var('paged') > 0 ) {
$user_ts_type = 'paged';
} else {
foreach ( array('single', 'category', 'page', 'day', 'month', 'year', 'home') as $type ) {
$func = 'is_' . $type;
if ( call_user_func($func) ) {
$user_ts_type = $type;
break;
}
}
}
$redirect['path'] = user_trailingslashit($redirect['path'], $user_ts_type);
} elseif ( is_front_page() ) {
$redirect['path'] = trailingslashit($redirect['path']);
}
// Strip multiple slashes out of the URL
if ( strpos($redirect['path'], '//') > -1 )
$redirect['path'] = preg_replace('|/+|', '/', $redirect['path']);
// Always trailing slash the Front Page URL
if ( trailingslashit( $redirect['path'] ) == trailingslashit( $user_home['path'] ) )
$redirect['path'] = trailingslashit($redirect['path']);
// Ignore differences in host capitalization, as this can lead to infinite redirects
// Only redirect no-www <=> yes-www
if ( strtolower($original['host']) == strtolower($redirect['host']) ||
( strtolower($original['host']) != 'www.' . strtolower($redirect['host']) && 'www.' . strtolower($original['host']) != strtolower($redirect['host']) ) )
$redirect['host'] = $original['host'];
$compare_original = array($original['host'], $original['path']);
if ( !empty( $original['port'] ) )
$compare_original[] = $original['port'];
if ( !empty( $original['query'] ) )
$compare_original[] = $original['query'];
$compare_redirect = array($redirect['host'], $redirect['path']);
if ( !empty( $redirect['port'] ) )
$compare_redirect[] = $redirect['port'];
if ( !empty( $redirect['query'] ) )
$compare_redirect[] = $redirect['query'];
if ( $compare_original !== $compare_redirect ) {
$redirect_url = $redirect['scheme'] . '://' . $redirect['host'];
if ( !empty($redirect['port']) )
$redirect_url .= ':' . $redirect['port'];
$redirect_url .= $redirect['path'];
if ( !empty($redirect['query']) )
$redirect_url .= '?' . $redirect['query'];
}
if ( !$redirect_url || $redirect_url == $requested_url )
return false;
// Hex encoded octets are case-insensitive.
if ( false !== strpos($requested_url, '%') ) {
if ( !function_exists('lowercase_octets') ) {
function lowercase_octets($matches) {
return strtolower( $matches[0] );
}
}
$requested_url = preg_replace_callback('|%[a-fA-F0-9][a-fA-F0-9]|', 'lowercase_octets', $requested_url);
}
/**
* Filter the canonical redirect URL.
*
* Returning false to this filter will cancel the redirect.
*
* @since 2.3.0
*
* @param string $redirect_url The redirect URL.
* @param string $requested_url The requested URL.
*/
$redirect_url = apply_filters( 'redirect_canonical', $redirect_url, $requested_url );
if ( !$redirect_url || $redirect_url == $requested_url ) // yes, again -- in case the filter aborted the request
return false;
if ( $do_redirect ) {
// protect against chained redirects
if ( !redirect_canonical($redirect_url, false) ) {
wp_redirect($redirect_url, 301);
exit();
} else {
// Debug
// die("1: $redirect_url<br />2: " . redirect_canonical( $redirect_url, false ) );
return false;
}
} else {
return $redirect_url;
}
}
/**
* Removes arguments from a query string if they are not present in a URL
* DO NOT use this in plugin code.
*
* @since 3.4.0
* @access private
*
* @return string The altered query string
*/
function _remove_qs_args_if_not_in_url( $query_string, Array $args_to_check, $url ) {
$parsed_url = @parse_url( $url );
if ( ! empty( $parsed_url['query'] ) ) {
parse_str( $parsed_url['query'], $parsed_query );
foreach ( $args_to_check as $qv ) {
if ( !isset( $parsed_query[$qv] ) )
$query_string = remove_query_arg( $qv, $query_string );
}
} else {
$query_string = remove_query_arg( $args_to_check, $query_string );
}
return $query_string;
}
/**
* Attempts to guess the correct URL based on query vars
*
* @since 2.3.0
* @uses $wpdb
*
* @return bool|string The correct URL if one is found. False on failure.
*/
function redirect_guess_404_permalink() {
global $wpdb, $wp_rewrite;
if ( get_query_var('name') ) {
$where = $wpdb->prepare("post_name LIKE %s", like_escape( get_query_var('name') ) . '%');
// if any of post_type, year, monthnum, or day are set, use them to refine the query
if ( get_query_var('post_type') )
$where .= $wpdb->prepare(" AND post_type = %s", get_query_var('post_type'));
else
$where .= " AND post_type IN ('" . implode( "', '", get_post_types( array( 'public' => true ) ) ) . "')";
if ( get_query_var('year') )
$where .= $wpdb->prepare(" AND YEAR(post_date) = %d", get_query_var('year'));
if ( get_query_var('monthnum') )
$where .= $wpdb->prepare(" AND MONTH(post_date) = %d", get_query_var('monthnum'));
if ( get_query_var('day') )
$where .= $wpdb->prepare(" AND DAYOFMONTH(post_date) = %d", get_query_var('day'));
$post_id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE $where AND post_status = 'publish'");
if ( ! $post_id )
return false;
if ( get_query_var( 'feed' ) )
return get_post_comments_feed_link( $post_id, get_query_var( 'feed' ) );
elseif ( get_query_var( 'page' ) )
return trailingslashit( get_permalink( $post_id ) ) . user_trailingslashit( get_query_var( 'page' ), 'single_paged' );
else
return get_permalink( $post_id );
}
return false;
}
add_action('template_redirect', 'redirect_canonical');
function wp_redirect_admin_locations() {
global $wp_rewrite;
if ( ! ( is_404() && $wp_rewrite->using_permalinks() ) )
return;
$admins = array(
home_url( 'wp-admin', 'relative' ),
home_url( 'dashboard', 'relative' ),
home_url( 'admin', 'relative' ),
site_url( 'dashboard', 'relative' ),
site_url( 'admin', 'relative' ),
);
if ( in_array( untrailingslashit( $_SERVER['REQUEST_URI'] ), $admins ) ) {
wp_redirect( admin_url() );
exit;
}
$logins = array(
home_url( 'wp-login.php', 'relative' ),
home_url( 'login', 'relative' ),
site_url( 'login', 'relative' ),
);
if ( in_array( untrailingslashit( $_SERVER['REQUEST_URI'] ), $logins ) ) {
wp_redirect( site_url( 'wp-login.php', 'login' ) );
exit;
}
}
add_action( 'template_redirect', 'wp_redirect_admin_locations', 1000 );
| PHP |
<?php
/**
* WordPress CRON API
*
* @package WordPress
*/
/**
* Schedules a hook to run only once.
*
* Schedules a hook which will be executed once by the WordPress actions core at
* a time which you specify. The action will fire off when someone visits your
* WordPress site, if the schedule time has passed.
*
* @since 2.1.0
* @link http://codex.wordpress.org/Function_Reference/wp_schedule_single_event
*
* @param int $timestamp Timestamp for when to run the event.
* @param string $hook Action hook to execute when cron is run.
* @param array $args Optional. Arguments to pass to the hook's callback function.
*/
function wp_schedule_single_event( $timestamp, $hook, $args = array()) {
// don't schedule a duplicate if there's already an identical event due in the next 10 minutes
$next = wp_next_scheduled($hook, $args);
if ( $next && $next <= $timestamp + 10 * MINUTE_IN_SECONDS )
return;
$crons = _get_cron_array();
$event = (object) array( 'hook' => $hook, 'timestamp' => $timestamp, 'schedule' => false, 'args' => $args );
/**
* Filter a single event before it is scheduled.
*
* @since 3.1.0
*
* @param object $event An object containing an event's data.
*/
$event = apply_filters( 'schedule_event', $event );
// A plugin disallowed this event
if ( ! $event )
return false;
$key = md5(serialize($event->args));
$crons[$event->timestamp][$event->hook][$key] = array( 'schedule' => $event->schedule, 'args' => $event->args );
uksort( $crons, "strnatcasecmp" );
_set_cron_array( $crons );
}
/**
* Schedule a periodic event.
*
* Schedules a hook which will be executed by the WordPress actions core on a
* specific interval, specified by you. The action will trigger when someone
* visits your WordPress site, if the scheduled time has passed.
*
* Valid values for the recurrence are hourly, daily and twicedaily. These can
* be extended using the cron_schedules filter in wp_get_schedules().
*
* Use wp_next_scheduled() to prevent duplicates
*
* @since 2.1.0
*
* @param int $timestamp Timestamp for when to run the event.
* @param string $recurrence How often the event should recur.
* @param string $hook Action hook to execute when cron is run.
* @param array $args Optional. Arguments to pass to the hook's callback function.
* @return bool|null False on failure, null when complete with scheduling event.
*/
function wp_schedule_event( $timestamp, $recurrence, $hook, $args = array()) {
$crons = _get_cron_array();
$schedules = wp_get_schedules();
if ( !isset( $schedules[$recurrence] ) )
return false;
$event = (object) array( 'hook' => $hook, 'timestamp' => $timestamp, 'schedule' => $recurrence, 'args' => $args, 'interval' => $schedules[$recurrence]['interval'] );
/** This filter is documented in wp-includes/cron.php */
$event = apply_filters( 'schedule_event', $event );
// A plugin disallowed this event
if ( ! $event )
return false;
$key = md5(serialize($event->args));
$crons[$event->timestamp][$event->hook][$key] = array( 'schedule' => $event->schedule, 'args' => $event->args, 'interval' => $event->interval );
uksort( $crons, "strnatcasecmp" );
_set_cron_array( $crons );
}
/**
* Reschedule a recurring event.
*
* @since 2.1.0
*
* @param int $timestamp Timestamp for when to run the event.
* @param string $recurrence How often the event should recur.
* @param string $hook Action hook to execute when cron is run.
* @param array $args Optional. Arguments to pass to the hook's callback function.
* @return bool|null False on failure. Null when event is rescheduled.
*/
function wp_reschedule_event( $timestamp, $recurrence, $hook, $args = array()) {
$crons = _get_cron_array();
$schedules = wp_get_schedules();
$key = md5(serialize($args));
$interval = 0;
// First we try to get it from the schedule
if ( 0 == $interval )
$interval = $schedules[$recurrence]['interval'];
// Now we try to get it from the saved interval in case the schedule disappears
if ( 0 == $interval )
$interval = $crons[$timestamp][$hook][$key]['interval'];
// Now we assume something is wrong and fail to schedule
if ( 0 == $interval )
return false;
$now = time();
if ( $timestamp >= $now )
$timestamp = $now + $interval;
else
$timestamp = $now + ($interval - (($now - $timestamp) % $interval));
wp_schedule_event( $timestamp, $recurrence, $hook, $args );
}
/**
* Unschedule a previously scheduled cron job.
*
* The $timestamp and $hook parameters are required, so that the event can be
* identified.
*
* @since 2.1.0
*
* @param int $timestamp Timestamp for when to run the event.
* @param string $hook Action hook, the execution of which will be unscheduled.
* @param array $args Arguments to pass to the hook's callback function.
* Although not passed to a callback function, these arguments are used
* to uniquely identify the scheduled event, so they should be the same
* as those used when originally scheduling the event.
*/
function wp_unschedule_event( $timestamp, $hook, $args = array() ) {
$crons = _get_cron_array();
$key = md5(serialize($args));
unset( $crons[$timestamp][$hook][$key] );
if ( empty($crons[$timestamp][$hook]) )
unset( $crons[$timestamp][$hook] );
if ( empty($crons[$timestamp]) )
unset( $crons[$timestamp] );
_set_cron_array( $crons );
}
/**
* Unschedule all cron jobs attached to a specific hook.
*
* @since 2.1.0
*
* @param string $hook Action hook, the execution of which will be unscheduled.
* @param array $args Optional. Arguments that were to be pass to the hook's callback function.
*/
function wp_clear_scheduled_hook( $hook, $args = array() ) {
// Backward compatibility
// Previously this function took the arguments as discrete vars rather than an array like the rest of the API
if ( !is_array($args) ) {
_deprecated_argument( __FUNCTION__, '3.0', __('This argument has changed to an array to match the behavior of the other cron functions.') );
$args = array_slice( func_get_args(), 1 );
}
// This logic duplicates wp_next_scheduled()
// It's required due to a scenario where wp_unschedule_event() fails due to update_option() failing,
// and, wp_next_scheduled() returns the same schedule in an infinite loop.
$crons = _get_cron_array();
if ( empty( $crons ) )
return;
$key = md5( serialize( $args ) );
foreach ( $crons as $timestamp => $cron ) {
if ( isset( $cron[ $hook ][ $key ] ) ) {
wp_unschedule_event( $timestamp, $hook, $args );
}
}
}
/**
* Retrieve the next timestamp for a cron event.
*
* @since 2.1.0
*
* @param string $hook Action hook to execute when cron is run.
* @param array $args Optional. Arguments to pass to the hook's callback function.
* @return bool|int The UNIX timestamp of the next time the scheduled event will occur.
*/
function wp_next_scheduled( $hook, $args = array() ) {
$crons = _get_cron_array();
$key = md5(serialize($args));
if ( empty($crons) )
return false;
foreach ( $crons as $timestamp => $cron ) {
if ( isset( $cron[$hook][$key] ) )
return $timestamp;
}
return false;
}
/**
* Send request to run cron through HTTP request that doesn't halt page loading.
*
* @since 2.1.0
*
* @return null Cron could not be spawned, because it is not needed to run.
*/
function spawn_cron( $gmt_time = 0 ) {
if ( ! $gmt_time )
$gmt_time = microtime( true );
if ( defined('DOING_CRON') || isset($_GET['doing_wp_cron']) )
return;
/*
* multiple processes on multiple web servers can run this code concurrently
* try to make this as atomic as possible by setting doing_cron switch
*/
$lock = get_transient('doing_cron');
if ( $lock > $gmt_time + 10 * MINUTE_IN_SECONDS )
$lock = 0;
// don't run if another process is currently running it or more than once every 60 sec.
if ( $lock + WP_CRON_LOCK_TIMEOUT > $gmt_time )
return;
//sanity check
$crons = _get_cron_array();
if ( !is_array($crons) )
return;
$keys = array_keys( $crons );
if ( isset($keys[0]) && $keys[0] > $gmt_time )
return;
if ( defined('ALTERNATE_WP_CRON') && ALTERNATE_WP_CRON ) {
if ( !empty($_POST) || defined('DOING_AJAX') )
return;
$doing_wp_cron = sprintf( '%.22F', $gmt_time );
set_transient( 'doing_cron', $doing_wp_cron );
ob_start();
wp_redirect( add_query_arg( 'doing_wp_cron', $doing_wp_cron, wp_unslash( $_SERVER['REQUEST_URI'] ) ) );
echo ' ';
// flush any buffers and send the headers
while ( @ob_end_flush() );
flush();
WP_DEBUG ? include_once( ABSPATH . 'wp-cron.php' ) : @include_once( ABSPATH . 'wp-cron.php' );
return;
}
$doing_wp_cron = sprintf( '%.22F', $gmt_time );
set_transient( 'doing_cron', $doing_wp_cron );
/**
* Filter the cron request arguments.
*
* @since 3.5.0
*
* @param array $cron_request_array {
* An array of cron request URL arguments.
*
* @type string $url The cron request URL.
* @type int $key The 22 digit GMT microtime.
* @type array $args {
* An array of cron request arguments.
*
* @type int $timeout The request timeout in seconds. Default .01 seconds.
* @type bool $blocking Whether to set blocking for the request. Default false.
* @type bool $sslverify Whether to sslverify. Default true.
* }
* }
*/
$cron_request = apply_filters( 'cron_request', array(
'url' => add_query_arg( 'doing_wp_cron', $doing_wp_cron, site_url( 'wp-cron.php' ) ),
'key' => $doing_wp_cron,
'args' => array(
'timeout' => 0.01,
'blocking' => false,
/** This filter is documented in wp-includes/class-http.php */
'sslverify' => apply_filters( 'https_local_ssl_verify', true )
)
) );
wp_remote_post( $cron_request['url'], $cron_request['args'] );
}
/**
* Run scheduled callbacks or spawn cron for all scheduled events.
*
* @since 2.1.0
*
* @return null When doesn't need to run Cron.
*/
function wp_cron() {
// Prevent infinite loops caused by lack of wp-cron.php
if ( strpos($_SERVER['REQUEST_URI'], '/wp-cron.php') !== false || ( defined('DISABLE_WP_CRON') && DISABLE_WP_CRON ) )
return;
if ( false === $crons = _get_cron_array() )
return;
$gmt_time = microtime( true );
$keys = array_keys( $crons );
if ( isset($keys[0]) && $keys[0] > $gmt_time )
return;
$schedules = wp_get_schedules();
foreach ( $crons as $timestamp => $cronhooks ) {
if ( $timestamp > $gmt_time ) break;
foreach ( (array) $cronhooks as $hook => $args ) {
if ( isset($schedules[$hook]['callback']) && !call_user_func( $schedules[$hook]['callback'] ) )
continue;
spawn_cron( $gmt_time );
break 2;
}
}
}
/**
* Retrieve supported and filtered Cron recurrences.
*
* The supported recurrences are 'hourly' and 'daily'. A plugin may add more by
* hooking into the 'cron_schedules' filter. The filter accepts an array of
* arrays. The outer array has a key that is the name of the schedule or for
* example 'weekly'. The value is an array with two keys, one is 'interval' and
* the other is 'display'.
*
* The 'interval' is a number in seconds of when the cron job should run. So for
* 'hourly', the time is 3600 or 60*60. For weekly, the value would be
* 60*60*24*7 or 604800. The value of 'interval' would then be 604800.
*
* The 'display' is the description. For the 'weekly' key, the 'display' would
* be <code>__('Once Weekly')</code>.
*
* For your plugin, you will be passed an array. you can easily add your
* schedule by doing the following.
* <code>
* // filter parameter variable name is 'array'
* $array['weekly'] = array(
* 'interval' => 604800,
* 'display' => __('Once Weekly')
* );
* </code>
*
* @since 2.1.0
*
* @return array
*/
function wp_get_schedules() {
$schedules = array(
'hourly' => array( 'interval' => HOUR_IN_SECONDS, 'display' => __( 'Once Hourly' ) ),
'twicedaily' => array( 'interval' => 12 * HOUR_IN_SECONDS, 'display' => __( 'Twice Daily' ) ),
'daily' => array( 'interval' => DAY_IN_SECONDS, 'display' => __( 'Once Daily' ) ),
);
/**
* Filter the non-default cron schedules.
*
* @since 2.1.0
*
* @param array $new_schedules An array of non-default cron schedules. Default empty.
*/
return array_merge( apply_filters( 'cron_schedules', array() ), $schedules );
}
/**
* Retrieve Cron schedule for hook with arguments.
*
* @since 2.1.0
*
* @param string $hook Action hook to execute when cron is run.
* @param array $args Optional. Arguments to pass to the hook's callback function.
* @return string|bool False, if no schedule. Schedule on success.
*/
function wp_get_schedule($hook, $args = array()) {
$crons = _get_cron_array();
$key = md5(serialize($args));
if ( empty($crons) )
return false;
foreach ( $crons as $timestamp => $cron ) {
if ( isset( $cron[$hook][$key] ) )
return $cron[$hook][$key]['schedule'];
}
return false;
}
//
// Private functions
//
/**
* Retrieve cron info array option.
*
* @since 2.1.0
* @access private
*
* @return array CRON info array.
*/
function _get_cron_array() {
$cron = get_option('cron');
if ( ! is_array($cron) )
return false;
if ( !isset($cron['version']) )
$cron = _upgrade_cron_array($cron);
unset($cron['version']);
return $cron;
}
/**
* Updates the CRON option with the new CRON array.
*
* @since 2.1.0
* @access private
*
* @param array $cron Cron info array from {@link _get_cron_array()}.
*/
function _set_cron_array($cron) {
$cron['version'] = 2;
update_option( 'cron', $cron );
}
/**
* Upgrade a Cron info array.
*
* This function upgrades the Cron info array to version 2.
*
* @since 2.1.0
* @access private
*
* @param array $cron Cron info array from {@link _get_cron_array()}.
* @return array An upgraded Cron info array.
*/
function _upgrade_cron_array($cron) {
if ( isset($cron['version']) && 2 == $cron['version'])
return $cron;
$new_cron = array();
foreach ( (array) $cron as $timestamp => $hooks) {
foreach ( (array) $hooks as $hook => $args ) {
$key = md5(serialize($args['args']));
$new_cron[$timestamp][$hook][$key] = $args;
}
}
$new_cron['version'] = 2;
update_option( 'cron', $new_cron );
return $new_cron;
}
| PHP |
<?php
/**
* WordPress Link Template Functions
*
* @package WordPress
* @subpackage Template
*/
/**
* Display the permalink for the current post.
*
* @since 1.2.0
*/
function the_permalink() {
/**
* Filter the display of the permalink for the current post.
*
* @since 1.5.0
*
* @param string $permalink The permalink for the current post.
*/
echo esc_url( apply_filters( 'the_permalink', get_permalink() ) );
}
/**
* Retrieve trailing slash string, if blog set for adding trailing slashes.
*
* Conditionally adds a trailing slash if the permalink structure has a trailing
* slash, strips the trailing slash if not. The string is passed through the
* 'user_trailingslashit' filter. Will remove trailing slash from string, if
* blog is not set to have them.
*
* @since 2.2.0
* @uses $wp_rewrite
*
* @param string $string URL with or without a trailing slash.
* @param string $type_of_url The type of URL being considered (e.g. single, category, etc) for use in the filter.
* @return string
*/
function user_trailingslashit($string, $type_of_url = '') {
global $wp_rewrite;
if ( $wp_rewrite->use_trailing_slashes )
$string = trailingslashit($string);
else
$string = untrailingslashit($string);
/**
* Filter the trailing slashed string, depending on whether the site is set
* to use training slashes.
*
* @since 2.2.0
*
* @param string $string URL with or without a trailing slash.
* @param string $type_of_url The type of URL being considered. Accepts 'single', 'single_trackback',
* 'single_feed', 'single_paged', 'feed', 'category', 'page', 'year',
* 'month', 'day', 'paged', 'post_type_archive'.
*/
$string = apply_filters( 'user_trailingslashit', $string, $type_of_url );
return $string;
}
/**
* Display permalink anchor for current post.
*
* The permalink mode title will use the post title for the 'a' element 'id'
* attribute. The id mode uses 'post-' with the post ID for the 'id' attribute.
*
* @since 0.71
*
* @param string $mode Permalink mode can be either 'title', 'id', or default, which is 'id'.
*/
function permalink_anchor( $mode = 'id' ) {
$post = get_post();
switch ( strtolower( $mode ) ) {
case 'title':
$title = sanitize_title( $post->post_title ) . '-' . $post->ID;
echo '<a id="'.$title.'"></a>';
break;
case 'id':
default:
echo '<a id="post-' . $post->ID . '"></a>';
break;
}
}
/**
* Retrieve full permalink for current post or post ID.
*
* This function is an alias for get_permalink().
*
* @since 3.9.0
*
* @see get_permalink()
*
* @param int|WP_Post $id Optional. Post ID or post object. Default is the current post.
* @param bool $leavename Optional. Whether to keep post name or page name. Default false.
* @return string|bool The permalink URL or false if post does not exist.
*/
function get_the_permalink( $id = 0, $leavename = false ) {
return get_permalink( $id, $leavename );
}
/**
* Retrieve full permalink for current post or post ID.
*
* @since 1.0.0
*
* @param int|WP_Post $id Optional. Post ID or post object. Default current post.
* @param bool $leavename Optional. Whether to keep post name or page name. Default false.
* @return string|bool The permalink URL or false if post does not exist.
*/
function get_permalink( $id = 0, $leavename = false ) {
$rewritecode = array(
'%year%',
'%monthnum%',
'%day%',
'%hour%',
'%minute%',
'%second%',
$leavename? '' : '%postname%',
'%post_id%',
'%category%',
'%author%',
$leavename? '' : '%pagename%',
);
if ( is_object($id) && isset($id->filter) && 'sample' == $id->filter ) {
$post = $id;
$sample = true;
} else {
$post = get_post($id);
$sample = false;
}
if ( empty($post->ID) )
return false;
if ( $post->post_type == 'page' )
return get_page_link($post->ID, $leavename, $sample);
elseif ( $post->post_type == 'attachment' )
return get_attachment_link( $post->ID, $leavename );
elseif ( in_array($post->post_type, get_post_types( array('_builtin' => false) ) ) )
return get_post_permalink($post->ID, $leavename, $sample);
$permalink = get_option('permalink_structure');
/**
* Filter the permalink structure for a post before token replacement occurs.
*
* Only applies to posts with post_type of 'post'.
*
* @since 3.0.0
*
* @param string $permalink The site's permalink structure.
* @param WP_Post $post The post in question.
* @param bool $leavename Whether to keep the post name.
*/
$permalink = apply_filters( 'pre_post_link', $permalink, $post, $leavename );
if ( '' != $permalink && !in_array($post->post_status, array('draft', 'pending', 'auto-draft')) ) {
$unixtime = strtotime($post->post_date);
$category = '';
if ( strpos($permalink, '%category%') !== false ) {
$cats = get_the_category($post->ID);
if ( $cats ) {
usort($cats, '_usort_terms_by_ID'); // order by ID
/**
* Filter the category that gets used in the %category% permalink token.
*
* @since 3.5.0
*
* @param stdClass $cat The category to use in the permalink.
* @param array $cats Array of all categories associated with the post.
* @param WP_Post $post The post in question.
*/
$category_object = apply_filters( 'post_link_category', $cats[0], $cats, $post );
$category_object = get_term( $category_object, 'category' );
$category = $category_object->slug;
if ( $parent = $category_object->parent )
$category = get_category_parents($parent, false, '/', true) . $category;
}
// show default category in permalinks, without
// having to assign it explicitly
if ( empty($category) ) {
$default_category = get_term( get_option( 'default_category' ), 'category' );
$category = is_wp_error( $default_category ) ? '' : $default_category->slug;
}
}
$author = '';
if ( strpos($permalink, '%author%') !== false ) {
$authordata = get_userdata($post->post_author);
$author = $authordata->user_nicename;
}
$date = explode(" ",date('Y m d H i s', $unixtime));
$rewritereplace =
array(
$date[0],
$date[1],
$date[2],
$date[3],
$date[4],
$date[5],
$post->post_name,
$post->ID,
$category,
$author,
$post->post_name,
);
$permalink = home_url( str_replace($rewritecode, $rewritereplace, $permalink) );
$permalink = user_trailingslashit($permalink, 'single');
} else { // if they're not using the fancy permalink option
$permalink = home_url('?p=' . $post->ID);
}
/**
* Filter the permalink for a post.
*
* Only applies to posts with post_type of 'post'.
*
* @since 1.5.0
*
* @param string $permalink The post's permalink.
* @param WP_Post $post The post in question.
* @param bool $leavename Whether to keep the post name.
*/
return apply_filters( 'post_link', $permalink, $post, $leavename );
}
/**
* Retrieve the permalink for a post with a custom post type.
*
* @since 3.0.0
*
* @param int $id Optional. Post ID.
* @param bool $leavename Optional, defaults to false. Whether to keep post name.
* @param bool $sample Optional, defaults to false. Is it a sample permalink.
* @return string
*/
function get_post_permalink( $id = 0, $leavename = false, $sample = false ) {
global $wp_rewrite;
$post = get_post($id);
if ( is_wp_error( $post ) )
return $post;
$post_link = $wp_rewrite->get_extra_permastruct($post->post_type);
$slug = $post->post_name;
$draft_or_pending = isset($post->post_status) && in_array( $post->post_status, array( 'draft', 'pending', 'auto-draft' ) );
$post_type = get_post_type_object($post->post_type);
if ( !empty($post_link) && ( !$draft_or_pending || $sample ) ) {
if ( ! $leavename ) {
if ( $post_type->hierarchical )
$slug = get_page_uri($id);
$post_link = str_replace("%$post->post_type%", $slug, $post_link);
}
$post_link = home_url( user_trailingslashit($post_link) );
} else {
if ( $post_type->query_var && ( isset($post->post_status) && !$draft_or_pending ) )
$post_link = add_query_arg($post_type->query_var, $slug, '');
else
$post_link = add_query_arg(array('post_type' => $post->post_type, 'p' => $post->ID), '');
$post_link = home_url($post_link);
}
/**
* Filter the permalink for a post with a custom post type.
*
* @since 3.0.0
*
* @param string $post_link The post's permalink.
* @param WP_Post $post The post in question.
* @param bool $leavename Whether to keep the post name.
* @param bool $sample Is it a sample permalink.
*/
return apply_filters( 'post_type_link', $post_link, $post, $leavename, $sample );
}
/**
* Retrieve permalink from post ID.
*
* @since 1.0.0
*
* @param int $post_id Optional. Post ID.
* @param mixed $deprecated Not used.
* @return string
*/
function post_permalink( $post_id = 0, $deprecated = '' ) {
if ( !empty( $deprecated ) )
_deprecated_argument( __FUNCTION__, '1.3' );
return get_permalink($post_id);
}
/**
* Retrieve the permalink for current page or page ID.
*
* Respects page_on_front. Use this one.
*
* @since 1.5.0
*
* @param int|object $post Optional. Post ID or object.
* @param bool $leavename Optional, defaults to false. Whether to keep page name.
* @param bool $sample Optional, defaults to false. Is it a sample permalink.
* @return string
*/
function get_page_link( $post = false, $leavename = false, $sample = false ) {
$post = get_post( $post );
if ( 'page' == get_option( 'show_on_front' ) && $post->ID == get_option( 'page_on_front' ) )
$link = home_url('/');
else
$link = _get_page_link( $post, $leavename, $sample );
/**
* Filter the permalink for a page.
*
* @since 1.5.0
*
* @param string $link The page's permalink.
* @param int $post_id The ID of the page.
* @param bool $sample Is it a sample permalink.
*/
return apply_filters( 'page_link', $link, $post->ID, $sample );
}
/**
* Retrieve the page permalink.
*
* Ignores page_on_front. Internal use only.
*
* @since 2.1.0
* @access private
*
* @param int|object $post Optional. Post ID or object.
* @param bool $leavename Optional. Leave name.
* @param bool $sample Optional. Sample permalink.
* @return string
*/
function _get_page_link( $post = false, $leavename = false, $sample = false ) {
global $wp_rewrite;
$post = get_post( $post );
$draft_or_pending = in_array( $post->post_status, array( 'draft', 'pending', 'auto-draft' ) );
$link = $wp_rewrite->get_page_permastruct();
if ( !empty($link) && ( ( isset($post->post_status) && !$draft_or_pending ) || $sample ) ) {
if ( ! $leavename ) {
$link = str_replace('%pagename%', get_page_uri( $post ), $link);
}
$link = home_url($link);
$link = user_trailingslashit($link, 'page');
} else {
$link = home_url( '?page_id=' . $post->ID );
}
/**
* Filter the permalink for a non-page_on_front page.
*
* @since 2.1.0
*
* @param string $link The page's permalink.
* @param int $post_id The ID of the page.
*/
return apply_filters( '_get_page_link', $link, $post->ID );
}
/**
* Retrieve permalink for attachment.
*
* This can be used in the WordPress Loop or outside of it.
*
* @since 2.0.0
*
* @param int|object $post Optional. Post ID or object.
* @param bool $leavename Optional. Leave name.
* @return string
*/
function get_attachment_link( $post = null, $leavename = false ) {
global $wp_rewrite;
$link = false;
$post = get_post( $post );
$parent = ( $post->post_parent > 0 && $post->post_parent != $post->ID ) ? get_post( $post->post_parent ) : false;
if ( $wp_rewrite->using_permalinks() && $parent ) {
if ( 'page' == $parent->post_type )
$parentlink = _get_page_link( $post->post_parent ); // Ignores page_on_front
else
$parentlink = get_permalink( $post->post_parent );
if ( is_numeric($post->post_name) || false !== strpos(get_option('permalink_structure'), '%category%') )
$name = 'attachment/' . $post->post_name; // <permalink>/<int>/ is paged so we use the explicit attachment marker
else
$name = $post->post_name;
if ( strpos($parentlink, '?') === false )
$link = user_trailingslashit( trailingslashit($parentlink) . '%postname%' );
if ( ! $leavename )
$link = str_replace( '%postname%', $name, $link );
}
if ( ! $link )
$link = home_url( '/?attachment_id=' . $post->ID );
/**
* Filter the permalink for an attachment.
*
* @since 2.0.0
*
* @param string $link The attachment's permalink.
* @param int $post_id Attachment ID.
*/
return apply_filters( 'attachment_link', $link, $post->ID );
}
/**
* Retrieve the permalink for the year archives.
*
* @since 1.5.0
*
* @param int|bool $year False for current year or year for permalink.
* @return string
*/
function get_year_link($year) {
global $wp_rewrite;
if ( !$year )
$year = gmdate('Y', current_time('timestamp'));
$yearlink = $wp_rewrite->get_year_permastruct();
if ( !empty($yearlink) ) {
$yearlink = str_replace('%year%', $year, $yearlink);
$yearlink = home_url( user_trailingslashit( $yearlink, 'year' ) );
} else {
$yearlink = home_url( '?m=' . $year );
}
/**
* Filter the year archive permalink.
*
* @since 1.5.0
*
* @param string $yearlink Permalink for the year archive.
* @param int $year Year for the archive.
*/
return apply_filters( 'year_link', $yearlink, $year );
}
/**
* Retrieve the permalink for the month archives with year.
*
* @since 1.0.0
*
* @param bool|int $year False for current year. Integer of year.
* @param bool|int $month False for current month. Integer of month.
* @return string
*/
function get_month_link($year, $month) {
global $wp_rewrite;
if ( !$year )
$year = gmdate('Y', current_time('timestamp'));
if ( !$month )
$month = gmdate('m', current_time('timestamp'));
$monthlink = $wp_rewrite->get_month_permastruct();
if ( !empty($monthlink) ) {
$monthlink = str_replace('%year%', $year, $monthlink);
$monthlink = str_replace('%monthnum%', zeroise(intval($month), 2), $monthlink);
$monthlink = home_url( user_trailingslashit( $monthlink, 'month' ) );
} else {
$monthlink = home_url( '?m=' . $year . zeroise( $month, 2 ) );
}
/**
* Filter the month archive permalink.
*
* @since 1.5.0
*
* @param string $monthlink Permalink for the month archive.
* @param int $year Year for the archive.
* @param int $month The month for the archive.
*/
return apply_filters( 'month_link', $monthlink, $year, $month );
}
/**
* Retrieve the permalink for the day archives with year and month.
*
* @since 1.0.0
*
* @param bool|int $year False for current year. Integer of year.
* @param bool|int $month False for current month. Integer of month.
* @param bool|int $day False for current day. Integer of day.
* @return string
*/
function get_day_link($year, $month, $day) {
global $wp_rewrite;
if ( !$year )
$year = gmdate('Y', current_time('timestamp'));
if ( !$month )
$month = gmdate('m', current_time('timestamp'));
if ( !$day )
$day = gmdate('j', current_time('timestamp'));
$daylink = $wp_rewrite->get_day_permastruct();
if ( !empty($daylink) ) {
$daylink = str_replace('%year%', $year, $daylink);
$daylink = str_replace('%monthnum%', zeroise(intval($month), 2), $daylink);
$daylink = str_replace('%day%', zeroise(intval($day), 2), $daylink);
$daylink = home_url( user_trailingslashit( $daylink, 'day' ) );
} else {
$daylink = home_url( '?m=' . $year . zeroise( $month, 2 ) . zeroise( $day, 2 ) );
}
/**
* Filter the day archive permalink.
*
* @since 1.5.0
*
* @param string $daylink Permalink for the day archive.
* @param int $year Year for the archive.
* @param int $month Month for the archive.
* @param int $day The day for the archive.
*/
return apply_filters( 'day_link', $daylink, $year, $month, $day );
}
/**
* Display the permalink for the feed type.
*
* @since 3.0.0
*
* @param string $anchor The link's anchor text.
* @param string $feed Optional, defaults to default feed. Feed type.
*/
function the_feed_link( $anchor, $feed = '' ) {
$link = '<a href="' . esc_url( get_feed_link( $feed ) ) . '">' . $anchor . '</a>';
/**
* Filter the feed link anchor tag.
*
* @since 3.0.0
*
* @param string $link The complete anchor tag for a feed link.
* @param string $feed The feed type, or an empty string for the
* default feed type.
*/
echo apply_filters( 'the_feed_link', $link, $feed );
}
/**
* Retrieve the permalink for the feed type.
*
* @since 1.5.0
*
* @param string $feed Optional, defaults to default feed. Feed type.
* @return string
*/
function get_feed_link($feed = '') {
global $wp_rewrite;
$permalink = $wp_rewrite->get_feed_permastruct();
if ( '' != $permalink ) {
if ( false !== strpos($feed, 'comments_') ) {
$feed = str_replace('comments_', '', $feed);
$permalink = $wp_rewrite->get_comment_feed_permastruct();
}
if ( get_default_feed() == $feed )
$feed = '';
$permalink = str_replace('%feed%', $feed, $permalink);
$permalink = preg_replace('#/+#', '/', "/$permalink");
$output = home_url( user_trailingslashit($permalink, 'feed') );
} else {
if ( empty($feed) )
$feed = get_default_feed();
if ( false !== strpos($feed, 'comments_') )
$feed = str_replace('comments_', 'comments-', $feed);
$output = home_url("?feed={$feed}");
}
/**
* Filter the feed type permalink.
*
* @since 1.5.0
*
* @param string $output The feed permalink.
* @param string $feed Feed type.
*/
return apply_filters( 'feed_link', $output, $feed );
}
/**
* Retrieve the permalink for the post comments feed.
*
* @since 2.2.0
*
* @param int $post_id Optional. Post ID.
* @param string $feed Optional. Feed type.
* @return string
*/
function get_post_comments_feed_link($post_id = 0, $feed = '') {
$post_id = absint( $post_id );
if ( ! $post_id )
$post_id = get_the_ID();
if ( empty( $feed ) )
$feed = get_default_feed();
if ( '' != get_option('permalink_structure') ) {
if ( 'page' == get_option('show_on_front') && $post_id == get_option('page_on_front') )
$url = _get_page_link( $post_id );
else
$url = get_permalink($post_id);
$url = trailingslashit($url) . 'feed';
if ( $feed != get_default_feed() )
$url .= "/$feed";
$url = user_trailingslashit($url, 'single_feed');
} else {
$type = get_post_field('post_type', $post_id);
if ( 'page' == $type )
$url = add_query_arg( array( 'feed' => $feed, 'page_id' => $post_id ), home_url( '/' ) );
else
$url = add_query_arg( array( 'feed' => $feed, 'p' => $post_id ), home_url( '/' ) );
}
/**
* Filter the post comments feed permalink.
*
* @since 1.5.1
*
* @param string $url Post comments feed permalink.
*/
return apply_filters( 'post_comments_feed_link', $url );
}
/**
* Display the comment feed link for a post.
*
* Prints out the comment feed link for a post. Link text is placed in the
* anchor. If no link text is specified, default text is used. If no post ID is
* specified, the current post is used.
*
* @since 2.5.0
*
* @param string $link_text Descriptive text.
* @param int $post_id Optional post ID. Default to current post.
* @param string $feed Optional. Feed format.
* @return string Link to the comment feed for the current post.
*/
function post_comments_feed_link( $link_text = '', $post_id = '', $feed = '' ) {
$url = esc_url( get_post_comments_feed_link( $post_id, $feed ) );
if ( empty($link_text) )
$link_text = __('Comments Feed');
/**
* Filter the post comment feed link anchor tag.
*
* @since 2.8.0
*
* @param string $link The complete anchor tag for the comment feed link.
* @param int $post_id Post ID.
* @param string $feed The feed type, or an empty string for the default feed type.
*/
echo apply_filters( 'post_comments_feed_link_html', "<a href='$url'>$link_text</a>", $post_id, $feed );
}
/**
* Retrieve the feed link for a given author.
*
* Returns a link to the feed for all posts by a given author. A specific feed
* can be requested or left blank to get the default feed.
*
* @since 2.5.0
*
* @param int $author_id ID of an author.
* @param string $feed Optional. Feed type.
* @return string Link to the feed for the author specified by $author_id.
*/
function get_author_feed_link( $author_id, $feed = '' ) {
$author_id = (int) $author_id;
$permalink_structure = get_option('permalink_structure');
if ( empty($feed) )
$feed = get_default_feed();
if ( '' == $permalink_structure ) {
$link = home_url("?feed=$feed&author=" . $author_id);
} else {
$link = get_author_posts_url($author_id);
if ( $feed == get_default_feed() )
$feed_link = 'feed';
else
$feed_link = "feed/$feed";
$link = trailingslashit($link) . user_trailingslashit($feed_link, 'feed');
}
/**
* Filter the feed link for a given author.
*
* @since 1.5.1
*
* @param string $link The author feed link.
* @param string $feed Feed type.
*/
$link = apply_filters( 'author_feed_link', $link, $feed );
return $link;
}
/**
* Retrieve the feed link for a category.
*
* Returns a link to the feed for all posts in a given category. A specific feed
* can be requested or left blank to get the default feed.
*
* @since 2.5.0
*
* @param int $cat_id ID of a category.
* @param string $feed Optional. Feed type.
* @return string Link to the feed for the category specified by $cat_id.
*/
function get_category_feed_link($cat_id, $feed = '') {
return get_term_feed_link($cat_id, 'category', $feed);
}
/**
* Retrieve the feed link for a term.
*
* Returns a link to the feed for all posts in a given term. A specific feed
* can be requested or left blank to get the default feed.
*
* @since 3.0.0
*
* @param int $term_id ID of a category.
* @param string $taxonomy Optional. Taxonomy of $term_id
* @param string $feed Optional. Feed type.
* @return string Link to the feed for the term specified by $term_id and $taxonomy.
*/
function get_term_feed_link( $term_id, $taxonomy = 'category', $feed = '' ) {
$term_id = ( int ) $term_id;
$term = get_term( $term_id, $taxonomy );
if ( empty( $term ) || is_wp_error( $term ) )
return false;
if ( empty( $feed ) )
$feed = get_default_feed();
$permalink_structure = get_option( 'permalink_structure' );
if ( '' == $permalink_structure ) {
if ( 'category' == $taxonomy ) {
$link = home_url("?feed=$feed&cat=$term_id");
}
elseif ( 'post_tag' == $taxonomy ) {
$link = home_url("?feed=$feed&tag=$term->slug");
} else {
$t = get_taxonomy( $taxonomy );
$link = home_url("?feed=$feed&$t->query_var=$term->slug");
}
} else {
$link = get_term_link( $term_id, $term->taxonomy );
if ( $feed == get_default_feed() )
$feed_link = 'feed';
else
$feed_link = "feed/$feed";
$link = trailingslashit( $link ) . user_trailingslashit( $feed_link, 'feed' );
}
if ( 'category' == $taxonomy ) {
/**
* Filter the category feed link.
*
* @since 1.5.1
*
* @param string $link The category feed link.
* @param string $feed Feed type.
*/
$link = apply_filters( 'category_feed_link', $link, $feed );
} elseif ( 'post_tag' == $taxonomy ) {
/**
* Filter the post tag feed link.
*
* @since 2.3.0
*
* @param string $link The tag feed link.
* @param string $feed Feed type.
*/
$link = apply_filters( 'tag_feed_link', $link, $feed );
} else {
/**
* Filter the feed link for a taxonomy other than 'category' or 'post_tag'.
*
* @since 3.0.0
*
* @param string $link The taxonomy feed link.
* @param string $feed Feed type.
* @param string $feed The taxonomy name.
*/
$link = apply_filters( 'taxonomy_feed_link', $link, $feed, $taxonomy );
}
return $link;
}
/**
* Retrieve permalink for feed of tag.
*
* @since 2.3.0
*
* @param int $tag_id Tag ID.
* @param string $feed Optional. Feed type.
* @return string
*/
function get_tag_feed_link($tag_id, $feed = '') {
return get_term_feed_link($tag_id, 'post_tag', $feed);
}
/**
* Retrieve edit tag link.
*
* @since 2.7.0
*
* @param int $tag_id Tag ID
* @param string $taxonomy Taxonomy
* @return string
*/
function get_edit_tag_link( $tag_id, $taxonomy = 'post_tag' ) {
/**
* Filter the edit link for a tag (or term in another taxonomy).
*
* @since 2.7.0
*
* @param string $link The term edit link.
*/
return apply_filters( 'get_edit_tag_link', get_edit_term_link( $tag_id, $taxonomy ) );
}
/**
* Display or retrieve edit tag link with formatting.
*
* @since 2.7.0
*
* @param string $link Optional. Anchor text.
* @param string $before Optional. Display before edit link.
* @param string $after Optional. Display after edit link.
* @param object $tag Tag object.
* @return string HTML content.
*/
function edit_tag_link( $link = '', $before = '', $after = '', $tag = null ) {
$link = edit_term_link( $link, '', '', $tag, false );
/**
* Filter the anchor tag for the edit link for a tag (or term in another taxonomy).
*
* @since 2.7.0
*
* @param string $link The anchor tag for the edit link.
*/
echo $before . apply_filters( 'edit_tag_link', $link ) . $after;
}
/**
* Retrieve edit term url.
*
* @since 3.1.0
*
* @param int $term_id Term ID
* @param string $taxonomy Taxonomy
* @param string $object_type The object type
* @return string
*/
function get_edit_term_link( $term_id, $taxonomy, $object_type = '' ) {
$tax = get_taxonomy( $taxonomy );
if ( !current_user_can( $tax->cap->edit_terms ) )
return;
$term = get_term( $term_id, $taxonomy );
$args = array(
'action' => 'edit',
'taxonomy' => $taxonomy,
'tag_ID' => $term->term_id,
);
if ( $object_type )
$args['post_type'] = $object_type;
$location = add_query_arg( $args, admin_url( 'edit-tags.php' ) );
/**
* Filter the edit link for a term.
*
* @since 3.1.0
*
* @param string $location The edit link.
* @param int $term_id Term ID.
* @param string $taxonomy Taxonomy name.
* @param string $object_type The object type (eg. the post type).
*/
return apply_filters( 'get_edit_term_link', $location, $term_id, $taxonomy, $object_type );
}
/**
* Display or retrieve edit term link with formatting.
*
* @since 3.1.0
*
* @param string $link Optional. Anchor text.
* @param string $before Optional. Display before edit link.
* @param string $after Optional. Display after edit link.
* @param object $term Term object.
* @return string HTML content.
*/
function edit_term_link( $link = '', $before = '', $after = '', $term = null, $echo = true ) {
if ( is_null( $term ) )
$term = get_queried_object();
if ( ! $term )
return;
$tax = get_taxonomy( $term->taxonomy );
if ( ! current_user_can( $tax->cap->edit_terms ) )
return;
if ( empty( $link ) )
$link = __('Edit This');
$link = '<a href="' . get_edit_term_link( $term->term_id, $term->taxonomy ) . '">' . $link . '</a>';
/**
* Filter the anchor tag for the edit link of a term.
*
* @since 3.1.0
*
* @param string $link The anchor tag for the edit link.
* @param int $term_id Term ID.
*/
$link = $before . apply_filters( 'edit_term_link', $link, $term->term_id ) . $after;
if ( $echo )
echo $link;
else
return $link;
}
/**
* Retrieve permalink for search.
*
* @since 3.0.0
*
* @param string $query Optional. The query string to use. If empty the current query is used.
* @return string
*/
function get_search_link( $query = '' ) {
global $wp_rewrite;
if ( empty($query) )
$search = get_search_query( false );
else
$search = stripslashes($query);
$permastruct = $wp_rewrite->get_search_permastruct();
if ( empty( $permastruct ) ) {
$link = home_url('?s=' . urlencode($search) );
} else {
$search = urlencode($search);
$search = str_replace('%2F', '/', $search); // %2F(/) is not valid within a URL, send it unencoded.
$link = str_replace( '%search%', $search, $permastruct );
$link = home_url( user_trailingslashit( $link, 'search' ) );
}
/**
* Filter the search permalink.
*
* @since 3.0.0
*
* @param string $link Search permalink.
* @param string $search The URL-encoded search term.
*/
return apply_filters( 'search_link', $link, $search );
}
/**
* Retrieve the permalink for the feed of the search results.
*
* @since 2.5.0
*
* @param string $search_query Optional. Search query.
* @param string $feed Optional. Feed type.
* @return string
*/
function get_search_feed_link($search_query = '', $feed = '') {
global $wp_rewrite;
$link = get_search_link($search_query);
if ( empty($feed) )
$feed = get_default_feed();
$permastruct = $wp_rewrite->get_search_permastruct();
if ( empty($permastruct) ) {
$link = add_query_arg('feed', $feed, $link);
} else {
$link = trailingslashit($link);
$link .= "feed/$feed/";
}
/**
* Filter the search feed link.
*
* @since 2.5.0
*
* @param string $link Search feed link.
* @param string $feed Feed type.
* @param string $type The search type. One of 'posts' or 'comments'.
*/
$link = apply_filters( 'search_feed_link', $link, $feed, 'posts' );
return $link;
}
/**
* Retrieve the permalink for the comments feed of the search results.
*
* @since 2.5.0
*
* @param string $search_query Optional. Search query.
* @param string $feed Optional. Feed type.
* @return string
*/
function get_search_comments_feed_link($search_query = '', $feed = '') {
global $wp_rewrite;
if ( empty($feed) )
$feed = get_default_feed();
$link = get_search_feed_link($search_query, $feed);
$permastruct = $wp_rewrite->get_search_permastruct();
if ( empty($permastruct) )
$link = add_query_arg('feed', 'comments-' . $feed, $link);
else
$link = add_query_arg('withcomments', 1, $link);
/** This filter is documented in wp-includes/link-template.php */
$link = apply_filters('search_feed_link', $link, $feed, 'comments');
return $link;
}
/**
* Retrieve the permalink for a post type archive.
*
* @since 3.1.0
*
* @param string $post_type Post type
* @return string
*/
function get_post_type_archive_link( $post_type ) {
global $wp_rewrite;
if ( ! $post_type_obj = get_post_type_object( $post_type ) )
return false;
if ( ! $post_type_obj->has_archive )
return false;
if ( get_option( 'permalink_structure' ) && is_array( $post_type_obj->rewrite ) ) {
$struct = ( true === $post_type_obj->has_archive ) ? $post_type_obj->rewrite['slug'] : $post_type_obj->has_archive;
if ( $post_type_obj->rewrite['with_front'] )
$struct = $wp_rewrite->front . $struct;
else
$struct = $wp_rewrite->root . $struct;
$link = home_url( user_trailingslashit( $struct, 'post_type_archive' ) );
} else {
$link = home_url( '?post_type=' . $post_type );
}
/**
* Filter the post type archive permalink.
*
* @since 3.1.0
*
* @param string $link The post type archive permalink.
* @param string $post_type Post type name.
*/
return apply_filters( 'post_type_archive_link', $link, $post_type );
}
/**
* Retrieve the permalink for a post type archive feed.
*
* @since 3.1.0
*
* @param string $post_type Post type
* @param string $feed Optional. Feed type
* @return string
*/
function get_post_type_archive_feed_link( $post_type, $feed = '' ) {
$default_feed = get_default_feed();
if ( empty( $feed ) )
$feed = $default_feed;
if ( ! $link = get_post_type_archive_link( $post_type ) )
return false;
$post_type_obj = get_post_type_object( $post_type );
if ( get_option( 'permalink_structure' ) && is_array( $post_type_obj->rewrite ) && $post_type_obj->rewrite['feeds'] ) {
$link = trailingslashit( $link );
$link .= 'feed/';
if ( $feed != $default_feed )
$link .= "$feed/";
} else {
$link = add_query_arg( 'feed', $feed, $link );
}
/**
* Filter the post type archive feed link.
*
* @since 3.1.0
*
* @param string $link The post type archive feed link.
* @param string $feed Feed type.
*/
return apply_filters( 'post_type_archive_feed_link', $link, $feed );
}
/**
* Retrieve edit posts link for post.
*
* Can be used within the WordPress loop or outside of it. Can be used with
* pages, posts, attachments, and revisions.
*
* @since 2.3.0
*
* @param int $id Optional. Post ID.
* @param string $context Optional, defaults to display. How to write the '&', defaults to '&'.
* @return string
*/
function get_edit_post_link( $id = 0, $context = 'display' ) {
if ( ! $post = get_post( $id ) )
return;
if ( 'revision' === $post->post_type )
$action = '';
elseif ( 'display' == $context )
$action = '&action=edit';
else
$action = '&action=edit';
$post_type_object = get_post_type_object( $post->post_type );
if ( !$post_type_object )
return;
if ( !current_user_can( 'edit_post', $post->ID ) )
return;
/**
* Filter the post edit link.
*
* @since 2.3.0
*
* @param string $link The edit link.
* @param int $post_id Post ID.
* @param string $context The link context. If set to 'display' then ampersands
* are encoded.
*/
return apply_filters( 'get_edit_post_link', admin_url( sprintf( $post_type_object->_edit_link . $action, $post->ID ) ), $post->ID, $context );
}
/**
* Display edit post link for post.
*
* @since 1.0.0
*
* @param string $link Optional. Anchor text.
* @param string $before Optional. Display before edit link.
* @param string $after Optional. Display after edit link.
* @param int $id Optional. Post ID.
*/
function edit_post_link( $link = null, $before = '', $after = '', $id = 0 ) {
if ( !$post = get_post( $id ) )
return;
if ( !$url = get_edit_post_link( $post->ID ) )
return;
if ( null === $link )
$link = __('Edit This');
$post_type_obj = get_post_type_object( $post->post_type );
$link = '<a class="post-edit-link" href="' . $url . '">' . $link . '</a>';
/**
* Filter the post edit link anchor tag.
*
* @since 2.3.0
*
* @param string $link Anchor tag for the edit link.
* @param int $post_id Post ID.
*/
echo $before . apply_filters( 'edit_post_link', $link, $post->ID ) . $after;
}
/**
* Retrieve delete posts link for post.
*
* Can be used within the WordPress loop or outside of it, with any post type.
*
* @since 2.9.0
*
* @param int $id Optional. Post ID.
* @param string $deprecated Not used.
* @param bool $force_delete Whether to bypass trash and force deletion. Default is false.
* @return string
*/
function get_delete_post_link( $id = 0, $deprecated = '', $force_delete = false ) {
if ( ! empty( $deprecated ) )
_deprecated_argument( __FUNCTION__, '3.0' );
if ( !$post = get_post( $id ) )
return;
$post_type_object = get_post_type_object( $post->post_type );
if ( !$post_type_object )
return;
if ( !current_user_can( 'delete_post', $post->ID ) )
return;
$action = ( $force_delete || !EMPTY_TRASH_DAYS ) ? 'delete' : 'trash';
$delete_link = add_query_arg( 'action', $action, admin_url( sprintf( $post_type_object->_edit_link, $post->ID ) ) );
/**
* Filter the post delete link.
*
* @since 2.9.0
*
* @param string $link The delete link.
* @param int $post_id Post ID.
* @param bool $force_delete Whether to bypass the trash and force deletion. Default false.
*/
return apply_filters( 'get_delete_post_link', wp_nonce_url( $delete_link, "$action-post_{$post->ID}" ), $post->ID, $force_delete );
}
/**
* Retrieve edit comment link.
*
* @since 2.3.0
*
* @param int $comment_id Optional. Comment ID.
* @return string
*/
function get_edit_comment_link( $comment_id = 0 ) {
$comment = get_comment( $comment_id );
if ( !current_user_can( 'edit_comment', $comment->comment_ID ) )
return;
$location = admin_url('comment.php?action=editcomment&c=') . $comment->comment_ID;
/**
* Filter the comment edit link.
*
* @since 2.3.0
*
* @param string $location The edit link.
*/
return apply_filters( 'get_edit_comment_link', $location );
}
/**
* Display edit comment link with formatting.
*
* @since 1.0.0
*
* @param string $link Optional. Anchor text.
* @param string $before Optional. Display before edit link.
* @param string $after Optional. Display after edit link.
*/
function edit_comment_link( $link = null, $before = '', $after = '' ) {
global $comment;
if ( !current_user_can( 'edit_comment', $comment->comment_ID ) )
return;
if ( null === $link )
$link = __('Edit This');
$link = '<a class="comment-edit-link" href="' . get_edit_comment_link( $comment->comment_ID ) . '">' . $link . '</a>';
/**
* Filter the comment edit link anchor tag.
*
* @since 2.3.0
*
* @param string $link Anchor tag for the edit link.
* @param int $comment_id Comment ID.
*/
echo $before . apply_filters( 'edit_comment_link', $link, $comment->comment_ID ) . $after;
}
/**
* Display edit bookmark (literally a URL external to blog) link.
*
* @since 2.7.0
*
* @param int $link Optional. Bookmark ID.
* @return string
*/
function get_edit_bookmark_link( $link = 0 ) {
$link = get_bookmark( $link );
if ( !current_user_can('manage_links') )
return;
$location = admin_url('link.php?action=edit&link_id=') . $link->link_id;
/**
* Filter the bookmark (link) edit link.
*
* @since 2.7.0
*
* @param string $location The edit link.
* @param int $link_id Bookmark ID.
*/
return apply_filters( 'get_edit_bookmark_link', $location, $link->link_id );
}
/**
* Display edit bookmark (literally a URL external to blog) link anchor content.
*
* @since 2.7.0
*
* @param string $link Optional. Anchor text.
* @param string $before Optional. Display before edit link.
* @param string $after Optional. Display after edit link.
* @param int $bookmark Optional. Bookmark ID.
*/
function edit_bookmark_link( $link = '', $before = '', $after = '', $bookmark = null ) {
$bookmark = get_bookmark($bookmark);
if ( !current_user_can('manage_links') )
return;
if ( empty($link) )
$link = __('Edit This');
$link = '<a href="' . get_edit_bookmark_link( $bookmark ) . '">' . $link . '</a>';
/**
* Filter the bookmark edit link anchor tag.
*
* @since 2.7.0
*
* @param string $link Anchor tag for the edit link.
* @param int $link_id Bookmark ID.
*/
echo $before . apply_filters( 'edit_bookmark_link', $link, $bookmark->link_id ) . $after;
}
/**
* Retrieve edit user link
*
* @since 3.5.0
*
* @param int $user_id Optional. User ID. Defaults to the current user.
* @return string URL to edit user page or empty string.
*/
function get_edit_user_link( $user_id = null ) {
if ( ! $user_id )
$user_id = get_current_user_id();
if ( empty( $user_id ) || ! current_user_can( 'edit_user', $user_id ) )
return '';
$user = get_userdata( $user_id );
if ( ! $user )
return '';
if ( get_current_user_id() == $user->ID )
$link = get_edit_profile_url( $user->ID );
else
$link = add_query_arg( 'user_id', $user->ID, self_admin_url( 'user-edit.php' ) );
/**
* Filter the user edit link.
*
* @since 3.5.0
*
* @param string $link The edit link.
* @param int $user_id User ID.
*/
return apply_filters( 'get_edit_user_link', $link, $user->ID );
}
// Navigation links
/**
* Retrieve previous post that is adjacent to current post.
*
* @since 1.5.0
*
* @param bool $in_same_term Optional. Whether post should be in a same taxonomy term.
* @param array|string $excluded_terms Optional. Array or comma-separated list of excluded term IDs.
* @param string $taxonomy Optional. Taxonomy, if $in_same_term is true. Default 'category'.
* @return mixed Post object if successful. Null if global $post is not set. Empty string if no corresponding post exists.
*/
function get_previous_post( $in_same_term = false, $excluded_terms = '', $taxonomy = 'category' ) {
return get_adjacent_post( $in_same_term, $excluded_terms, true, $taxonomy );
}
/**
* Retrieve next post that is adjacent to current post.
*
* @since 1.5.0
*
* @param bool $in_same_term Optional. Whether post should be in a same taxonomy term.
* @param array|string $excluded_terms Optional. Array or comma-separated list of excluded term IDs.
* @param string $taxonomy Optional. Taxonomy, if $in_same_term is true. Default 'category'.
* @return mixed Post object if successful. Null if global $post is not set. Empty string if no corresponding post exists.
*/
function get_next_post( $in_same_term = false, $excluded_terms = '', $taxonomy = 'category' ) {
return get_adjacent_post( $in_same_term, $excluded_terms, false, $taxonomy );
}
/**
* Retrieve adjacent post.
*
* Can either be next or previous post.
*
* @since 2.5.0
*
* @param bool $in_same_term Optional. Whether post should be in a same taxonomy term.
* @param array|string $excluded_terms Optional. Array or comma-separated list of excluded term IDs.
* @param bool $previous Optional. Whether to retrieve previous post.
* @param string $taxonomy Optional. Taxonomy, if $in_same_term is true. Default 'category'.
* @return mixed Post object if successful. Null if global $post is not set. Empty string if no corresponding post exists.
*/
function get_adjacent_post( $in_same_term = false, $excluded_terms = '', $previous = true, $taxonomy = 'category' ) {
global $wpdb;
if ( ( ! $post = get_post() ) || ! taxonomy_exists( $taxonomy ) )
return null;
$current_post_date = $post->post_date;
$join = '';
$posts_in_ex_terms_sql = '';
if ( $in_same_term || ! empty( $excluded_terms ) ) {
$join = " INNER JOIN $wpdb->term_relationships AS tr ON p.ID = tr.object_id INNER JOIN $wpdb->term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id";
if ( $in_same_term ) {
if ( ! is_object_in_taxonomy( $post->post_type, $taxonomy ) )
return '';
$term_array = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) );
if ( ! $term_array || is_wp_error( $term_array ) )
return '';
$join .= $wpdb->prepare( " AND tt.taxonomy = %s AND tt.term_id IN (" . implode( ',', array_map( 'intval', $term_array ) ) . ")", $taxonomy );
}
$posts_in_ex_terms_sql = $wpdb->prepare( "AND tt.taxonomy = %s", $taxonomy );
if ( ! empty( $excluded_terms ) ) {
if ( ! is_array( $excluded_terms ) ) {
// back-compat, $excluded_terms used to be $excluded_terms with IDs separated by " and "
if ( false !== strpos( $excluded_terms, ' and ' ) ) {
_deprecated_argument( __FUNCTION__, '3.3', sprintf( __( 'Use commas instead of %s to separate excluded terms.' ), "'and'" ) );
$excluded_terms = explode( ' and ', $excluded_terms );
} else {
$excluded_terms = explode( ',', $excluded_terms );
}
}
$excluded_terms = array_map( 'intval', $excluded_terms );
if ( ! empty( $term_array ) ) {
$excluded_terms = array_diff( $excluded_terms, $term_array );
$posts_in_ex_terms_sql = '';
}
if ( ! empty( $excluded_terms ) ) {
$posts_in_ex_terms_sql = $wpdb->prepare( " AND tt.taxonomy = %s AND tt.term_id NOT IN (" . implode( $excluded_terms, ',' ) . ')', $taxonomy );
}
}
}
$adjacent = $previous ? 'previous' : 'next';
$op = $previous ? '<' : '>';
$order = $previous ? 'DESC' : 'ASC';
/**
* Filter the JOIN clause in the SQL for an adjacent post query.
*
* The dynamic portion of the hook name, $adjacent, refers to the type
* of adjacency, 'next' or 'previous'.
*
* @since 2.5.0
*
* @param string $join The JOIN clause in the SQL.
* @param bool $in_same_term Whether post should be in a same taxonomy term.
* @param array $excluded_terms Array of excluded term IDs.
*/
$join = apply_filters( "get_{$adjacent}_post_join", $join, $in_same_term, $excluded_terms );
/**
* Filter the WHERE clause in the SQL for an adjacent post query.
*
* The dynamic portion of the hook name, $adjacent, refers to the type
* of adjacency, 'next' or 'previous'.
*
* @since 2.5.0
*
* @param string $where The WHERE clause in the SQL.
* @param bool $in_same_term Whether post should be in a same taxonomy term.
* @param array $excluded_terms Array of excluded term IDs.
*/
$where = apply_filters( "get_{$adjacent}_post_where", $wpdb->prepare( "WHERE p.post_date $op %s AND p.post_type = %s AND p.post_status = 'publish' $posts_in_ex_terms_sql", $current_post_date, $post->post_type), $in_same_term, $excluded_terms );
/**
* Filter the ORDER BY clause in the SQL for an adjacent post query.
*
* The dynamic portion of the hook name, $adjacent, refers to the type
* of adjacency, 'next' or 'previous'.
*
* @since 2.5.0
*
* @param string $order_by The ORDER BY clause in the SQL.
*/
$sort = apply_filters( "get_{$adjacent}_post_sort", "ORDER BY p.post_date $order LIMIT 1" );
$query = "SELECT p.ID FROM $wpdb->posts AS p $join $where $sort";
$query_key = 'adjacent_post_' . md5( $query );
$result = wp_cache_get( $query_key, 'counts' );
if ( false !== $result ) {
if ( $result )
$result = get_post( $result );
return $result;
}
$result = $wpdb->get_var( $query );
if ( null === $result )
$result = '';
wp_cache_set( $query_key, $result, 'counts' );
if ( $result )
$result = get_post( $result );
return $result;
}
/**
* Get adjacent post relational link.
*
* Can either be next or previous post relational link.
*
* @since 2.8.0
*
* @param string $title Optional. Link title format.
* @param bool $in_same_term Optional. Whether link should be in a same taxonomy term.
* @param array|string $excluded_terms Optional. Array or comma-separated list of excluded term IDs.
* @param bool $previous Optional. Whether to display link to previous or next post. Default true.
* @param string $taxonomy Optional. Taxonomy, if $in_same_term is true. Default 'category'.
* @return string
*/
function get_adjacent_post_rel_link( $title = '%title', $in_same_term = false, $excluded_terms = '', $previous = true, $taxonomy = 'category' ) {
if ( $previous && is_attachment() && $post = get_post() )
$post = get_post( $post->post_parent );
else
$post = get_adjacent_post( $in_same_term, $excluded_terms, $previous, $taxonomy );
if ( empty( $post ) )
return;
$post_title = the_title_attribute( array( 'echo' => false, 'post' => $post ) );
if ( empty( $post_title ) )
$post_title = $previous ? __( 'Previous Post' ) : __( 'Next Post' );
$date = mysql2date( get_option( 'date_format' ), $post->post_date );
$title = str_replace( '%title', $post_title, $title );
$title = str_replace( '%date', $date, $title );
$link = $previous ? "<link rel='prev' title='" : "<link rel='next' title='";
$link .= esc_attr( $title );
$link .= "' href='" . get_permalink( $post ) . "' />\n";
$adjacent = $previous ? 'previous' : 'next';
/**
* Filter the adjacent post relational link.
*
* The dynamic portion of the hook name, $adjacent, refers to the type
* of adjacency, 'next' or 'previous'.
*
* @since 2.8.0
*
* @param string $link The relational link.
*/
return apply_filters( "{$adjacent}_post_rel_link", $link );
}
/**
* Display relational links for the posts adjacent to the current post.
*
* @since 2.8.0
*
* @param string $title Optional. Link title format.
* @param bool $in_same_term Optional. Whether link should be in a same taxonomy term.
* @param array|string $excluded_terms Optional. Array or comma-separated list of excluded term IDs.
* @param string $taxonomy Optional. Taxonomy, if $in_same_term is true. Default 'category'.
*/
function adjacent_posts_rel_link( $title = '%title', $in_same_term = false, $excluded_terms = '', $taxonomy = 'category' ) {
echo get_adjacent_post_rel_link( $title, $in_same_term, $excluded_terms, true, $taxonomy );
echo get_adjacent_post_rel_link( $title, $in_same_term, $excluded_terms, false, $taxonomy );
}
/**
* Display relational links for the posts adjacent to the current post for single post pages.
*
* This is meant to be attached to actions like 'wp_head'. Do not call this directly in plugins or theme templates.
* @since 3.0.0
*
*/
function adjacent_posts_rel_link_wp_head() {
if ( !is_singular() || is_attachment() )
return;
adjacent_posts_rel_link();
}
/**
* Display relational link for the next post adjacent to the current post.
*
* @since 2.8.0
*
* @param string $title Optional. Link title format.
* @param bool $in_same_term Optional. Whether link should be in a same taxonomy term.
* @param array|string $excluded_terms Optional. Array or comma-separated list of excluded term IDs.
* @param string $taxonomy Optional. Taxonomy, if $in_same_term is true. Default 'category'.
*/
function next_post_rel_link( $title = '%title', $in_same_term = false, $excluded_terms = '', $taxonomy = 'category' ) {
echo get_adjacent_post_rel_link( $title, $in_same_term, $excluded_terms, false, $taxonomy );
}
/**
* Display relational link for the previous post adjacent to the current post.
*
* @since 2.8.0
*
* @param string $title Optional. Link title format.
* @param bool $in_same_term Optional. Whether link should be in a same taxonomy term.
* @param array|string $excluded_terms Optional. Array or comma-separated list of excluded term IDs. Default true.
* @param string $taxonomy Optional. Taxonomy, if $in_same_term is true. Default 'category'.
*/
function prev_post_rel_link( $title = '%title', $in_same_term = false, $excluded_terms = '', $taxonomy = 'category' ) {
echo get_adjacent_post_rel_link( $title, $in_same_term, $excluded_terms, true, $taxonomy );
}
/**
* Retrieve boundary post.
*
* Boundary being either the first or last post by publish date within the constraints specified
* by $in_same_term or $excluded_terms.
*
* @since 2.8.0
*
* @param bool $in_same_term Optional. Whether returned post should be in a same taxonomy term.
* @param array|string $excluded_terms Optional. Array or comma-separated list of excluded term IDs.
* @param bool $start Optional. Whether to retrieve first or last post.
* @param string $taxonomy Optional. Taxonomy, if $in_same_term is true. Default 'category'.
* @return mixed Array containing the boundary post object if successful, null otherwise.
*/
function get_boundary_post( $in_same_term = false, $excluded_terms = '', $start = true, $taxonomy = 'category' ) {
$post = get_post();
if ( ! $post || ! is_single() || is_attachment() || ! taxonomy_exists( $taxonomy ) )
return null;
$query_args = array(
'posts_per_page' => 1,
'order' => $start ? 'ASC' : 'DESC',
'update_post_term_cache' => false,
'update_post_meta_cache' => false
);
$term_array = array();
if ( ! is_array( $excluded_terms ) ) {
if ( ! empty( $excluded_terms ) )
$excluded_terms = explode( ',', $excluded_terms );
else
$excluded_terms = array();
}
if ( $in_same_term || ! empty( $excluded_terms ) ) {
if ( $in_same_term )
$term_array = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) );
if ( ! empty( $excluded_terms ) ) {
$excluded_terms = array_map( 'intval', $excluded_terms );
$excluded_terms = array_diff( $excluded_terms, $term_array );
$inverse_terms = array();
foreach ( $excluded_terms as $excluded_term )
$inverse_terms[] = $excluded_term * -1;
$excluded_terms = $inverse_terms;
}
$query_args[ 'tax_query' ] = array( array(
'taxonomy' => $taxonomy,
'terms' => array_merge( $term_array, $excluded_terms )
) );
}
return get_posts( $query_args );
}
/*
* Get previous post link that is adjacent to the current post.
*
* @since 3.7.0
*
* @param string $format Optional. Link anchor format.
* @param string $link Optional. Link permalink format.
* @param bool $in_same_term Optional. Whether link should be in a same taxonomy term.
* @param array|string $excluded_terms Optional. Array or comma-separated list of excluded term IDs.
* @param string $taxonomy Optional. Taxonomy, if $in_same_term is true. Default 'category'.
* @return string
*/
function get_previous_post_link( $format = '« %link', $link = '%title', $in_same_cat = false, $excluded_terms = '', $taxonomy = 'category' ) {
return get_adjacent_post_link( $format, $link, $in_same_cat, $excluded_terms, true, $taxonomy );
}
/**
* Display previous post link that is adjacent to the current post.
*
* @since 1.5.0
* @see get_previous_post_link()
*
* @param string $format Optional. Link anchor format.
* @param string $link Optional. Link permalink format.
* @param bool $in_same_term Optional. Whether link should be in a same taxonomy term.
* @param array|string $excluded_terms Optional. Array or comma-separated list of excluded term IDs.
* @param string $taxonomy Optional. Taxonomy, if $in_same_term is true. Default 'category'.
*/
function previous_post_link( $format = '« %link', $link = '%title', $in_same_cat = false, $excluded_terms = '', $taxonomy = 'category' ) {
echo get_previous_post_link( $format, $link, $in_same_cat, $excluded_terms, $taxonomy );
}
/**
* Get next post link that is adjacent to the current post.
*
* @since 3.7.0
*
* @param string $format Optional. Link anchor format.
* @param string $link Optional. Link permalink format.
* @param bool $in_same_term Optional. Whether link should be in a same taxonomy term.
* @param array|string $excluded_terms Optional. Array or comma-separated list of excluded term IDs.
* @param string $taxonomy Optional. Taxonomy, if $in_same_term is true. Default 'category'.
* @return string
*/
function get_next_post_link( $format = '%link »', $link = '%title', $in_same_cat = false, $excluded_terms = '', $taxonomy = 'category' ) {
return get_adjacent_post_link( $format, $link, $in_same_cat, $excluded_terms, false, $taxonomy );
}
/**
* Display next post link that is adjacent to the current post.
*
* @since 1.5.0
* @see get_next_post_link()
*
* @param string $format Optional. Link anchor format.
* @param string $link Optional. Link permalink format.
* @param bool $in_same_term Optional. Whether link should be in a same taxonomy term.
* @param array|string $excluded_terms Optional. Array or comma-separated list of excluded term IDs.
* @param string $taxonomy Optional. Taxonomy, if $in_same_term is true. Default 'category'.
*/
function next_post_link( $format = '%link »', $link = '%title', $in_same_cat = false, $excluded_terms = '', $taxonomy = 'category' ) {
echo get_next_post_link( $format, $link, $in_same_cat, $excluded_terms, $taxonomy );
}
/**
* Get adjacent post link.
*
* Can be either next post link or previous.
*
* @since 3.7.0
*
* @param string $format Link anchor format.
* @param string $link Link permalink format.
* @param bool $in_same_term Optional. Whether link should be in a same taxonomy term.
* @param array|string $excluded_terms Optional. Array or comma-separated list of excluded terms IDs.
* @param bool $previous Optional. Whether to display link to previous or next post. Default true.
* @param string $taxonomy Optional. Taxonomy, if $in_same_term is true. Default 'category'.
* @return string
*/
function get_adjacent_post_link( $format, $link, $in_same_cat = false, $excluded_terms = '', $previous = true, $taxonomy = 'category' ) {
if ( $previous && is_attachment() )
$post = get_post( get_post()->post_parent );
else
$post = get_adjacent_post( $in_same_cat, $excluded_terms, $previous, $taxonomy );
if ( ! $post ) {
$output = '';
} else {
$title = $post->post_title;
if ( empty( $post->post_title ) )
$title = $previous ? __( 'Previous Post' ) : __( 'Next Post' );
/** This filter is documented in wp-includes/post-template.php */
$title = apply_filters( 'the_title', $title, $post->ID );
$date = mysql2date( get_option( 'date_format' ), $post->post_date );
$rel = $previous ? 'prev' : 'next';
$string = '<a href="' . get_permalink( $post ) . '" rel="'.$rel.'">';
$inlink = str_replace( '%title', $title, $link );
$inlink = str_replace( '%date', $date, $inlink );
$inlink = $string . $inlink . '</a>';
$output = str_replace( '%link', $inlink, $format );
}
$adjacent = $previous ? 'previous' : 'next';
/**
* Filter the adjacent post link.
*
* The dynamic portion of the hook name, $adjacent, refers to the type
* of adjacency, 'next' or 'previous'.
*
* @since 2.6.0
*
* @param string $output The adjacent post link.
* @param string $format Link anchor format.
* @param string $link Link permalink format.
* @param WP_Post $post The adjacent post.
*/
return apply_filters( "{$adjacent}_post_link", $output, $format, $link, $post );
}
/**
* Display adjacent post link.
*
* Can be either next post link or previous.
*
* @since 2.5.0
* @uses get_adjacent_post_link()
*
* @param string $format Link anchor format.
* @param string $link Link permalink format.
* @param bool $in_same_cat Optional. Whether link should be in a same category.
* @param array|string $excluded_terms Optional. Array or comma-separated list of excluded category IDs.
* @param bool $previous Optional. Whether to display link to previous or next post. Default true.
* @param string $taxonomy Optional. Taxonomy, if $in_same_term is true. Default 'category'.
* @return string
*/
function adjacent_post_link( $format, $link, $in_same_cat = false, $excluded_terms = '', $previous = true, $taxonomy = 'category' ) {
echo get_adjacent_post_link( $format, $link, $in_same_cat, $excluded_terms, $previous, $taxonomy );
}
/**
* Retrieve links for page numbers.
*
* @since 1.5.0
*
* @param int $pagenum Optional. Page ID.
* @param bool $escape Optional. Whether to escape the URL for display, with esc_url(). Defaults to true.
* Otherwise, prepares the URL with esc_url_raw().
* @return string
*/
function get_pagenum_link($pagenum = 1, $escape = true ) {
global $wp_rewrite;
$pagenum = (int) $pagenum;
$request = remove_query_arg( 'paged' );
$home_root = parse_url(home_url());
$home_root = ( isset($home_root['path']) ) ? $home_root['path'] : '';
$home_root = preg_quote( $home_root, '|' );
$request = preg_replace('|^'. $home_root . '|i', '', $request);
$request = preg_replace('|^/+|', '', $request);
if ( !$wp_rewrite->using_permalinks() || is_admin() ) {
$base = trailingslashit( get_bloginfo( 'url' ) );
if ( $pagenum > 1 ) {
$result = add_query_arg( 'paged', $pagenum, $base . $request );
} else {
$result = $base . $request;
}
} else {
$qs_regex = '|\?.*?$|';
preg_match( $qs_regex, $request, $qs_match );
if ( !empty( $qs_match[0] ) ) {
$query_string = $qs_match[0];
$request = preg_replace( $qs_regex, '', $request );
} else {
$query_string = '';
}
$request = preg_replace( "|$wp_rewrite->pagination_base/\d+/?$|", '', $request);
$request = preg_replace( '|^' . preg_quote( $wp_rewrite->index, '|' ) . '|i', '', $request);
$request = ltrim($request, '/');
$base = trailingslashit( get_bloginfo( 'url' ) );
if ( $wp_rewrite->using_index_permalinks() && ( $pagenum > 1 || '' != $request ) )
$base .= $wp_rewrite->index . '/';
if ( $pagenum > 1 ) {
$request = ( ( !empty( $request ) ) ? trailingslashit( $request ) : $request ) . user_trailingslashit( $wp_rewrite->pagination_base . "/" . $pagenum, 'paged' );
}
$result = $base . $request . $query_string;
}
/**
* Filter the page number link for the current request.
*
* @since 2.5.0
*
* @param string $result The page number link.
*/
$result = apply_filters( 'get_pagenum_link', $result );
if ( $escape )
return esc_url( $result );
else
return esc_url_raw( $result );
}
/**
* Retrieve next posts page link.
*
* Backported from 2.1.3 to 2.0.10.
*
* @since 2.0.10
*
* @param int $max_page Optional. Max pages.
* @return string
*/
function get_next_posts_page_link($max_page = 0) {
global $paged;
if ( !is_single() ) {
if ( !$paged )
$paged = 1;
$nextpage = intval($paged) + 1;
if ( !$max_page || $max_page >= $nextpage )
return get_pagenum_link($nextpage);
}
}
/**
* Display or return the next posts page link.
*
* @since 0.71
*
* @param int $max_page Optional. Max pages.
* @param boolean $echo Optional. Echo or return;
*/
function next_posts( $max_page = 0, $echo = true ) {
$output = esc_url( get_next_posts_page_link( $max_page ) );
if ( $echo )
echo $output;
else
return $output;
}
/**
* Return the next posts page link.
*
* @since 2.7.0
*
* @param string $label Content for link text.
* @param int $max_page Optional. Max pages.
* @return string|null
*/
function get_next_posts_link( $label = null, $max_page = 0 ) {
global $paged, $wp_query;
if ( !$max_page )
$max_page = $wp_query->max_num_pages;
if ( !$paged )
$paged = 1;
$nextpage = intval($paged) + 1;
if ( null === $label )
$label = __( 'Next Page »' );
if ( !is_single() && ( $nextpage <= $max_page ) ) {
/**
* Filter the anchor tag attributes for the next posts page link.
*
* @since 2.7.0
*
* @param string $attributes Attributes for the anchor tag.
*/
$attr = apply_filters( 'next_posts_link_attributes', '' );
return '<a href="' . next_posts( $max_page, false ) . "\" $attr>" . preg_replace('/&([^#])(?![a-z]{1,8};)/i', '&$1', $label) . '</a>';
}
}
/**
* Display the next posts page link.
*
* @since 0.71
* @uses get_next_posts_link()
*
* @param string $label Content for link text.
* @param int $max_page Optional. Max pages.
*/
function next_posts_link( $label = null, $max_page = 0 ) {
echo get_next_posts_link( $label, $max_page );
}
/**
* Retrieve previous posts page link.
*
* Will only return string, if not on a single page or post.
*
* Backported to 2.0.10 from 2.1.3.
*
* @since 2.0.10
*
* @return string|null
*/
function get_previous_posts_page_link() {
global $paged;
if ( !is_single() ) {
$nextpage = intval($paged) - 1;
if ( $nextpage < 1 )
$nextpage = 1;
return get_pagenum_link($nextpage);
}
}
/**
* Display or return the previous posts page link.
*
* @since 0.71
*
* @param boolean $echo Optional. Echo or return;
*/
function previous_posts( $echo = true ) {
$output = esc_url( get_previous_posts_page_link() );
if ( $echo )
echo $output;
else
return $output;
}
/**
* Return the previous posts page link.
*
* @since 2.7.0
*
* @param string $label Optional. Previous page link text.
* @return string|null
*/
function get_previous_posts_link( $label = null ) {
global $paged;
if ( null === $label )
$label = __( '« Previous Page' );
if ( !is_single() && $paged > 1 ) {
/**
* Filter the anchor tag attributes for the previous posts page link.
*
* @since 2.7.0
*
* @param string $attributes Attributes for the anchor tag.
*/
$attr = apply_filters( 'previous_posts_link_attributes', '' );
return '<a href="' . previous_posts( false ) . "\" $attr>". preg_replace( '/&([^#])(?![a-z]{1,8};)/i', '&$1', $label ) .'</a>';
}
}
/**
* Display the previous posts page link.
*
* @since 0.71
* @uses get_previous_posts_link()
*
* @param string $label Optional. Previous page link text.
*/
function previous_posts_link( $label = null ) {
echo get_previous_posts_link( $label );
}
/**
* Return post pages link navigation for previous and next pages.
*
* @since 2.8.0
*
* @param string|array $args Optional args.
* @return string The posts link navigation.
*/
function get_posts_nav_link( $args = array() ) {
global $wp_query;
$return = '';
if ( !is_singular() ) {
$defaults = array(
'sep' => ' — ',
'prelabel' => __('« Previous Page'),
'nxtlabel' => __('Next Page »'),
);
$args = wp_parse_args( $args, $defaults );
$max_num_pages = $wp_query->max_num_pages;
$paged = get_query_var('paged');
//only have sep if there's both prev and next results
if ($paged < 2 || $paged >= $max_num_pages) {
$args['sep'] = '';
}
if ( $max_num_pages > 1 ) {
$return = get_previous_posts_link($args['prelabel']);
$return .= preg_replace('/&([^#])(?![a-z]{1,8};)/i', '&$1', $args['sep']);
$return .= get_next_posts_link($args['nxtlabel']);
}
}
return $return;
}
/**
* Display post pages link navigation for previous and next pages.
*
* @since 0.71
*
* @param string $sep Optional. Separator for posts navigation links.
* @param string $prelabel Optional. Label for previous pages.
* @param string $nxtlabel Optional Label for next pages.
*/
function posts_nav_link( $sep = '', $prelabel = '', $nxtlabel = '' ) {
$args = array_filter( compact('sep', 'prelabel', 'nxtlabel') );
echo get_posts_nav_link($args);
}
/**
* Retrieve comments page number link.
*
* @since 2.7.0
*
* @param int $pagenum Optional. Page number.
* @return string
*/
function get_comments_pagenum_link( $pagenum = 1, $max_page = 0 ) {
global $wp_rewrite;
$pagenum = (int) $pagenum;
$result = get_permalink();
if ( 'newest' == get_option('default_comments_page') ) {
if ( $pagenum != $max_page ) {
if ( $wp_rewrite->using_permalinks() )
$result = user_trailingslashit( trailingslashit($result) . 'comment-page-' . $pagenum, 'commentpaged');
else
$result = add_query_arg( 'cpage', $pagenum, $result );
}
} elseif ( $pagenum > 1 ) {
if ( $wp_rewrite->using_permalinks() )
$result = user_trailingslashit( trailingslashit($result) . 'comment-page-' . $pagenum, 'commentpaged');
else
$result = add_query_arg( 'cpage', $pagenum, $result );
}
$result .= '#comments';
/**
* Filter the comments page number link for the current request.
*
* @since 2.7.0
*
* @param string $result The comments page number link.
*/
$result = apply_filters( 'get_comments_pagenum_link', $result );
return $result;
}
/**
* Return the link to next comments page.
*
* @since 2.7.1
*
* @param string $label Optional. Label for link text.
* @param int $max_page Optional. Max page.
* @return string|null
*/
function get_next_comments_link( $label = '', $max_page = 0 ) {
global $wp_query;
if ( !is_singular() || !get_option('page_comments') )
return;
$page = get_query_var('cpage');
$nextpage = intval($page) + 1;
if ( empty($max_page) )
$max_page = $wp_query->max_num_comment_pages;
if ( empty($max_page) )
$max_page = get_comment_pages_count();
if ( $nextpage > $max_page )
return;
if ( empty($label) )
$label = __('Newer Comments »');
/**
* Filter the anchor tag attributes for the next comments page link.
*
* @since 2.7.0
*
* @param string $attributes Attributes for the anchor tag.
*/
return '<a href="' . esc_url( get_comments_pagenum_link( $nextpage, $max_page ) ) . '" ' . apply_filters( 'next_comments_link_attributes', '' ) . '>'. preg_replace('/&([^#])(?![a-z]{1,8};)/i', '&$1', $label) .'</a>';
}
/**
* Display the link to next comments page.
*
* @since 2.7.0
*
* @param string $label Optional. Label for link text.
* @param int $max_page Optional. Max page.
*/
function next_comments_link( $label = '', $max_page = 0 ) {
echo get_next_comments_link( $label, $max_page );
}
/**
* Return the previous comments page link.
*
* @since 2.7.1
*
* @param string $label Optional. Label for comments link text.
* @return string|null
*/
function get_previous_comments_link( $label = '' ) {
if ( !is_singular() || !get_option('page_comments') )
return;
$page = get_query_var('cpage');
if ( intval($page) <= 1 )
return;
$prevpage = intval($page) - 1;
if ( empty($label) )
$label = __('« Older Comments');
/**
* Filter the anchor tag attributes for the previous comments page link.
*
* @since 2.7.0
*
* @param string $attributes Attributes for the anchor tag.
*/
return '<a href="' . esc_url( get_comments_pagenum_link( $prevpage ) ) . '" ' . apply_filters( 'previous_comments_link_attributes', '' ) . '>' . preg_replace('/&([^#])(?![a-z]{1,8};)/i', '&$1', $label) .'</a>';
}
/**
* Display the previous comments page link.
*
* @since 2.7.0
*
* @param string $label Optional. Label for comments link text.
*/
function previous_comments_link( $label = '' ) {
echo get_previous_comments_link( $label );
}
/**
* Create pagination links for the comments on the current post.
*
* @see paginate_links()
* @since 2.7.0
*
* @param string|array $args Optional args. See paginate_links().
* @return string Markup for pagination links.
*/
function paginate_comments_links($args = array()) {
global $wp_rewrite;
if ( !is_singular() || !get_option('page_comments') )
return;
$page = get_query_var('cpage');
if ( !$page )
$page = 1;
$max_page = get_comment_pages_count();
$defaults = array(
'base' => add_query_arg( 'cpage', '%#%' ),
'format' => '',
'total' => $max_page,
'current' => $page,
'echo' => true,
'add_fragment' => '#comments'
);
if ( $wp_rewrite->using_permalinks() )
$defaults['base'] = user_trailingslashit(trailingslashit(get_permalink()) . 'comment-page-%#%', 'commentpaged');
$args = wp_parse_args( $args, $defaults );
$page_links = paginate_links( $args );
if ( $args['echo'] )
echo $page_links;
else
return $page_links;
}
/**
* Retrieve the Press This bookmarklet link.
*
* Use this in 'a' element 'href' attribute.
*
* @since 2.6.0
*
* @return string
*/
function get_shortcut_link() {
// In case of breaking changes, version this. #WP20071
$link = "javascript:
var d=document,
w=window,
e=w.getSelection,
k=d.getSelection,
x=d.selection,
s=(e?e():(k)?k():(x?x.createRange().text:0)),
f='" . admin_url('press-this.php') . "',
l=d.location,
e=encodeURIComponent,
u=f+'?u='+e(l.href)+'&t='+e(d.title)+'&s='+e(s)+'&v=4';
a=function(){if(!w.open(u,'t','toolbar=0,resizable=1,scrollbars=1,status=1,width=720,height=570'))l.href=u;};
if (/Firefox/.test(navigator.userAgent)) setTimeout(a, 0); else a();
void(0)";
$link = str_replace(array("\r", "\n", "\t"), '', $link);
/**
* Filter the Press This bookmarklet link.
*
* @since 2.6.0
*
* @param string $link The Press This bookmarklet link.
*/
return apply_filters( 'shortcut_link', $link );
}
/**
* Retrieve the home url for the current site.
*
* Returns the 'home' option with the appropriate protocol, 'https' if
* is_ssl() and 'http' otherwise. If $scheme is 'http' or 'https', is_ssl() is
* overridden.
*
* @since 3.0.0
*
* @uses get_home_url()
*
* @param string $path (optional) Path relative to the home url.
* @param string $scheme (optional) Scheme to give the home url context. Currently 'http', 'https', or 'relative'.
* @return string Home url link with optional path appended.
*/
function home_url( $path = '', $scheme = null ) {
return get_home_url( null, $path, $scheme );
}
/**
* Retrieve the home url for a given site.
*
* Returns the 'home' option with the appropriate protocol, 'https' if
* is_ssl() and 'http' otherwise. If $scheme is 'http' or 'https', is_ssl() is
* overridden.
*
* @since 3.0.0
*
* @param int $blog_id (optional) Blog ID. Defaults to current blog.
* @param string $path (optional) Path relative to the home url.
* @param string $scheme (optional) Scheme to give the home url context. Currently 'http', 'https', or 'relative'.
* @return string Home url link with optional path appended.
*/
function get_home_url( $blog_id = null, $path = '', $scheme = null ) {
$orig_scheme = $scheme;
if ( empty( $blog_id ) || !is_multisite() ) {
$url = get_option( 'home' );
} else {
switch_to_blog( $blog_id );
$url = get_option( 'home' );
restore_current_blog();
}
if ( ! in_array( $scheme, array( 'http', 'https', 'relative' ) ) ) {
if ( is_ssl() && ! is_admin() && 'wp-login.php' !== $GLOBALS['pagenow'] )
$scheme = 'https';
else
$scheme = parse_url( $url, PHP_URL_SCHEME );
}
$url = set_url_scheme( $url, $scheme );
if ( $path && is_string( $path ) )
$url .= '/' . ltrim( $path, '/' );
/**
* Filter the home URL.
*
* @since 3.0.0
*
* @param string $url The complete home URL including scheme and path.
* @param string $path Path relative to the home URL. Blank string if no path is specified.
* @param string|null $orig_scheme Scheme to give the home URL context. Accepts 'http', 'https', 'relative' or null.
* @param int|null $blog_id Blog ID, or null for the current blog.
*/
return apply_filters( 'home_url', $url, $path, $orig_scheme, $blog_id );
}
/**
* Retrieve the site url for the current site.
*
* Returns the 'site_url' option with the appropriate protocol, 'https' if
* is_ssl() and 'http' otherwise. If $scheme is 'http' or 'https', is_ssl() is
* overridden.
*
* @since 3.0.0
*
* @uses get_site_url()
*
* @param string $path Optional. Path relative to the site url.
* @param string $scheme Optional. Scheme to give the site url context. See set_url_scheme().
* @return string Site url link with optional path appended.
*/
function site_url( $path = '', $scheme = null ) {
return get_site_url( null, $path, $scheme );
}
/**
* Retrieve the site url for a given site.
*
* Returns the 'site_url' option with the appropriate protocol, 'https' if
* is_ssl() and 'http' otherwise. If $scheme is 'http' or 'https', is_ssl() is
* overridden.
*
* @since 3.0.0
*
* @param int $blog_id (optional) Blog ID. Defaults to current blog.
* @param string $path Optional. Path relative to the site url.
* @param string $scheme Optional. Scheme to give the site url context. Currently 'http', 'https', 'login', 'login_post', 'admin', or 'relative'.
* @return string Site url link with optional path appended.
*/
function get_site_url( $blog_id = null, $path = '', $scheme = null ) {
if ( empty( $blog_id ) || !is_multisite() ) {
$url = get_option( 'siteurl' );
} else {
switch_to_blog( $blog_id );
$url = get_option( 'siteurl' );
restore_current_blog();
}
$url = set_url_scheme( $url, $scheme );
if ( $path && is_string( $path ) )
$url .= '/' . ltrim( $path, '/' );
/**
* Filter the site URL.
*
* @since 2.7.0
*
* @param string $url The complete site URL including scheme and path.
* @param string $path Path relative to the site URL. Blank string if no path is specified.
* @param string|null $scheme Scheme to give the site URL context. Accepts 'http', 'https', 'login',
* 'login_post', 'admin', 'relative' or null.
* @param int|null $blog_id Blog ID, or null for the current blog.
*/
return apply_filters( 'site_url', $url, $path, $scheme, $blog_id );
}
/**
* Retrieve the url to the admin area for the current site.
*
* @since 2.6.0
*
* @param string $path Optional path relative to the admin url.
* @param string $scheme The scheme to use. Default is 'admin', which obeys force_ssl_admin() and is_ssl(). 'http' or 'https' can be passed to force those schemes.
* @return string Admin url link with optional path appended.
*/
function admin_url( $path = '', $scheme = 'admin' ) {
return get_admin_url( null, $path, $scheme );
}
/**
* Retrieve the url to the admin area for a given site.
*
* @since 3.0.0
*
* @param int $blog_id (optional) Blog ID. Defaults to current blog.
* @param string $path Optional path relative to the admin url.
* @param string $scheme The scheme to use. Default is 'admin', which obeys force_ssl_admin() and is_ssl(). 'http' or 'https' can be passed to force those schemes.
* @return string Admin url link with optional path appended.
*/
function get_admin_url( $blog_id = null, $path = '', $scheme = 'admin' ) {
$url = get_site_url($blog_id, 'wp-admin/', $scheme);
if ( $path && is_string( $path ) )
$url .= ltrim( $path, '/' );
/**
* Filter the admin area URL.
*
* @since 2.8.0
*
* @param string $url The complete admin area URL including scheme and path.
* @param string $path Path relative to the admin area URL. Blank string if no path is specified.
* @param int|null $blog_id Blog ID, or null for the current blog.
*/
return apply_filters( 'admin_url', $url, $path, $blog_id );
}
/**
* Retrieve the url to the includes directory.
*
* @since 2.6.0
*
* @param string $path Optional. Path relative to the includes url.
* @param string $scheme Optional. Scheme to give the includes url context.
* @return string Includes url link with optional path appended.
*/
function includes_url( $path = '', $scheme = null ) {
$url = site_url( '/' . WPINC . '/', $scheme );
if ( $path && is_string( $path ) )
$url .= ltrim($path, '/');
/**
* Filter the URL to the includes directory.
*
* @since 2.8.0
*
* @param string $url The complete URL to the includes directory including scheme and path.
* @param string $path Path relative to the URL to the wp-includes directory. Blank string
* if no path is specified.
*/
return apply_filters( 'includes_url', $url, $path );
}
/**
* Retrieve the url to the content directory.
*
* @since 2.6.0
*
* @param string $path Optional. Path relative to the content url.
* @return string Content url link with optional path appended.
*/
function content_url($path = '') {
$url = set_url_scheme( WP_CONTENT_URL );
if ( $path && is_string( $path ) )
$url .= '/' . ltrim($path, '/');
/**
* Filter the URL to the content directory.
*
* @since 2.8.0
*
* @param string $url The complete URL to the content directory including scheme and path.
* @param string $path Path relative to the URL to the content directory. Blank string
* if no path is specified.
*/
return apply_filters( 'content_url', $url, $path);
}
/**
* Retrieve the url to the plugins directory or to a specific file within that directory.
* You can hardcode the plugin slug in $path or pass __FILE__ as a second argument to get the correct folder name.
*
* @since 2.6.0
*
* @param string $path Optional. Path relative to the plugins url.
* @param string $plugin Optional. The plugin file that you want to be relative to - i.e. pass in __FILE__
* @return string Plugins url link with optional path appended.
*/
function plugins_url($path = '', $plugin = '') {
$mu_plugin_dir = WPMU_PLUGIN_DIR;
foreach ( array('path', 'plugin', 'mu_plugin_dir') as $var ) {
$$var = str_replace('\\' ,'/', $$var); // sanitize for Win32 installs
$$var = preg_replace('|/+|', '/', $$var);
}
if ( !empty($plugin) && 0 === strpos($plugin, $mu_plugin_dir) )
$url = WPMU_PLUGIN_URL;
else
$url = WP_PLUGIN_URL;
$url = set_url_scheme( $url );
if ( !empty($plugin) && is_string($plugin) ) {
$folder = dirname(plugin_basename($plugin));
if ( '.' != $folder )
$url .= '/' . ltrim($folder, '/');
}
if ( $path && is_string( $path ) )
$url .= '/' . ltrim($path, '/');
/**
* Filter the URL to the plugins directory.
*
* @since 2.8.0
*
* @param string $url The complete URL to the plugins directory including scheme and path.
* @param string $path Path relative to the URL to the plugins directory. Blank string
* if no path is specified.
* @param string $plugin The plugin file path to be relative to. Blank string if no plugin
* is specified.
*/
return apply_filters( 'plugins_url', $url, $path, $plugin );
}
/**
* Retrieve the site url for the current network.
*
* Returns the site url with the appropriate protocol, 'https' if
* is_ssl() and 'http' otherwise. If $scheme is 'http' or 'https', is_ssl() is
* overridden.
*
* @since 3.0.0
*
* @param string $path Optional. Path relative to the site url.
* @param string $scheme Optional. Scheme to give the site url context. See set_url_scheme().
* @return string Site url link with optional path appended.
*/
function network_site_url( $path = '', $scheme = null ) {
if ( ! is_multisite() )
return site_url($path, $scheme);
$current_site = get_current_site();
if ( 'relative' == $scheme )
$url = $current_site->path;
else
$url = set_url_scheme( 'http://' . $current_site->domain . $current_site->path, $scheme );
if ( $path && is_string( $path ) )
$url .= ltrim( $path, '/' );
/**
* Filter the network site URL.
*
* @since 3.0.0
*
* @param string $url The complete network site URL including scheme and path.
* @param string $path Path relative to the network site URL. Blank string if
* no path is specified.
* @param string|null $scheme Scheme to give the URL context. Accepts 'http', 'https',
* 'relative' or null.
*/
return apply_filters( 'network_site_url', $url, $path, $scheme );
}
/**
* Retrieve the home url for the current network.
*
* Returns the home url with the appropriate protocol, 'https' if
* is_ssl() and 'http' otherwise. If $scheme is 'http' or 'https', is_ssl() is
* overridden.
*
* @since 3.0.0
*
* @param string $path (optional) Path relative to the home url.
* @param string $scheme (optional) Scheme to give the home url context. Currently 'http', 'https', or 'relative'.
* @return string Home url link with optional path appended.
*/
function network_home_url( $path = '', $scheme = null ) {
if ( ! is_multisite() )
return home_url($path, $scheme);
$current_site = get_current_site();
$orig_scheme = $scheme;
if ( ! in_array( $scheme, array( 'http', 'https', 'relative' ) ) )
$scheme = is_ssl() && ! is_admin() ? 'https' : 'http';
if ( 'relative' == $scheme )
$url = $current_site->path;
else
$url = set_url_scheme( 'http://' . $current_site->domain . $current_site->path, $scheme );
if ( $path && is_string( $path ) )
$url .= ltrim( $path, '/' );
/**
* Filter the network home URL.
*
* @since 3.0.0
*
* @param string $url The complete network home URL including scheme and path.
* @param string $path Path relative to the network home URL. Blank string
* if no path is specified.
* @param string|null $orig_scheme Scheme to give the URL context. Accepts 'http', 'https',
* 'relative' or null.
*/
return apply_filters( 'network_home_url', $url, $path, $orig_scheme);
}
/**
* Retrieve the url to the admin area for the network.
*
* @since 3.0.0
*
* @param string $path Optional path relative to the admin url.
* @param string $scheme The scheme to use. Default is 'admin', which obeys force_ssl_admin() and is_ssl(). 'http' or 'https' can be passed to force those schemes.
* @return string Admin url link with optional path appended.
*/
function network_admin_url( $path = '', $scheme = 'admin' ) {
if ( ! is_multisite() )
return admin_url( $path, $scheme );
$url = network_site_url('wp-admin/network/', $scheme);
if ( $path && is_string( $path ) )
$url .= ltrim($path, '/');
/**
* Filter the network admin URL.
*
* @since 3.0.0
*
* @param string $url The complete network admin URL including scheme and path.
* @param string $path Path relative to the network admin URL. Blank string if
* no path is specified.
*/
return apply_filters( 'network_admin_url', $url, $path );
}
/**
* Retrieve the url to the admin area for the current user.
*
* @since 3.0.0
*
* @param string $path Optional path relative to the admin url.
* @param string $scheme The scheme to use. Default is 'admin', which obeys force_ssl_admin() and is_ssl(). 'http' or 'https' can be passed to force those schemes.
* @return string Admin url link with optional path appended.
*/
function user_admin_url( $path = '', $scheme = 'admin' ) {
$url = network_site_url('wp-admin/user/', $scheme);
if ( $path && is_string( $path ) )
$url .= ltrim($path, '/');
/**
* Filter the user admin URL for the current user.
*
* @since 3.1.0
*
* @param string $url The complete URL including scheme and path.
* @param string $path Path relative to the URL. Blank string if
* no path is specified.
*/
return apply_filters( 'user_admin_url', $url, $path );
}
/**
* Retrieve the url to the admin area for either the current blog or the network depending on context.
*
* @since 3.1.0
*
* @param string $path Optional path relative to the admin url.
* @param string $scheme The scheme to use. Default is 'admin', which obeys force_ssl_admin() and is_ssl(). 'http' or 'https' can be passed to force those schemes.
* @return string Admin url link with optional path appended.
*/
function self_admin_url($path = '', $scheme = 'admin') {
if ( is_network_admin() )
return network_admin_url($path, $scheme);
elseif ( is_user_admin() )
return user_admin_url($path, $scheme);
else
return admin_url($path, $scheme);
}
/**
* Set the scheme for a URL
*
* @since 3.4.0
*
* @param string $url Absolute url that includes a scheme
* @param string $scheme Optional. Scheme to give $url. Currently 'http', 'https', 'login', 'login_post', 'admin', or 'relative'.
* @return string $url URL with chosen scheme.
*/
function set_url_scheme( $url, $scheme = null ) {
$orig_scheme = $scheme;
if ( ! in_array( $scheme, array( 'http', 'https', 'relative' ) ) ) {
if ( ( 'login_post' == $scheme || 'rpc' == $scheme ) && ( force_ssl_login() || force_ssl_admin() ) )
$scheme = 'https';
elseif ( ( 'login' == $scheme ) && force_ssl_admin() )
$scheme = 'https';
elseif ( ( 'admin' == $scheme ) && force_ssl_admin() )
$scheme = 'https';
else
$scheme = ( is_ssl() ? 'https' : 'http' );
}
$url = trim( $url );
if ( substr( $url, 0, 2 ) === '//' )
$url = 'http:' . $url;
if ( 'relative' == $scheme ) {
$url = ltrim( preg_replace( '#^\w+://[^/]*#', '', $url ) );
if ( $url !== '' && $url[0] === '/' )
$url = '/' . ltrim($url , "/ \t\n\r\0\x0B" );
} else {
$url = preg_replace( '#^\w+://#', $scheme . '://', $url );
}
/**
* Filter the resulting URL after setting the scheme.
*
* @since 3.4.0
*
* @param string $url The complete URL including scheme and path.
* @param string $scheme Scheme applied to the URL. One of 'http', 'https', or 'relative'.
* @param string $orig_scheme Scheme requested for the URL. One of 'http', 'https', 'login',
* 'login_post', 'admin', 'rpc', or 'relative'.
*/
return apply_filters( 'set_url_scheme', $url, $scheme, $orig_scheme );
}
/**
* Get the URL to the user's dashboard.
*
* If a user does not belong to any site, the global user dashboard is used. If the user belongs to the current site,
* the dashboard for the current site is returned. If the user cannot edit the current site, the dashboard to the user's
* primary blog is returned.
*
* @since 3.1.0
*
* @param int $user_id Optional. User ID. Defaults to current user.
* @param string $path Optional path relative to the dashboard. Use only paths known to both blog and user admins.
* @param string $scheme The scheme to use. Default is 'admin', which obeys force_ssl_admin() and is_ssl(). 'http' or 'https' can be passed to force those schemes.
* @return string Dashboard url link with optional path appended.
*/
function get_dashboard_url( $user_id = 0, $path = '', $scheme = 'admin' ) {
$user_id = $user_id ? (int) $user_id : get_current_user_id();
$blogs = get_blogs_of_user( $user_id );
if ( ! is_super_admin() && empty($blogs) ) {
$url = user_admin_url( $path, $scheme );
} elseif ( ! is_multisite() ) {
$url = admin_url( $path, $scheme );
} else {
$current_blog = get_current_blog_id();
if ( $current_blog && ( is_super_admin( $user_id ) || in_array( $current_blog, array_keys( $blogs ) ) ) ) {
$url = admin_url( $path, $scheme );
} else {
$active = get_active_blog_for_user( $user_id );
if ( $active )
$url = get_admin_url( $active->blog_id, $path, $scheme );
else
$url = user_admin_url( $path, $scheme );
}
}
/**
* Filter the dashboard URL for a user.
*
* @since 3.1.0
*
* @param string $url The complete URL including scheme and path.
* @param int $user_id The user ID.
* @param string $path Path relative to the URL. Blank string if no path is specified.
* @param string $scheme Scheme to give the URL context. Accepts 'http', 'https', 'login',
* 'login_post', 'admin', 'relative' or null.
*/
return apply_filters( 'user_dashboard_url', $url, $user_id, $path, $scheme);
}
/**
* Get the URL to the user's profile editor.
*
* @since 3.1.0
*
* @param int $user_id Optional. User ID. Defaults to current user.
* @param string $scheme The scheme to use. Default is 'admin', which obeys force_ssl_admin() and is_ssl().
* 'http' or 'https' can be passed to force those schemes.
* @return string Dashboard url link with optional path appended.
*/
function get_edit_profile_url( $user_id = 0, $scheme = 'admin' ) {
$user_id = $user_id ? (int) $user_id : get_current_user_id();
if ( is_user_admin() )
$url = user_admin_url( 'profile.php', $scheme );
elseif ( is_network_admin() )
$url = network_admin_url( 'profile.php', $scheme );
else
$url = get_dashboard_url( $user_id, 'profile.php', $scheme );
/**
* Filter the URL for a user's profile editor.
*
* @since 3.1.0
*
* @param string $url The complete URL including scheme and path.
* @param int $user_id The user ID.
* @param string $scheme Scheme to give the URL context. Accepts 'http', 'https', 'login',
* 'login_post', 'admin', 'relative' or null.
*/
return apply_filters( 'edit_profile_url', $url, $user_id, $scheme);
}
/**
* Output rel=canonical for singular queries.
*
* @since 2.9.0
*/
function rel_canonical() {
if ( !is_singular() )
return;
global $wp_the_query;
if ( !$id = $wp_the_query->get_queried_object_id() )
return;
$link = get_permalink( $id );
if ( $page = get_query_var('cpage') )
$link = get_comments_pagenum_link( $page );
echo "<link rel='canonical' href='$link' />\n";
}
/**
* Return a shortlink for a post, page, attachment, or blog.
*
* This function exists to provide a shortlink tag that all themes and plugins can target. A plugin must hook in to
* provide the actual shortlinks. Default shortlink support is limited to providing ?p= style links for posts.
* Plugins can short-circuit this function via the pre_get_shortlink filter or filter the output
* via the get_shortlink filter.
*
* @since 3.0.0.
*
* @param int $id A post or blog id. Default is 0, which means the current post or blog.
* @param string $context Whether the id is a 'blog' id, 'post' id, or 'media' id. If 'post', the post_type of the post is consulted. If 'query', the current query is consulted to determine the id and context. Default is 'post'.
* @param bool $allow_slugs Whether to allow post slugs in the shortlink. It is up to the plugin how and whether to honor this.
* @return string A shortlink or an empty string if no shortlink exists for the requested resource or if shortlinks are not enabled.
*/
function wp_get_shortlink($id = 0, $context = 'post', $allow_slugs = true) {
/**
* Filter whether to preempt generating a shortlink for the given post.
*
* Passing a truthy value to the filter will effectively short-circuit the
* shortlink-generation process, returning that value instead.
*
* @since 3.0.0
*
* @param bool|string $return Short-circuit return value. Either false or a URL string.
* @param int $id Post ID, or 0 for the current post.
* @param string $context The context for the link. One of 'post' or 'query',
* @param bool $allow_slugs Whether to allow post slugs in the shortlink.
*/
$shortlink = apply_filters( 'pre_get_shortlink', false, $id, $context, $allow_slugs );
if ( false !== $shortlink )
return $shortlink;
global $wp_query;
$post_id = 0;
if ( 'query' == $context && is_singular() ) {
$post_id = $wp_query->get_queried_object_id();
$post = get_post( $post_id );
} elseif ( 'post' == $context ) {
$post = get_post( $id );
if ( ! empty( $post->ID ) )
$post_id = $post->ID;
}
$shortlink = '';
// Return p= link for all public post types.
if ( ! empty( $post_id ) ) {
$post_type = get_post_type_object( $post->post_type );
if ( 'page' === $post->post_type && $post->ID == get_option( 'page_on_front' ) && 'page' == get_option( 'show_on_front' ) ) {
$shortlink = home_url( '/' );
} elseif ( $post_type->public ) {
$shortlink = home_url( '?p=' . $post_id );
}
}
/**
* Filter the shortlink for a post.
*
* @since 3.0.0
*
* @param string $shortlink Shortlink URL.
* @param int $id Post ID, or 0 for the current post.
* @param string $context The context for the link. One of 'post' or 'query',
* @param bool $allow_slugs Whether to allow post slugs in the shortlink. Not used by default.
*/
return apply_filters( 'get_shortlink', $shortlink, $id, $context, $allow_slugs );
}
/**
* Inject rel=shortlink into head if a shortlink is defined for the current page.
*
* Attached to the wp_head action.
*
* @since 3.0.0
*
* @uses wp_get_shortlink()
*/
function wp_shortlink_wp_head() {
$shortlink = wp_get_shortlink( 0, 'query' );
if ( empty( $shortlink ) )
return;
echo "<link rel='shortlink' href='" . esc_url( $shortlink ) . "' />\n";
}
/**
* Send a Link: rel=shortlink header if a shortlink is defined for the current page.
*
* Attached to the wp action.
*
* @since 3.0.0
*
* @uses wp_get_shortlink()
*/
function wp_shortlink_header() {
if ( headers_sent() )
return;
$shortlink = wp_get_shortlink(0, 'query');
if ( empty($shortlink) )
return;
header('Link: <' . $shortlink . '>; rel=shortlink', false);
}
/**
* Display the Short Link for a Post
*
* Must be called from inside "The Loop"
*
* Call like the_shortlink(__('Shortlinkage FTW'))
*
* @since 3.0.0
*
* @param string $text Optional The link text or HTML to be displayed. Defaults to 'This is the short link.'
* @param string $title Optional The tooltip for the link. Must be sanitized. Defaults to the sanitized post title.
* @param string $before Optional HTML to display before the link.
* @param string $after Optional HTML to display after the link.
*/
function the_shortlink( $text = '', $title = '', $before = '', $after = '' ) {
$post = get_post();
if ( empty( $text ) )
$text = __('This is the short link.');
if ( empty( $title ) )
$title = the_title_attribute( array( 'echo' => false ) );
$shortlink = wp_get_shortlink( $post->ID );
if ( !empty( $shortlink ) ) {
$link = '<a rel="shortlink" href="' . esc_url( $shortlink ) . '" title="' . $title . '">' . $text . '</a>';
/**
* Filter the shortlink anchor tag for a post.
*
* @since 3.0.0
*
* @param string $link Shortlink anchor tag.
* @param string $shortlink Shortlink URL.
* @param string $text Shortlink's text.
* @param string $title Shortlink's title attribute.
*/
$link = apply_filters( 'the_shortlink', $link, $shortlink, $text, $title );
echo $before, $link, $after;
}
}
| PHP |
<?php
/////////////////////////////////////////////////////////////////
/// getID3() by James Heinrich <info@getid3.org> //
// available at http://getid3.sourceforge.net //
// or http://www.getid3.org //
/////////////////////////////////////////////////////////////////
// See readme.txt for more details //
/////////////////////////////////////////////////////////////////
// //
// module.audio.ac3.php //
// module for analyzing AC-3 (aka Dolby Digital) audio files //
// dependencies: NONE //
// ///
/////////////////////////////////////////////////////////////////
class getid3_ac3 extends getid3_handler
{
private $AC3header = array();
private $BSIoffset = 0;
const syncword = "\x0B\x77";
public function Analyze() {
$info = &$this->getid3->info;
///AH
$info['ac3']['raw']['bsi'] = array();
$thisfile_ac3 = &$info['ac3'];
$thisfile_ac3_raw = &$thisfile_ac3['raw'];
$thisfile_ac3_raw_bsi = &$thisfile_ac3_raw['bsi'];
// http://www.atsc.org/standards/a_52a.pdf
$info['fileformat'] = 'ac3';
// An AC-3 serial coded audio bit stream is made up of a sequence of synchronization frames
// Each synchronization frame contains 6 coded audio blocks (AB), each of which represent 256
// new audio samples per channel. A synchronization information (SI) header at the beginning
// of each frame contains information needed to acquire and maintain synchronization. A
// bit stream information (BSI) header follows SI, and contains parameters describing the coded
// audio service. The coded audio blocks may be followed by an auxiliary data (Aux) field. At the
// end of each frame is an error check field that includes a CRC word for error detection. An
// additional CRC word is located in the SI header, the use of which, by a decoder, is optional.
//
// syncinfo() | bsi() | AB0 | AB1 | AB2 | AB3 | AB4 | AB5 | Aux | CRC
// syncinfo() {
// syncword 16
// crc1 16
// fscod 2
// frmsizecod 6
// } /* end of syncinfo */
$this->fseek($info['avdataoffset']);
$this->AC3header['syncinfo'] = $this->fread(5);
if (strpos($this->AC3header['syncinfo'], self::syncword) === 0) {
$thisfile_ac3_raw['synchinfo']['synchword'] = self::syncword;
$offset = 2;
} else {
if (!$this->isDependencyFor('matroska')) {
unset($info['fileformat'], $info['ac3']);
return $this->error('Expecting "'.getid3_lib::PrintHexBytes(self::syncword).'" at offset '.$info['avdataoffset'].', found "'.getid3_lib::PrintHexBytes(substr($this->AC3header['syncinfo'], 0, 2)).'"');
}
$offset = 0;
$this->fseek(-2, SEEK_CUR);
}
$info['audio']['dataformat'] = 'ac3';
$info['audio']['bitrate_mode'] = 'cbr';
$info['audio']['lossless'] = false;
$thisfile_ac3_raw['synchinfo']['crc1'] = getid3_lib::LittleEndian2Int(substr($this->AC3header['syncinfo'], $offset, 2));
$ac3_synchinfo_fscod_frmsizecod = getid3_lib::LittleEndian2Int(substr($this->AC3header['syncinfo'], ($offset + 2), 1));
$thisfile_ac3_raw['synchinfo']['fscod'] = ($ac3_synchinfo_fscod_frmsizecod & 0xC0) >> 6;
$thisfile_ac3_raw['synchinfo']['frmsizecod'] = ($ac3_synchinfo_fscod_frmsizecod & 0x3F);
$thisfile_ac3['sample_rate'] = self::sampleRateCodeLookup($thisfile_ac3_raw['synchinfo']['fscod']);
if ($thisfile_ac3_raw['synchinfo']['fscod'] <= 3) {
$info['audio']['sample_rate'] = $thisfile_ac3['sample_rate'];
}
$thisfile_ac3['frame_length'] = self::frameSizeLookup($thisfile_ac3_raw['synchinfo']['frmsizecod'], $thisfile_ac3_raw['synchinfo']['fscod']);
$thisfile_ac3['bitrate'] = self::bitrateLookup($thisfile_ac3_raw['synchinfo']['frmsizecod']);
$info['audio']['bitrate'] = $thisfile_ac3['bitrate'];
$this->AC3header['bsi'] = getid3_lib::BigEndian2Bin($this->fread(15));
$ac3_bsi_offset = 0;
$thisfile_ac3_raw_bsi['bsid'] = $this->readHeaderBSI(5);
if ($thisfile_ac3_raw_bsi['bsid'] > 8) {
// Decoders which can decode version 8 will thus be able to decode version numbers less than 8.
// If this standard is extended by the addition of additional elements or features, a value of bsid greater than 8 will be used.
// Decoders built to this version of the standard will not be able to decode versions with bsid greater than 8.
$this->error('Bit stream identification is version '.$thisfile_ac3_raw_bsi['bsid'].', but getID3() only understands up to version 8');
unset($info['ac3']);
return false;
}
$thisfile_ac3_raw_bsi['bsmod'] = $this->readHeaderBSI(3);
$thisfile_ac3_raw_bsi['acmod'] = $this->readHeaderBSI(3);
$thisfile_ac3['service_type'] = self::serviceTypeLookup($thisfile_ac3_raw_bsi['bsmod'], $thisfile_ac3_raw_bsi['acmod']);
$ac3_coding_mode = self::audioCodingModeLookup($thisfile_ac3_raw_bsi['acmod']);
foreach($ac3_coding_mode as $key => $value) {
$thisfile_ac3[$key] = $value;
}
switch ($thisfile_ac3_raw_bsi['acmod']) {
case 0:
case 1:
$info['audio']['channelmode'] = 'mono';
break;
case 3:
case 4:
$info['audio']['channelmode'] = 'stereo';
break;
default:
$info['audio']['channelmode'] = 'surround';
break;
}
$info['audio']['channels'] = $thisfile_ac3['num_channels'];
if ($thisfile_ac3_raw_bsi['acmod'] & 0x01) {
// If the lsb of acmod is a 1, center channel is in use and cmixlev follows in the bit stream.
$thisfile_ac3_raw_bsi['cmixlev'] = $this->readHeaderBSI(2);
$thisfile_ac3['center_mix_level'] = self::centerMixLevelLookup($thisfile_ac3_raw_bsi['cmixlev']);
}
if ($thisfile_ac3_raw_bsi['acmod'] & 0x04) {
// If the msb of acmod is a 1, surround channels are in use and surmixlev follows in the bit stream.
$thisfile_ac3_raw_bsi['surmixlev'] = $this->readHeaderBSI(2);
$thisfile_ac3['surround_mix_level'] = self::surroundMixLevelLookup($thisfile_ac3_raw_bsi['surmixlev']);
}
if ($thisfile_ac3_raw_bsi['acmod'] == 0x02) {
// When operating in the two channel mode, this 2-bit code indicates whether or not the program has been encoded in Dolby Surround.
$thisfile_ac3_raw_bsi['dsurmod'] = $this->readHeaderBSI(2);
$thisfile_ac3['dolby_surround_mode'] = self::dolbySurroundModeLookup($thisfile_ac3_raw_bsi['dsurmod']);
}
$thisfile_ac3_raw_bsi['lfeon'] = (bool) $this->readHeaderBSI(1);
$thisfile_ac3['lfe_enabled'] = $thisfile_ac3_raw_bsi['lfeon'];
if ($thisfile_ac3_raw_bsi['lfeon']) {
//$info['audio']['channels']++;
$info['audio']['channels'] .= '.1';
}
$thisfile_ac3['channels_enabled'] = self::channelsEnabledLookup($thisfile_ac3_raw_bsi['acmod'], $thisfile_ac3_raw_bsi['lfeon']);
// This indicates how far the average dialogue level is below digital 100 percent. Valid values are 1-31.
// The value of 0 is reserved. The values of 1 to 31 are interpreted as -1 dB to -31 dB with respect to digital 100 percent.
$thisfile_ac3_raw_bsi['dialnorm'] = $this->readHeaderBSI(5);
$thisfile_ac3['dialogue_normalization'] = '-'.$thisfile_ac3_raw_bsi['dialnorm'].'dB';
$thisfile_ac3_raw_bsi['compre_flag'] = (bool) $this->readHeaderBSI(1);
if ($thisfile_ac3_raw_bsi['compre_flag']) {
$thisfile_ac3_raw_bsi['compr'] = $this->readHeaderBSI(8);
$thisfile_ac3['heavy_compression'] = self::heavyCompression($thisfile_ac3_raw_bsi['compr']);
}
$thisfile_ac3_raw_bsi['langcode_flag'] = (bool) $this->readHeaderBSI(1);
if ($thisfile_ac3_raw_bsi['langcode_flag']) {
$thisfile_ac3_raw_bsi['langcod'] = $this->readHeaderBSI(8);
}
$thisfile_ac3_raw_bsi['audprodie'] = (bool) $this->readHeaderBSI(1);
if ($thisfile_ac3_raw_bsi['audprodie']) {
$thisfile_ac3_raw_bsi['mixlevel'] = $this->readHeaderBSI(5);
$thisfile_ac3_raw_bsi['roomtyp'] = $this->readHeaderBSI(2);
$thisfile_ac3['mixing_level'] = (80 + $thisfile_ac3_raw_bsi['mixlevel']).'dB';
$thisfile_ac3['room_type'] = self::roomTypeLookup($thisfile_ac3_raw_bsi['roomtyp']);
}
if ($thisfile_ac3_raw_bsi['acmod'] == 0x00) {
// If acmod is 0, then two completely independent program channels (dual mono)
// are encoded into the bit stream, and are referenced as Ch1, Ch2. In this case,
// a number of additional items are present in BSI or audblk to fully describe Ch2.
// This indicates how far the average dialogue level is below digital 100 percent. Valid values are 1-31.
// The value of 0 is reserved. The values of 1 to 31 are interpreted as -1 dB to -31 dB with respect to digital 100 percent.
$thisfile_ac3_raw_bsi['dialnorm2'] = $this->readHeaderBSI(5);
$thisfile_ac3['dialogue_normalization2'] = '-'.$thisfile_ac3_raw_bsi['dialnorm2'].'dB';
$thisfile_ac3_raw_bsi['compre_flag2'] = (bool) $this->readHeaderBSI(1);
if ($thisfile_ac3_raw_bsi['compre_flag2']) {
$thisfile_ac3_raw_bsi['compr2'] = $this->readHeaderBSI(8);
$thisfile_ac3['heavy_compression2'] = self::heavyCompression($thisfile_ac3_raw_bsi['compr2']);
}
$thisfile_ac3_raw_bsi['langcode_flag2'] = (bool) $this->readHeaderBSI(1);
if ($thisfile_ac3_raw_bsi['langcode_flag2']) {
$thisfile_ac3_raw_bsi['langcod2'] = $this->readHeaderBSI(8);
}
$thisfile_ac3_raw_bsi['audprodie2'] = (bool) $this->readHeaderBSI(1);
if ($thisfile_ac3_raw_bsi['audprodie2']) {
$thisfile_ac3_raw_bsi['mixlevel2'] = $this->readHeaderBSI(5);
$thisfile_ac3_raw_bsi['roomtyp2'] = $this->readHeaderBSI(2);
$thisfile_ac3['mixing_level2'] = (80 + $thisfile_ac3_raw_bsi['mixlevel2']).'dB';
$thisfile_ac3['room_type2'] = self::roomTypeLookup($thisfile_ac3_raw_bsi['roomtyp2']);
}
}
$thisfile_ac3_raw_bsi['copyright'] = (bool) $this->readHeaderBSI(1);
$thisfile_ac3_raw_bsi['original'] = (bool) $this->readHeaderBSI(1);
$thisfile_ac3_raw_bsi['timecode1_flag'] = (bool) $this->readHeaderBSI(1);
if ($thisfile_ac3_raw_bsi['timecode1_flag']) {
$thisfile_ac3_raw_bsi['timecode1'] = $this->readHeaderBSI(14);
}
$thisfile_ac3_raw_bsi['timecode2_flag'] = (bool) $this->readHeaderBSI(1);
if ($thisfile_ac3_raw_bsi['timecode2_flag']) {
$thisfile_ac3_raw_bsi['timecode2'] = $this->readHeaderBSI(14);
}
$thisfile_ac3_raw_bsi['addbsi_flag'] = (bool) $this->readHeaderBSI(1);
if ($thisfile_ac3_raw_bsi['addbsi_flag']) {
$thisfile_ac3_raw_bsi['addbsi_length'] = $this->readHeaderBSI(6);
$this->AC3header['bsi'] .= getid3_lib::BigEndian2Bin($this->fread($thisfile_ac3_raw_bsi['addbsi_length']));
$thisfile_ac3_raw_bsi['addbsi_data'] = substr($this->AC3header['bsi'], $this->BSIoffset, $thisfile_ac3_raw_bsi['addbsi_length'] * 8);
$this->BSIoffset += $thisfile_ac3_raw_bsi['addbsi_length'] * 8;
}
return true;
}
private function readHeaderBSI($length) {
$data = substr($this->AC3header['bsi'], $this->BSIoffset, $length);
$this->BSIoffset += $length;
return bindec($data);
}
public static function sampleRateCodeLookup($fscod) {
static $sampleRateCodeLookup = array(
0 => 48000,
1 => 44100,
2 => 32000,
3 => 'reserved' // If the reserved code is indicated, the decoder should not attempt to decode audio and should mute.
);
return (isset($sampleRateCodeLookup[$fscod]) ? $sampleRateCodeLookup[$fscod] : false);
}
public static function serviceTypeLookup($bsmod, $acmod) {
static $serviceTypeLookup = array();
if (empty($serviceTypeLookup)) {
for ($i = 0; $i <= 7; $i++) {
$serviceTypeLookup[0][$i] = 'main audio service: complete main (CM)';
$serviceTypeLookup[1][$i] = 'main audio service: music and effects (ME)';
$serviceTypeLookup[2][$i] = 'associated service: visually impaired (VI)';
$serviceTypeLookup[3][$i] = 'associated service: hearing impaired (HI)';
$serviceTypeLookup[4][$i] = 'associated service: dialogue (D)';
$serviceTypeLookup[5][$i] = 'associated service: commentary (C)';
$serviceTypeLookup[6][$i] = 'associated service: emergency (E)';
}
$serviceTypeLookup[7][1] = 'associated service: voice over (VO)';
for ($i = 2; $i <= 7; $i++) {
$serviceTypeLookup[7][$i] = 'main audio service: karaoke';
}
}
return (isset($serviceTypeLookup[$bsmod][$acmod]) ? $serviceTypeLookup[$bsmod][$acmod] : false);
}
public static function audioCodingModeLookup($acmod) {
// array(channel configuration, # channels (not incl LFE), channel order)
static $audioCodingModeLookup = array (
0 => array('channel_config'=>'1+1', 'num_channels'=>2, 'channel_order'=>'Ch1,Ch2'),
1 => array('channel_config'=>'1/0', 'num_channels'=>1, 'channel_order'=>'C'),
2 => array('channel_config'=>'2/0', 'num_channels'=>2, 'channel_order'=>'L,R'),
3 => array('channel_config'=>'3/0', 'num_channels'=>3, 'channel_order'=>'L,C,R'),
4 => array('channel_config'=>'2/1', 'num_channels'=>3, 'channel_order'=>'L,R,S'),
5 => array('channel_config'=>'3/1', 'num_channels'=>4, 'channel_order'=>'L,C,R,S'),
6 => array('channel_config'=>'2/2', 'num_channels'=>4, 'channel_order'=>'L,R,SL,SR'),
7 => array('channel_config'=>'3/2', 'num_channels'=>5, 'channel_order'=>'L,C,R,SL,SR'),
);
return (isset($audioCodingModeLookup[$acmod]) ? $audioCodingModeLookup[$acmod] : false);
}
public static function centerMixLevelLookup($cmixlev) {
static $centerMixLevelLookup;
if (empty($centerMixLevelLookup)) {
$centerMixLevelLookup = array(
0 => pow(2, -3.0 / 6), // 0.707 (-3.0 dB)
1 => pow(2, -4.5 / 6), // 0.595 (-4.5 dB)
2 => pow(2, -6.0 / 6), // 0.500 (-6.0 dB)
3 => 'reserved'
);
}
return (isset($centerMixLevelLookup[$cmixlev]) ? $centerMixLevelLookup[$cmixlev] : false);
}
public static function surroundMixLevelLookup($surmixlev) {
static $surroundMixLevelLookup;
if (empty($surroundMixLevelLookup)) {
$surroundMixLevelLookup = array(
0 => pow(2, -3.0 / 6),
1 => pow(2, -6.0 / 6),
2 => 0,
3 => 'reserved'
);
}
return (isset($surroundMixLevelLookup[$surmixlev]) ? $surroundMixLevelLookup[$surmixlev] : false);
}
public static function dolbySurroundModeLookup($dsurmod) {
static $dolbySurroundModeLookup = array(
0 => 'not indicated',
1 => 'Not Dolby Surround encoded',
2 => 'Dolby Surround encoded',
3 => 'reserved'
);
return (isset($dolbySurroundModeLookup[$dsurmod]) ? $dolbySurroundModeLookup[$dsurmod] : false);
}
public static function channelsEnabledLookup($acmod, $lfeon) {
$lookup = array(
'ch1'=>(bool) ($acmod == 0),
'ch2'=>(bool) ($acmod == 0),
'left'=>(bool) ($acmod > 1),
'right'=>(bool) ($acmod > 1),
'center'=>(bool) ($acmod & 0x01),
'surround_mono'=>false,
'surround_left'=>false,
'surround_right'=>false,
'lfe'=>$lfeon);
switch ($acmod) {
case 4:
case 5:
$lookup['surround_mono'] = true;
break;
case 6:
case 7:
$lookup['surround_left'] = true;
$lookup['surround_right'] = true;
break;
}
return $lookup;
}
public static function heavyCompression($compre) {
// The first four bits indicate gain changes in 6.02dB increments which can be
// implemented with an arithmetic shift operation. The following four bits
// indicate linear gain changes, and require a 5-bit multiply.
// We will represent the two 4-bit fields of compr as follows:
// X0 X1 X2 X3 . Y4 Y5 Y6 Y7
// The meaning of the X values is most simply described by considering X to represent a 4-bit
// signed integer with values from -8 to +7. The gain indicated by X is then (X + 1) * 6.02 dB. The
// following table shows this in detail.
// Meaning of 4 msb of compr
// 7 +48.16 dB
// 6 +42.14 dB
// 5 +36.12 dB
// 4 +30.10 dB
// 3 +24.08 dB
// 2 +18.06 dB
// 1 +12.04 dB
// 0 +6.02 dB
// -1 0 dB
// -2 -6.02 dB
// -3 -12.04 dB
// -4 -18.06 dB
// -5 -24.08 dB
// -6 -30.10 dB
// -7 -36.12 dB
// -8 -42.14 dB
$fourbit = str_pad(decbin(($compre & 0xF0) >> 4), 4, '0', STR_PAD_LEFT);
if ($fourbit{0} == '1') {
$log_gain = -8 + bindec(substr($fourbit, 1));
} else {
$log_gain = bindec(substr($fourbit, 1));
}
$log_gain = ($log_gain + 1) * getid3_lib::RGADamplitude2dB(2);
// The value of Y is a linear representation of a gain change of up to -6 dB. Y is considered to
// be an unsigned fractional integer, with a leading value of 1, or: 0.1 Y4 Y5 Y6 Y7 (base 2). Y can
// represent values between 0.111112 (or 31/32) and 0.100002 (or 1/2). Thus, Y can represent gain
// changes from -0.28 dB to -6.02 dB.
$lin_gain = (16 + ($compre & 0x0F)) / 32;
// The combination of X and Y values allows compr to indicate gain changes from
// 48.16 - 0.28 = +47.89 dB, to
// -42.14 - 6.02 = -48.16 dB.
return $log_gain - $lin_gain;
}
public static function roomTypeLookup($roomtyp) {
static $roomTypeLookup = array(
0 => 'not indicated',
1 => 'large room, X curve monitor',
2 => 'small room, flat monitor',
3 => 'reserved'
);
return (isset($roomTypeLookup[$roomtyp]) ? $roomTypeLookup[$roomtyp] : false);
}
public static function frameSizeLookup($frmsizecod, $fscod) {
$padding = (bool) ($frmsizecod % 2);
$framesizeid = floor($frmsizecod / 2);
static $frameSizeLookup = array();
if (empty($frameSizeLookup)) {
$frameSizeLookup = array (
0 => array(128, 138, 192),
1 => array(40, 160, 174, 240),
2 => array(48, 192, 208, 288),
3 => array(56, 224, 242, 336),
4 => array(64, 256, 278, 384),
5 => array(80, 320, 348, 480),
6 => array(96, 384, 416, 576),
7 => array(112, 448, 486, 672),
8 => array(128, 512, 556, 768),
9 => array(160, 640, 696, 960),
10 => array(192, 768, 834, 1152),
11 => array(224, 896, 974, 1344),
12 => array(256, 1024, 1114, 1536),
13 => array(320, 1280, 1392, 1920),
14 => array(384, 1536, 1670, 2304),
15 => array(448, 1792, 1950, 2688),
16 => array(512, 2048, 2228, 3072),
17 => array(576, 2304, 2506, 3456),
18 => array(640, 2560, 2786, 3840)
);
}
if (($fscod == 1) && $padding) {
// frame lengths are padded by 1 word (16 bits) at 44100
$frameSizeLookup[$frmsizecod] += 2;
}
return (isset($frameSizeLookup[$framesizeid][$fscod]) ? $frameSizeLookup[$framesizeid][$fscod] : false);
}
public static function bitrateLookup($frmsizecod) {
$framesizeid = floor($frmsizecod / 2);
static $bitrateLookup = array(
0 => 32000,
1 => 40000,
2 => 48000,
3 => 56000,
4 => 64000,
5 => 80000,
6 => 96000,
7 => 112000,
8 => 128000,
9 => 160000,
10 => 192000,
11 => 224000,
12 => 256000,
13 => 320000,
14 => 384000,
15 => 448000,
16 => 512000,
17 => 576000,
18 => 640000
);
return (isset($bitrateLookup[$framesizeid]) ? $bitrateLookup[$framesizeid] : false);
}
}
| PHP |
<?php
/////////////////////////////////////////////////////////////////
/// getID3() by James Heinrich <info@getid3.org> //
// available at http://getid3.sourceforge.net //
// or http://www.getid3.org //
/////////////////////////////////////////////////////////////////
// See readme.txt for more details //
/////////////////////////////////////////////////////////////////
// //
// module.tag.id3v1.php //
// module for analyzing ID3v1 tags //
// dependencies: NONE //
// ///
/////////////////////////////////////////////////////////////////
class getid3_id3v1 extends getid3_handler
{
public function Analyze() {
$info = &$this->getid3->info;
if (!getid3_lib::intValueSupported($info['filesize'])) {
$info['warning'][] = 'Unable to check for ID3v1 because file is larger than '.round(PHP_INT_MAX / 1073741824).'GB';
return false;
}
fseek($this->getid3->fp, -256, SEEK_END);
$preid3v1 = fread($this->getid3->fp, 128);
$id3v1tag = fread($this->getid3->fp, 128);
if (substr($id3v1tag, 0, 3) == 'TAG') {
$info['avdataend'] = $info['filesize'] - 128;
$ParsedID3v1['title'] = $this->cutfield(substr($id3v1tag, 3, 30));
$ParsedID3v1['artist'] = $this->cutfield(substr($id3v1tag, 33, 30));
$ParsedID3v1['album'] = $this->cutfield(substr($id3v1tag, 63, 30));
$ParsedID3v1['year'] = $this->cutfield(substr($id3v1tag, 93, 4));
$ParsedID3v1['comment'] = substr($id3v1tag, 97, 30); // can't remove nulls yet, track detection depends on them
$ParsedID3v1['genreid'] = ord(substr($id3v1tag, 127, 1));
// If second-last byte of comment field is null and last byte of comment field is non-null
// then this is ID3v1.1 and the comment field is 28 bytes long and the 30th byte is the track number
if (($id3v1tag{125} === "\x00") && ($id3v1tag{126} !== "\x00")) {
$ParsedID3v1['track'] = ord(substr($ParsedID3v1['comment'], 29, 1));
$ParsedID3v1['comment'] = substr($ParsedID3v1['comment'], 0, 28);
}
$ParsedID3v1['comment'] = $this->cutfield($ParsedID3v1['comment']);
$ParsedID3v1['genre'] = $this->LookupGenreName($ParsedID3v1['genreid']);
if (!empty($ParsedID3v1['genre'])) {
unset($ParsedID3v1['genreid']);
}
if (isset($ParsedID3v1['genre']) && (empty($ParsedID3v1['genre']) || ($ParsedID3v1['genre'] == 'Unknown'))) {
unset($ParsedID3v1['genre']);
}
foreach ($ParsedID3v1 as $key => $value) {
$ParsedID3v1['comments'][$key][0] = $value;
}
// ID3v1 data is supposed to be padded with NULL characters, but some taggers pad with spaces
$GoodFormatID3v1tag = $this->GenerateID3v1Tag(
$ParsedID3v1['title'],
$ParsedID3v1['artist'],
$ParsedID3v1['album'],
$ParsedID3v1['year'],
(isset($ParsedID3v1['genre']) ? $this->LookupGenreID($ParsedID3v1['genre']) : false),
$ParsedID3v1['comment'],
(!empty($ParsedID3v1['track']) ? $ParsedID3v1['track'] : ''));
$ParsedID3v1['padding_valid'] = true;
if ($id3v1tag !== $GoodFormatID3v1tag) {
$ParsedID3v1['padding_valid'] = false;
$info['warning'][] = 'Some ID3v1 fields do not use NULL characters for padding';
}
$ParsedID3v1['tag_offset_end'] = $info['filesize'];
$ParsedID3v1['tag_offset_start'] = $ParsedID3v1['tag_offset_end'] - 128;
$info['id3v1'] = $ParsedID3v1;
}
if (substr($preid3v1, 0, 3) == 'TAG') {
// The way iTunes handles tags is, well, brain-damaged.
// It completely ignores v1 if ID3v2 is present.
// This goes as far as adding a new v1 tag *even if there already is one*
// A suspected double-ID3v1 tag has been detected, but it could be that
// the "TAG" identifier is a legitimate part of an APE or Lyrics3 tag
if (substr($preid3v1, 96, 8) == 'APETAGEX') {
// an APE tag footer was found before the last ID3v1, assume false "TAG" synch
} elseif (substr($preid3v1, 119, 6) == 'LYRICS') {
// a Lyrics3 tag footer was found before the last ID3v1, assume false "TAG" synch
} else {
// APE and Lyrics3 footers not found - assume double ID3v1
$info['warning'][] = 'Duplicate ID3v1 tag detected - this has been known to happen with iTunes';
$info['avdataend'] -= 128;
}
}
return true;
}
public static function cutfield($str) {
return trim(substr($str, 0, strcspn($str, "\x00")));
}
public static function ArrayOfGenres($allowSCMPXextended=false) {
static $GenreLookup = array(
0 => 'Blues',
1 => 'Classic Rock',
2 => 'Country',
3 => 'Dance',
4 => 'Disco',
5 => 'Funk',
6 => 'Grunge',
7 => 'Hip-Hop',
8 => 'Jazz',
9 => 'Metal',
10 => 'New Age',
11 => 'Oldies',
12 => 'Other',
13 => 'Pop',
14 => 'R&B',
15 => 'Rap',
16 => 'Reggae',
17 => 'Rock',
18 => 'Techno',
19 => 'Industrial',
20 => 'Alternative',
21 => 'Ska',
22 => 'Death Metal',
23 => 'Pranks',
24 => 'Soundtrack',
25 => 'Euro-Techno',
26 => 'Ambient',
27 => 'Trip-Hop',
28 => 'Vocal',
29 => 'Jazz+Funk',
30 => 'Fusion',
31 => 'Trance',
32 => 'Classical',
33 => 'Instrumental',
34 => 'Acid',
35 => 'House',
36 => 'Game',
37 => 'Sound Clip',
38 => 'Gospel',
39 => 'Noise',
40 => 'Alt. Rock',
41 => 'Bass',
42 => 'Soul',
43 => 'Punk',
44 => 'Space',
45 => 'Meditative',
46 => 'Instrumental Pop',
47 => 'Instrumental Rock',
48 => 'Ethnic',
49 => 'Gothic',
50 => 'Darkwave',
51 => 'Techno-Industrial',
52 => 'Electronic',
53 => 'Pop-Folk',
54 => 'Eurodance',
55 => 'Dream',
56 => 'Southern Rock',
57 => 'Comedy',
58 => 'Cult',
59 => 'Gangsta Rap',
60 => 'Top 40',
61 => 'Christian Rap',
62 => 'Pop/Funk',
63 => 'Jungle',
64 => 'Native American',
65 => 'Cabaret',
66 => 'New Wave',
67 => 'Psychedelic',
68 => 'Rave',
69 => 'Showtunes',
70 => 'Trailer',
71 => 'Lo-Fi',
72 => 'Tribal',
73 => 'Acid Punk',
74 => 'Acid Jazz',
75 => 'Polka',
76 => 'Retro',
77 => 'Musical',
78 => 'Rock & Roll',
79 => 'Hard Rock',
80 => 'Folk',
81 => 'Folk/Rock',
82 => 'National Folk',
83 => 'Swing',
84 => 'Fast-Fusion',
85 => 'Bebob',
86 => 'Latin',
87 => 'Revival',
88 => 'Celtic',
89 => 'Bluegrass',
90 => 'Avantgarde',
91 => 'Gothic Rock',
92 => 'Progressive Rock',
93 => 'Psychedelic Rock',
94 => 'Symphonic Rock',
95 => 'Slow Rock',
96 => 'Big Band',
97 => 'Chorus',
98 => 'Easy Listening',
99 => 'Acoustic',
100 => 'Humour',
101 => 'Speech',
102 => 'Chanson',
103 => 'Opera',
104 => 'Chamber Music',
105 => 'Sonata',
106 => 'Symphony',
107 => 'Booty Bass',
108 => 'Primus',
109 => 'Porn Groove',
110 => 'Satire',
111 => 'Slow Jam',
112 => 'Club',
113 => 'Tango',
114 => 'Samba',
115 => 'Folklore',
116 => 'Ballad',
117 => 'Power Ballad',
118 => 'Rhythmic Soul',
119 => 'Freestyle',
120 => 'Duet',
121 => 'Punk Rock',
122 => 'Drum Solo',
123 => 'A Cappella',
124 => 'Euro-House',
125 => 'Dance Hall',
126 => 'Goa',
127 => 'Drum & Bass',
128 => 'Club-House',
129 => 'Hardcore',
130 => 'Terror',
131 => 'Indie',
132 => 'BritPop',
133 => 'Negerpunk',
134 => 'Polsk Punk',
135 => 'Beat',
136 => 'Christian Gangsta Rap',
137 => 'Heavy Metal',
138 => 'Black Metal',
139 => 'Crossover',
140 => 'Contemporary Christian',
141 => 'Christian Rock',
142 => 'Merengue',
143 => 'Salsa',
144 => 'Thrash Metal',
145 => 'Anime',
146 => 'JPop',
147 => 'Synthpop',
255 => 'Unknown',
'CR' => 'Cover',
'RX' => 'Remix'
);
static $GenreLookupSCMPX = array();
if ($allowSCMPXextended && empty($GenreLookupSCMPX)) {
$GenreLookupSCMPX = $GenreLookup;
// http://www.geocities.co.jp/SiliconValley-Oakland/3664/alittle.html#GenreExtended
// Extended ID3v1 genres invented by SCMPX
// Note that 255 "Japanese Anime" conflicts with standard "Unknown"
$GenreLookupSCMPX[240] = 'Sacred';
$GenreLookupSCMPX[241] = 'Northern Europe';
$GenreLookupSCMPX[242] = 'Irish & Scottish';
$GenreLookupSCMPX[243] = 'Scotland';
$GenreLookupSCMPX[244] = 'Ethnic Europe';
$GenreLookupSCMPX[245] = 'Enka';
$GenreLookupSCMPX[246] = 'Children\'s Song';
$GenreLookupSCMPX[247] = 'Japanese Sky';
$GenreLookupSCMPX[248] = 'Japanese Heavy Rock';
$GenreLookupSCMPX[249] = 'Japanese Doom Rock';
$GenreLookupSCMPX[250] = 'Japanese J-POP';
$GenreLookupSCMPX[251] = 'Japanese Seiyu';
$GenreLookupSCMPX[252] = 'Japanese Ambient Techno';
$GenreLookupSCMPX[253] = 'Japanese Moemoe';
$GenreLookupSCMPX[254] = 'Japanese Tokusatsu';
//$GenreLookupSCMPX[255] = 'Japanese Anime';
}
return ($allowSCMPXextended ? $GenreLookupSCMPX : $GenreLookup);
}
public static function LookupGenreName($genreid, $allowSCMPXextended=true) {
switch ($genreid) {
case 'RX':
case 'CR':
break;
default:
if (!is_numeric($genreid)) {
return false;
}
$genreid = intval($genreid); // to handle 3 or '3' or '03'
break;
}
$GenreLookup = self::ArrayOfGenres($allowSCMPXextended);
return (isset($GenreLookup[$genreid]) ? $GenreLookup[$genreid] : false);
}
public static function LookupGenreID($genre, $allowSCMPXextended=false) {
$GenreLookup = self::ArrayOfGenres($allowSCMPXextended);
$LowerCaseNoSpaceSearchTerm = strtolower(str_replace(' ', '', $genre));
foreach ($GenreLookup as $key => $value) {
if (strtolower(str_replace(' ', '', $value)) == $LowerCaseNoSpaceSearchTerm) {
return $key;
}
}
return false;
}
public static function StandardiseID3v1GenreName($OriginalGenre) {
if (($GenreID = self::LookupGenreID($OriginalGenre)) !== false) {
return self::LookupGenreName($GenreID);
}
return $OriginalGenre;
}
public static function GenerateID3v1Tag($title, $artist, $album, $year, $genreid, $comment, $track='') {
$ID3v1Tag = 'TAG';
$ID3v1Tag .= str_pad(trim(substr($title, 0, 30)), 30, "\x00", STR_PAD_RIGHT);
$ID3v1Tag .= str_pad(trim(substr($artist, 0, 30)), 30, "\x00", STR_PAD_RIGHT);
$ID3v1Tag .= str_pad(trim(substr($album, 0, 30)), 30, "\x00", STR_PAD_RIGHT);
$ID3v1Tag .= str_pad(trim(substr($year, 0, 4)), 4, "\x00", STR_PAD_LEFT);
if (!empty($track) && ($track > 0) && ($track <= 255)) {
$ID3v1Tag .= str_pad(trim(substr($comment, 0, 28)), 28, "\x00", STR_PAD_RIGHT);
$ID3v1Tag .= "\x00";
if (gettype($track) == 'string') {
$track = (int) $track;
}
$ID3v1Tag .= chr($track);
} else {
$ID3v1Tag .= str_pad(trim(substr($comment, 0, 30)), 30, "\x00", STR_PAD_RIGHT);
}
if (($genreid < 0) || ($genreid > 147)) {
$genreid = 255; // 'unknown' genre
}
switch (gettype($genreid)) {
case 'string':
case 'integer':
$ID3v1Tag .= chr(intval($genreid));
break;
default:
$ID3v1Tag .= chr(255); // 'unknown' genre
break;
}
return $ID3v1Tag;
}
}
| PHP |
<?php
/////////////////////////////////////////////////////////////////
/// getID3() by James Heinrich <info@getid3.org> //
// available at http://getid3.sourceforge.net //
// or http://www.getid3.org //
/////////////////////////////////////////////////////////////////
// See readme.txt for more details //
/////////////////////////////////////////////////////////////////
// //
// module.tag.apetag.php //
// module for analyzing APE tags //
// dependencies: NONE //
// ///
/////////////////////////////////////////////////////////////////
class getid3_apetag extends getid3_handler
{
public $inline_attachments = true; // true: return full data for all attachments; false: return no data for all attachments; integer: return data for attachments <= than this; string: save as file to this directory
public $overrideendoffset = 0;
public function Analyze() {
$info = &$this->getid3->info;
if (!getid3_lib::intValueSupported($info['filesize'])) {
$info['warning'][] = 'Unable to check for APEtags because file is larger than '.round(PHP_INT_MAX / 1073741824).'GB';
return false;
}
$id3v1tagsize = 128;
$apetagheadersize = 32;
$lyrics3tagsize = 10;
if ($this->overrideendoffset == 0) {
fseek($this->getid3->fp, 0 - $id3v1tagsize - $apetagheadersize - $lyrics3tagsize, SEEK_END);
$APEfooterID3v1 = fread($this->getid3->fp, $id3v1tagsize + $apetagheadersize + $lyrics3tagsize);
//if (preg_match('/APETAGEX.{24}TAG.{125}$/i', $APEfooterID3v1)) {
if (substr($APEfooterID3v1, strlen($APEfooterID3v1) - $id3v1tagsize - $apetagheadersize, 8) == 'APETAGEX') {
// APE tag found before ID3v1
$info['ape']['tag_offset_end'] = $info['filesize'] - $id3v1tagsize;
//} elseif (preg_match('/APETAGEX.{24}$/i', $APEfooterID3v1)) {
} elseif (substr($APEfooterID3v1, strlen($APEfooterID3v1) - $apetagheadersize, 8) == 'APETAGEX') {
// APE tag found, no ID3v1
$info['ape']['tag_offset_end'] = $info['filesize'];
}
} else {
fseek($this->getid3->fp, $this->overrideendoffset - $apetagheadersize, SEEK_SET);
if (fread($this->getid3->fp, 8) == 'APETAGEX') {
$info['ape']['tag_offset_end'] = $this->overrideendoffset;
}
}
if (!isset($info['ape']['tag_offset_end'])) {
// APE tag not found
unset($info['ape']);
return false;
}
// shortcut
$thisfile_ape = &$info['ape'];
fseek($this->getid3->fp, $thisfile_ape['tag_offset_end'] - $apetagheadersize, SEEK_SET);
$APEfooterData = fread($this->getid3->fp, 32);
if (!($thisfile_ape['footer'] = $this->parseAPEheaderFooter($APEfooterData))) {
$info['error'][] = 'Error parsing APE footer at offset '.$thisfile_ape['tag_offset_end'];
return false;
}
if (isset($thisfile_ape['footer']['flags']['header']) && $thisfile_ape['footer']['flags']['header']) {
fseek($this->getid3->fp, $thisfile_ape['tag_offset_end'] - $thisfile_ape['footer']['raw']['tagsize'] - $apetagheadersize, SEEK_SET);
$thisfile_ape['tag_offset_start'] = ftell($this->getid3->fp);
$APEtagData = fread($this->getid3->fp, $thisfile_ape['footer']['raw']['tagsize'] + $apetagheadersize);
} else {
$thisfile_ape['tag_offset_start'] = $thisfile_ape['tag_offset_end'] - $thisfile_ape['footer']['raw']['tagsize'];
fseek($this->getid3->fp, $thisfile_ape['tag_offset_start'], SEEK_SET);
$APEtagData = fread($this->getid3->fp, $thisfile_ape['footer']['raw']['tagsize']);
}
$info['avdataend'] = $thisfile_ape['tag_offset_start'];
if (isset($info['id3v1']['tag_offset_start']) && ($info['id3v1']['tag_offset_start'] < $thisfile_ape['tag_offset_end'])) {
$info['warning'][] = 'ID3v1 tag information ignored since it appears to be a false synch in APEtag data';
unset($info['id3v1']);
foreach ($info['warning'] as $key => $value) {
if ($value == 'Some ID3v1 fields do not use NULL characters for padding') {
unset($info['warning'][$key]);
sort($info['warning']);
break;
}
}
}
$offset = 0;
if (isset($thisfile_ape['footer']['flags']['header']) && $thisfile_ape['footer']['flags']['header']) {
if ($thisfile_ape['header'] = $this->parseAPEheaderFooter(substr($APEtagData, 0, $apetagheadersize))) {
$offset += $apetagheadersize;
} else {
$info['error'][] = 'Error parsing APE header at offset '.$thisfile_ape['tag_offset_start'];
return false;
}
}
// shortcut
$info['replay_gain'] = array();
$thisfile_replaygain = &$info['replay_gain'];
for ($i = 0; $i < $thisfile_ape['footer']['raw']['tag_items']; $i++) {
$value_size = getid3_lib::LittleEndian2Int(substr($APEtagData, $offset, 4));
$offset += 4;
$item_flags = getid3_lib::LittleEndian2Int(substr($APEtagData, $offset, 4));
$offset += 4;
if (strstr(substr($APEtagData, $offset), "\x00") === false) {
$info['error'][] = 'Cannot find null-byte (0x00) seperator between ItemKey #'.$i.' and value. ItemKey starts '.$offset.' bytes into the APE tag, at file offset '.($thisfile_ape['tag_offset_start'] + $offset);
return false;
}
$ItemKeyLength = strpos($APEtagData, "\x00", $offset) - $offset;
$item_key = strtolower(substr($APEtagData, $offset, $ItemKeyLength));
// shortcut
$thisfile_ape['items'][$item_key] = array();
$thisfile_ape_items_current = &$thisfile_ape['items'][$item_key];
$thisfile_ape_items_current['offset'] = $thisfile_ape['tag_offset_start'] + $offset;
$offset += ($ItemKeyLength + 1); // skip 0x00 terminator
$thisfile_ape_items_current['data'] = substr($APEtagData, $offset, $value_size);
$offset += $value_size;
$thisfile_ape_items_current['flags'] = $this->parseAPEtagFlags($item_flags);
switch ($thisfile_ape_items_current['flags']['item_contents_raw']) {
case 0: // UTF-8
case 3: // Locator (URL, filename, etc), UTF-8 encoded
$thisfile_ape_items_current['data'] = explode("\x00", trim($thisfile_ape_items_current['data']));
break;
default: // binary data
break;
}
switch (strtolower($item_key)) {
case 'replaygain_track_gain':
$thisfile_replaygain['track']['adjustment'] = (float) str_replace(',', '.', $thisfile_ape_items_current['data'][0]); // float casting will see "0,95" as zero!
$thisfile_replaygain['track']['originator'] = 'unspecified';
break;
case 'replaygain_track_peak':
$thisfile_replaygain['track']['peak'] = (float) str_replace(',', '.', $thisfile_ape_items_current['data'][0]); // float casting will see "0,95" as zero!
$thisfile_replaygain['track']['originator'] = 'unspecified';
if ($thisfile_replaygain['track']['peak'] <= 0) {
$info['warning'][] = 'ReplayGain Track peak from APEtag appears invalid: '.$thisfile_replaygain['track']['peak'].' (original value = "'.$thisfile_ape_items_current['data'][0].'")';
}
break;
case 'replaygain_album_gain':
$thisfile_replaygain['album']['adjustment'] = (float) str_replace(',', '.', $thisfile_ape_items_current['data'][0]); // float casting will see "0,95" as zero!
$thisfile_replaygain['album']['originator'] = 'unspecified';
break;
case 'replaygain_album_peak':
$thisfile_replaygain['album']['peak'] = (float) str_replace(',', '.', $thisfile_ape_items_current['data'][0]); // float casting will see "0,95" as zero!
$thisfile_replaygain['album']['originator'] = 'unspecified';
if ($thisfile_replaygain['album']['peak'] <= 0) {
$info['warning'][] = 'ReplayGain Album peak from APEtag appears invalid: '.$thisfile_replaygain['album']['peak'].' (original value = "'.$thisfile_ape_items_current['data'][0].'")';
}
break;
case 'mp3gain_undo':
list($mp3gain_undo_left, $mp3gain_undo_right, $mp3gain_undo_wrap) = explode(',', $thisfile_ape_items_current['data'][0]);
$thisfile_replaygain['mp3gain']['undo_left'] = intval($mp3gain_undo_left);
$thisfile_replaygain['mp3gain']['undo_right'] = intval($mp3gain_undo_right);
$thisfile_replaygain['mp3gain']['undo_wrap'] = (($mp3gain_undo_wrap == 'Y') ? true : false);
break;
case 'mp3gain_minmax':
list($mp3gain_globalgain_min, $mp3gain_globalgain_max) = explode(',', $thisfile_ape_items_current['data'][0]);
$thisfile_replaygain['mp3gain']['globalgain_track_min'] = intval($mp3gain_globalgain_min);
$thisfile_replaygain['mp3gain']['globalgain_track_max'] = intval($mp3gain_globalgain_max);
break;
case 'mp3gain_album_minmax':
list($mp3gain_globalgain_album_min, $mp3gain_globalgain_album_max) = explode(',', $thisfile_ape_items_current['data'][0]);
$thisfile_replaygain['mp3gain']['globalgain_album_min'] = intval($mp3gain_globalgain_album_min);
$thisfile_replaygain['mp3gain']['globalgain_album_max'] = intval($mp3gain_globalgain_album_max);
break;
case 'tracknumber':
if (is_array($thisfile_ape_items_current['data'])) {
foreach ($thisfile_ape_items_current['data'] as $comment) {
$thisfile_ape['comments']['track'][] = $comment;
}
}
break;
case 'cover art (artist)':
case 'cover art (back)':
case 'cover art (band logo)':
case 'cover art (band)':
case 'cover art (colored fish)':
case 'cover art (composer)':
case 'cover art (conductor)':
case 'cover art (front)':
case 'cover art (icon)':
case 'cover art (illustration)':
case 'cover art (lead)':
case 'cover art (leaflet)':
case 'cover art (lyricist)':
case 'cover art (media)':
case 'cover art (movie scene)':
case 'cover art (other icon)':
case 'cover art (other)':
case 'cover art (performance)':
case 'cover art (publisher logo)':
case 'cover art (recording)':
case 'cover art (studio)':
// list of possible cover arts from http://taglib-sharp.sourcearchive.com/documentation/2.0.3.0-2/Ape_2Tag_8cs-source.html
list($thisfile_ape_items_current['filename'], $thisfile_ape_items_current['data']) = explode("\x00", $thisfile_ape_items_current['data'], 2);
$thisfile_ape_items_current['data_offset'] = $thisfile_ape_items_current['offset'] + strlen($thisfile_ape_items_current['filename']."\x00");
$thisfile_ape_items_current['data_length'] = strlen($thisfile_ape_items_current['data']);
$thisfile_ape_items_current['image_mime'] = '';
$imageinfo = array();
$imagechunkcheck = getid3_lib::GetDataImageSize($thisfile_ape_items_current['data'], $imageinfo);
$thisfile_ape_items_current['image_mime'] = image_type_to_mime_type($imagechunkcheck[2]);
do {
if ($this->inline_attachments === false) {
// skip entirely
unset($thisfile_ape_items_current['data']);
break;
}
if ($this->inline_attachments === true) {
// great
} elseif (is_int($this->inline_attachments)) {
if ($this->inline_attachments < $thisfile_ape_items_current['data_length']) {
// too big, skip
$info['warning'][] = 'attachment at '.$thisfile_ape_items_current['offset'].' is too large to process inline ('.number_format($thisfile_ape_items_current['data_length']).' bytes)';
unset($thisfile_ape_items_current['data']);
break;
}
} elseif (is_string($this->inline_attachments)) {
$this->inline_attachments = rtrim(str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $this->inline_attachments), DIRECTORY_SEPARATOR);
if (!is_dir($this->inline_attachments) || !is_writable($this->inline_attachments)) {
// cannot write, skip
$info['warning'][] = 'attachment at '.$thisfile_ape_items_current['offset'].' cannot be saved to "'.$this->inline_attachments.'" (not writable)';
unset($thisfile_ape_items_current['data']);
break;
}
}
// if we get this far, must be OK
if (is_string($this->inline_attachments)) {
$destination_filename = $this->inline_attachments.DIRECTORY_SEPARATOR.md5($info['filenamepath']).'_'.$thisfile_ape_items_current['data_offset'];
if (!file_exists($destination_filename) || is_writable($destination_filename)) {
file_put_contents($destination_filename, $thisfile_ape_items_current['data']);
} else {
$info['warning'][] = 'attachment at '.$thisfile_ape_items_current['offset'].' cannot be saved to "'.$destination_filename.'" (not writable)';
}
$thisfile_ape_items_current['data_filename'] = $destination_filename;
unset($thisfile_ape_items_current['data']);
} else {
if (!isset($info['ape']['comments']['picture'])) {
$info['ape']['comments']['picture'] = array();
}
$info['ape']['comments']['picture'][] = array('data'=>$thisfile_ape_items_current['data'], 'image_mime'=>$thisfile_ape_items_current['image_mime']);
}
} while (false);
break;
default:
if (is_array($thisfile_ape_items_current['data'])) {
foreach ($thisfile_ape_items_current['data'] as $comment) {
$thisfile_ape['comments'][strtolower($item_key)][] = $comment;
}
}
break;
}
}
if (empty($thisfile_replaygain)) {
unset($info['replay_gain']);
}
return true;
}
public function parseAPEheaderFooter($APEheaderFooterData) {
// http://www.uni-jena.de/~pfk/mpp/sv8/apeheader.html
// shortcut
$headerfooterinfo['raw'] = array();
$headerfooterinfo_raw = &$headerfooterinfo['raw'];
$headerfooterinfo_raw['footer_tag'] = substr($APEheaderFooterData, 0, 8);
if ($headerfooterinfo_raw['footer_tag'] != 'APETAGEX') {
return false;
}
$headerfooterinfo_raw['version'] = getid3_lib::LittleEndian2Int(substr($APEheaderFooterData, 8, 4));
$headerfooterinfo_raw['tagsize'] = getid3_lib::LittleEndian2Int(substr($APEheaderFooterData, 12, 4));
$headerfooterinfo_raw['tag_items'] = getid3_lib::LittleEndian2Int(substr($APEheaderFooterData, 16, 4));
$headerfooterinfo_raw['global_flags'] = getid3_lib::LittleEndian2Int(substr($APEheaderFooterData, 20, 4));
$headerfooterinfo_raw['reserved'] = substr($APEheaderFooterData, 24, 8);
$headerfooterinfo['tag_version'] = $headerfooterinfo_raw['version'] / 1000;
if ($headerfooterinfo['tag_version'] >= 2) {
$headerfooterinfo['flags'] = $this->parseAPEtagFlags($headerfooterinfo_raw['global_flags']);
}
return $headerfooterinfo;
}
public function parseAPEtagFlags($rawflagint) {
// "Note: APE Tags 1.0 do not use any of the APE Tag flags.
// All are set to zero on creation and ignored on reading."
// http://www.uni-jena.de/~pfk/mpp/sv8/apetagflags.html
$flags['header'] = (bool) ($rawflagint & 0x80000000);
$flags['footer'] = (bool) ($rawflagint & 0x40000000);
$flags['this_is_header'] = (bool) ($rawflagint & 0x20000000);
$flags['item_contents_raw'] = ($rawflagint & 0x00000006) >> 1;
$flags['read_only'] = (bool) ($rawflagint & 0x00000001);
$flags['item_contents'] = $this->APEcontentTypeFlagLookup($flags['item_contents_raw']);
return $flags;
}
public function APEcontentTypeFlagLookup($contenttypeid) {
static $APEcontentTypeFlagLookup = array(
0 => 'utf-8',
1 => 'binary',
2 => 'external',
3 => 'reserved'
);
return (isset($APEcontentTypeFlagLookup[$contenttypeid]) ? $APEcontentTypeFlagLookup[$contenttypeid] : 'invalid');
}
public function APEtagItemIsUTF8Lookup($itemkey) {
static $APEtagItemIsUTF8Lookup = array(
'title',
'subtitle',
'artist',
'album',
'debut album',
'publisher',
'conductor',
'track',
'composer',
'comment',
'copyright',
'publicationright',
'file',
'year',
'record date',
'record location',
'genre',
'media',
'related',
'isrc',
'abstract',
'language',
'bibliography'
);
return in_array(strtolower($itemkey), $APEtagItemIsUTF8Lookup);
}
}
| PHP |
<?php
/////////////////////////////////////////////////////////////////
/// getID3() by James Heinrich <info@getid3.org> //
// available at http://getid3.sourceforge.net //
// or http://www.getid3.org //
/////////////////////////////////////////////////////////////////
// See readme.txt for more details //
/////////////////////////////////////////////////////////////////
// //
// module.audio-video.quicktime.php //
// module for analyzing Quicktime and MP3-in-MP4 files //
// dependencies: module.audio.mp3.php //
// dependencies: module.tag.id3v2.php //
// ///
/////////////////////////////////////////////////////////////////
getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.audio.mp3.php', __FILE__, true);
getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.tag.id3v2.php', __FILE__, true); // needed for ISO 639-2 language code lookup
class getid3_quicktime extends getid3_handler
{
public $ReturnAtomData = true;
public $ParseAllPossibleAtoms = false;
public function Analyze() {
$info = &$this->getid3->info;
$info['fileformat'] = 'quicktime';
$info['quicktime']['hinting'] = false;
$info['quicktime']['controller'] = 'standard'; // may be overridden if 'ctyp' atom is present
fseek($this->getid3->fp, $info['avdataoffset'], SEEK_SET);
$offset = 0;
$atomcounter = 0;
while ($offset < $info['avdataend']) {
if (!getid3_lib::intValueSupported($offset)) {
$info['error'][] = 'Unable to parse atom at offset '.$offset.' because beyond '.round(PHP_INT_MAX / 1073741824).'GB limit of PHP filesystem functions';
break;
}
fseek($this->getid3->fp, $offset, SEEK_SET);
$AtomHeader = fread($this->getid3->fp, 8);
$atomsize = getid3_lib::BigEndian2Int(substr($AtomHeader, 0, 4));
$atomname = substr($AtomHeader, 4, 4);
// 64-bit MOV patch by jlegateØktnc*com
if ($atomsize == 1) {
$atomsize = getid3_lib::BigEndian2Int(fread($this->getid3->fp, 8));
}
$info['quicktime'][$atomname]['name'] = $atomname;
$info['quicktime'][$atomname]['size'] = $atomsize;
$info['quicktime'][$atomname]['offset'] = $offset;
if (($offset + $atomsize) > $info['avdataend']) {
$info['error'][] = 'Atom at offset '.$offset.' claims to go beyond end-of-file (length: '.$atomsize.' bytes)';
return false;
}
if ($atomsize == 0) {
// Furthermore, for historical reasons the list of atoms is optionally
// terminated by a 32-bit integer set to 0. If you are writing a program
// to read user data atoms, you should allow for the terminating 0.
break;
}
switch ($atomname) {
case 'mdat': // Media DATa atom
// 'mdat' contains the actual data for the audio/video
if (($atomsize > 8) && (!isset($info['avdataend_tmp']) || ($info['quicktime'][$atomname]['size'] > ($info['avdataend_tmp'] - $info['avdataoffset'])))) {
$info['avdataoffset'] = $info['quicktime'][$atomname]['offset'] + 8;
$OldAVDataEnd = $info['avdataend'];
$info['avdataend'] = $info['quicktime'][$atomname]['offset'] + $info['quicktime'][$atomname]['size'];
$getid3_temp = new getID3();
$getid3_temp->openfile($this->getid3->filename);
$getid3_temp->info['avdataoffset'] = $info['avdataoffset'];
$getid3_temp->info['avdataend'] = $info['avdataend'];
$getid3_mp3 = new getid3_mp3($getid3_temp);
if ($getid3_mp3->MPEGaudioHeaderValid($getid3_mp3->MPEGaudioHeaderDecode(fread($this->getid3->fp, 4)))) {
$getid3_mp3->getOnlyMPEGaudioInfo($getid3_temp->info['avdataoffset'], false);
if (!empty($getid3_temp->info['warning'])) {
foreach ($getid3_temp->info['warning'] as $value) {
$info['warning'][] = $value;
}
}
if (!empty($getid3_temp->info['mpeg'])) {
$info['mpeg'] = $getid3_temp->info['mpeg'];
if (isset($info['mpeg']['audio'])) {
$info['audio']['dataformat'] = 'mp3';
$info['audio']['codec'] = (!empty($info['mpeg']['audio']['encoder']) ? $info['mpeg']['audio']['encoder'] : (!empty($info['mpeg']['audio']['codec']) ? $info['mpeg']['audio']['codec'] : (!empty($info['mpeg']['audio']['LAME']) ? 'LAME' :'mp3')));
$info['audio']['sample_rate'] = $info['mpeg']['audio']['sample_rate'];
$info['audio']['channels'] = $info['mpeg']['audio']['channels'];
$info['audio']['bitrate'] = $info['mpeg']['audio']['bitrate'];
$info['audio']['bitrate_mode'] = strtolower($info['mpeg']['audio']['bitrate_mode']);
$info['bitrate'] = $info['audio']['bitrate'];
}
}
}
unset($getid3_mp3, $getid3_temp);
$info['avdataend'] = $OldAVDataEnd;
unset($OldAVDataEnd);
}
break;
case 'free': // FREE space atom
case 'skip': // SKIP atom
case 'wide': // 64-bit expansion placeholder atom
// 'free', 'skip' and 'wide' are just padding, contains no useful data at all
break;
default:
$atomHierarchy = array();
$info['quicktime'][$atomname] = $this->QuicktimeParseAtom($atomname, $atomsize, fread($this->getid3->fp, $atomsize), $offset, $atomHierarchy, $this->ParseAllPossibleAtoms);
break;
}
$offset += $atomsize;
$atomcounter++;
}
if (!empty($info['avdataend_tmp'])) {
// this value is assigned to a temp value and then erased because
// otherwise any atoms beyond the 'mdat' atom would not get parsed
$info['avdataend'] = $info['avdataend_tmp'];
unset($info['avdataend_tmp']);
}
if (!isset($info['bitrate']) && isset($info['playtime_seconds'])) {
$info['bitrate'] = (($info['avdataend'] - $info['avdataoffset']) * 8) / $info['playtime_seconds'];
}
if (isset($info['bitrate']) && !isset($info['audio']['bitrate']) && !isset($info['quicktime']['video'])) {
$info['audio']['bitrate'] = $info['bitrate'];
}
if (!empty($info['playtime_seconds']) && !isset($info['video']['frame_rate']) && !empty($info['quicktime']['stts_framecount'])) {
foreach ($info['quicktime']['stts_framecount'] as $key => $samples_count) {
$samples_per_second = $samples_count / $info['playtime_seconds'];
if ($samples_per_second > 240) {
// has to be audio samples
} else {
$info['video']['frame_rate'] = $samples_per_second;
break;
}
}
}
if (($info['audio']['dataformat'] == 'mp4') && empty($info['video']['resolution_x'])) {
$info['fileformat'] = 'mp4';
$info['mime_type'] = 'audio/mp4';
unset($info['video']['dataformat']);
}
if (!$this->ReturnAtomData) {
unset($info['quicktime']['moov']);
}
if (empty($info['audio']['dataformat']) && !empty($info['quicktime']['audio'])) {
$info['audio']['dataformat'] = 'quicktime';
}
if (empty($info['video']['dataformat']) && !empty($info['quicktime']['video'])) {
$info['video']['dataformat'] = 'quicktime';
}
return true;
}
public function QuicktimeParseAtom($atomname, $atomsize, $atom_data, $baseoffset, &$atomHierarchy, $ParseAllPossibleAtoms) {
// http://developer.apple.com/techpubs/quicktime/qtdevdocs/APIREF/INDEX/atomalphaindex.htm
$info = &$this->getid3->info;
//$atom_parent = array_pop($atomHierarchy);
$atom_parent = end($atomHierarchy); // http://www.getid3.org/phpBB3/viewtopic.php?t=1717
array_push($atomHierarchy, $atomname);
$atom_structure['hierarchy'] = implode(' ', $atomHierarchy);
$atom_structure['name'] = $atomname;
$atom_structure['size'] = $atomsize;
$atom_structure['offset'] = $baseoffset;
//echo getid3_lib::PrintHexBytes(substr($atom_data, 0, 8)).'<br>';
//echo getid3_lib::PrintHexBytes(substr($atom_data, 0, 8), false).'<br><br>';
switch ($atomname) {
case 'moov': // MOVie container atom
case 'trak': // TRAcK container atom
case 'clip': // CLIPping container atom
case 'matt': // track MATTe container atom
case 'edts': // EDiTS container atom
case 'tref': // Track REFerence container atom
case 'mdia': // MeDIA container atom
case 'minf': // Media INFormation container atom
case 'dinf': // Data INFormation container atom
case 'udta': // User DaTA container atom
case 'cmov': // Compressed MOVie container atom
case 'rmra': // Reference Movie Record Atom
case 'rmda': // Reference Movie Descriptor Atom
case 'gmhd': // Generic Media info HeaDer atom (seen on QTVR)
$atom_structure['subatoms'] = $this->QuicktimeParseContainerAtom($atom_data, $baseoffset + 8, $atomHierarchy, $ParseAllPossibleAtoms);
break;
case 'ilst': // Item LiST container atom
$atom_structure['subatoms'] = $this->QuicktimeParseContainerAtom($atom_data, $baseoffset + 8, $atomHierarchy, $ParseAllPossibleAtoms);
// some "ilst" atoms contain data atoms that have a numeric name, and the data is far more accessible if the returned array is compacted
$allnumericnames = true;
foreach ($atom_structure['subatoms'] as $subatomarray) {
if (!is_integer($subatomarray['name']) || (count($subatomarray['subatoms']) != 1)) {
$allnumericnames = false;
break;
}
}
if ($allnumericnames) {
$newData = array();
foreach ($atom_structure['subatoms'] as $subatomarray) {
foreach ($subatomarray['subatoms'] as $newData_subatomarray) {
unset($newData_subatomarray['hierarchy'], $newData_subatomarray['name']);
$newData[$subatomarray['name']] = $newData_subatomarray;
break;
}
}
$atom_structure['data'] = $newData;
unset($atom_structure['subatoms']);
}
break;
case "\x00\x00\x00\x01":
case "\x00\x00\x00\x02":
case "\x00\x00\x00\x03":
case "\x00\x00\x00\x04":
case "\x00\x00\x00\x05":
$atomname = getid3_lib::BigEndian2Int($atomname);
$atom_structure['name'] = $atomname;
$atom_structure['subatoms'] = $this->QuicktimeParseContainerAtom($atom_data, $baseoffset + 8, $atomHierarchy, $ParseAllPossibleAtoms);
break;
case 'stbl': // Sample TaBLe container atom
$atom_structure['subatoms'] = $this->QuicktimeParseContainerAtom($atom_data, $baseoffset + 8, $atomHierarchy, $ParseAllPossibleAtoms);
$isVideo = false;
$framerate = 0;
$framecount = 0;
foreach ($atom_structure['subatoms'] as $key => $value_array) {
if (isset($value_array['sample_description_table'])) {
foreach ($value_array['sample_description_table'] as $key2 => $value_array2) {
if (isset($value_array2['data_format'])) {
switch ($value_array2['data_format']) {
case 'avc1':
case 'mp4v':
// video data
$isVideo = true;
break;
case 'mp4a':
// audio data
break;
}
}
}
} elseif (isset($value_array['time_to_sample_table'])) {
foreach ($value_array['time_to_sample_table'] as $key2 => $value_array2) {
if (isset($value_array2['sample_count']) && isset($value_array2['sample_duration']) && ($value_array2['sample_duration'] > 0)) {
$framerate = round($info['quicktime']['time_scale'] / $value_array2['sample_duration'], 3);
$framecount = $value_array2['sample_count'];
}
}
}
}
if ($isVideo && $framerate) {
$info['quicktime']['video']['frame_rate'] = $framerate;
$info['video']['frame_rate'] = $info['quicktime']['video']['frame_rate'];
}
if ($isVideo && $framecount) {
$info['quicktime']['video']['frame_count'] = $framecount;
}
break;
case 'aART': // Album ARTist
case 'catg': // CaTeGory
case 'covr': // COVeR artwork
case 'cpil': // ComPILation
case 'cprt': // CoPyRighT
case 'desc': // DESCription
case 'disk': // DISK number
case 'egid': // Episode Global ID
case 'gnre': // GeNRE
case 'keyw': // KEYWord
case 'ldes':
case 'pcst': // PodCaST
case 'pgap': // GAPless Playback
case 'purd': // PURchase Date
case 'purl': // Podcast URL
case 'rati':
case 'rndu':
case 'rpdu':
case 'rtng': // RaTiNG
case 'stik':
case 'tmpo': // TeMPO (BPM)
case 'trkn': // TRacK Number
case 'tves': // TV EpiSode
case 'tvnn': // TV Network Name
case 'tvsh': // TV SHow Name
case 'tvsn': // TV SeasoN
case 'akID': // iTunes store account type
case 'apID':
case 'atID':
case 'cmID':
case 'cnID':
case 'geID':
case 'plID':
case 'sfID': // iTunes store country
case '©alb': // ALBum
case '©art': // ARTist
case '©ART':
case '©aut':
case '©cmt': // CoMmenT
case '©com': // COMposer
case '©cpy':
case '©day': // content created year
case '©dir':
case '©ed1':
case '©ed2':
case '©ed3':
case '©ed4':
case '©ed5':
case '©ed6':
case '©ed7':
case '©ed8':
case '©ed9':
case '©enc':
case '©fmt':
case '©gen': // GENre
case '©grp': // GRouPing
case '©hst':
case '©inf':
case '©lyr': // LYRics
case '©mak':
case '©mod':
case '©nam': // full NAMe
case '©ope':
case '©PRD':
case '©prd':
case '©prf':
case '©req':
case '©src':
case '©swr':
case '©too': // encoder
case '©trk': // TRacK
case '©url':
case '©wrn':
case '©wrt': // WRiTer
case '----': // itunes specific
if ($atom_parent == 'udta') {
// User data atom handler
$atom_structure['data_length'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 2));
$atom_structure['language_id'] = getid3_lib::BigEndian2Int(substr($atom_data, 2, 2));
$atom_structure['data'] = substr($atom_data, 4);
$atom_structure['language'] = $this->QuicktimeLanguageLookup($atom_structure['language_id']);
if (empty($info['comments']['language']) || (!in_array($atom_structure['language'], $info['comments']['language']))) {
$info['comments']['language'][] = $atom_structure['language'];
}
} else {
// Apple item list box atom handler
$atomoffset = 0;
if (substr($atom_data, 2, 2) == "\x10\xB5") {
// not sure what it means, but observed on iPhone4 data.
// Each $atom_data has 2 bytes of datasize, plus 0x10B5, then data
while ($atomoffset < strlen($atom_data)) {
$boxsmallsize = getid3_lib::BigEndian2Int(substr($atom_data, $atomoffset, 2));
$boxsmalltype = substr($atom_data, $atomoffset + 2, 2);
$boxsmalldata = substr($atom_data, $atomoffset + 4, $boxsmallsize);
if ($boxsmallsize <= 1) {
$info['warning'][] = 'Invalid QuickTime atom smallbox size "'.$boxsmallsize.'" in atom "'.$atomname.'" at offset: '.($atom_structure['offset'] + $atomoffset);
$atom_structure['data'] = null;
$atomoffset = strlen($atom_data);
break;
}
switch ($boxsmalltype) {
case "\x10\xB5":
$atom_structure['data'] = $boxsmalldata;
break;
default:
$info['warning'][] = 'Unknown QuickTime smallbox type: "'.getid3_lib::PrintHexBytes($boxsmalltype).'" at offset '.$baseoffset;
$atom_structure['data'] = $atom_data;
break;
}
$atomoffset += (4 + $boxsmallsize);
}
} else {
while ($atomoffset < strlen($atom_data)) {
$boxsize = getid3_lib::BigEndian2Int(substr($atom_data, $atomoffset, 4));
$boxtype = substr($atom_data, $atomoffset + 4, 4);
$boxdata = substr($atom_data, $atomoffset + 8, $boxsize - 8);
if ($boxsize <= 1) {
$info['warning'][] = 'Invalid QuickTime atom box size "'.$boxsize.'" in atom "'.$atomname.'" at offset: '.($atom_structure['offset'] + $atomoffset);
$atom_structure['data'] = null;
$atomoffset = strlen($atom_data);
break;
}
$atomoffset += $boxsize;
switch ($boxtype) {
case 'mean':
case 'name':
$atom_structure[$boxtype] = substr($boxdata, 4);
break;
case 'data':
$atom_structure['version'] = getid3_lib::BigEndian2Int(substr($boxdata, 0, 1));
$atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($boxdata, 1, 3));
switch ($atom_structure['flags_raw']) {
case 0: // data flag
case 21: // tmpo/cpil flag
switch ($atomname) {
case 'cpil':
case 'pcst':
case 'pgap':
$atom_structure['data'] = getid3_lib::BigEndian2Int(substr($boxdata, 8, 1));
break;
case 'tmpo':
$atom_structure['data'] = getid3_lib::BigEndian2Int(substr($boxdata, 8, 2));
break;
case 'disk':
case 'trkn':
$num = getid3_lib::BigEndian2Int(substr($boxdata, 10, 2));
$num_total = getid3_lib::BigEndian2Int(substr($boxdata, 12, 2));
$atom_structure['data'] = empty($num) ? '' : $num;
$atom_structure['data'] .= empty($num_total) ? '' : '/'.$num_total;
break;
case 'gnre':
$GenreID = getid3_lib::BigEndian2Int(substr($boxdata, 8, 4));
$atom_structure['data'] = getid3_id3v1::LookupGenreName($GenreID - 1);
break;
case 'rtng':
$atom_structure[$atomname] = getid3_lib::BigEndian2Int(substr($boxdata, 8, 1));
$atom_structure['data'] = $this->QuicktimeContentRatingLookup($atom_structure[$atomname]);
break;
case 'stik':
$atom_structure[$atomname] = getid3_lib::BigEndian2Int(substr($boxdata, 8, 1));
$atom_structure['data'] = $this->QuicktimeSTIKLookup($atom_structure[$atomname]);
break;
case 'sfID':
$atom_structure[$atomname] = getid3_lib::BigEndian2Int(substr($boxdata, 8, 4));
$atom_structure['data'] = $this->QuicktimeStoreFrontCodeLookup($atom_structure[$atomname]);
break;
case 'egid':
case 'purl':
$atom_structure['data'] = substr($boxdata, 8);
break;
default:
$atom_structure['data'] = getid3_lib::BigEndian2Int(substr($boxdata, 8, 4));
}
break;
case 1: // text flag
case 13: // image flag
default:
$atom_structure['data'] = substr($boxdata, 8);
break;
}
break;
default:
$info['warning'][] = 'Unknown QuickTime box type: "'.getid3_lib::PrintHexBytes($boxtype).'" at offset '.$baseoffset;
$atom_structure['data'] = $atom_data;
}
}
}
}
$this->CopyToAppropriateCommentsSection($atomname, $atom_structure['data'], $atom_structure['name']);
break;
case 'play': // auto-PLAY atom
$atom_structure['autoplay'] = (bool) getid3_lib::BigEndian2Int(substr($atom_data, 0, 1));
$info['quicktime']['autoplay'] = $atom_structure['autoplay'];
break;
case 'WLOC': // Window LOCation atom
$atom_structure['location_x'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 2));
$atom_structure['location_y'] = getid3_lib::BigEndian2Int(substr($atom_data, 2, 2));
break;
case 'LOOP': // LOOPing atom
case 'SelO': // play SELection Only atom
case 'AllF': // play ALL Frames atom
$atom_structure['data'] = getid3_lib::BigEndian2Int($atom_data);
break;
case 'name': //
case 'MCPS': // Media Cleaner PRo
case '@PRM': // adobe PReMiere version
case '@PRQ': // adobe PRemiere Quicktime version
$atom_structure['data'] = $atom_data;
break;
case 'cmvd': // Compressed MooV Data atom
// Code by ubergeekØubergeek*tv based on information from
// http://developer.apple.com/quicktime/icefloe/dispatch012.html
$atom_structure['unCompressedSize'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 4));
$CompressedFileData = substr($atom_data, 4);
if ($UncompressedHeader = @gzuncompress($CompressedFileData)) {
$atom_structure['subatoms'] = $this->QuicktimeParseContainerAtom($UncompressedHeader, 0, $atomHierarchy, $ParseAllPossibleAtoms);
} else {
$info['warning'][] = 'Error decompressing compressed MOV atom at offset '.$atom_structure['offset'];
}
break;
case 'dcom': // Data COMpression atom
$atom_structure['compression_id'] = $atom_data;
$atom_structure['compression_text'] = $this->QuicktimeDCOMLookup($atom_data);
break;
case 'rdrf': // Reference movie Data ReFerence atom
$atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1));
$atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3));
$atom_structure['flags']['internal_data'] = (bool) ($atom_structure['flags_raw'] & 0x000001);
$atom_structure['reference_type_name'] = substr($atom_data, 4, 4);
$atom_structure['reference_length'] = getid3_lib::BigEndian2Int(substr($atom_data, 8, 4));
switch ($atom_structure['reference_type_name']) {
case 'url ':
$atom_structure['url'] = $this->NoNullString(substr($atom_data, 12));
break;
case 'alis':
$atom_structure['file_alias'] = substr($atom_data, 12);
break;
case 'rsrc':
$atom_structure['resource_alias'] = substr($atom_data, 12);
break;
default:
$atom_structure['data'] = substr($atom_data, 12);
break;
}
break;
case 'rmqu': // Reference Movie QUality atom
$atom_structure['movie_quality'] = getid3_lib::BigEndian2Int($atom_data);
break;
case 'rmcs': // Reference Movie Cpu Speed atom
$atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1));
$atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); // hardcoded: 0x0000
$atom_structure['cpu_speed_rating'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 2));
break;
case 'rmvc': // Reference Movie Version Check atom
$atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1));
$atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); // hardcoded: 0x0000
$atom_structure['gestalt_selector'] = substr($atom_data, 4, 4);
$atom_structure['gestalt_value_mask'] = getid3_lib::BigEndian2Int(substr($atom_data, 8, 4));
$atom_structure['gestalt_value'] = getid3_lib::BigEndian2Int(substr($atom_data, 12, 4));
$atom_structure['gestalt_check_type'] = getid3_lib::BigEndian2Int(substr($atom_data, 14, 2));
break;
case 'rmcd': // Reference Movie Component check atom
$atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1));
$atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); // hardcoded: 0x0000
$atom_structure['component_type'] = substr($atom_data, 4, 4);
$atom_structure['component_subtype'] = substr($atom_data, 8, 4);
$atom_structure['component_manufacturer'] = substr($atom_data, 12, 4);
$atom_structure['component_flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 16, 4));
$atom_structure['component_flags_mask'] = getid3_lib::BigEndian2Int(substr($atom_data, 20, 4));
$atom_structure['component_min_version'] = getid3_lib::BigEndian2Int(substr($atom_data, 24, 4));
break;
case 'rmdr': // Reference Movie Data Rate atom
$atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1));
$atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); // hardcoded: 0x0000
$atom_structure['data_rate'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 4));
$atom_structure['data_rate_bps'] = $atom_structure['data_rate'] * 10;
break;
case 'rmla': // Reference Movie Language Atom
$atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1));
$atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); // hardcoded: 0x0000
$atom_structure['language_id'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 2));
$atom_structure['language'] = $this->QuicktimeLanguageLookup($atom_structure['language_id']);
if (empty($info['comments']['language']) || (!in_array($atom_structure['language'], $info['comments']['language']))) {
$info['comments']['language'][] = $atom_structure['language'];
}
break;
case 'rmla': // Reference Movie Language Atom
$atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1));
$atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); // hardcoded: 0x0000
$atom_structure['track_id'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 2));
break;
case 'ptv ': // Print To Video - defines a movie's full screen mode
// http://developer.apple.com/documentation/QuickTime/APIREF/SOURCESIV/at_ptv-_pg.htm
$atom_structure['display_size_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 2));
$atom_structure['reserved_1'] = getid3_lib::BigEndian2Int(substr($atom_data, 2, 2)); // hardcoded: 0x0000
$atom_structure['reserved_2'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 2)); // hardcoded: 0x0000
$atom_structure['slide_show_flag'] = getid3_lib::BigEndian2Int(substr($atom_data, 6, 1));
$atom_structure['play_on_open_flag'] = getid3_lib::BigEndian2Int(substr($atom_data, 7, 1));
$atom_structure['flags']['play_on_open'] = (bool) $atom_structure['play_on_open_flag'];
$atom_structure['flags']['slide_show'] = (bool) $atom_structure['slide_show_flag'];
$ptv_lookup[0] = 'normal';
$ptv_lookup[1] = 'double';
$ptv_lookup[2] = 'half';
$ptv_lookup[3] = 'full';
$ptv_lookup[4] = 'current';
if (isset($ptv_lookup[$atom_structure['display_size_raw']])) {
$atom_structure['display_size'] = $ptv_lookup[$atom_structure['display_size_raw']];
} else {
$info['warning'][] = 'unknown "ptv " display constant ('.$atom_structure['display_size_raw'].')';
}
break;
case 'stsd': // Sample Table Sample Description atom
$atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1));
$atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); // hardcoded: 0x0000
$atom_structure['number_entries'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 4));
$stsdEntriesDataOffset = 8;
for ($i = 0; $i < $atom_structure['number_entries']; $i++) {
$atom_structure['sample_description_table'][$i]['size'] = getid3_lib::BigEndian2Int(substr($atom_data, $stsdEntriesDataOffset, 4));
$stsdEntriesDataOffset += 4;
$atom_structure['sample_description_table'][$i]['data_format'] = substr($atom_data, $stsdEntriesDataOffset, 4);
$stsdEntriesDataOffset += 4;
$atom_structure['sample_description_table'][$i]['reserved'] = getid3_lib::BigEndian2Int(substr($atom_data, $stsdEntriesDataOffset, 6));
$stsdEntriesDataOffset += 6;
$atom_structure['sample_description_table'][$i]['reference_index'] = getid3_lib::BigEndian2Int(substr($atom_data, $stsdEntriesDataOffset, 2));
$stsdEntriesDataOffset += 2;
$atom_structure['sample_description_table'][$i]['data'] = substr($atom_data, $stsdEntriesDataOffset, ($atom_structure['sample_description_table'][$i]['size'] - 4 - 4 - 6 - 2));
$stsdEntriesDataOffset += ($atom_structure['sample_description_table'][$i]['size'] - 4 - 4 - 6 - 2);
$atom_structure['sample_description_table'][$i]['encoder_version'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 0, 2));
$atom_structure['sample_description_table'][$i]['encoder_revision'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 2, 2));
$atom_structure['sample_description_table'][$i]['encoder_vendor'] = substr($atom_structure['sample_description_table'][$i]['data'], 4, 4);
switch ($atom_structure['sample_description_table'][$i]['encoder_vendor']) {
case "\x00\x00\x00\x00":
// audio tracks
$atom_structure['sample_description_table'][$i]['audio_channels'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 8, 2));
$atom_structure['sample_description_table'][$i]['audio_bit_depth'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 10, 2));
$atom_structure['sample_description_table'][$i]['audio_compression_id'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 12, 2));
$atom_structure['sample_description_table'][$i]['audio_packet_size'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 14, 2));
$atom_structure['sample_description_table'][$i]['audio_sample_rate'] = getid3_lib::FixedPoint16_16(substr($atom_structure['sample_description_table'][$i]['data'], 16, 4));
// video tracks
// http://developer.apple.com/library/mac/#documentation/QuickTime/QTFF/QTFFChap3/qtff3.html
$atom_structure['sample_description_table'][$i]['temporal_quality'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 8, 4));
$atom_structure['sample_description_table'][$i]['spatial_quality'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 12, 4));
$atom_structure['sample_description_table'][$i]['width'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 16, 2));
$atom_structure['sample_description_table'][$i]['height'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 18, 2));
$atom_structure['sample_description_table'][$i]['resolution_x'] = getid3_lib::FixedPoint16_16(substr($atom_structure['sample_description_table'][$i]['data'], 24, 4));
$atom_structure['sample_description_table'][$i]['resolution_y'] = getid3_lib::FixedPoint16_16(substr($atom_structure['sample_description_table'][$i]['data'], 28, 4));
$atom_structure['sample_description_table'][$i]['data_size'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 32, 4));
$atom_structure['sample_description_table'][$i]['frame_count'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 36, 2));
$atom_structure['sample_description_table'][$i]['compressor_name'] = substr($atom_structure['sample_description_table'][$i]['data'], 38, 4);
$atom_structure['sample_description_table'][$i]['pixel_depth'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 42, 2));
$atom_structure['sample_description_table'][$i]['color_table_id'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 44, 2));
switch ($atom_structure['sample_description_table'][$i]['data_format']) {
case '2vuY':
case 'avc1':
case 'cvid':
case 'dvc ':
case 'dvcp':
case 'gif ':
case 'h263':
case 'jpeg':
case 'kpcd':
case 'mjpa':
case 'mjpb':
case 'mp4v':
case 'png ':
case 'raw ':
case 'rle ':
case 'rpza':
case 'smc ':
case 'SVQ1':
case 'SVQ3':
case 'tiff':
case 'v210':
case 'v216':
case 'v308':
case 'v408':
case 'v410':
case 'yuv2':
$info['fileformat'] = 'mp4';
$info['video']['fourcc'] = $atom_structure['sample_description_table'][$i]['data_format'];
// http://www.getid3.org/phpBB3/viewtopic.php?t=1550
//if ((!empty($atom_structure['sample_description_table'][$i]['width']) && !empty($atom_structure['sample_description_table'][$i]['width'])) && (empty($info['video']['resolution_x']) || empty($info['video']['resolution_y']) || (number_format($info['video']['resolution_x'], 6) != number_format(round($info['video']['resolution_x']), 6)) || (number_format($info['video']['resolution_y'], 6) != number_format(round($info['video']['resolution_y']), 6)))) { // ugly check for floating point numbers
if (!empty($atom_structure['sample_description_table'][$i]['width']) && !empty($atom_structure['sample_description_table'][$i]['height'])) {
// assume that values stored here are more important than values stored in [tkhd] atom
$info['video']['resolution_x'] = $atom_structure['sample_description_table'][$i]['width'];
$info['video']['resolution_y'] = $atom_structure['sample_description_table'][$i]['height'];
$info['quicktime']['video']['resolution_x'] = $info['video']['resolution_x'];
$info['quicktime']['video']['resolution_y'] = $info['video']['resolution_y'];
}
break;
case 'qtvr':
$info['video']['dataformat'] = 'quicktimevr';
break;
case 'mp4a':
default:
$info['quicktime']['audio']['codec'] = $this->QuicktimeAudioCodecLookup($atom_structure['sample_description_table'][$i]['data_format']);
$info['quicktime']['audio']['sample_rate'] = $atom_structure['sample_description_table'][$i]['audio_sample_rate'];
$info['quicktime']['audio']['channels'] = $atom_structure['sample_description_table'][$i]['audio_channels'];
$info['quicktime']['audio']['bit_depth'] = $atom_structure['sample_description_table'][$i]['audio_bit_depth'];
$info['audio']['codec'] = $info['quicktime']['audio']['codec'];
$info['audio']['sample_rate'] = $info['quicktime']['audio']['sample_rate'];
$info['audio']['channels'] = $info['quicktime']['audio']['channels'];
$info['audio']['bits_per_sample'] = $info['quicktime']['audio']['bit_depth'];
switch ($atom_structure['sample_description_table'][$i]['data_format']) {
case 'raw ': // PCM
case 'alac': // Apple Lossless Audio Codec
$info['audio']['lossless'] = true;
break;
default:
$info['audio']['lossless'] = false;
break;
}
break;
}
break;
default:
switch ($atom_structure['sample_description_table'][$i]['data_format']) {
case 'mp4s':
$info['fileformat'] = 'mp4';
break;
default:
// video atom
$atom_structure['sample_description_table'][$i]['video_temporal_quality'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 8, 4));
$atom_structure['sample_description_table'][$i]['video_spatial_quality'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 12, 4));
$atom_structure['sample_description_table'][$i]['video_frame_width'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 16, 2));
$atom_structure['sample_description_table'][$i]['video_frame_height'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 18, 2));
$atom_structure['sample_description_table'][$i]['video_resolution_x'] = getid3_lib::FixedPoint16_16(substr($atom_structure['sample_description_table'][$i]['data'], 20, 4));
$atom_structure['sample_description_table'][$i]['video_resolution_y'] = getid3_lib::FixedPoint16_16(substr($atom_structure['sample_description_table'][$i]['data'], 24, 4));
$atom_structure['sample_description_table'][$i]['video_data_size'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 28, 4));
$atom_structure['sample_description_table'][$i]['video_frame_count'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 32, 2));
$atom_structure['sample_description_table'][$i]['video_encoder_name_len'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 34, 1));
$atom_structure['sample_description_table'][$i]['video_encoder_name'] = substr($atom_structure['sample_description_table'][$i]['data'], 35, $atom_structure['sample_description_table'][$i]['video_encoder_name_len']);
$atom_structure['sample_description_table'][$i]['video_pixel_color_depth'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 66, 2));
$atom_structure['sample_description_table'][$i]['video_color_table_id'] = getid3_lib::BigEndian2Int(substr($atom_structure['sample_description_table'][$i]['data'], 68, 2));
$atom_structure['sample_description_table'][$i]['video_pixel_color_type'] = (($atom_structure['sample_description_table'][$i]['video_pixel_color_depth'] > 32) ? 'grayscale' : 'color');
$atom_structure['sample_description_table'][$i]['video_pixel_color_name'] = $this->QuicktimeColorNameLookup($atom_structure['sample_description_table'][$i]['video_pixel_color_depth']);
if ($atom_structure['sample_description_table'][$i]['video_pixel_color_name'] != 'invalid') {
$info['quicktime']['video']['codec_fourcc'] = $atom_structure['sample_description_table'][$i]['data_format'];
$info['quicktime']['video']['codec_fourcc_lookup'] = $this->QuicktimeVideoCodecLookup($atom_structure['sample_description_table'][$i]['data_format']);
$info['quicktime']['video']['codec'] = (($atom_structure['sample_description_table'][$i]['video_encoder_name_len'] > 0) ? $atom_structure['sample_description_table'][$i]['video_encoder_name'] : $atom_structure['sample_description_table'][$i]['data_format']);
$info['quicktime']['video']['color_depth'] = $atom_structure['sample_description_table'][$i]['video_pixel_color_depth'];
$info['quicktime']['video']['color_depth_name'] = $atom_structure['sample_description_table'][$i]['video_pixel_color_name'];
$info['video']['codec'] = $info['quicktime']['video']['codec'];
$info['video']['bits_per_sample'] = $info['quicktime']['video']['color_depth'];
}
$info['video']['lossless'] = false;
$info['video']['pixel_aspect_ratio'] = (float) 1;
break;
}
break;
}
switch (strtolower($atom_structure['sample_description_table'][$i]['data_format'])) {
case 'mp4a':
$info['audio']['dataformat'] = 'mp4';
$info['quicktime']['audio']['codec'] = 'mp4';
break;
case '3ivx':
case '3iv1':
case '3iv2':
$info['video']['dataformat'] = '3ivx';
break;
case 'xvid':
$info['video']['dataformat'] = 'xvid';
break;
case 'mp4v':
$info['video']['dataformat'] = 'mpeg4';
break;
case 'divx':
case 'div1':
case 'div2':
case 'div3':
case 'div4':
case 'div5':
case 'div6':
$info['video']['dataformat'] = 'divx';
break;
default:
// do nothing
break;
}
unset($atom_structure['sample_description_table'][$i]['data']);
}
break;
case 'stts': // Sample Table Time-to-Sample atom
$atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1));
$atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); // hardcoded: 0x0000
$atom_structure['number_entries'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 4));
$sttsEntriesDataOffset = 8;
//$FrameRateCalculatorArray = array();
$frames_count = 0;
for ($i = 0; $i < $atom_structure['number_entries']; $i++) {
$atom_structure['time_to_sample_table'][$i]['sample_count'] = getid3_lib::BigEndian2Int(substr($atom_data, $sttsEntriesDataOffset, 4));
$sttsEntriesDataOffset += 4;
$atom_structure['time_to_sample_table'][$i]['sample_duration'] = getid3_lib::BigEndian2Int(substr($atom_data, $sttsEntriesDataOffset, 4));
$sttsEntriesDataOffset += 4;
$frames_count += $atom_structure['time_to_sample_table'][$i]['sample_count'];
// THIS SECTION REPLACED WITH CODE IN "stbl" ATOM
//if (!empty($info['quicktime']['time_scale']) && ($atom_structure['time_to_sample_table'][$i]['sample_duration'] > 0)) {
// $stts_new_framerate = $info['quicktime']['time_scale'] / $atom_structure['time_to_sample_table'][$i]['sample_duration'];
// if ($stts_new_framerate <= 60) {
// // some atoms have durations of "1" giving a very large framerate, which probably is not right
// $info['video']['frame_rate'] = max($info['video']['frame_rate'], $stts_new_framerate);
// }
//}
//
//$FrameRateCalculatorArray[($info['quicktime']['time_scale'] / $atom_structure['time_to_sample_table'][$i]['sample_duration'])] += $atom_structure['time_to_sample_table'][$i]['sample_count'];
}
$info['quicktime']['stts_framecount'][] = $frames_count;
//$sttsFramesTotal = 0;
//$sttsSecondsTotal = 0;
//foreach ($FrameRateCalculatorArray as $frames_per_second => $frame_count) {
// if (($frames_per_second > 60) || ($frames_per_second < 1)) {
// // not video FPS information, probably audio information
// $sttsFramesTotal = 0;
// $sttsSecondsTotal = 0;
// break;
// }
// $sttsFramesTotal += $frame_count;
// $sttsSecondsTotal += $frame_count / $frames_per_second;
//}
//if (($sttsFramesTotal > 0) && ($sttsSecondsTotal > 0)) {
// if (($sttsFramesTotal / $sttsSecondsTotal) > $info['video']['frame_rate']) {
// $info['video']['frame_rate'] = $sttsFramesTotal / $sttsSecondsTotal;
// }
//}
break;
case 'stss': // Sample Table Sync Sample (key frames) atom
if ($ParseAllPossibleAtoms) {
$atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1));
$atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); // hardcoded: 0x0000
$atom_structure['number_entries'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 4));
$stssEntriesDataOffset = 8;
for ($i = 0; $i < $atom_structure['number_entries']; $i++) {
$atom_structure['time_to_sample_table'][$i] = getid3_lib::BigEndian2Int(substr($atom_data, $stssEntriesDataOffset, 4));
$stssEntriesDataOffset += 4;
}
}
break;
case 'stsc': // Sample Table Sample-to-Chunk atom
if ($ParseAllPossibleAtoms) {
$atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1));
$atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); // hardcoded: 0x0000
$atom_structure['number_entries'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 4));
$stscEntriesDataOffset = 8;
for ($i = 0; $i < $atom_structure['number_entries']; $i++) {
$atom_structure['sample_to_chunk_table'][$i]['first_chunk'] = getid3_lib::BigEndian2Int(substr($atom_data, $stscEntriesDataOffset, 4));
$stscEntriesDataOffset += 4;
$atom_structure['sample_to_chunk_table'][$i]['samples_per_chunk'] = getid3_lib::BigEndian2Int(substr($atom_data, $stscEntriesDataOffset, 4));
$stscEntriesDataOffset += 4;
$atom_structure['sample_to_chunk_table'][$i]['sample_description'] = getid3_lib::BigEndian2Int(substr($atom_data, $stscEntriesDataOffset, 4));
$stscEntriesDataOffset += 4;
}
}
break;
case 'stsz': // Sample Table SiZe atom
if ($ParseAllPossibleAtoms) {
$atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1));
$atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); // hardcoded: 0x0000
$atom_structure['sample_size'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 4));
$atom_structure['number_entries'] = getid3_lib::BigEndian2Int(substr($atom_data, 8, 4));
$stszEntriesDataOffset = 12;
if ($atom_structure['sample_size'] == 0) {
for ($i = 0; $i < $atom_structure['number_entries']; $i++) {
$atom_structure['sample_size_table'][$i] = getid3_lib::BigEndian2Int(substr($atom_data, $stszEntriesDataOffset, 4));
$stszEntriesDataOffset += 4;
}
}
}
break;
case 'stco': // Sample Table Chunk Offset atom
if ($ParseAllPossibleAtoms) {
$atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1));
$atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); // hardcoded: 0x0000
$atom_structure['number_entries'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 4));
$stcoEntriesDataOffset = 8;
for ($i = 0; $i < $atom_structure['number_entries']; $i++) {
$atom_structure['chunk_offset_table'][$i] = getid3_lib::BigEndian2Int(substr($atom_data, $stcoEntriesDataOffset, 4));
$stcoEntriesDataOffset += 4;
}
}
break;
case 'co64': // Chunk Offset 64-bit (version of "stco" that supports > 2GB files)
if ($ParseAllPossibleAtoms) {
$atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1));
$atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); // hardcoded: 0x0000
$atom_structure['number_entries'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 4));
$stcoEntriesDataOffset = 8;
for ($i = 0; $i < $atom_structure['number_entries']; $i++) {
$atom_structure['chunk_offset_table'][$i] = getid3_lib::BigEndian2Int(substr($atom_data, $stcoEntriesDataOffset, 8));
$stcoEntriesDataOffset += 8;
}
}
break;
case 'dref': // Data REFerence atom
$atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1));
$atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); // hardcoded: 0x0000
$atom_structure['number_entries'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 4));
$drefDataOffset = 8;
for ($i = 0; $i < $atom_structure['number_entries']; $i++) {
$atom_structure['data_references'][$i]['size'] = getid3_lib::BigEndian2Int(substr($atom_data, $drefDataOffset, 4));
$drefDataOffset += 4;
$atom_structure['data_references'][$i]['type'] = substr($atom_data, $drefDataOffset, 4);
$drefDataOffset += 4;
$atom_structure['data_references'][$i]['version'] = getid3_lib::BigEndian2Int(substr($atom_data, $drefDataOffset, 1));
$drefDataOffset += 1;
$atom_structure['data_references'][$i]['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, $drefDataOffset, 3)); // hardcoded: 0x0000
$drefDataOffset += 3;
$atom_structure['data_references'][$i]['data'] = substr($atom_data, $drefDataOffset, ($atom_structure['data_references'][$i]['size'] - 4 - 4 - 1 - 3));
$drefDataOffset += ($atom_structure['data_references'][$i]['size'] - 4 - 4 - 1 - 3);
$atom_structure['data_references'][$i]['flags']['self_reference'] = (bool) ($atom_structure['data_references'][$i]['flags_raw'] & 0x001);
}
break;
case 'gmin': // base Media INformation atom
$atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1));
$atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); // hardcoded: 0x0000
$atom_structure['graphics_mode'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 2));
$atom_structure['opcolor_red'] = getid3_lib::BigEndian2Int(substr($atom_data, 6, 2));
$atom_structure['opcolor_green'] = getid3_lib::BigEndian2Int(substr($atom_data, 8, 2));
$atom_structure['opcolor_blue'] = getid3_lib::BigEndian2Int(substr($atom_data, 10, 2));
$atom_structure['balance'] = getid3_lib::BigEndian2Int(substr($atom_data, 12, 2));
$atom_structure['reserved'] = getid3_lib::BigEndian2Int(substr($atom_data, 14, 2));
break;
case 'smhd': // Sound Media information HeaDer atom
$atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1));
$atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); // hardcoded: 0x0000
$atom_structure['balance'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 2));
$atom_structure['reserved'] = getid3_lib::BigEndian2Int(substr($atom_data, 6, 2));
break;
case 'vmhd': // Video Media information HeaDer atom
$atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1));
$atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3));
$atom_structure['graphics_mode'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 2));
$atom_structure['opcolor_red'] = getid3_lib::BigEndian2Int(substr($atom_data, 6, 2));
$atom_structure['opcolor_green'] = getid3_lib::BigEndian2Int(substr($atom_data, 8, 2));
$atom_structure['opcolor_blue'] = getid3_lib::BigEndian2Int(substr($atom_data, 10, 2));
$atom_structure['flags']['no_lean_ahead'] = (bool) ($atom_structure['flags_raw'] & 0x001);
break;
case 'hdlr': // HanDLeR reference atom
$atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1));
$atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); // hardcoded: 0x0000
$atom_structure['component_type'] = substr($atom_data, 4, 4);
$atom_structure['component_subtype'] = substr($atom_data, 8, 4);
$atom_structure['component_manufacturer'] = substr($atom_data, 12, 4);
$atom_structure['component_flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 16, 4));
$atom_structure['component_flags_mask'] = getid3_lib::BigEndian2Int(substr($atom_data, 20, 4));
$atom_structure['component_name'] = $this->Pascal2String(substr($atom_data, 24));
if (($atom_structure['component_subtype'] == 'STpn') && ($atom_structure['component_manufacturer'] == 'zzzz')) {
$info['video']['dataformat'] = 'quicktimevr';
}
break;
case 'mdhd': // MeDia HeaDer atom
$atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1));
$atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); // hardcoded: 0x0000
$atom_structure['creation_time'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 4));
$atom_structure['modify_time'] = getid3_lib::BigEndian2Int(substr($atom_data, 8, 4));
$atom_structure['time_scale'] = getid3_lib::BigEndian2Int(substr($atom_data, 12, 4));
$atom_structure['duration'] = getid3_lib::BigEndian2Int(substr($atom_data, 16, 4));
$atom_structure['language_id'] = getid3_lib::BigEndian2Int(substr($atom_data, 20, 2));
$atom_structure['quality'] = getid3_lib::BigEndian2Int(substr($atom_data, 22, 2));
if ($atom_structure['time_scale'] == 0) {
$info['error'][] = 'Corrupt Quicktime file: mdhd.time_scale == zero';
return false;
}
$info['quicktime']['time_scale'] = (isset($info['quicktime']['time_scale']) ? max($info['quicktime']['time_scale'], $atom_structure['time_scale']) : $atom_structure['time_scale']);
$atom_structure['creation_time_unix'] = getid3_lib::DateMac2Unix($atom_structure['creation_time']);
$atom_structure['modify_time_unix'] = getid3_lib::DateMac2Unix($atom_structure['modify_time']);
$atom_structure['playtime_seconds'] = $atom_structure['duration'] / $atom_structure['time_scale'];
$atom_structure['language'] = $this->QuicktimeLanguageLookup($atom_structure['language_id']);
if (empty($info['comments']['language']) || (!in_array($atom_structure['language'], $info['comments']['language']))) {
$info['comments']['language'][] = $atom_structure['language'];
}
break;
case 'pnot': // Preview atom
$atom_structure['modification_date'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 4)); // "standard Macintosh format"
$atom_structure['version_number'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 2)); // hardcoded: 0x00
$atom_structure['atom_type'] = substr($atom_data, 6, 4); // usually: 'PICT'
$atom_structure['atom_index'] = getid3_lib::BigEndian2Int(substr($atom_data, 10, 2)); // usually: 0x01
$atom_structure['modification_date_unix'] = getid3_lib::DateMac2Unix($atom_structure['modification_date']);
break;
case 'crgn': // Clipping ReGioN atom
$atom_structure['region_size'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 2)); // The Region size, Region boundary box,
$atom_structure['boundary_box'] = getid3_lib::BigEndian2Int(substr($atom_data, 2, 8)); // and Clipping region data fields
$atom_structure['clipping_data'] = substr($atom_data, 10); // constitute a QuickDraw region.
break;
case 'load': // track LOAD settings atom
$atom_structure['preload_start_time'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 4));
$atom_structure['preload_duration'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 4));
$atom_structure['preload_flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 8, 4));
$atom_structure['default_hints_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 12, 4));
$atom_structure['default_hints']['double_buffer'] = (bool) ($atom_structure['default_hints_raw'] & 0x0020);
$atom_structure['default_hints']['high_quality'] = (bool) ($atom_structure['default_hints_raw'] & 0x0100);
break;
case 'tmcd': // TiMe CoDe atom
case 'chap': // CHAPter list atom
case 'sync': // SYNChronization atom
case 'scpt': // tranSCriPT atom
case 'ssrc': // non-primary SouRCe atom
for ($i = 0; $i < (strlen($atom_data) % 4); $i++) {
$atom_structure['track_id'][$i] = getid3_lib::BigEndian2Int(substr($atom_data, $i * 4, 4));
}
break;
case 'elst': // Edit LiST atom
$atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1));
$atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); // hardcoded: 0x0000
$atom_structure['number_entries'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 4));
for ($i = 0; $i < $atom_structure['number_entries']; $i++ ) {
$atom_structure['edit_list'][$i]['track_duration'] = getid3_lib::BigEndian2Int(substr($atom_data, 8 + ($i * 12) + 0, 4));
$atom_structure['edit_list'][$i]['media_time'] = getid3_lib::BigEndian2Int(substr($atom_data, 8 + ($i * 12) + 4, 4));
$atom_structure['edit_list'][$i]['media_rate'] = getid3_lib::FixedPoint16_16(substr($atom_data, 8 + ($i * 12) + 8, 4));
}
break;
case 'kmat': // compressed MATte atom
$atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1));
$atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3)); // hardcoded: 0x0000
$atom_structure['matte_data_raw'] = substr($atom_data, 4);
break;
case 'ctab': // Color TABle atom
$atom_structure['color_table_seed'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 4)); // hardcoded: 0x00000000
$atom_structure['color_table_flags'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 2)); // hardcoded: 0x8000
$atom_structure['color_table_size'] = getid3_lib::BigEndian2Int(substr($atom_data, 6, 2)) + 1;
for ($colortableentry = 0; $colortableentry < $atom_structure['color_table_size']; $colortableentry++) {
$atom_structure['color_table'][$colortableentry]['alpha'] = getid3_lib::BigEndian2Int(substr($atom_data, 8 + ($colortableentry * 8) + 0, 2));
$atom_structure['color_table'][$colortableentry]['red'] = getid3_lib::BigEndian2Int(substr($atom_data, 8 + ($colortableentry * 8) + 2, 2));
$atom_structure['color_table'][$colortableentry]['green'] = getid3_lib::BigEndian2Int(substr($atom_data, 8 + ($colortableentry * 8) + 4, 2));
$atom_structure['color_table'][$colortableentry]['blue'] = getid3_lib::BigEndian2Int(substr($atom_data, 8 + ($colortableentry * 8) + 6, 2));
}
break;
case 'mvhd': // MoVie HeaDer atom
$atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1));
$atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3));
$atom_structure['creation_time'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 4));
$atom_structure['modify_time'] = getid3_lib::BigEndian2Int(substr($atom_data, 8, 4));
$atom_structure['time_scale'] = getid3_lib::BigEndian2Int(substr($atom_data, 12, 4));
$atom_structure['duration'] = getid3_lib::BigEndian2Int(substr($atom_data, 16, 4));
$atom_structure['preferred_rate'] = getid3_lib::FixedPoint16_16(substr($atom_data, 20, 4));
$atom_structure['preferred_volume'] = getid3_lib::FixedPoint8_8(substr($atom_data, 24, 2));
$atom_structure['reserved'] = substr($atom_data, 26, 10);
$atom_structure['matrix_a'] = getid3_lib::FixedPoint16_16(substr($atom_data, 36, 4));
$atom_structure['matrix_b'] = getid3_lib::FixedPoint16_16(substr($atom_data, 40, 4));
$atom_structure['matrix_u'] = getid3_lib::FixedPoint2_30(substr($atom_data, 44, 4));
$atom_structure['matrix_c'] = getid3_lib::FixedPoint16_16(substr($atom_data, 48, 4));
$atom_structure['matrix_d'] = getid3_lib::FixedPoint16_16(substr($atom_data, 52, 4));
$atom_structure['matrix_v'] = getid3_lib::FixedPoint2_30(substr($atom_data, 56, 4));
$atom_structure['matrix_x'] = getid3_lib::FixedPoint16_16(substr($atom_data, 60, 4));
$atom_structure['matrix_y'] = getid3_lib::FixedPoint16_16(substr($atom_data, 64, 4));
$atom_structure['matrix_w'] = getid3_lib::FixedPoint2_30(substr($atom_data, 68, 4));
$atom_structure['preview_time'] = getid3_lib::BigEndian2Int(substr($atom_data, 72, 4));
$atom_structure['preview_duration'] = getid3_lib::BigEndian2Int(substr($atom_data, 76, 4));
$atom_structure['poster_time'] = getid3_lib::BigEndian2Int(substr($atom_data, 80, 4));
$atom_structure['selection_time'] = getid3_lib::BigEndian2Int(substr($atom_data, 84, 4));
$atom_structure['selection_duration'] = getid3_lib::BigEndian2Int(substr($atom_data, 88, 4));
$atom_structure['current_time'] = getid3_lib::BigEndian2Int(substr($atom_data, 92, 4));
$atom_structure['next_track_id'] = getid3_lib::BigEndian2Int(substr($atom_data, 96, 4));
if ($atom_structure['time_scale'] == 0) {
$info['error'][] = 'Corrupt Quicktime file: mvhd.time_scale == zero';
return false;
}
$atom_structure['creation_time_unix'] = getid3_lib::DateMac2Unix($atom_structure['creation_time']);
$atom_structure['modify_time_unix'] = getid3_lib::DateMac2Unix($atom_structure['modify_time']);
$info['quicktime']['time_scale'] = (isset($info['quicktime']['time_scale']) ? max($info['quicktime']['time_scale'], $atom_structure['time_scale']) : $atom_structure['time_scale']);
$info['quicktime']['display_scale'] = $atom_structure['matrix_a'];
$info['playtime_seconds'] = $atom_structure['duration'] / $atom_structure['time_scale'];
break;
case 'tkhd': // TracK HeaDer atom
$atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1));
$atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3));
$atom_structure['creation_time'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 4));
$atom_structure['modify_time'] = getid3_lib::BigEndian2Int(substr($atom_data, 8, 4));
$atom_structure['trackid'] = getid3_lib::BigEndian2Int(substr($atom_data, 12, 4));
$atom_structure['reserved1'] = getid3_lib::BigEndian2Int(substr($atom_data, 16, 4));
$atom_structure['duration'] = getid3_lib::BigEndian2Int(substr($atom_data, 20, 4));
$atom_structure['reserved2'] = getid3_lib::BigEndian2Int(substr($atom_data, 24, 8));
$atom_structure['layer'] = getid3_lib::BigEndian2Int(substr($atom_data, 32, 2));
$atom_structure['alternate_group'] = getid3_lib::BigEndian2Int(substr($atom_data, 34, 2));
$atom_structure['volume'] = getid3_lib::FixedPoint8_8(substr($atom_data, 36, 2));
$atom_structure['reserved3'] = getid3_lib::BigEndian2Int(substr($atom_data, 38, 2));
// http://developer.apple.com/library/mac/#documentation/QuickTime/RM/MovieBasics/MTEditing/K-Chapter/11MatrixFunctions.html
// http://developer.apple.com/library/mac/#documentation/QuickTime/qtff/QTFFChap4/qtff4.html#//apple_ref/doc/uid/TP40000939-CH206-18737
$atom_structure['matrix_a'] = getid3_lib::FixedPoint16_16(substr($atom_data, 40, 4));
$atom_structure['matrix_b'] = getid3_lib::FixedPoint16_16(substr($atom_data, 44, 4));
$atom_structure['matrix_u'] = getid3_lib::FixedPoint2_30(substr($atom_data, 48, 4));
$atom_structure['matrix_c'] = getid3_lib::FixedPoint16_16(substr($atom_data, 52, 4));
$atom_structure['matrix_d'] = getid3_lib::FixedPoint16_16(substr($atom_data, 56, 4));
$atom_structure['matrix_v'] = getid3_lib::FixedPoint2_30(substr($atom_data, 60, 4));
$atom_structure['matrix_x'] = getid3_lib::FixedPoint16_16(substr($atom_data, 64, 4));
$atom_structure['matrix_y'] = getid3_lib::FixedPoint16_16(substr($atom_data, 68, 4));
$atom_structure['matrix_w'] = getid3_lib::FixedPoint2_30(substr($atom_data, 72, 4));
$atom_structure['width'] = getid3_lib::FixedPoint16_16(substr($atom_data, 76, 4));
$atom_structure['height'] = getid3_lib::FixedPoint16_16(substr($atom_data, 80, 4));
$atom_structure['flags']['enabled'] = (bool) ($atom_structure['flags_raw'] & 0x0001);
$atom_structure['flags']['in_movie'] = (bool) ($atom_structure['flags_raw'] & 0x0002);
$atom_structure['flags']['in_preview'] = (bool) ($atom_structure['flags_raw'] & 0x0004);
$atom_structure['flags']['in_poster'] = (bool) ($atom_structure['flags_raw'] & 0x0008);
$atom_structure['creation_time_unix'] = getid3_lib::DateMac2Unix($atom_structure['creation_time']);
$atom_structure['modify_time_unix'] = getid3_lib::DateMac2Unix($atom_structure['modify_time']);
if ($atom_structure['flags']['enabled'] == 1) {
if (!isset($info['video']['resolution_x']) || !isset($info['video']['resolution_y'])) {
$info['video']['resolution_x'] = $atom_structure['width'];
$info['video']['resolution_y'] = $atom_structure['height'];
}
$info['video']['resolution_x'] = max($info['video']['resolution_x'], $atom_structure['width']);
$info['video']['resolution_y'] = max($info['video']['resolution_y'], $atom_structure['height']);
$info['quicktime']['video']['resolution_x'] = $info['video']['resolution_x'];
$info['quicktime']['video']['resolution_y'] = $info['video']['resolution_y'];
} else {
// see: http://www.getid3.org/phpBB3/viewtopic.php?t=1295
//if (isset($info['video']['resolution_x'])) { unset($info['video']['resolution_x']); }
//if (isset($info['video']['resolution_y'])) { unset($info['video']['resolution_y']); }
//if (isset($info['quicktime']['video'])) { unset($info['quicktime']['video']); }
}
break;
case 'iods': // Initial Object DeScriptor atom
// http://www.koders.com/c/fid1FAB3E762903DC482D8A246D4A4BF9F28E049594.aspx?s=windows.h
// http://libquicktime.sourcearchive.com/documentation/1.0.2plus-pdebian/iods_8c-source.html
$offset = 0;
$atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, $offset, 1));
$offset += 1;
$atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, $offset, 3));
$offset += 3;
$atom_structure['mp4_iod_tag'] = getid3_lib::BigEndian2Int(substr($atom_data, $offset, 1));
$offset += 1;
$atom_structure['length'] = $this->quicktime_read_mp4_descr_length($atom_data, $offset);
//$offset already adjusted by quicktime_read_mp4_descr_length()
$atom_structure['object_descriptor_id'] = getid3_lib::BigEndian2Int(substr($atom_data, $offset, 2));
$offset += 2;
$atom_structure['od_profile_level'] = getid3_lib::BigEndian2Int(substr($atom_data, $offset, 1));
$offset += 1;
$atom_structure['scene_profile_level'] = getid3_lib::BigEndian2Int(substr($atom_data, $offset, 1));
$offset += 1;
$atom_structure['audio_profile_id'] = getid3_lib::BigEndian2Int(substr($atom_data, $offset, 1));
$offset += 1;
$atom_structure['video_profile_id'] = getid3_lib::BigEndian2Int(substr($atom_data, $offset, 1));
$offset += 1;
$atom_structure['graphics_profile_level'] = getid3_lib::BigEndian2Int(substr($atom_data, $offset, 1));
$offset += 1;
$atom_structure['num_iods_tracks'] = ($atom_structure['length'] - 7) / 6; // 6 bytes would only be right if all tracks use 1-byte length fields
for ($i = 0; $i < $atom_structure['num_iods_tracks']; $i++) {
$atom_structure['track'][$i]['ES_ID_IncTag'] = getid3_lib::BigEndian2Int(substr($atom_data, $offset, 1));
$offset += 1;
$atom_structure['track'][$i]['length'] = $this->quicktime_read_mp4_descr_length($atom_data, $offset);
//$offset already adjusted by quicktime_read_mp4_descr_length()
$atom_structure['track'][$i]['track_id'] = getid3_lib::BigEndian2Int(substr($atom_data, $offset, 4));
$offset += 4;
}
$atom_structure['audio_profile_name'] = $this->QuicktimeIODSaudioProfileName($atom_structure['audio_profile_id']);
$atom_structure['video_profile_name'] = $this->QuicktimeIODSvideoProfileName($atom_structure['video_profile_id']);
break;
case 'ftyp': // FileTYPe (?) atom (for MP4 it seems)
$atom_structure['signature'] = substr($atom_data, 0, 4);
$atom_structure['unknown_1'] = getid3_lib::BigEndian2Int(substr($atom_data, 4, 4));
$atom_structure['fourcc'] = substr($atom_data, 8, 4);
break;
case 'mdat': // Media DATa atom
case 'free': // FREE space atom
case 'skip': // SKIP atom
case 'wide': // 64-bit expansion placeholder atom
// 'mdat' data is too big to deal with, contains no useful metadata
// 'free', 'skip' and 'wide' are just padding, contains no useful data at all
// When writing QuickTime files, it is sometimes necessary to update an atom's size.
// It is impossible to update a 32-bit atom to a 64-bit atom since the 32-bit atom
// is only 8 bytes in size, and the 64-bit atom requires 16 bytes. Therefore, QuickTime
// puts an 8-byte placeholder atom before any atoms it may have to update the size of.
// In this way, if the atom needs to be converted from a 32-bit to a 64-bit atom, the
// placeholder atom can be overwritten to obtain the necessary 8 extra bytes.
// The placeholder atom has a type of kWideAtomPlaceholderType ( 'wide' ).
break;
case 'nsav': // NoSAVe atom
// http://developer.apple.com/technotes/tn/tn2038.html
$atom_structure['data'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 4));
break;
case 'ctyp': // Controller TYPe atom (seen on QTVR)
// http://homepages.slingshot.co.nz/~helmboy/quicktime/formats/qtm-layout.txt
// some controller names are:
// 0x00 + 'std' for linear movie
// 'none' for no controls
$atom_structure['ctyp'] = substr($atom_data, 0, 4);
$info['quicktime']['controller'] = $atom_structure['ctyp'];
switch ($atom_structure['ctyp']) {
case 'qtvr':
$info['video']['dataformat'] = 'quicktimevr';
break;
}
break;
case 'pano': // PANOrama track (seen on QTVR)
$atom_structure['pano'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 4));
break;
case 'hint': // HINT track
case 'hinf': //
case 'hinv': //
case 'hnti': //
$info['quicktime']['hinting'] = true;
break;
case 'imgt': // IMaGe Track reference (kQTVRImageTrackRefType) (seen on QTVR)
for ($i = 0; $i < ($atom_structure['size'] - 8); $i += 4) {
$atom_structure['imgt'][] = getid3_lib::BigEndian2Int(substr($atom_data, $i, 4));
}
break;
// Observed-but-not-handled atom types are just listed here to prevent warnings being generated
case 'FXTC': // Something to do with Adobe After Effects (?)
case 'PrmA':
case 'code':
case 'FIEL': // this is NOT "fiel" (Field Ordering) as describe here: http://developer.apple.com/documentation/QuickTime/QTFF/QTFFChap3/chapter_4_section_2.html
case 'tapt': // TrackApertureModeDimensionsAID - http://developer.apple.com/documentation/QuickTime/Reference/QT7-1_Update_Reference/Constants/Constants.html
// tapt seems to be used to compute the video size [http://www.getid3.org/phpBB3/viewtopic.php?t=838]
// * http://lists.apple.com/archives/quicktime-api/2006/Aug/msg00014.html
// * http://handbrake.fr/irclogs/handbrake-dev/handbrake-dev20080128_pg2.html
case 'ctts':// STCompositionOffsetAID - http://developer.apple.com/documentation/QuickTime/Reference/QTRef_Constants/Reference/reference.html
case 'cslg':// STCompositionShiftLeastGreatestAID - http://developer.apple.com/documentation/QuickTime/Reference/QTRef_Constants/Reference/reference.html
case 'sdtp':// STSampleDependencyAID - http://developer.apple.com/documentation/QuickTime/Reference/QTRef_Constants/Reference/reference.html
case 'stps':// STPartialSyncSampleAID - http://developer.apple.com/documentation/QuickTime/Reference/QTRef_Constants/Reference/reference.html
//$atom_structure['data'] = $atom_data;
break;
case '©xyz': // GPS latitude+longitude+altitude
$atom_structure['data'] = $atom_data;
if (preg_match('#([\\+\\-][0-9\\.]+)([\\+\\-][0-9\\.]+)([\\+\\-][0-9\\.]+)?/$#i', $atom_data, $matches)) {
@list($all, $latitude, $longitude, $altitude) = $matches;
$info['quicktime']['comments']['gps_latitude'][] = floatval($latitude);
$info['quicktime']['comments']['gps_longitude'][] = floatval($longitude);
if (!empty($altitude)) {
$info['quicktime']['comments']['gps_altitude'][] = floatval($altitude);
}
} else {
$info['warning'][] = 'QuickTime atom "©xyz" data does not match expected data pattern at offset '.$baseoffset.'. Please report as getID3() bug.';
}
break;
case 'NCDT':
// http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/Nikon.html
// Nikon-specific QuickTime tags found in the NCDT atom of MOV videos from some Nikon cameras such as the Coolpix S8000 and D5100
$atom_structure['subatoms'] = $this->QuicktimeParseContainerAtom($atom_data, $baseoffset + 4, $atomHierarchy, $ParseAllPossibleAtoms);
break;
case 'NCTH': // Nikon Camera THumbnail image
case 'NCVW': // Nikon Camera preVieW image
// http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/Nikon.html
if (preg_match('/^\xFF\xD8\xFF/', $atom_data)) {
$atom_structure['data'] = $atom_data;
$atom_structure['image_mime'] = 'image/jpeg';
$atom_structure['description'] = (($atomname == 'NCTH') ? 'Nikon Camera Thumbnail Image' : (($atomname == 'NCVW') ? 'Nikon Camera Preview Image' : 'Nikon preview image'));
$info['quicktime']['comments']['picture'][] = array('image_mime'=>$atom_structure['image_mime'], 'data'=>$atom_data, 'description'=>$atom_structure['description']);
}
break;
case 'NCHD': // MakerNoteVersion
// http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/Nikon.html
$atom_structure['data'] = $atom_data;
break;
case 'NCTG': // NikonTags
// http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/Nikon.html#NCTG
$atom_structure['data'] = $this->QuicktimeParseNikonNCTG($atom_data);
break;
case 'NCDB': // NikonTags
// http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/Nikon.html
$atom_structure['data'] = $atom_data;
break;
case "\x00\x00\x00\x00":
case 'meta': // METAdata atom
// some kind of metacontainer, may contain a big data dump such as:
// mdta keys mdtacom.apple.quicktime.make (mdtacom.apple.quicktime.creationdate ,mdtacom.apple.quicktime.location.ISO6709 $mdtacom.apple.quicktime.software !mdtacom.apple.quicktime.model ilst data DEApple 0 (data DE2011-05-11T17:54:04+0200 2 *data DE+52.4936+013.3897+040.247/ data DE4.3.1 data DEiPhone 4
// http://www.geocities.com/xhelmboyx/quicktime/formats/qti-layout.txt
$atom_structure['version'] = getid3_lib::BigEndian2Int(substr($atom_data, 0, 1));
$atom_structure['flags_raw'] = getid3_lib::BigEndian2Int(substr($atom_data, 1, 3));
$atom_structure['subatoms'] = $this->QuicktimeParseContainerAtom(substr($atom_data, 4), $baseoffset + 8, $atomHierarchy, $ParseAllPossibleAtoms);
//$atom_structure['subatoms'] = $this->QuicktimeParseContainerAtom($atom_data, $baseoffset + 8, $atomHierarchy, $ParseAllPossibleAtoms);
break;
case 'data': // metaDATA atom
// seems to be 2 bytes language code (ASCII), 2 bytes unknown (set to 0x10B5 in sample I have), remainder is useful data
$atom_structure['language'] = substr($atom_data, 4 + 0, 2);
$atom_structure['unknown'] = getid3_lib::BigEndian2Int(substr($atom_data, 4 + 2, 2));
$atom_structure['data'] = substr($atom_data, 4 + 4);
break;
default:
$info['warning'][] = 'Unknown QuickTime atom type: "'.$atomname.'" ('.trim(getid3_lib::PrintHexBytes($atomname)).') at offset '.$baseoffset;
$atom_structure['data'] = $atom_data;
break;
}
array_pop($atomHierarchy);
return $atom_structure;
}
public function QuicktimeParseContainerAtom($atom_data, $baseoffset, &$atomHierarchy, $ParseAllPossibleAtoms) {
//echo 'QuicktimeParseContainerAtom('.substr($atom_data, 4, 4).') @ '.$baseoffset.'<br><br>';
$atom_structure = false;
$subatomoffset = 0;
$subatomcounter = 0;
if ((strlen($atom_data) == 4) && (getid3_lib::BigEndian2Int($atom_data) == 0x00000000)) {
return false;
}
while ($subatomoffset < strlen($atom_data)) {
$subatomsize = getid3_lib::BigEndian2Int(substr($atom_data, $subatomoffset + 0, 4));
$subatomname = substr($atom_data, $subatomoffset + 4, 4);
$subatomdata = substr($atom_data, $subatomoffset + 8, $subatomsize - 8);
if ($subatomsize == 0) {
// Furthermore, for historical reasons the list of atoms is optionally
// terminated by a 32-bit integer set to 0. If you are writing a program
// to read user data atoms, you should allow for the terminating 0.
return $atom_structure;
}
$atom_structure[$subatomcounter] = $this->QuicktimeParseAtom($subatomname, $subatomsize, $subatomdata, $baseoffset + $subatomoffset, $atomHierarchy, $ParseAllPossibleAtoms);
$subatomoffset += $subatomsize;
$subatomcounter++;
}
return $atom_structure;
}
public function quicktime_read_mp4_descr_length($data, &$offset) {
// http://libquicktime.sourcearchive.com/documentation/2:1.0.2plus-pdebian-2build1/esds_8c-source.html
$num_bytes = 0;
$length = 0;
do {
$b = ord(substr($data, $offset++, 1));
$length = ($length << 7) | ($b & 0x7F);
} while (($b & 0x80) && ($num_bytes++ < 4));
return $length;
}
public function QuicktimeLanguageLookup($languageid) {
// http://developer.apple.com/library/mac/#documentation/QuickTime/QTFF/QTFFChap4/qtff4.html#//apple_ref/doc/uid/TP40000939-CH206-34353
static $QuicktimeLanguageLookup = array();
if (empty($QuicktimeLanguageLookup)) {
$QuicktimeLanguageLookup[0] = 'English';
$QuicktimeLanguageLookup[1] = 'French';
$QuicktimeLanguageLookup[2] = 'German';
$QuicktimeLanguageLookup[3] = 'Italian';
$QuicktimeLanguageLookup[4] = 'Dutch';
$QuicktimeLanguageLookup[5] = 'Swedish';
$QuicktimeLanguageLookup[6] = 'Spanish';
$QuicktimeLanguageLookup[7] = 'Danish';
$QuicktimeLanguageLookup[8] = 'Portuguese';
$QuicktimeLanguageLookup[9] = 'Norwegian';
$QuicktimeLanguageLookup[10] = 'Hebrew';
$QuicktimeLanguageLookup[11] = 'Japanese';
$QuicktimeLanguageLookup[12] = 'Arabic';
$QuicktimeLanguageLookup[13] = 'Finnish';
$QuicktimeLanguageLookup[14] = 'Greek';
$QuicktimeLanguageLookup[15] = 'Icelandic';
$QuicktimeLanguageLookup[16] = 'Maltese';
$QuicktimeLanguageLookup[17] = 'Turkish';
$QuicktimeLanguageLookup[18] = 'Croatian';
$QuicktimeLanguageLookup[19] = 'Chinese (Traditional)';
$QuicktimeLanguageLookup[20] = 'Urdu';
$QuicktimeLanguageLookup[21] = 'Hindi';
$QuicktimeLanguageLookup[22] = 'Thai';
$QuicktimeLanguageLookup[23] = 'Korean';
$QuicktimeLanguageLookup[24] = 'Lithuanian';
$QuicktimeLanguageLookup[25] = 'Polish';
$QuicktimeLanguageLookup[26] = 'Hungarian';
$QuicktimeLanguageLookup[27] = 'Estonian';
$QuicktimeLanguageLookup[28] = 'Lettish';
$QuicktimeLanguageLookup[28] = 'Latvian';
$QuicktimeLanguageLookup[29] = 'Saamisk';
$QuicktimeLanguageLookup[29] = 'Lappish';
$QuicktimeLanguageLookup[30] = 'Faeroese';
$QuicktimeLanguageLookup[31] = 'Farsi';
$QuicktimeLanguageLookup[31] = 'Persian';
$QuicktimeLanguageLookup[32] = 'Russian';
$QuicktimeLanguageLookup[33] = 'Chinese (Simplified)';
$QuicktimeLanguageLookup[34] = 'Flemish';
$QuicktimeLanguageLookup[35] = 'Irish';
$QuicktimeLanguageLookup[36] = 'Albanian';
$QuicktimeLanguageLookup[37] = 'Romanian';
$QuicktimeLanguageLookup[38] = 'Czech';
$QuicktimeLanguageLookup[39] = 'Slovak';
$QuicktimeLanguageLookup[40] = 'Slovenian';
$QuicktimeLanguageLookup[41] = 'Yiddish';
$QuicktimeLanguageLookup[42] = 'Serbian';
$QuicktimeLanguageLookup[43] = 'Macedonian';
$QuicktimeLanguageLookup[44] = 'Bulgarian';
$QuicktimeLanguageLookup[45] = 'Ukrainian';
$QuicktimeLanguageLookup[46] = 'Byelorussian';
$QuicktimeLanguageLookup[47] = 'Uzbek';
$QuicktimeLanguageLookup[48] = 'Kazakh';
$QuicktimeLanguageLookup[49] = 'Azerbaijani';
$QuicktimeLanguageLookup[50] = 'AzerbaijanAr';
$QuicktimeLanguageLookup[51] = 'Armenian';
$QuicktimeLanguageLookup[52] = 'Georgian';
$QuicktimeLanguageLookup[53] = 'Moldavian';
$QuicktimeLanguageLookup[54] = 'Kirghiz';
$QuicktimeLanguageLookup[55] = 'Tajiki';
$QuicktimeLanguageLookup[56] = 'Turkmen';
$QuicktimeLanguageLookup[57] = 'Mongolian';
$QuicktimeLanguageLookup[58] = 'MongolianCyr';
$QuicktimeLanguageLookup[59] = 'Pashto';
$QuicktimeLanguageLookup[60] = 'Kurdish';
$QuicktimeLanguageLookup[61] = 'Kashmiri';
$QuicktimeLanguageLookup[62] = 'Sindhi';
$QuicktimeLanguageLookup[63] = 'Tibetan';
$QuicktimeLanguageLookup[64] = 'Nepali';
$QuicktimeLanguageLookup[65] = 'Sanskrit';
$QuicktimeLanguageLookup[66] = 'Marathi';
$QuicktimeLanguageLookup[67] = 'Bengali';
$QuicktimeLanguageLookup[68] = 'Assamese';
$QuicktimeLanguageLookup[69] = 'Gujarati';
$QuicktimeLanguageLookup[70] = 'Punjabi';
$QuicktimeLanguageLookup[71] = 'Oriya';
$QuicktimeLanguageLookup[72] = 'Malayalam';
$QuicktimeLanguageLookup[73] = 'Kannada';
$QuicktimeLanguageLookup[74] = 'Tamil';
$QuicktimeLanguageLookup[75] = 'Telugu';
$QuicktimeLanguageLookup[76] = 'Sinhalese';
$QuicktimeLanguageLookup[77] = 'Burmese';
$QuicktimeLanguageLookup[78] = 'Khmer';
$QuicktimeLanguageLookup[79] = 'Lao';
$QuicktimeLanguageLookup[80] = 'Vietnamese';
$QuicktimeLanguageLookup[81] = 'Indonesian';
$QuicktimeLanguageLookup[82] = 'Tagalog';
$QuicktimeLanguageLookup[83] = 'MalayRoman';
$QuicktimeLanguageLookup[84] = 'MalayArabic';
$QuicktimeLanguageLookup[85] = 'Amharic';
$QuicktimeLanguageLookup[86] = 'Tigrinya';
$QuicktimeLanguageLookup[87] = 'Galla';
$QuicktimeLanguageLookup[87] = 'Oromo';
$QuicktimeLanguageLookup[88] = 'Somali';
$QuicktimeLanguageLookup[89] = 'Swahili';
$QuicktimeLanguageLookup[90] = 'Ruanda';
$QuicktimeLanguageLookup[91] = 'Rundi';
$QuicktimeLanguageLookup[92] = 'Chewa';
$QuicktimeLanguageLookup[93] = 'Malagasy';
$QuicktimeLanguageLookup[94] = 'Esperanto';
$QuicktimeLanguageLookup[128] = 'Welsh';
$QuicktimeLanguageLookup[129] = 'Basque';
$QuicktimeLanguageLookup[130] = 'Catalan';
$QuicktimeLanguageLookup[131] = 'Latin';
$QuicktimeLanguageLookup[132] = 'Quechua';
$QuicktimeLanguageLookup[133] = 'Guarani';
$QuicktimeLanguageLookup[134] = 'Aymara';
$QuicktimeLanguageLookup[135] = 'Tatar';
$QuicktimeLanguageLookup[136] = 'Uighur';
$QuicktimeLanguageLookup[137] = 'Dzongkha';
$QuicktimeLanguageLookup[138] = 'JavaneseRom';
$QuicktimeLanguageLookup[32767] = 'Unspecified';
}
if (($languageid > 138) && ($languageid < 32767)) {
/*
ISO Language Codes - http://www.loc.gov/standards/iso639-2/php/code_list.php
Because the language codes specified by ISO 639-2/T are three characters long, they must be packed to fit into a 16-bit field.
The packing algorithm must map each of the three characters, which are always lowercase, into a 5-bit integer and then concatenate
these integers into the least significant 15 bits of a 16-bit integer, leaving the 16-bit integer's most significant bit set to zero.
One algorithm for performing this packing is to treat each ISO character as a 16-bit integer. Subtract 0x60 from the first character
and multiply by 2^10 (0x400), subtract 0x60 from the second character and multiply by 2^5 (0x20), subtract 0x60 from the third character,
and add the three 16-bit values. This will result in a single 16-bit value with the three codes correctly packed into the 15 least
significant bits and the most significant bit set to zero.
*/
$iso_language_id = '';
$iso_language_id .= chr((($languageid & 0x7C00) >> 10) + 0x60);
$iso_language_id .= chr((($languageid & 0x03E0) >> 5) + 0x60);
$iso_language_id .= chr((($languageid & 0x001F) >> 0) + 0x60);
$QuicktimeLanguageLookup[$languageid] = getid3_id3v2::LanguageLookup($iso_language_id);
}
return (isset($QuicktimeLanguageLookup[$languageid]) ? $QuicktimeLanguageLookup[$languageid] : 'invalid');
}
public function QuicktimeVideoCodecLookup($codecid) {
static $QuicktimeVideoCodecLookup = array();
if (empty($QuicktimeVideoCodecLookup)) {
$QuicktimeVideoCodecLookup['.SGI'] = 'SGI';
$QuicktimeVideoCodecLookup['3IV1'] = '3ivx MPEG-4 v1';
$QuicktimeVideoCodecLookup['3IV2'] = '3ivx MPEG-4 v2';
$QuicktimeVideoCodecLookup['3IVX'] = '3ivx MPEG-4';
$QuicktimeVideoCodecLookup['8BPS'] = 'Planar RGB';
$QuicktimeVideoCodecLookup['avc1'] = 'H.264/MPEG-4 AVC';
$QuicktimeVideoCodecLookup['avr '] = 'AVR-JPEG';
$QuicktimeVideoCodecLookup['b16g'] = '16Gray';
$QuicktimeVideoCodecLookup['b32a'] = '32AlphaGray';
$QuicktimeVideoCodecLookup['b48r'] = '48RGB';
$QuicktimeVideoCodecLookup['b64a'] = '64ARGB';
$QuicktimeVideoCodecLookup['base'] = 'Base';
$QuicktimeVideoCodecLookup['clou'] = 'Cloud';
$QuicktimeVideoCodecLookup['cmyk'] = 'CMYK';
$QuicktimeVideoCodecLookup['cvid'] = 'Cinepak';
$QuicktimeVideoCodecLookup['dmb1'] = 'OpenDML JPEG';
$QuicktimeVideoCodecLookup['dvc '] = 'DVC-NTSC';
$QuicktimeVideoCodecLookup['dvcp'] = 'DVC-PAL';
$QuicktimeVideoCodecLookup['dvpn'] = 'DVCPro-NTSC';
$QuicktimeVideoCodecLookup['dvpp'] = 'DVCPro-PAL';
$QuicktimeVideoCodecLookup['fire'] = 'Fire';
$QuicktimeVideoCodecLookup['flic'] = 'FLC';
$QuicktimeVideoCodecLookup['gif '] = 'GIF';
$QuicktimeVideoCodecLookup['h261'] = 'H261';
$QuicktimeVideoCodecLookup['h263'] = 'H263';
$QuicktimeVideoCodecLookup['IV41'] = 'Indeo4';
$QuicktimeVideoCodecLookup['jpeg'] = 'JPEG';
$QuicktimeVideoCodecLookup['kpcd'] = 'PhotoCD';
$QuicktimeVideoCodecLookup['mjpa'] = 'Motion JPEG-A';
$QuicktimeVideoCodecLookup['mjpb'] = 'Motion JPEG-B';
$QuicktimeVideoCodecLookup['msvc'] = 'Microsoft Video1';
$QuicktimeVideoCodecLookup['myuv'] = 'MPEG YUV420';
$QuicktimeVideoCodecLookup['path'] = 'Vector';
$QuicktimeVideoCodecLookup['png '] = 'PNG';
$QuicktimeVideoCodecLookup['PNTG'] = 'MacPaint';
$QuicktimeVideoCodecLookup['qdgx'] = 'QuickDrawGX';
$QuicktimeVideoCodecLookup['qdrw'] = 'QuickDraw';
$QuicktimeVideoCodecLookup['raw '] = 'RAW';
$QuicktimeVideoCodecLookup['ripl'] = 'WaterRipple';
$QuicktimeVideoCodecLookup['rpza'] = 'Video';
$QuicktimeVideoCodecLookup['smc '] = 'Graphics';
$QuicktimeVideoCodecLookup['SVQ1'] = 'Sorenson Video 1';
$QuicktimeVideoCodecLookup['SVQ1'] = 'Sorenson Video 3';
$QuicktimeVideoCodecLookup['syv9'] = 'Sorenson YUV9';
$QuicktimeVideoCodecLookup['tga '] = 'Targa';
$QuicktimeVideoCodecLookup['tiff'] = 'TIFF';
$QuicktimeVideoCodecLookup['WRAW'] = 'Windows RAW';
$QuicktimeVideoCodecLookup['WRLE'] = 'BMP';
$QuicktimeVideoCodecLookup['y420'] = 'YUV420';
$QuicktimeVideoCodecLookup['yuv2'] = 'ComponentVideo';
$QuicktimeVideoCodecLookup['yuvs'] = 'ComponentVideoUnsigned';
$QuicktimeVideoCodecLookup['yuvu'] = 'ComponentVideoSigned';
}
return (isset($QuicktimeVideoCodecLookup[$codecid]) ? $QuicktimeVideoCodecLookup[$codecid] : '');
}
public function QuicktimeAudioCodecLookup($codecid) {
static $QuicktimeAudioCodecLookup = array();
if (empty($QuicktimeAudioCodecLookup)) {
$QuicktimeAudioCodecLookup['.mp3'] = 'Fraunhofer MPEG Layer-III alias';
$QuicktimeAudioCodecLookup['aac '] = 'ISO/IEC 14496-3 AAC';
$QuicktimeAudioCodecLookup['agsm'] = 'Apple GSM 10:1';
$QuicktimeAudioCodecLookup['alac'] = 'Apple Lossless Audio Codec';
$QuicktimeAudioCodecLookup['alaw'] = 'A-law 2:1';
$QuicktimeAudioCodecLookup['conv'] = 'Sample Format';
$QuicktimeAudioCodecLookup['dvca'] = 'DV';
$QuicktimeAudioCodecLookup['dvi '] = 'DV 4:1';
$QuicktimeAudioCodecLookup['eqal'] = 'Frequency Equalizer';
$QuicktimeAudioCodecLookup['fl32'] = '32-bit Floating Point';
$QuicktimeAudioCodecLookup['fl64'] = '64-bit Floating Point';
$QuicktimeAudioCodecLookup['ima4'] = 'Interactive Multimedia Association 4:1';
$QuicktimeAudioCodecLookup['in24'] = '24-bit Integer';
$QuicktimeAudioCodecLookup['in32'] = '32-bit Integer';
$QuicktimeAudioCodecLookup['lpc '] = 'LPC 23:1';
$QuicktimeAudioCodecLookup['MAC3'] = 'Macintosh Audio Compression/Expansion (MACE) 3:1';
$QuicktimeAudioCodecLookup['MAC6'] = 'Macintosh Audio Compression/Expansion (MACE) 6:1';
$QuicktimeAudioCodecLookup['mixb'] = '8-bit Mixer';
$QuicktimeAudioCodecLookup['mixw'] = '16-bit Mixer';
$QuicktimeAudioCodecLookup['mp4a'] = 'ISO/IEC 14496-3 AAC';
$QuicktimeAudioCodecLookup['MS'."\x00\x02"] = 'Microsoft ADPCM';
$QuicktimeAudioCodecLookup['MS'."\x00\x11"] = 'DV IMA';
$QuicktimeAudioCodecLookup['MS'."\x00\x55"] = 'Fraunhofer MPEG Layer III';
$QuicktimeAudioCodecLookup['NONE'] = 'No Encoding';
$QuicktimeAudioCodecLookup['Qclp'] = 'Qualcomm PureVoice';
$QuicktimeAudioCodecLookup['QDM2'] = 'QDesign Music 2';
$QuicktimeAudioCodecLookup['QDMC'] = 'QDesign Music 1';
$QuicktimeAudioCodecLookup['ratb'] = '8-bit Rate';
$QuicktimeAudioCodecLookup['ratw'] = '16-bit Rate';
$QuicktimeAudioCodecLookup['raw '] = 'raw PCM';
$QuicktimeAudioCodecLookup['sour'] = 'Sound Source';
$QuicktimeAudioCodecLookup['sowt'] = 'signed/two\'s complement (Little Endian)';
$QuicktimeAudioCodecLookup['str1'] = 'Iomega MPEG layer II';
$QuicktimeAudioCodecLookup['str2'] = 'Iomega MPEG *layer II';
$QuicktimeAudioCodecLookup['str3'] = 'Iomega MPEG **layer II';
$QuicktimeAudioCodecLookup['str4'] = 'Iomega MPEG ***layer II';
$QuicktimeAudioCodecLookup['twos'] = 'signed/two\'s complement (Big Endian)';
$QuicktimeAudioCodecLookup['ulaw'] = 'mu-law 2:1';
}
return (isset($QuicktimeAudioCodecLookup[$codecid]) ? $QuicktimeAudioCodecLookup[$codecid] : '');
}
public function QuicktimeDCOMLookup($compressionid) {
static $QuicktimeDCOMLookup = array();
if (empty($QuicktimeDCOMLookup)) {
$QuicktimeDCOMLookup['zlib'] = 'ZLib Deflate';
$QuicktimeDCOMLookup['adec'] = 'Apple Compression';
}
return (isset($QuicktimeDCOMLookup[$compressionid]) ? $QuicktimeDCOMLookup[$compressionid] : '');
}
public function QuicktimeColorNameLookup($colordepthid) {
static $QuicktimeColorNameLookup = array();
if (empty($QuicktimeColorNameLookup)) {
$QuicktimeColorNameLookup[1] = '2-color (monochrome)';
$QuicktimeColorNameLookup[2] = '4-color';
$QuicktimeColorNameLookup[4] = '16-color';
$QuicktimeColorNameLookup[8] = '256-color';
$QuicktimeColorNameLookup[16] = 'thousands (16-bit color)';
$QuicktimeColorNameLookup[24] = 'millions (24-bit color)';
$QuicktimeColorNameLookup[32] = 'millions+ (32-bit color)';
$QuicktimeColorNameLookup[33] = 'black & white';
$QuicktimeColorNameLookup[34] = '4-gray';
$QuicktimeColorNameLookup[36] = '16-gray';
$QuicktimeColorNameLookup[40] = '256-gray';
}
return (isset($QuicktimeColorNameLookup[$colordepthid]) ? $QuicktimeColorNameLookup[$colordepthid] : 'invalid');
}
public function QuicktimeSTIKLookup($stik) {
static $QuicktimeSTIKLookup = array();
if (empty($QuicktimeSTIKLookup)) {
$QuicktimeSTIKLookup[0] = 'Movie';
$QuicktimeSTIKLookup[1] = 'Normal';
$QuicktimeSTIKLookup[2] = 'Audiobook';
$QuicktimeSTIKLookup[5] = 'Whacked Bookmark';
$QuicktimeSTIKLookup[6] = 'Music Video';
$QuicktimeSTIKLookup[9] = 'Short Film';
$QuicktimeSTIKLookup[10] = 'TV Show';
$QuicktimeSTIKLookup[11] = 'Booklet';
$QuicktimeSTIKLookup[14] = 'Ringtone';
$QuicktimeSTIKLookup[21] = 'Podcast';
}
return (isset($QuicktimeSTIKLookup[$stik]) ? $QuicktimeSTIKLookup[$stik] : 'invalid');
}
public function QuicktimeIODSaudioProfileName($audio_profile_id) {
static $QuicktimeIODSaudioProfileNameLookup = array();
if (empty($QuicktimeIODSaudioProfileNameLookup)) {
$QuicktimeIODSaudioProfileNameLookup = array(
0x00 => 'ISO Reserved (0x00)',
0x01 => 'Main Audio Profile @ Level 1',
0x02 => 'Main Audio Profile @ Level 2',
0x03 => 'Main Audio Profile @ Level 3',
0x04 => 'Main Audio Profile @ Level 4',
0x05 => 'Scalable Audio Profile @ Level 1',
0x06 => 'Scalable Audio Profile @ Level 2',
0x07 => 'Scalable Audio Profile @ Level 3',
0x08 => 'Scalable Audio Profile @ Level 4',
0x09 => 'Speech Audio Profile @ Level 1',
0x0A => 'Speech Audio Profile @ Level 2',
0x0B => 'Synthetic Audio Profile @ Level 1',
0x0C => 'Synthetic Audio Profile @ Level 2',
0x0D => 'Synthetic Audio Profile @ Level 3',
0x0E => 'High Quality Audio Profile @ Level 1',
0x0F => 'High Quality Audio Profile @ Level 2',
0x10 => 'High Quality Audio Profile @ Level 3',
0x11 => 'High Quality Audio Profile @ Level 4',
0x12 => 'High Quality Audio Profile @ Level 5',
0x13 => 'High Quality Audio Profile @ Level 6',
0x14 => 'High Quality Audio Profile @ Level 7',
0x15 => 'High Quality Audio Profile @ Level 8',
0x16 => 'Low Delay Audio Profile @ Level 1',
0x17 => 'Low Delay Audio Profile @ Level 2',
0x18 => 'Low Delay Audio Profile @ Level 3',
0x19 => 'Low Delay Audio Profile @ Level 4',
0x1A => 'Low Delay Audio Profile @ Level 5',
0x1B => 'Low Delay Audio Profile @ Level 6',
0x1C => 'Low Delay Audio Profile @ Level 7',
0x1D => 'Low Delay Audio Profile @ Level 8',
0x1E => 'Natural Audio Profile @ Level 1',
0x1F => 'Natural Audio Profile @ Level 2',
0x20 => 'Natural Audio Profile @ Level 3',
0x21 => 'Natural Audio Profile @ Level 4',
0x22 => 'Mobile Audio Internetworking Profile @ Level 1',
0x23 => 'Mobile Audio Internetworking Profile @ Level 2',
0x24 => 'Mobile Audio Internetworking Profile @ Level 3',
0x25 => 'Mobile Audio Internetworking Profile @ Level 4',
0x26 => 'Mobile Audio Internetworking Profile @ Level 5',
0x27 => 'Mobile Audio Internetworking Profile @ Level 6',
0x28 => 'AAC Profile @ Level 1',
0x29 => 'AAC Profile @ Level 2',
0x2A => 'AAC Profile @ Level 4',
0x2B => 'AAC Profile @ Level 5',
0x2C => 'High Efficiency AAC Profile @ Level 2',
0x2D => 'High Efficiency AAC Profile @ Level 3',
0x2E => 'High Efficiency AAC Profile @ Level 4',
0x2F => 'High Efficiency AAC Profile @ Level 5',
0xFE => 'Not part of MPEG-4 audio profiles',
0xFF => 'No audio capability required',
);
}
return (isset($QuicktimeIODSaudioProfileNameLookup[$audio_profile_id]) ? $QuicktimeIODSaudioProfileNameLookup[$audio_profile_id] : 'ISO Reserved / User Private');
}
public function QuicktimeIODSvideoProfileName($video_profile_id) {
static $QuicktimeIODSvideoProfileNameLookup = array();
if (empty($QuicktimeIODSvideoProfileNameLookup)) {
$QuicktimeIODSvideoProfileNameLookup = array(
0x00 => 'Reserved (0x00) Profile',
0x01 => 'Simple Profile @ Level 1',
0x02 => 'Simple Profile @ Level 2',
0x03 => 'Simple Profile @ Level 3',
0x08 => 'Simple Profile @ Level 0',
0x10 => 'Simple Scalable Profile @ Level 0',
0x11 => 'Simple Scalable Profile @ Level 1',
0x12 => 'Simple Scalable Profile @ Level 2',
0x15 => 'AVC/H264 Profile',
0x21 => 'Core Profile @ Level 1',
0x22 => 'Core Profile @ Level 2',
0x32 => 'Main Profile @ Level 2',
0x33 => 'Main Profile @ Level 3',
0x34 => 'Main Profile @ Level 4',
0x42 => 'N-bit Profile @ Level 2',
0x51 => 'Scalable Texture Profile @ Level 1',
0x61 => 'Simple Face Animation Profile @ Level 1',
0x62 => 'Simple Face Animation Profile @ Level 2',
0x63 => 'Simple FBA Profile @ Level 1',
0x64 => 'Simple FBA Profile @ Level 2',
0x71 => 'Basic Animated Texture Profile @ Level 1',
0x72 => 'Basic Animated Texture Profile @ Level 2',
0x81 => 'Hybrid Profile @ Level 1',
0x82 => 'Hybrid Profile @ Level 2',
0x91 => 'Advanced Real Time Simple Profile @ Level 1',
0x92 => 'Advanced Real Time Simple Profile @ Level 2',
0x93 => 'Advanced Real Time Simple Profile @ Level 3',
0x94 => 'Advanced Real Time Simple Profile @ Level 4',
0xA1 => 'Core Scalable Profile @ Level1',
0xA2 => 'Core Scalable Profile @ Level2',
0xA3 => 'Core Scalable Profile @ Level3',
0xB1 => 'Advanced Coding Efficiency Profile @ Level 1',
0xB2 => 'Advanced Coding Efficiency Profile @ Level 2',
0xB3 => 'Advanced Coding Efficiency Profile @ Level 3',
0xB4 => 'Advanced Coding Efficiency Profile @ Level 4',
0xC1 => 'Advanced Core Profile @ Level 1',
0xC2 => 'Advanced Core Profile @ Level 2',
0xD1 => 'Advanced Scalable Texture @ Level1',
0xD2 => 'Advanced Scalable Texture @ Level2',
0xE1 => 'Simple Studio Profile @ Level 1',
0xE2 => 'Simple Studio Profile @ Level 2',
0xE3 => 'Simple Studio Profile @ Level 3',
0xE4 => 'Simple Studio Profile @ Level 4',
0xE5 => 'Core Studio Profile @ Level 1',
0xE6 => 'Core Studio Profile @ Level 2',
0xE7 => 'Core Studio Profile @ Level 3',
0xE8 => 'Core Studio Profile @ Level 4',
0xF0 => 'Advanced Simple Profile @ Level 0',
0xF1 => 'Advanced Simple Profile @ Level 1',
0xF2 => 'Advanced Simple Profile @ Level 2',
0xF3 => 'Advanced Simple Profile @ Level 3',
0xF4 => 'Advanced Simple Profile @ Level 4',
0xF5 => 'Advanced Simple Profile @ Level 5',
0xF7 => 'Advanced Simple Profile @ Level 3b',
0xF8 => 'Fine Granularity Scalable Profile @ Level 0',
0xF9 => 'Fine Granularity Scalable Profile @ Level 1',
0xFA => 'Fine Granularity Scalable Profile @ Level 2',
0xFB => 'Fine Granularity Scalable Profile @ Level 3',
0xFC => 'Fine Granularity Scalable Profile @ Level 4',
0xFD => 'Fine Granularity Scalable Profile @ Level 5',
0xFE => 'Not part of MPEG-4 Visual profiles',
0xFF => 'No visual capability required',
);
}
return (isset($QuicktimeIODSvideoProfileNameLookup[$video_profile_id]) ? $QuicktimeIODSvideoProfileNameLookup[$video_profile_id] : 'ISO Reserved Profile');
}
public function QuicktimeContentRatingLookup($rtng) {
static $QuicktimeContentRatingLookup = array();
if (empty($QuicktimeContentRatingLookup)) {
$QuicktimeContentRatingLookup[0] = 'None';
$QuicktimeContentRatingLookup[2] = 'Clean';
$QuicktimeContentRatingLookup[4] = 'Explicit';
}
return (isset($QuicktimeContentRatingLookup[$rtng]) ? $QuicktimeContentRatingLookup[$rtng] : 'invalid');
}
public function QuicktimeStoreAccountTypeLookup($akid) {
static $QuicktimeStoreAccountTypeLookup = array();
if (empty($QuicktimeStoreAccountTypeLookup)) {
$QuicktimeStoreAccountTypeLookup[0] = 'iTunes';
$QuicktimeStoreAccountTypeLookup[1] = 'AOL';
}
return (isset($QuicktimeStoreAccountTypeLookup[$akid]) ? $QuicktimeStoreAccountTypeLookup[$akid] : 'invalid');
}
public function QuicktimeStoreFrontCodeLookup($sfid) {
static $QuicktimeStoreFrontCodeLookup = array();
if (empty($QuicktimeStoreFrontCodeLookup)) {
$QuicktimeStoreFrontCodeLookup[143460] = 'Australia';
$QuicktimeStoreFrontCodeLookup[143445] = 'Austria';
$QuicktimeStoreFrontCodeLookup[143446] = 'Belgium';
$QuicktimeStoreFrontCodeLookup[143455] = 'Canada';
$QuicktimeStoreFrontCodeLookup[143458] = 'Denmark';
$QuicktimeStoreFrontCodeLookup[143447] = 'Finland';
$QuicktimeStoreFrontCodeLookup[143442] = 'France';
$QuicktimeStoreFrontCodeLookup[143443] = 'Germany';
$QuicktimeStoreFrontCodeLookup[143448] = 'Greece';
$QuicktimeStoreFrontCodeLookup[143449] = 'Ireland';
$QuicktimeStoreFrontCodeLookup[143450] = 'Italy';
$QuicktimeStoreFrontCodeLookup[143462] = 'Japan';
$QuicktimeStoreFrontCodeLookup[143451] = 'Luxembourg';
$QuicktimeStoreFrontCodeLookup[143452] = 'Netherlands';
$QuicktimeStoreFrontCodeLookup[143461] = 'New Zealand';
$QuicktimeStoreFrontCodeLookup[143457] = 'Norway';
$QuicktimeStoreFrontCodeLookup[143453] = 'Portugal';
$QuicktimeStoreFrontCodeLookup[143454] = 'Spain';
$QuicktimeStoreFrontCodeLookup[143456] = 'Sweden';
$QuicktimeStoreFrontCodeLookup[143459] = 'Switzerland';
$QuicktimeStoreFrontCodeLookup[143444] = 'United Kingdom';
$QuicktimeStoreFrontCodeLookup[143441] = 'United States';
}
return (isset($QuicktimeStoreFrontCodeLookup[$sfid]) ? $QuicktimeStoreFrontCodeLookup[$sfid] : 'invalid');
}
public function QuicktimeParseNikonNCTG($atom_data) {
// http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/Nikon.html#NCTG
// Nikon-specific QuickTime tags found in the NCDT atom of MOV videos from some Nikon cameras such as the Coolpix S8000 and D5100
// Data is stored as records of:
// * 4 bytes record type
// * 2 bytes size of data field type:
// 0x0001 = flag (size field *= 1-byte)
// 0x0002 = char (size field *= 1-byte)
// 0x0003 = DWORD+ (size field *= 2-byte), values are stored CDAB
// 0x0004 = QWORD+ (size field *= 4-byte), values are stored EFGHABCD
// 0x0005 = float (size field *= 8-byte), values are stored aaaabbbb where value is aaaa/bbbb; possibly multiple sets of values appended together
// 0x0007 = bytes (size field *= 1-byte), values are stored as ??????
// 0x0008 = ????? (size field *= 2-byte), values are stored as ??????
// * 2 bytes data size field
// * ? bytes data (string data may be null-padded; datestamp fields are in the format "2011:05:25 20:24:15")
// all integers are stored BigEndian
$NCTGtagName = array(
0x00000001 => 'Make',
0x00000002 => 'Model',
0x00000003 => 'Software',
0x00000011 => 'CreateDate',
0x00000012 => 'DateTimeOriginal',
0x00000013 => 'FrameCount',
0x00000016 => 'FrameRate',
0x00000022 => 'FrameWidth',
0x00000023 => 'FrameHeight',
0x00000032 => 'AudioChannels',
0x00000033 => 'AudioBitsPerSample',
0x00000034 => 'AudioSampleRate',
0x02000001 => 'MakerNoteVersion',
0x02000005 => 'WhiteBalance',
0x0200000b => 'WhiteBalanceFineTune',
0x0200001e => 'ColorSpace',
0x02000023 => 'PictureControlData',
0x02000024 => 'WorldTime',
0x02000032 => 'UnknownInfo',
0x02000083 => 'LensType',
0x02000084 => 'Lens',
);
$offset = 0;
$datalength = strlen($atom_data);
$parsed = array();
while ($offset < $datalength) {
//echo getid3_lib::PrintHexBytes(substr($atom_data, $offset, 4)).'<br>';
$record_type = getid3_lib::BigEndian2Int(substr($atom_data, $offset, 4)); $offset += 4;
$data_size_type = getid3_lib::BigEndian2Int(substr($atom_data, $offset, 2)); $offset += 2;
$data_size = getid3_lib::BigEndian2Int(substr($atom_data, $offset, 2)); $offset += 2;
switch ($data_size_type) {
case 0x0001: // 0x0001 = flag (size field *= 1-byte)
$data = getid3_lib::BigEndian2Int(substr($atom_data, $offset, $data_size * 1));
$offset += ($data_size * 1);
break;
case 0x0002: // 0x0002 = char (size field *= 1-byte)
$data = substr($atom_data, $offset, $data_size * 1);
$offset += ($data_size * 1);
$data = rtrim($data, "\x00");
break;
case 0x0003: // 0x0003 = DWORD+ (size field *= 2-byte), values are stored CDAB
$data = '';
for ($i = $data_size - 1; $i >= 0; $i--) {
$data .= substr($atom_data, $offset + ($i * 2), 2);
}
$data = getid3_lib::BigEndian2Int($data);
$offset += ($data_size * 2);
break;
case 0x0004: // 0x0004 = QWORD+ (size field *= 4-byte), values are stored EFGHABCD
$data = '';
for ($i = $data_size - 1; $i >= 0; $i--) {
$data .= substr($atom_data, $offset + ($i * 4), 4);
}
$data = getid3_lib::BigEndian2Int($data);
$offset += ($data_size * 4);
break;
case 0x0005: // 0x0005 = float (size field *= 8-byte), values are stored aaaabbbb where value is aaaa/bbbb; possibly multiple sets of values appended together
$data = array();
for ($i = 0; $i < $data_size; $i++) {
$numerator = getid3_lib::BigEndian2Int(substr($atom_data, $offset + ($i * 8) + 0, 4));
$denomninator = getid3_lib::BigEndian2Int(substr($atom_data, $offset + ($i * 8) + 4, 4));
if ($denomninator == 0) {
$data[$i] = false;
} else {
$data[$i] = (double) $numerator / $denomninator;
}
}
$offset += (8 * $data_size);
if (count($data) == 1) {
$data = $data[0];
}
break;
case 0x0007: // 0x0007 = bytes (size field *= 1-byte), values are stored as ??????
$data = substr($atom_data, $offset, $data_size * 1);
$offset += ($data_size * 1);
break;
case 0x0008: // 0x0008 = ????? (size field *= 2-byte), values are stored as ??????
$data = substr($atom_data, $offset, $data_size * 2);
$offset += ($data_size * 2);
break;
default:
echo 'QuicktimeParseNikonNCTG()::unknown $data_size_type: '.$data_size_type.'<br>';
break 2;
}
switch ($record_type) {
case 0x00000011: // CreateDate
case 0x00000012: // DateTimeOriginal
$data = strtotime($data);
break;
case 0x0200001e: // ColorSpace
switch ($data) {
case 1:
$data = 'sRGB';
break;
case 2:
$data = 'Adobe RGB';
break;
}
break;
case 0x02000023: // PictureControlData
$PictureControlAdjust = array(0=>'default', 1=>'quick', 2=>'full');
$FilterEffect = array(0x80=>'off', 0x81=>'yellow', 0x82=>'orange', 0x83=>'red', 0x84=>'green', 0xff=>'n/a');
$ToningEffect = array(0x80=>'b&w', 0x81=>'sepia', 0x82=>'cyanotype', 0x83=>'red', 0x84=>'yellow', 0x85=>'green', 0x86=>'blue-green', 0x87=>'blue', 0x88=>'purple-blue', 0x89=>'red-purple', 0xff=>'n/a');
$data = array(
'PictureControlVersion' => substr($data, 0, 4),
'PictureControlName' => rtrim(substr($data, 4, 20), "\x00"),
'PictureControlBase' => rtrim(substr($data, 24, 20), "\x00"),
//'?' => substr($data, 44, 4),
'PictureControlAdjust' => $PictureControlAdjust[ord(substr($data, 48, 1))],
'PictureControlQuickAdjust' => ord(substr($data, 49, 1)),
'Sharpness' => ord(substr($data, 50, 1)),
'Contrast' => ord(substr($data, 51, 1)),
'Brightness' => ord(substr($data, 52, 1)),
'Saturation' => ord(substr($data, 53, 1)),
'HueAdjustment' => ord(substr($data, 54, 1)),
'FilterEffect' => $FilterEffect[ord(substr($data, 55, 1))],
'ToningEffect' => $ToningEffect[ord(substr($data, 56, 1))],
'ToningSaturation' => ord(substr($data, 57, 1)),
);
break;
case 0x02000024: // WorldTime
// http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/Nikon.html#WorldTime
// timezone is stored as offset from GMT in minutes
$timezone = getid3_lib::BigEndian2Int(substr($data, 0, 2));
if ($timezone & 0x8000) {
$timezone = 0 - (0x10000 - $timezone);
}
$timezone /= 60;
$dst = (bool) getid3_lib::BigEndian2Int(substr($data, 2, 1));
switch (getid3_lib::BigEndian2Int(substr($data, 3, 1))) {
case 2:
$datedisplayformat = 'D/M/Y'; break;
case 1:
$datedisplayformat = 'M/D/Y'; break;
case 0:
default:
$datedisplayformat = 'Y/M/D'; break;
}
$data = array('timezone'=>floatval($timezone), 'dst'=>$dst, 'display'=>$datedisplayformat);
break;
case 0x02000083: // LensType
$data = array(
//'_' => $data,
'mf' => (bool) ($data & 0x01),
'd' => (bool) ($data & 0x02),
'g' => (bool) ($data & 0x04),
'vr' => (bool) ($data & 0x08),
);
break;
}
$tag_name = (isset($NCTGtagName[$record_type]) ? $NCTGtagName[$record_type] : '0x'.str_pad(dechex($record_type), 8, '0', STR_PAD_LEFT));
$parsed[$tag_name] = $data;
}
return $parsed;
}
public function CopyToAppropriateCommentsSection($keyname, $data, $boxname='') {
static $handyatomtranslatorarray = array();
if (empty($handyatomtranslatorarray)) {
$handyatomtranslatorarray['©cpy'] = 'copyright';
$handyatomtranslatorarray['©day'] = 'creation_date'; // iTunes 4.0
$handyatomtranslatorarray['©dir'] = 'director';
$handyatomtranslatorarray['©ed1'] = 'edit1';
$handyatomtranslatorarray['©ed2'] = 'edit2';
$handyatomtranslatorarray['©ed3'] = 'edit3';
$handyatomtranslatorarray['©ed4'] = 'edit4';
$handyatomtranslatorarray['©ed5'] = 'edit5';
$handyatomtranslatorarray['©ed6'] = 'edit6';
$handyatomtranslatorarray['©ed7'] = 'edit7';
$handyatomtranslatorarray['©ed8'] = 'edit8';
$handyatomtranslatorarray['©ed9'] = 'edit9';
$handyatomtranslatorarray['©fmt'] = 'format';
$handyatomtranslatorarray['©inf'] = 'information';
$handyatomtranslatorarray['©prd'] = 'producer';
$handyatomtranslatorarray['©prf'] = 'performers';
$handyatomtranslatorarray['©req'] = 'system_requirements';
$handyatomtranslatorarray['©src'] = 'source_credit';
$handyatomtranslatorarray['©wrt'] = 'writer';
// http://www.geocities.com/xhelmboyx/quicktime/formats/qtm-layout.txt
$handyatomtranslatorarray['©nam'] = 'title'; // iTunes 4.0
$handyatomtranslatorarray['©cmt'] = 'comment'; // iTunes 4.0
$handyatomtranslatorarray['©wrn'] = 'warning';
$handyatomtranslatorarray['©hst'] = 'host_computer';
$handyatomtranslatorarray['©mak'] = 'make';
$handyatomtranslatorarray['©mod'] = 'model';
$handyatomtranslatorarray['©PRD'] = 'product';
$handyatomtranslatorarray['©swr'] = 'software';
$handyatomtranslatorarray['©aut'] = 'author';
$handyatomtranslatorarray['©ART'] = 'artist';
$handyatomtranslatorarray['©trk'] = 'track';
$handyatomtranslatorarray['©alb'] = 'album'; // iTunes 4.0
$handyatomtranslatorarray['©com'] = 'comment';
$handyatomtranslatorarray['©gen'] = 'genre'; // iTunes 4.0
$handyatomtranslatorarray['©ope'] = 'composer';
$handyatomtranslatorarray['©url'] = 'url';
$handyatomtranslatorarray['©enc'] = 'encoder';
// http://atomicparsley.sourceforge.net/mpeg-4files.html
$handyatomtranslatorarray['©art'] = 'artist'; // iTunes 4.0
$handyatomtranslatorarray['aART'] = 'album_artist';
$handyatomtranslatorarray['trkn'] = 'track_number'; // iTunes 4.0
$handyatomtranslatorarray['disk'] = 'disc_number'; // iTunes 4.0
$handyatomtranslatorarray['gnre'] = 'genre'; // iTunes 4.0
$handyatomtranslatorarray['©too'] = 'encoder'; // iTunes 4.0
$handyatomtranslatorarray['tmpo'] = 'bpm'; // iTunes 4.0
$handyatomtranslatorarray['cprt'] = 'copyright'; // iTunes 4.0?
$handyatomtranslatorarray['cpil'] = 'compilation'; // iTunes 4.0
$handyatomtranslatorarray['covr'] = 'picture'; // iTunes 4.0
$handyatomtranslatorarray['rtng'] = 'rating'; // iTunes 4.0
$handyatomtranslatorarray['©grp'] = 'grouping'; // iTunes 4.2
$handyatomtranslatorarray['stik'] = 'stik'; // iTunes 4.9
$handyatomtranslatorarray['pcst'] = 'podcast'; // iTunes 4.9
$handyatomtranslatorarray['catg'] = 'category'; // iTunes 4.9
$handyatomtranslatorarray['keyw'] = 'keyword'; // iTunes 4.9
$handyatomtranslatorarray['purl'] = 'podcast_url'; // iTunes 4.9
$handyatomtranslatorarray['egid'] = 'episode_guid'; // iTunes 4.9
$handyatomtranslatorarray['desc'] = 'description'; // iTunes 5.0
$handyatomtranslatorarray['©lyr'] = 'lyrics'; // iTunes 5.0
$handyatomtranslatorarray['tvnn'] = 'tv_network_name'; // iTunes 6.0
$handyatomtranslatorarray['tvsh'] = 'tv_show_name'; // iTunes 6.0
$handyatomtranslatorarray['tvsn'] = 'tv_season'; // iTunes 6.0
$handyatomtranslatorarray['tves'] = 'tv_episode'; // iTunes 6.0
$handyatomtranslatorarray['purd'] = 'purchase_date'; // iTunes 6.0.2
$handyatomtranslatorarray['pgap'] = 'gapless_playback'; // iTunes 7.0
// http://www.geocities.com/xhelmboyx/quicktime/formats/mp4-layout.txt
// boxnames:
/*
$handyatomtranslatorarray['iTunSMPB'] = 'iTunSMPB';
$handyatomtranslatorarray['iTunNORM'] = 'iTunNORM';
$handyatomtranslatorarray['Encoding Params'] = 'Encoding Params';
$handyatomtranslatorarray['replaygain_track_gain'] = 'replaygain_track_gain';
$handyatomtranslatorarray['replaygain_track_peak'] = 'replaygain_track_peak';
$handyatomtranslatorarray['replaygain_track_minmax'] = 'replaygain_track_minmax';
$handyatomtranslatorarray['MusicIP PUID'] = 'MusicIP PUID';
$handyatomtranslatorarray['MusicBrainz Artist Id'] = 'MusicBrainz Artist Id';
$handyatomtranslatorarray['MusicBrainz Album Id'] = 'MusicBrainz Album Id';
$handyatomtranslatorarray['MusicBrainz Album Artist Id'] = 'MusicBrainz Album Artist Id';
$handyatomtranslatorarray['MusicBrainz Track Id'] = 'MusicBrainz Track Id';
$handyatomtranslatorarray['MusicBrainz Disc Id'] = 'MusicBrainz Disc Id';
// http://age.hobba.nl/audio/tag_frame_reference.html
$handyatomtranslatorarray['PLAY_COUNTER'] = 'play_counter'; // Foobar2000 - http://www.getid3.org/phpBB3/viewtopic.php?t=1355
$handyatomtranslatorarray['MEDIATYPE'] = 'mediatype'; // Foobar2000 - http://www.getid3.org/phpBB3/viewtopic.php?t=1355
*/
}
$info = &$this->getid3->info;
$comment_key = '';
if ($boxname && ($boxname != $keyname)) {
$comment_key = (isset($handyatomtranslatorarray[$boxname]) ? $handyatomtranslatorarray[$boxname] : $boxname);
} elseif (isset($handyatomtranslatorarray[$keyname])) {
$comment_key = $handyatomtranslatorarray[$keyname];
}
if ($comment_key) {
if ($comment_key == 'picture') {
if (!is_array($data)) {
$image_mime = '';
if (preg_match('#^\x89\x50\x4E\x47\x0D\x0A\x1A\x0A#', $data)) {
$image_mime = 'image/png';
} elseif (preg_match('#^\xFF\xD8\xFF#', $data)) {
$image_mime = 'image/jpeg';
} elseif (preg_match('#^GIF#', $data)) {
$image_mime = 'image/gif';
} elseif (preg_match('#^BM#', $data)) {
$image_mime = 'image/bmp';
}
$data = array('data'=>$data, 'image_mime'=>$image_mime);
}
}
$info['quicktime']['comments'][$comment_key][] = $data;
}
return true;
}
public function NoNullString($nullterminatedstring) {
// remove the single null terminator on null terminated strings
if (substr($nullterminatedstring, strlen($nullterminatedstring) - 1, 1) === "\x00") {
return substr($nullterminatedstring, 0, strlen($nullterminatedstring) - 1);
}
return $nullterminatedstring;
}
public function Pascal2String($pascalstring) {
// Pascal strings have 1 unsigned byte at the beginning saying how many chars (1-255) are in the string
return substr($pascalstring, 1);
}
}
| PHP |
<?php
/////////////////////////////////////////////////////////////////
/// getID3() by James Heinrich <info@getid3.org> //
// available at http://getid3.sourceforge.net //
// or http://www.getid3.org //
/////////////////////////////////////////////////////////////////
// See readme.txt for more details //
/////////////////////////////////////////////////////////////////
/// //
// module.tag.id3v2.php //
// module for analyzing ID3v2 tags //
// dependencies: module.tag.id3v1.php //
// ///
/////////////////////////////////////////////////////////////////
getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.tag.id3v1.php', __FILE__, true);
class getid3_id3v2 extends getid3_handler
{
public $StartingOffset = 0;
public function Analyze() {
$info = &$this->getid3->info;
// Overall tag structure:
// +-----------------------------+
// | Header (10 bytes) |
// +-----------------------------+
// | Extended Header |
// | (variable length, OPTIONAL) |
// +-----------------------------+
// | Frames (variable length) |
// +-----------------------------+
// | Padding |
// | (variable length, OPTIONAL) |
// +-----------------------------+
// | Footer (10 bytes, OPTIONAL) |
// +-----------------------------+
// Header
// ID3v2/file identifier "ID3"
// ID3v2 version $04 00
// ID3v2 flags (%ab000000 in v2.2, %abc00000 in v2.3, %abcd0000 in v2.4.x)
// ID3v2 size 4 * %0xxxxxxx
// shortcuts
$info['id3v2']['header'] = true;
$thisfile_id3v2 = &$info['id3v2'];
$thisfile_id3v2['flags'] = array();
$thisfile_id3v2_flags = &$thisfile_id3v2['flags'];
fseek($this->getid3->fp, $this->StartingOffset, SEEK_SET);
$header = fread($this->getid3->fp, 10);
if (substr($header, 0, 3) == 'ID3' && strlen($header) == 10) {
$thisfile_id3v2['majorversion'] = ord($header{3});
$thisfile_id3v2['minorversion'] = ord($header{4});
// shortcut
$id3v2_majorversion = &$thisfile_id3v2['majorversion'];
} else {
unset($info['id3v2']);
return false;
}
if ($id3v2_majorversion > 4) { // this script probably won't correctly parse ID3v2.5.x and above (if it ever exists)
$info['error'][] = 'this script only parses up to ID3v2.4.x - this tag is ID3v2.'.$id3v2_majorversion.'.'.$thisfile_id3v2['minorversion'];
return false;
}
$id3_flags = ord($header{5});
switch ($id3v2_majorversion) {
case 2:
// %ab000000 in v2.2
$thisfile_id3v2_flags['unsynch'] = (bool) ($id3_flags & 0x80); // a - Unsynchronisation
$thisfile_id3v2_flags['compression'] = (bool) ($id3_flags & 0x40); // b - Compression
break;
case 3:
// %abc00000 in v2.3
$thisfile_id3v2_flags['unsynch'] = (bool) ($id3_flags & 0x80); // a - Unsynchronisation
$thisfile_id3v2_flags['exthead'] = (bool) ($id3_flags & 0x40); // b - Extended header
$thisfile_id3v2_flags['experim'] = (bool) ($id3_flags & 0x20); // c - Experimental indicator
break;
case 4:
// %abcd0000 in v2.4
$thisfile_id3v2_flags['unsynch'] = (bool) ($id3_flags & 0x80); // a - Unsynchronisation
$thisfile_id3v2_flags['exthead'] = (bool) ($id3_flags & 0x40); // b - Extended header
$thisfile_id3v2_flags['experim'] = (bool) ($id3_flags & 0x20); // c - Experimental indicator
$thisfile_id3v2_flags['isfooter'] = (bool) ($id3_flags & 0x10); // d - Footer present
break;
}
$thisfile_id3v2['headerlength'] = getid3_lib::BigEndian2Int(substr($header, 6, 4), 1) + 10; // length of ID3v2 tag in 10-byte header doesn't include 10-byte header length
$thisfile_id3v2['tag_offset_start'] = $this->StartingOffset;
$thisfile_id3v2['tag_offset_end'] = $thisfile_id3v2['tag_offset_start'] + $thisfile_id3v2['headerlength'];
// create 'encoding' key - used by getid3::HandleAllTags()
// in ID3v2 every field can have it's own encoding type
// so force everything to UTF-8 so it can be handled consistantly
$thisfile_id3v2['encoding'] = 'UTF-8';
// Frames
// All ID3v2 frames consists of one frame header followed by one or more
// fields containing the actual information. The header is always 10
// bytes and laid out as follows:
//
// Frame ID $xx xx xx xx (four characters)
// Size 4 * %0xxxxxxx
// Flags $xx xx
$sizeofframes = $thisfile_id3v2['headerlength'] - 10; // not including 10-byte initial header
if (!empty($thisfile_id3v2['exthead']['length'])) {
$sizeofframes -= ($thisfile_id3v2['exthead']['length'] + 4);
}
if (!empty($thisfile_id3v2_flags['isfooter'])) {
$sizeofframes -= 10; // footer takes last 10 bytes of ID3v2 header, after frame data, before audio
}
if ($sizeofframes > 0) {
$framedata = fread($this->getid3->fp, $sizeofframes); // read all frames from file into $framedata variable
// if entire frame data is unsynched, de-unsynch it now (ID3v2.3.x)
if (!empty($thisfile_id3v2_flags['unsynch']) && ($id3v2_majorversion <= 3)) {
$framedata = $this->DeUnsynchronise($framedata);
}
// [in ID3v2.4.0] Unsynchronisation [S:6.1] is done on frame level, instead
// of on tag level, making it easier to skip frames, increasing the streamability
// of the tag. The unsynchronisation flag in the header [S:3.1] indicates that
// there exists an unsynchronised frame, while the new unsynchronisation flag in
// the frame header [S:4.1.2] indicates unsynchronisation.
//$framedataoffset = 10 + ($thisfile_id3v2['exthead']['length'] ? $thisfile_id3v2['exthead']['length'] + 4 : 0); // how many bytes into the stream - start from after the 10-byte header (and extended header length+4, if present)
$framedataoffset = 10; // how many bytes into the stream - start from after the 10-byte header
// Extended Header
if (!empty($thisfile_id3v2_flags['exthead'])) {
$extended_header_offset = 0;
if ($id3v2_majorversion == 3) {
// v2.3 definition:
//Extended header size $xx xx xx xx // 32-bit integer
//Extended Flags $xx xx
// %x0000000 %00000000 // v2.3
// x - CRC data present
//Size of padding $xx xx xx xx
$thisfile_id3v2['exthead']['length'] = getid3_lib::BigEndian2Int(substr($framedata, $extended_header_offset, 4), 0);
$extended_header_offset += 4;
$thisfile_id3v2['exthead']['flag_bytes'] = 2;
$thisfile_id3v2['exthead']['flag_raw'] = getid3_lib::BigEndian2Int(substr($framedata, $extended_header_offset, $thisfile_id3v2['exthead']['flag_bytes']));
$extended_header_offset += $thisfile_id3v2['exthead']['flag_bytes'];
$thisfile_id3v2['exthead']['flags']['crc'] = (bool) ($thisfile_id3v2['exthead']['flag_raw'] & 0x8000);
$thisfile_id3v2['exthead']['padding_size'] = getid3_lib::BigEndian2Int(substr($framedata, $extended_header_offset, 4));
$extended_header_offset += 4;
if ($thisfile_id3v2['exthead']['flags']['crc']) {
$thisfile_id3v2['exthead']['flag_data']['crc'] = getid3_lib::BigEndian2Int(substr($framedata, $extended_header_offset, 4));
$extended_header_offset += 4;
}
$extended_header_offset += $thisfile_id3v2['exthead']['padding_size'];
} elseif ($id3v2_majorversion == 4) {
// v2.4 definition:
//Extended header size 4 * %0xxxxxxx // 28-bit synchsafe integer
//Number of flag bytes $01
//Extended Flags $xx
// %0bcd0000 // v2.4
// b - Tag is an update
// Flag data length $00
// c - CRC data present
// Flag data length $05
// Total frame CRC 5 * %0xxxxxxx
// d - Tag restrictions
// Flag data length $01
$thisfile_id3v2['exthead']['length'] = getid3_lib::BigEndian2Int(substr($framedata, $extended_header_offset, 4), true);
$extended_header_offset += 4;
$thisfile_id3v2['exthead']['flag_bytes'] = getid3_lib::BigEndian2Int(substr($framedata, $extended_header_offset, 1)); // should always be 1
$extended_header_offset += 1;
$thisfile_id3v2['exthead']['flag_raw'] = getid3_lib::BigEndian2Int(substr($framedata, $extended_header_offset, $thisfile_id3v2['exthead']['flag_bytes']));
$extended_header_offset += $thisfile_id3v2['exthead']['flag_bytes'];
$thisfile_id3v2['exthead']['flags']['update'] = (bool) ($thisfile_id3v2['exthead']['flag_raw'] & 0x40);
$thisfile_id3v2['exthead']['flags']['crc'] = (bool) ($thisfile_id3v2['exthead']['flag_raw'] & 0x20);
$thisfile_id3v2['exthead']['flags']['restrictions'] = (bool) ($thisfile_id3v2['exthead']['flag_raw'] & 0x10);
if ($thisfile_id3v2['exthead']['flags']['update']) {
$ext_header_chunk_length = getid3_lib::BigEndian2Int(substr($framedata, $extended_header_offset, 1)); // should be 0
$extended_header_offset += 1;
}
if ($thisfile_id3v2['exthead']['flags']['crc']) {
$ext_header_chunk_length = getid3_lib::BigEndian2Int(substr($framedata, $extended_header_offset, 1)); // should be 5
$extended_header_offset += 1;
$thisfile_id3v2['exthead']['flag_data']['crc'] = getid3_lib::BigEndian2Int(substr($framedata, $extended_header_offset, $ext_header_chunk_length), true, false);
$extended_header_offset += $ext_header_chunk_length;
}
if ($thisfile_id3v2['exthead']['flags']['restrictions']) {
$ext_header_chunk_length = getid3_lib::BigEndian2Int(substr($framedata, $extended_header_offset, 1)); // should be 1
$extended_header_offset += 1;
// %ppqrrstt
$restrictions_raw = getid3_lib::BigEndian2Int(substr($framedata, $extended_header_offset, 1));
$extended_header_offset += 1;
$thisfile_id3v2['exthead']['flags']['restrictions']['tagsize'] = ($restrictions_raw & 0xC0) >> 6; // p - Tag size restrictions
$thisfile_id3v2['exthead']['flags']['restrictions']['textenc'] = ($restrictions_raw & 0x20) >> 5; // q - Text encoding restrictions
$thisfile_id3v2['exthead']['flags']['restrictions']['textsize'] = ($restrictions_raw & 0x18) >> 3; // r - Text fields size restrictions
$thisfile_id3v2['exthead']['flags']['restrictions']['imgenc'] = ($restrictions_raw & 0x04) >> 2; // s - Image encoding restrictions
$thisfile_id3v2['exthead']['flags']['restrictions']['imgsize'] = ($restrictions_raw & 0x03) >> 0; // t - Image size restrictions
$thisfile_id3v2['exthead']['flags']['restrictions_text']['tagsize'] = $this->LookupExtendedHeaderRestrictionsTagSizeLimits($thisfile_id3v2['exthead']['flags']['restrictions']['tagsize']);
$thisfile_id3v2['exthead']['flags']['restrictions_text']['textenc'] = $this->LookupExtendedHeaderRestrictionsTextEncodings($thisfile_id3v2['exthead']['flags']['restrictions']['textenc']);
$thisfile_id3v2['exthead']['flags']['restrictions_text']['textsize'] = $this->LookupExtendedHeaderRestrictionsTextFieldSize($thisfile_id3v2['exthead']['flags']['restrictions']['textsize']);
$thisfile_id3v2['exthead']['flags']['restrictions_text']['imgenc'] = $this->LookupExtendedHeaderRestrictionsImageEncoding($thisfile_id3v2['exthead']['flags']['restrictions']['imgenc']);
$thisfile_id3v2['exthead']['flags']['restrictions_text']['imgsize'] = $this->LookupExtendedHeaderRestrictionsImageSizeSize($thisfile_id3v2['exthead']['flags']['restrictions']['imgsize']);
}
if ($thisfile_id3v2['exthead']['length'] != $extended_header_offset) {
$info['warning'][] = 'ID3v2.4 extended header length mismatch (expecting '.intval($thisfile_id3v2['exthead']['length']).', found '.intval($extended_header_offset).')';
}
}
$framedataoffset += $extended_header_offset;
$framedata = substr($framedata, $extended_header_offset);
} // end extended header
while (isset($framedata) && (strlen($framedata) > 0)) { // cycle through until no more frame data is left to parse
if (strlen($framedata) <= $this->ID3v2HeaderLength($id3v2_majorversion)) {
// insufficient room left in ID3v2 header for actual data - must be padding
$thisfile_id3v2['padding']['start'] = $framedataoffset;
$thisfile_id3v2['padding']['length'] = strlen($framedata);
$thisfile_id3v2['padding']['valid'] = true;
for ($i = 0; $i < $thisfile_id3v2['padding']['length']; $i++) {
if ($framedata{$i} != "\x00") {
$thisfile_id3v2['padding']['valid'] = false;
$thisfile_id3v2['padding']['errorpos'] = $thisfile_id3v2['padding']['start'] + $i;
$info['warning'][] = 'Invalid ID3v2 padding found at offset '.$thisfile_id3v2['padding']['errorpos'].' (the remaining '.($thisfile_id3v2['padding']['length'] - $i).' bytes are considered invalid)';
break;
}
}
break; // skip rest of ID3v2 header
}
if ($id3v2_majorversion == 2) {
// Frame ID $xx xx xx (three characters)
// Size $xx xx xx (24-bit integer)
// Flags $xx xx
$frame_header = substr($framedata, 0, 6); // take next 6 bytes for header
$framedata = substr($framedata, 6); // and leave the rest in $framedata
$frame_name = substr($frame_header, 0, 3);
$frame_size = getid3_lib::BigEndian2Int(substr($frame_header, 3, 3), 0);
$frame_flags = 0; // not used for anything in ID3v2.2, just set to avoid E_NOTICEs
} elseif ($id3v2_majorversion > 2) {
// Frame ID $xx xx xx xx (four characters)
// Size $xx xx xx xx (32-bit integer in v2.3, 28-bit synchsafe in v2.4+)
// Flags $xx xx
$frame_header = substr($framedata, 0, 10); // take next 10 bytes for header
$framedata = substr($framedata, 10); // and leave the rest in $framedata
$frame_name = substr($frame_header, 0, 4);
if ($id3v2_majorversion == 3) {
$frame_size = getid3_lib::BigEndian2Int(substr($frame_header, 4, 4), 0); // 32-bit integer
} else { // ID3v2.4+
$frame_size = getid3_lib::BigEndian2Int(substr($frame_header, 4, 4), 1); // 32-bit synchsafe integer (28-bit value)
}
if ($frame_size < (strlen($framedata) + 4)) {
$nextFrameID = substr($framedata, $frame_size, 4);
if ($this->IsValidID3v2FrameName($nextFrameID, $id3v2_majorversion)) {
// next frame is OK
} elseif (($frame_name == "\x00".'MP3') || ($frame_name == "\x00\x00".'MP') || ($frame_name == ' MP3') || ($frame_name == 'MP3e')) {
// MP3ext known broken frames - "ok" for the purposes of this test
} elseif (($id3v2_majorversion == 4) && ($this->IsValidID3v2FrameName(substr($framedata, getid3_lib::BigEndian2Int(substr($frame_header, 4, 4), 0), 4), 3))) {
$info['warning'][] = 'ID3v2 tag written as ID3v2.4, but with non-synchsafe integers (ID3v2.3 style). Older versions of (Helium2; iTunes) are known culprits of this. Tag has been parsed as ID3v2.3';
$id3v2_majorversion = 3;
$frame_size = getid3_lib::BigEndian2Int(substr($frame_header, 4, 4), 0); // 32-bit integer
}
}
$frame_flags = getid3_lib::BigEndian2Int(substr($frame_header, 8, 2));
}
if ((($id3v2_majorversion == 2) && ($frame_name == "\x00\x00\x00")) || ($frame_name == "\x00\x00\x00\x00")) {
// padding encountered
$thisfile_id3v2['padding']['start'] = $framedataoffset;
$thisfile_id3v2['padding']['length'] = strlen($frame_header) + strlen($framedata);
$thisfile_id3v2['padding']['valid'] = true;
$len = strlen($framedata);
for ($i = 0; $i < $len; $i++) {
if ($framedata{$i} != "\x00") {
$thisfile_id3v2['padding']['valid'] = false;
$thisfile_id3v2['padding']['errorpos'] = $thisfile_id3v2['padding']['start'] + $i;
$info['warning'][] = 'Invalid ID3v2 padding found at offset '.$thisfile_id3v2['padding']['errorpos'].' (the remaining '.($thisfile_id3v2['padding']['length'] - $i).' bytes are considered invalid)';
break;
}
}
break; // skip rest of ID3v2 header
}
if ($frame_name == 'COM ') {
$info['warning'][] = 'error parsing "'.$frame_name.'" ('.$framedataoffset.' bytes into the ID3v2.'.$id3v2_majorversion.' tag). (ERROR: IsValidID3v2FrameName("'.str_replace("\x00", ' ', $frame_name).'", '.$id3v2_majorversion.'))). [Note: this particular error has been known to happen with tags edited by iTunes (versions "X v2.0.3", "v3.0.1" are known-guilty, probably others too)]';
$frame_name = 'COMM';
}
if (($frame_size <= strlen($framedata)) && ($this->IsValidID3v2FrameName($frame_name, $id3v2_majorversion))) {
unset($parsedFrame);
$parsedFrame['frame_name'] = $frame_name;
$parsedFrame['frame_flags_raw'] = $frame_flags;
$parsedFrame['data'] = substr($framedata, 0, $frame_size);
$parsedFrame['datalength'] = getid3_lib::CastAsInt($frame_size);
$parsedFrame['dataoffset'] = $framedataoffset;
$this->ParseID3v2Frame($parsedFrame);
$thisfile_id3v2[$frame_name][] = $parsedFrame;
$framedata = substr($framedata, $frame_size);
} else { // invalid frame length or FrameID
if ($frame_size <= strlen($framedata)) {
if ($this->IsValidID3v2FrameName(substr($framedata, $frame_size, 4), $id3v2_majorversion)) {
// next frame is valid, just skip the current frame
$framedata = substr($framedata, $frame_size);
$info['warning'][] = 'Next ID3v2 frame is valid, skipping current frame.';
} else {
// next frame is invalid too, abort processing
//unset($framedata);
$framedata = null;
$info['error'][] = 'Next ID3v2 frame is also invalid, aborting processing.';
}
} elseif ($frame_size == strlen($framedata)) {
// this is the last frame, just skip
$info['warning'][] = 'This was the last ID3v2 frame.';
} else {
// next frame is invalid too, abort processing
//unset($framedata);
$framedata = null;
$info['warning'][] = 'Invalid ID3v2 frame size, aborting.';
}
if (!$this->IsValidID3v2FrameName($frame_name, $id3v2_majorversion)) {
switch ($frame_name) {
case "\x00\x00".'MP':
case "\x00".'MP3':
case ' MP3':
case 'MP3e':
case "\x00".'MP':
case ' MP':
case 'MP3':
$info['warning'][] = 'error parsing "'.$frame_name.'" ('.$framedataoffset.' bytes into the ID3v2.'.$id3v2_majorversion.' tag). (ERROR: !IsValidID3v2FrameName("'.str_replace("\x00", ' ', $frame_name).'", '.$id3v2_majorversion.'))). [Note: this particular error has been known to happen with tags edited by "MP3ext (www.mutschler.de/mp3ext/)"]';
break;
default:
$info['warning'][] = 'error parsing "'.$frame_name.'" ('.$framedataoffset.' bytes into the ID3v2.'.$id3v2_majorversion.' tag). (ERROR: !IsValidID3v2FrameName("'.str_replace("\x00", ' ', $frame_name).'", '.$id3v2_majorversion.'))).';
break;
}
} elseif (!isset($framedata) || ($frame_size > strlen($framedata))) {
$info['error'][] = 'error parsing "'.$frame_name.'" ('.$framedataoffset.' bytes into the ID3v2.'.$id3v2_majorversion.' tag). (ERROR: $frame_size ('.$frame_size.') > strlen($framedata) ('.(isset($framedata) ? strlen($framedata) : 'null').')).';
} else {
$info['error'][] = 'error parsing "'.$frame_name.'" ('.$framedataoffset.' bytes into the ID3v2.'.$id3v2_majorversion.' tag).';
}
}
$framedataoffset += ($frame_size + $this->ID3v2HeaderLength($id3v2_majorversion));
}
}
// Footer
// The footer is a copy of the header, but with a different identifier.
// ID3v2 identifier "3DI"
// ID3v2 version $04 00
// ID3v2 flags %abcd0000
// ID3v2 size 4 * %0xxxxxxx
if (isset($thisfile_id3v2_flags['isfooter']) && $thisfile_id3v2_flags['isfooter']) {
$footer = fread($this->getid3->fp, 10);
if (substr($footer, 0, 3) == '3DI') {
$thisfile_id3v2['footer'] = true;
$thisfile_id3v2['majorversion_footer'] = ord($footer{3});
$thisfile_id3v2['minorversion_footer'] = ord($footer{4});
}
if ($thisfile_id3v2['majorversion_footer'] <= 4) {
$id3_flags = ord(substr($footer{5}));
$thisfile_id3v2_flags['unsynch_footer'] = (bool) ($id3_flags & 0x80);
$thisfile_id3v2_flags['extfoot_footer'] = (bool) ($id3_flags & 0x40);
$thisfile_id3v2_flags['experim_footer'] = (bool) ($id3_flags & 0x20);
$thisfile_id3v2_flags['isfooter_footer'] = (bool) ($id3_flags & 0x10);
$thisfile_id3v2['footerlength'] = getid3_lib::BigEndian2Int(substr($footer, 6, 4), 1);
}
} // end footer
if (isset($thisfile_id3v2['comments']['genre'])) {
foreach ($thisfile_id3v2['comments']['genre'] as $key => $value) {
unset($thisfile_id3v2['comments']['genre'][$key]);
$thisfile_id3v2['comments'] = getid3_lib::array_merge_noclobber($thisfile_id3v2['comments'], array('genre'=>$this->ParseID3v2GenreString($value)));
}
}
if (isset($thisfile_id3v2['comments']['track'])) {
foreach ($thisfile_id3v2['comments']['track'] as $key => $value) {
if (strstr($value, '/')) {
list($thisfile_id3v2['comments']['tracknum'][$key], $thisfile_id3v2['comments']['totaltracks'][$key]) = explode('/', $thisfile_id3v2['comments']['track'][$key]);
}
}
}
if (!isset($thisfile_id3v2['comments']['year']) && !empty($thisfile_id3v2['comments']['recording_time'][0]) && preg_match('#^([0-9]{4})#', trim($thisfile_id3v2['comments']['recording_time'][0]), $matches)) {
$thisfile_id3v2['comments']['year'] = array($matches[1]);
}
if (!empty($thisfile_id3v2['TXXX'])) {
// MediaMonkey does this, maybe others: write a blank RGAD frame, but put replay-gain adjustment values in TXXX frames
foreach ($thisfile_id3v2['TXXX'] as $txxx_array) {
switch ($txxx_array['description']) {
case 'replaygain_track_gain':
if (empty($info['replay_gain']['track']['adjustment']) && !empty($txxx_array['data'])) {
$info['replay_gain']['track']['adjustment'] = floatval(trim(str_replace('dB', '', $txxx_array['data'])));
}
break;
case 'replaygain_track_peak':
if (empty($info['replay_gain']['track']['peak']) && !empty($txxx_array['data'])) {
$info['replay_gain']['track']['peak'] = floatval($txxx_array['data']);
}
break;
case 'replaygain_album_gain':
if (empty($info['replay_gain']['album']['adjustment']) && !empty($txxx_array['data'])) {
$info['replay_gain']['album']['adjustment'] = floatval(trim(str_replace('dB', '', $txxx_array['data'])));
}
break;
}
}
}
// Set avdataoffset
$info['avdataoffset'] = $thisfile_id3v2['headerlength'];
if (isset($thisfile_id3v2['footer'])) {
$info['avdataoffset'] += 10;
}
return true;
}
public function ParseID3v2GenreString($genrestring) {
// Parse genres into arrays of genreName and genreID
// ID3v2.2.x, ID3v2.3.x: '(21)' or '(4)Eurodisco' or '(51)(39)' or '(55)((I think...)'
// ID3v2.4.x: '21' $00 'Eurodisco' $00
$clean_genres = array();
if (strpos($genrestring, "\x00") === false) {
$genrestring = preg_replace('#\(([0-9]{1,3})\)#', '$1'."\x00", $genrestring);
}
$genre_elements = explode("\x00", $genrestring);
foreach ($genre_elements as $element) {
$element = trim($element);
if ($element) {
if (preg_match('#^[0-9]{1,3}#', $element)) {
$clean_genres[] = getid3_id3v1::LookupGenreName($element);
} else {
$clean_genres[] = str_replace('((', '(', $element);
}
}
}
return $clean_genres;
}
public function ParseID3v2Frame(&$parsedFrame) {
// shortcuts
$info = &$this->getid3->info;
$id3v2_majorversion = $info['id3v2']['majorversion'];
$parsedFrame['framenamelong'] = $this->FrameNameLongLookup($parsedFrame['frame_name']);
if (empty($parsedFrame['framenamelong'])) {
unset($parsedFrame['framenamelong']);
}
$parsedFrame['framenameshort'] = $this->FrameNameShortLookup($parsedFrame['frame_name']);
if (empty($parsedFrame['framenameshort'])) {
unset($parsedFrame['framenameshort']);
}
if ($id3v2_majorversion >= 3) { // frame flags are not part of the ID3v2.2 standard
if ($id3v2_majorversion == 3) {
// Frame Header Flags
// %abc00000 %ijk00000
$parsedFrame['flags']['TagAlterPreservation'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x8000); // a - Tag alter preservation
$parsedFrame['flags']['FileAlterPreservation'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x4000); // b - File alter preservation
$parsedFrame['flags']['ReadOnly'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x2000); // c - Read only
$parsedFrame['flags']['compression'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x0080); // i - Compression
$parsedFrame['flags']['Encryption'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x0040); // j - Encryption
$parsedFrame['flags']['GroupingIdentity'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x0020); // k - Grouping identity
} elseif ($id3v2_majorversion == 4) {
// Frame Header Flags
// %0abc0000 %0h00kmnp
$parsedFrame['flags']['TagAlterPreservation'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x4000); // a - Tag alter preservation
$parsedFrame['flags']['FileAlterPreservation'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x2000); // b - File alter preservation
$parsedFrame['flags']['ReadOnly'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x1000); // c - Read only
$parsedFrame['flags']['GroupingIdentity'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x0040); // h - Grouping identity
$parsedFrame['flags']['compression'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x0008); // k - Compression
$parsedFrame['flags']['Encryption'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x0004); // m - Encryption
$parsedFrame['flags']['Unsynchronisation'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x0002); // n - Unsynchronisation
$parsedFrame['flags']['DataLengthIndicator'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x0001); // p - Data length indicator
// Frame-level de-unsynchronisation - ID3v2.4
if ($parsedFrame['flags']['Unsynchronisation']) {
$parsedFrame['data'] = $this->DeUnsynchronise($parsedFrame['data']);
}
if ($parsedFrame['flags']['DataLengthIndicator']) {
$parsedFrame['data_length_indicator'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], 0, 4), 1);
$parsedFrame['data'] = substr($parsedFrame['data'], 4);
}
}
// Frame-level de-compression
if ($parsedFrame['flags']['compression']) {
$parsedFrame['decompressed_size'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], 0, 4));
if (!function_exists('gzuncompress')) {
$info['warning'][] = 'gzuncompress() support required to decompress ID3v2 frame "'.$parsedFrame['frame_name'].'"';
} else {
if ($decompresseddata = @gzuncompress(substr($parsedFrame['data'], 4))) {
//if ($decompresseddata = @gzuncompress($parsedFrame['data'])) {
$parsedFrame['data'] = $decompresseddata;
unset($decompresseddata);
} else {
$info['warning'][] = 'gzuncompress() failed on compressed contents of ID3v2 frame "'.$parsedFrame['frame_name'].'"';
}
}
}
}
if (!empty($parsedFrame['flags']['DataLengthIndicator'])) {
if ($parsedFrame['data_length_indicator'] != strlen($parsedFrame['data'])) {
$info['warning'][] = 'ID3v2 frame "'.$parsedFrame['frame_name'].'" should be '.$parsedFrame['data_length_indicator'].' bytes long according to DataLengthIndicator, but found '.strlen($parsedFrame['data']).' bytes of data';
}
}
if (isset($parsedFrame['datalength']) && ($parsedFrame['datalength'] == 0)) {
$warning = 'Frame "'.$parsedFrame['frame_name'].'" at offset '.$parsedFrame['dataoffset'].' has no data portion';
switch ($parsedFrame['frame_name']) {
case 'WCOM':
$warning .= ' (this is known to happen with files tagged by RioPort)';
break;
default:
break;
}
$info['warning'][] = $warning;
} elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'UFID')) || // 4.1 UFID Unique file identifier
(($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'UFI'))) { // 4.1 UFI Unique file identifier
// There may be more than one 'UFID' frame in a tag,
// but only one with the same 'Owner identifier'.
// <Header for 'Unique file identifier', ID: 'UFID'>
// Owner identifier <text string> $00
// Identifier <up to 64 bytes binary data>
$exploded = explode("\x00", $parsedFrame['data'], 2);
$parsedFrame['ownerid'] = (isset($exploded[0]) ? $exploded[0] : '');
$parsedFrame['data'] = (isset($exploded[1]) ? $exploded[1] : '');
} elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'TXXX')) || // 4.2.2 TXXX User defined text information frame
(($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'TXX'))) { // 4.2.2 TXX User defined text information frame
// There may be more than one 'TXXX' frame in each tag,
// but only one with the same description.
// <Header for 'User defined text information frame', ID: 'TXXX'>
// Text encoding $xx
// Description <text string according to encoding> $00 (00)
// Value <text string according to encoding>
$frame_offset = 0;
$frame_textencoding = ord(substr($parsedFrame['data'], $frame_offset++, 1));
if ((($id3v2_majorversion <= 3) && ($frame_textencoding > 1)) || (($id3v2_majorversion == 4) && ($frame_textencoding > 3))) {
$info['warning'][] = 'Invalid text encoding byte ('.$frame_textencoding.') in frame "'.$parsedFrame['frame_name'].'" - defaulting to ISO-8859-1 encoding';
}
$frame_terminatorpos = strpos($parsedFrame['data'], $this->TextEncodingTerminatorLookup($frame_textencoding), $frame_offset);
if (ord(substr($parsedFrame['data'], $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding)), 1)) === 0) {
$frame_terminatorpos++; // strpos() fooled because 2nd byte of Unicode chars are often 0x00
}
$frame_description = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset);
if (ord($frame_description) === 0) {
$frame_description = '';
}
$parsedFrame['encodingid'] = $frame_textencoding;
$parsedFrame['encoding'] = $this->TextEncodingNameLookup($frame_textencoding);
$parsedFrame['description'] = $frame_description;
$parsedFrame['data'] = substr($parsedFrame['data'], $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding)));
if (!empty($parsedFrame['framenameshort']) && !empty($parsedFrame['data'])) {
$info['id3v2']['comments'][$parsedFrame['framenameshort']][] = trim(getid3_lib::iconv_fallback($parsedFrame['encoding'], $info['id3v2']['encoding'], $parsedFrame['data']));
}
//unset($parsedFrame['data']); do not unset, may be needed elsewhere, e.g. for replaygain
} elseif ($parsedFrame['frame_name']{0} == 'T') { // 4.2. T??[?] Text information frame
// There may only be one text information frame of its kind in an tag.
// <Header for 'Text information frame', ID: 'T000' - 'TZZZ',
// excluding 'TXXX' described in 4.2.6.>
// Text encoding $xx
// Information <text string(s) according to encoding>
$frame_offset = 0;
$frame_textencoding = ord(substr($parsedFrame['data'], $frame_offset++, 1));
if ((($id3v2_majorversion <= 3) && ($frame_textencoding > 1)) || (($id3v2_majorversion == 4) && ($frame_textencoding > 3))) {
$info['warning'][] = 'Invalid text encoding byte ('.$frame_textencoding.') in frame "'.$parsedFrame['frame_name'].'" - defaulting to ISO-8859-1 encoding';
}
$parsedFrame['data'] = (string) substr($parsedFrame['data'], $frame_offset);
$parsedFrame['encodingid'] = $frame_textencoding;
$parsedFrame['encoding'] = $this->TextEncodingNameLookup($frame_textencoding);
if (!empty($parsedFrame['framenameshort']) && !empty($parsedFrame['data'])) {
// ID3v2.3 specs say that TPE1 (and others) can contain multiple artist values separated with /
// This of course breaks when an artist name contains slash character, e.g. "AC/DC"
// MP3tag (maybe others) implement alternative system where multiple artists are null-separated, which makes more sense
// getID3 will split null-separated artists into multiple artists and leave slash-separated ones to the user
switch ($parsedFrame['encoding']) {
case 'UTF-16':
case 'UTF-16BE':
case 'UTF-16LE':
$wordsize = 2;
break;
case 'ISO-8859-1':
case 'UTF-8':
default:
$wordsize = 1;
break;
}
$Txxx_elements = array();
$Txxx_elements_start_offset = 0;
for ($i = 0; $i < strlen($parsedFrame['data']); $i += $wordsize) {
if (substr($parsedFrame['data'], $i, $wordsize) == str_repeat("\x00", $wordsize)) {
$Txxx_elements[] = substr($parsedFrame['data'], $Txxx_elements_start_offset, $i - $Txxx_elements_start_offset);
$Txxx_elements_start_offset = $i + $wordsize;
}
}
$Txxx_elements[] = substr($parsedFrame['data'], $Txxx_elements_start_offset, $i - $Txxx_elements_start_offset);
foreach ($Txxx_elements as $Txxx_element) {
$string = getid3_lib::iconv_fallback($parsedFrame['encoding'], $info['id3v2']['encoding'], $Txxx_element);
if (!empty($string)) {
$info['id3v2']['comments'][$parsedFrame['framenameshort']][] = $string;
}
}
unset($string, $wordsize, $i, $Txxx_elements, $Txxx_element, $Txxx_elements_start_offset);
}
} elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'WXXX')) || // 4.3.2 WXXX User defined URL link frame
(($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'WXX'))) { // 4.3.2 WXX User defined URL link frame
// There may be more than one 'WXXX' frame in each tag,
// but only one with the same description
// <Header for 'User defined URL link frame', ID: 'WXXX'>
// Text encoding $xx
// Description <text string according to encoding> $00 (00)
// URL <text string>
$frame_offset = 0;
$frame_textencoding = ord(substr($parsedFrame['data'], $frame_offset++, 1));
if ((($id3v2_majorversion <= 3) && ($frame_textencoding > 1)) || (($id3v2_majorversion == 4) && ($frame_textencoding > 3))) {
$info['warning'][] = 'Invalid text encoding byte ('.$frame_textencoding.') in frame "'.$parsedFrame['frame_name'].'" - defaulting to ISO-8859-1 encoding';
}
$frame_terminatorpos = strpos($parsedFrame['data'], $this->TextEncodingTerminatorLookup($frame_textencoding), $frame_offset);
if (ord(substr($parsedFrame['data'], $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding)), 1)) === 0) {
$frame_terminatorpos++; // strpos() fooled because 2nd byte of Unicode chars are often 0x00
}
$frame_description = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset);
if (ord($frame_description) === 0) {
$frame_description = '';
}
$parsedFrame['data'] = substr($parsedFrame['data'], $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding)));
$frame_terminatorpos = strpos($parsedFrame['data'], $this->TextEncodingTerminatorLookup($frame_textencoding));
if (ord(substr($parsedFrame['data'], $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding)), 1)) === 0) {
$frame_terminatorpos++; // strpos() fooled because 2nd byte of Unicode chars are often 0x00
}
if ($frame_terminatorpos) {
// there are null bytes after the data - this is not according to spec
// only use data up to first null byte
$frame_urldata = (string) substr($parsedFrame['data'], 0, $frame_terminatorpos);
} else {
// no null bytes following data, just use all data
$frame_urldata = (string) $parsedFrame['data'];
}
$parsedFrame['encodingid'] = $frame_textencoding;
$parsedFrame['encoding'] = $this->TextEncodingNameLookup($frame_textencoding);
$parsedFrame['url'] = $frame_urldata;
$parsedFrame['description'] = $frame_description;
if (!empty($parsedFrame['framenameshort']) && $parsedFrame['url']) {
$info['id3v2']['comments'][$parsedFrame['framenameshort']][] = getid3_lib::iconv_fallback($parsedFrame['encoding'], $info['id3v2']['encoding'], $parsedFrame['url']);
}
unset($parsedFrame['data']);
} elseif ($parsedFrame['frame_name']{0} == 'W') { // 4.3. W??? URL link frames
// There may only be one URL link frame of its kind in a tag,
// except when stated otherwise in the frame description
// <Header for 'URL link frame', ID: 'W000' - 'WZZZ', excluding 'WXXX'
// described in 4.3.2.>
// URL <text string>
$parsedFrame['url'] = trim($parsedFrame['data']);
if (!empty($parsedFrame['framenameshort']) && $parsedFrame['url']) {
$info['id3v2']['comments'][$parsedFrame['framenameshort']][] = $parsedFrame['url'];
}
unset($parsedFrame['data']);
} elseif ((($id3v2_majorversion == 3) && ($parsedFrame['frame_name'] == 'IPLS')) || // 4.4 IPLS Involved people list (ID3v2.3 only)
(($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'IPL'))) { // 4.4 IPL Involved people list (ID3v2.2 only)
// http://id3.org/id3v2.3.0#sec4.4
// There may only be one 'IPL' frame in each tag
// <Header for 'User defined URL link frame', ID: 'IPL'>
// Text encoding $xx
// People list strings <textstrings>
$frame_offset = 0;
$frame_textencoding = ord(substr($parsedFrame['data'], $frame_offset++, 1));
if ((($id3v2_majorversion <= 3) && ($frame_textencoding > 1)) || (($id3v2_majorversion == 4) && ($frame_textencoding > 3))) {
$info['warning'][] = 'Invalid text encoding byte ('.$frame_textencoding.') in frame "'.$parsedFrame['frame_name'].'" - defaulting to ISO-8859-1 encoding';
}
$parsedFrame['encodingid'] = $frame_textencoding;
$parsedFrame['encoding'] = $this->TextEncodingNameLookup($parsedFrame['encodingid']);
$parsedFrame['data_raw'] = (string) substr($parsedFrame['data'], $frame_offset);
// http://www.getid3.org/phpBB3/viewtopic.php?t=1369
// "this tag typically contains null terminated strings, which are associated in pairs"
// "there are users that use the tag incorrectly"
$IPLS_parts = array();
if (strpos($parsedFrame['data_raw'], "\x00") !== false) {
$IPLS_parts_unsorted = array();
if (((strlen($parsedFrame['data_raw']) % 2) == 0) && ((substr($parsedFrame['data_raw'], 0, 2) == "\xFF\xFE") || (substr($parsedFrame['data_raw'], 0, 2) == "\xFE\xFF"))) {
// UTF-16, be careful looking for null bytes since most 2-byte characters may contain one; you need to find twin null bytes, and on even padding
$thisILPS = '';
for ($i = 0; $i < strlen($parsedFrame['data_raw']); $i += 2) {
$twobytes = substr($parsedFrame['data_raw'], $i, 2);
if ($twobytes === "\x00\x00") {
$IPLS_parts_unsorted[] = getid3_lib::iconv_fallback($parsedFrame['encoding'], $info['id3v2']['encoding'], $thisILPS);
$thisILPS = '';
} else {
$thisILPS .= $twobytes;
}
}
if (strlen($thisILPS) > 2) { // 2-byte BOM
$IPLS_parts_unsorted[] = getid3_lib::iconv_fallback($parsedFrame['encoding'], $info['id3v2']['encoding'], $thisILPS);
}
} else {
// ISO-8859-1 or UTF-8 or other single-byte-null character set
$IPLS_parts_unsorted = explode("\x00", $parsedFrame['data_raw']);
}
if (count($IPLS_parts_unsorted) == 1) {
// just a list of names, e.g. "Dino Baptiste, Jimmy Copley, John Gordon, Bernie Marsden, Sharon Watson"
foreach ($IPLS_parts_unsorted as $key => $value) {
$IPLS_parts_sorted = preg_split('#[;,\\r\\n\\t]#', $value);
$position = '';
foreach ($IPLS_parts_sorted as $person) {
$IPLS_parts[] = array('position'=>$position, 'person'=>$person);
}
}
} elseif ((count($IPLS_parts_unsorted) % 2) == 0) {
$position = '';
$person = '';
foreach ($IPLS_parts_unsorted as $key => $value) {
if (($key % 2) == 0) {
$position = $value;
} else {
$person = $value;
$IPLS_parts[] = array('position'=>$position, 'person'=>$person);
$position = '';
$person = '';
}
}
} else {
foreach ($IPLS_parts_unsorted as $key => $value) {
$IPLS_parts[] = array($value);
}
}
} else {
$IPLS_parts = preg_split('#[;,\\r\\n\\t]#', $parsedFrame['data_raw']);
}
$parsedFrame['data'] = $IPLS_parts;
if (!empty($parsedFrame['framenameshort']) && !empty($parsedFrame['data'])) {
$info['id3v2']['comments'][$parsedFrame['framenameshort']][] = $parsedFrame['data'];
}
} elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'MCDI')) || // 4.4 MCDI Music CD identifier
(($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'MCI'))) { // 4.5 MCI Music CD identifier
// There may only be one 'MCDI' frame in each tag
// <Header for 'Music CD identifier', ID: 'MCDI'>
// CD TOC <binary data>
if (!empty($parsedFrame['framenameshort']) && !empty($parsedFrame['data'])) {
$info['id3v2']['comments'][$parsedFrame['framenameshort']][] = $parsedFrame['data'];
}
} elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'ETCO')) || // 4.5 ETCO Event timing codes
(($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'ETC'))) { // 4.6 ETC Event timing codes
// There may only be one 'ETCO' frame in each tag
// <Header for 'Event timing codes', ID: 'ETCO'>
// Time stamp format $xx
// Where time stamp format is:
// $01 (32-bit value) MPEG frames from beginning of file
// $02 (32-bit value) milliseconds from beginning of file
// Followed by a list of key events in the following format:
// Type of event $xx
// Time stamp $xx (xx ...)
// The 'Time stamp' is set to zero if directly at the beginning of the sound
// or after the previous event. All events MUST be sorted in chronological order.
$frame_offset = 0;
$parsedFrame['timestampformat'] = ord(substr($parsedFrame['data'], $frame_offset++, 1));
while ($frame_offset < strlen($parsedFrame['data'])) {
$parsedFrame['typeid'] = substr($parsedFrame['data'], $frame_offset++, 1);
$parsedFrame['type'] = $this->ETCOEventLookup($parsedFrame['typeid']);
$parsedFrame['timestamp'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 4));
$frame_offset += 4;
}
unset($parsedFrame['data']);
} elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'MLLT')) || // 4.6 MLLT MPEG location lookup table
(($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'MLL'))) { // 4.7 MLL MPEG location lookup table
// There may only be one 'MLLT' frame in each tag
// <Header for 'Location lookup table', ID: 'MLLT'>
// MPEG frames between reference $xx xx
// Bytes between reference $xx xx xx
// Milliseconds between reference $xx xx xx
// Bits for bytes deviation $xx
// Bits for milliseconds dev. $xx
// Then for every reference the following data is included;
// Deviation in bytes %xxx....
// Deviation in milliseconds %xxx....
$frame_offset = 0;
$parsedFrame['framesbetweenreferences'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], 0, 2));
$parsedFrame['bytesbetweenreferences'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], 2, 3));
$parsedFrame['msbetweenreferences'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], 5, 3));
$parsedFrame['bitsforbytesdeviation'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], 8, 1));
$parsedFrame['bitsformsdeviation'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], 9, 1));
$parsedFrame['data'] = substr($parsedFrame['data'], 10);
while ($frame_offset < strlen($parsedFrame['data'])) {
$deviationbitstream .= getid3_lib::BigEndian2Bin(substr($parsedFrame['data'], $frame_offset++, 1));
}
$reference_counter = 0;
while (strlen($deviationbitstream) > 0) {
$parsedFrame[$reference_counter]['bytedeviation'] = bindec(substr($deviationbitstream, 0, $parsedFrame['bitsforbytesdeviation']));
$parsedFrame[$reference_counter]['msdeviation'] = bindec(substr($deviationbitstream, $parsedFrame['bitsforbytesdeviation'], $parsedFrame['bitsformsdeviation']));
$deviationbitstream = substr($deviationbitstream, $parsedFrame['bitsforbytesdeviation'] + $parsedFrame['bitsformsdeviation']);
$reference_counter++;
}
unset($parsedFrame['data']);
} elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'SYTC')) || // 4.7 SYTC Synchronised tempo codes
(($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'STC'))) { // 4.8 STC Synchronised tempo codes
// There may only be one 'SYTC' frame in each tag
// <Header for 'Synchronised tempo codes', ID: 'SYTC'>
// Time stamp format $xx
// Tempo data <binary data>
// Where time stamp format is:
// $01 (32-bit value) MPEG frames from beginning of file
// $02 (32-bit value) milliseconds from beginning of file
$frame_offset = 0;
$parsedFrame['timestampformat'] = ord(substr($parsedFrame['data'], $frame_offset++, 1));
$timestamp_counter = 0;
while ($frame_offset < strlen($parsedFrame['data'])) {
$parsedFrame[$timestamp_counter]['tempo'] = ord(substr($parsedFrame['data'], $frame_offset++, 1));
if ($parsedFrame[$timestamp_counter]['tempo'] == 255) {
$parsedFrame[$timestamp_counter]['tempo'] += ord(substr($parsedFrame['data'], $frame_offset++, 1));
}
$parsedFrame[$timestamp_counter]['timestamp'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 4));
$frame_offset += 4;
$timestamp_counter++;
}
unset($parsedFrame['data']);
} elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'USLT')) || // 4.8 USLT Unsynchronised lyric/text transcription
(($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'ULT'))) { // 4.9 ULT Unsynchronised lyric/text transcription
// There may be more than one 'Unsynchronised lyrics/text transcription' frame
// in each tag, but only one with the same language and content descriptor.
// <Header for 'Unsynchronised lyrics/text transcription', ID: 'USLT'>
// Text encoding $xx
// Language $xx xx xx
// Content descriptor <text string according to encoding> $00 (00)
// Lyrics/text <full text string according to encoding>
$frame_offset = 0;
$frame_textencoding = ord(substr($parsedFrame['data'], $frame_offset++, 1));
if ((($id3v2_majorversion <= 3) && ($frame_textencoding > 1)) || (($id3v2_majorversion == 4) && ($frame_textencoding > 3))) {
$info['warning'][] = 'Invalid text encoding byte ('.$frame_textencoding.') in frame "'.$parsedFrame['frame_name'].'" - defaulting to ISO-8859-1 encoding';
}
$frame_language = substr($parsedFrame['data'], $frame_offset, 3);
$frame_offset += 3;
$frame_terminatorpos = strpos($parsedFrame['data'], $this->TextEncodingTerminatorLookup($frame_textencoding), $frame_offset);
if (ord(substr($parsedFrame['data'], $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding)), 1)) === 0) {
$frame_terminatorpos++; // strpos() fooled because 2nd byte of Unicode chars are often 0x00
}
$frame_description = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset);
if (ord($frame_description) === 0) {
$frame_description = '';
}
$parsedFrame['data'] = substr($parsedFrame['data'], $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding)));
$parsedFrame['encodingid'] = $frame_textencoding;
$parsedFrame['encoding'] = $this->TextEncodingNameLookup($frame_textencoding);
$parsedFrame['data'] = $parsedFrame['data'];
$parsedFrame['language'] = $frame_language;
$parsedFrame['languagename'] = $this->LanguageLookup($frame_language, false);
$parsedFrame['description'] = $frame_description;
if (!empty($parsedFrame['framenameshort']) && !empty($parsedFrame['data'])) {
$info['id3v2']['comments'][$parsedFrame['framenameshort']][] = getid3_lib::iconv_fallback($parsedFrame['encoding'], $info['id3v2']['encoding'], $parsedFrame['data']);
}
unset($parsedFrame['data']);
} elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'SYLT')) || // 4.9 SYLT Synchronised lyric/text
(($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'SLT'))) { // 4.10 SLT Synchronised lyric/text
// There may be more than one 'SYLT' frame in each tag,
// but only one with the same language and content descriptor.
// <Header for 'Synchronised lyrics/text', ID: 'SYLT'>
// Text encoding $xx
// Language $xx xx xx
// Time stamp format $xx
// $01 (32-bit value) MPEG frames from beginning of file
// $02 (32-bit value) milliseconds from beginning of file
// Content type $xx
// Content descriptor <text string according to encoding> $00 (00)
// Terminated text to be synced (typically a syllable)
// Sync identifier (terminator to above string) $00 (00)
// Time stamp $xx (xx ...)
$frame_offset = 0;
$frame_textencoding = ord(substr($parsedFrame['data'], $frame_offset++, 1));
if ((($id3v2_majorversion <= 3) && ($frame_textencoding > 1)) || (($id3v2_majorversion == 4) && ($frame_textencoding > 3))) {
$info['warning'][] = 'Invalid text encoding byte ('.$frame_textencoding.') in frame "'.$parsedFrame['frame_name'].'" - defaulting to ISO-8859-1 encoding';
}
$frame_language = substr($parsedFrame['data'], $frame_offset, 3);
$frame_offset += 3;
$parsedFrame['timestampformat'] = ord(substr($parsedFrame['data'], $frame_offset++, 1));
$parsedFrame['contenttypeid'] = ord(substr($parsedFrame['data'], $frame_offset++, 1));
$parsedFrame['contenttype'] = $this->SYTLContentTypeLookup($parsedFrame['contenttypeid']);
$parsedFrame['encodingid'] = $frame_textencoding;
$parsedFrame['encoding'] = $this->TextEncodingNameLookup($frame_textencoding);
$parsedFrame['language'] = $frame_language;
$parsedFrame['languagename'] = $this->LanguageLookup($frame_language, false);
$timestampindex = 0;
$frame_remainingdata = substr($parsedFrame['data'], $frame_offset);
while (strlen($frame_remainingdata)) {
$frame_offset = 0;
$frame_terminatorpos = strpos($frame_remainingdata, $this->TextEncodingTerminatorLookup($frame_textencoding));
if ($frame_terminatorpos === false) {
$frame_remainingdata = '';
} else {
if (ord(substr($frame_remainingdata, $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding)), 1)) === 0) {
$frame_terminatorpos++; // strpos() fooled because 2nd byte of Unicode chars are often 0x00
}
$parsedFrame['lyrics'][$timestampindex]['data'] = substr($frame_remainingdata, $frame_offset, $frame_terminatorpos - $frame_offset);
$frame_remainingdata = substr($frame_remainingdata, $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding)));
if (($timestampindex == 0) && (ord($frame_remainingdata{0}) != 0)) {
// timestamp probably omitted for first data item
} else {
$parsedFrame['lyrics'][$timestampindex]['timestamp'] = getid3_lib::BigEndian2Int(substr($frame_remainingdata, 0, 4));
$frame_remainingdata = substr($frame_remainingdata, 4);
}
$timestampindex++;
}
}
unset($parsedFrame['data']);
} elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'COMM')) || // 4.10 COMM Comments
(($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'COM'))) { // 4.11 COM Comments
// There may be more than one comment frame in each tag,
// but only one with the same language and content descriptor.
// <Header for 'Comment', ID: 'COMM'>
// Text encoding $xx
// Language $xx xx xx
// Short content descrip. <text string according to encoding> $00 (00)
// The actual text <full text string according to encoding>
if (strlen($parsedFrame['data']) < 5) {
$info['warning'][] = 'Invalid data (too short) for "'.$parsedFrame['frame_name'].'" frame at offset '.$parsedFrame['dataoffset'];
} else {
$frame_offset = 0;
$frame_textencoding = ord(substr($parsedFrame['data'], $frame_offset++, 1));
if ((($id3v2_majorversion <= 3) && ($frame_textencoding > 1)) || (($id3v2_majorversion == 4) && ($frame_textencoding > 3))) {
$info['warning'][] = 'Invalid text encoding byte ('.$frame_textencoding.') in frame "'.$parsedFrame['frame_name'].'" - defaulting to ISO-8859-1 encoding';
}
$frame_language = substr($parsedFrame['data'], $frame_offset, 3);
$frame_offset += 3;
$frame_terminatorpos = strpos($parsedFrame['data'], $this->TextEncodingTerminatorLookup($frame_textencoding), $frame_offset);
if (ord(substr($parsedFrame['data'], $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding)), 1)) === 0) {
$frame_terminatorpos++; // strpos() fooled because 2nd byte of Unicode chars are often 0x00
}
$frame_description = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset);
if (ord($frame_description) === 0) {
$frame_description = '';
}
$frame_text = (string) substr($parsedFrame['data'], $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding)));
$parsedFrame['encodingid'] = $frame_textencoding;
$parsedFrame['encoding'] = $this->TextEncodingNameLookup($frame_textencoding);
$parsedFrame['language'] = $frame_language;
$parsedFrame['languagename'] = $this->LanguageLookup($frame_language, false);
$parsedFrame['description'] = $frame_description;
$parsedFrame['data'] = $frame_text;
if (!empty($parsedFrame['framenameshort']) && !empty($parsedFrame['data'])) {
$info['id3v2']['comments'][$parsedFrame['framenameshort']][] = getid3_lib::iconv_fallback($parsedFrame['encoding'], $info['id3v2']['encoding'], $parsedFrame['data']);
}
}
} elseif (($id3v2_majorversion >= 4) && ($parsedFrame['frame_name'] == 'RVA2')) { // 4.11 RVA2 Relative volume adjustment (2) (ID3v2.4+ only)
// There may be more than one 'RVA2' frame in each tag,
// but only one with the same identification string
// <Header for 'Relative volume adjustment (2)', ID: 'RVA2'>
// Identification <text string> $00
// The 'identification' string is used to identify the situation and/or
// device where this adjustment should apply. The following is then
// repeated for every channel:
// Type of channel $xx
// Volume adjustment $xx xx
// Bits representing peak $xx
// Peak volume $xx (xx ...)
$frame_terminatorpos = strpos($parsedFrame['data'], "\x00");
$frame_idstring = substr($parsedFrame['data'], 0, $frame_terminatorpos);
if (ord($frame_idstring) === 0) {
$frame_idstring = '';
}
$frame_remainingdata = substr($parsedFrame['data'], $frame_terminatorpos + strlen("\x00"));
$parsedFrame['description'] = $frame_idstring;
$RVA2channelcounter = 0;
while (strlen($frame_remainingdata) >= 5) {
$frame_offset = 0;
$frame_channeltypeid = ord(substr($frame_remainingdata, $frame_offset++, 1));
$parsedFrame[$RVA2channelcounter]['channeltypeid'] = $frame_channeltypeid;
$parsedFrame[$RVA2channelcounter]['channeltype'] = $this->RVA2ChannelTypeLookup($frame_channeltypeid);
$parsedFrame[$RVA2channelcounter]['volumeadjust'] = getid3_lib::BigEndian2Int(substr($frame_remainingdata, $frame_offset, 2), false, true); // 16-bit signed
$frame_offset += 2;
$parsedFrame[$RVA2channelcounter]['bitspeakvolume'] = ord(substr($frame_remainingdata, $frame_offset++, 1));
if (($parsedFrame[$RVA2channelcounter]['bitspeakvolume'] < 1) || ($parsedFrame[$RVA2channelcounter]['bitspeakvolume'] > 4)) {
$info['warning'][] = 'ID3v2::RVA2 frame['.$RVA2channelcounter.'] contains invalid '.$parsedFrame[$RVA2channelcounter]['bitspeakvolume'].'-byte bits-representing-peak value';
break;
}
$frame_bytespeakvolume = ceil($parsedFrame[$RVA2channelcounter]['bitspeakvolume'] / 8);
$parsedFrame[$RVA2channelcounter]['peakvolume'] = getid3_lib::BigEndian2Int(substr($frame_remainingdata, $frame_offset, $frame_bytespeakvolume));
$frame_remainingdata = substr($frame_remainingdata, $frame_offset + $frame_bytespeakvolume);
$RVA2channelcounter++;
}
unset($parsedFrame['data']);
} elseif ((($id3v2_majorversion == 3) && ($parsedFrame['frame_name'] == 'RVAD')) || // 4.12 RVAD Relative volume adjustment (ID3v2.3 only)
(($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'RVA'))) { // 4.12 RVA Relative volume adjustment (ID3v2.2 only)
// There may only be one 'RVA' frame in each tag
// <Header for 'Relative volume adjustment', ID: 'RVA'>
// ID3v2.2 => Increment/decrement %000000ba
// ID3v2.3 => Increment/decrement %00fedcba
// Bits used for volume descr. $xx
// Relative volume change, right $xx xx (xx ...) // a
// Relative volume change, left $xx xx (xx ...) // b
// Peak volume right $xx xx (xx ...)
// Peak volume left $xx xx (xx ...)
// ID3v2.3 only, optional (not present in ID3v2.2):
// Relative volume change, right back $xx xx (xx ...) // c
// Relative volume change, left back $xx xx (xx ...) // d
// Peak volume right back $xx xx (xx ...)
// Peak volume left back $xx xx (xx ...)
// ID3v2.3 only, optional (not present in ID3v2.2):
// Relative volume change, center $xx xx (xx ...) // e
// Peak volume center $xx xx (xx ...)
// ID3v2.3 only, optional (not present in ID3v2.2):
// Relative volume change, bass $xx xx (xx ...) // f
// Peak volume bass $xx xx (xx ...)
$frame_offset = 0;
$frame_incrdecrflags = getid3_lib::BigEndian2Bin(substr($parsedFrame['data'], $frame_offset++, 1));
$parsedFrame['incdec']['right'] = (bool) substr($frame_incrdecrflags, 6, 1);
$parsedFrame['incdec']['left'] = (bool) substr($frame_incrdecrflags, 7, 1);
$parsedFrame['bitsvolume'] = ord(substr($parsedFrame['data'], $frame_offset++, 1));
$frame_bytesvolume = ceil($parsedFrame['bitsvolume'] / 8);
$parsedFrame['volumechange']['right'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, $frame_bytesvolume));
if ($parsedFrame['incdec']['right'] === false) {
$parsedFrame['volumechange']['right'] *= -1;
}
$frame_offset += $frame_bytesvolume;
$parsedFrame['volumechange']['left'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, $frame_bytesvolume));
if ($parsedFrame['incdec']['left'] === false) {
$parsedFrame['volumechange']['left'] *= -1;
}
$frame_offset += $frame_bytesvolume;
$parsedFrame['peakvolume']['right'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, $frame_bytesvolume));
$frame_offset += $frame_bytesvolume;
$parsedFrame['peakvolume']['left'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, $frame_bytesvolume));
$frame_offset += $frame_bytesvolume;
if ($id3v2_majorversion == 3) {
$parsedFrame['data'] = substr($parsedFrame['data'], $frame_offset);
if (strlen($parsedFrame['data']) > 0) {
$parsedFrame['incdec']['rightrear'] = (bool) substr($frame_incrdecrflags, 4, 1);
$parsedFrame['incdec']['leftrear'] = (bool) substr($frame_incrdecrflags, 5, 1);
$parsedFrame['volumechange']['rightrear'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, $frame_bytesvolume));
if ($parsedFrame['incdec']['rightrear'] === false) {
$parsedFrame['volumechange']['rightrear'] *= -1;
}
$frame_offset += $frame_bytesvolume;
$parsedFrame['volumechange']['leftrear'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, $frame_bytesvolume));
if ($parsedFrame['incdec']['leftrear'] === false) {
$parsedFrame['volumechange']['leftrear'] *= -1;
}
$frame_offset += $frame_bytesvolume;
$parsedFrame['peakvolume']['rightrear'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, $frame_bytesvolume));
$frame_offset += $frame_bytesvolume;
$parsedFrame['peakvolume']['leftrear'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, $frame_bytesvolume));
$frame_offset += $frame_bytesvolume;
}
$parsedFrame['data'] = substr($parsedFrame['data'], $frame_offset);
if (strlen($parsedFrame['data']) > 0) {
$parsedFrame['incdec']['center'] = (bool) substr($frame_incrdecrflags, 3, 1);
$parsedFrame['volumechange']['center'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, $frame_bytesvolume));
if ($parsedFrame['incdec']['center'] === false) {
$parsedFrame['volumechange']['center'] *= -1;
}
$frame_offset += $frame_bytesvolume;
$parsedFrame['peakvolume']['center'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, $frame_bytesvolume));
$frame_offset += $frame_bytesvolume;
}
$parsedFrame['data'] = substr($parsedFrame['data'], $frame_offset);
if (strlen($parsedFrame['data']) > 0) {
$parsedFrame['incdec']['bass'] = (bool) substr($frame_incrdecrflags, 2, 1);
$parsedFrame['volumechange']['bass'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, $frame_bytesvolume));
if ($parsedFrame['incdec']['bass'] === false) {
$parsedFrame['volumechange']['bass'] *= -1;
}
$frame_offset += $frame_bytesvolume;
$parsedFrame['peakvolume']['bass'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, $frame_bytesvolume));
$frame_offset += $frame_bytesvolume;
}
}
unset($parsedFrame['data']);
} elseif (($id3v2_majorversion >= 4) && ($parsedFrame['frame_name'] == 'EQU2')) { // 4.12 EQU2 Equalisation (2) (ID3v2.4+ only)
// There may be more than one 'EQU2' frame in each tag,
// but only one with the same identification string
// <Header of 'Equalisation (2)', ID: 'EQU2'>
// Interpolation method $xx
// $00 Band
// $01 Linear
// Identification <text string> $00
// The following is then repeated for every adjustment point
// Frequency $xx xx
// Volume adjustment $xx xx
$frame_offset = 0;
$frame_interpolationmethod = ord(substr($parsedFrame['data'], $frame_offset++, 1));
$frame_terminatorpos = strpos($parsedFrame['data'], "\x00", $frame_offset);
$frame_idstring = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset);
if (ord($frame_idstring) === 0) {
$frame_idstring = '';
}
$parsedFrame['description'] = $frame_idstring;
$frame_remainingdata = substr($parsedFrame['data'], $frame_terminatorpos + strlen("\x00"));
while (strlen($frame_remainingdata)) {
$frame_frequency = getid3_lib::BigEndian2Int(substr($frame_remainingdata, 0, 2)) / 2;
$parsedFrame['data'][$frame_frequency] = getid3_lib::BigEndian2Int(substr($frame_remainingdata, 2, 2), false, true);
$frame_remainingdata = substr($frame_remainingdata, 4);
}
$parsedFrame['interpolationmethod'] = $frame_interpolationmethod;
unset($parsedFrame['data']);
} elseif ((($id3v2_majorversion == 3) && ($parsedFrame['frame_name'] == 'EQUA')) || // 4.12 EQUA Equalisation (ID3v2.3 only)
(($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'EQU'))) { // 4.13 EQU Equalisation (ID3v2.2 only)
// There may only be one 'EQUA' frame in each tag
// <Header for 'Relative volume adjustment', ID: 'EQU'>
// Adjustment bits $xx
// This is followed by 2 bytes + ('adjustment bits' rounded up to the
// nearest byte) for every equalisation band in the following format,
// giving a frequency range of 0 - 32767Hz:
// Increment/decrement %x (MSB of the Frequency)
// Frequency (lower 15 bits)
// Adjustment $xx (xx ...)
$frame_offset = 0;
$parsedFrame['adjustmentbits'] = substr($parsedFrame['data'], $frame_offset++, 1);
$frame_adjustmentbytes = ceil($parsedFrame['adjustmentbits'] / 8);
$frame_remainingdata = (string) substr($parsedFrame['data'], $frame_offset);
while (strlen($frame_remainingdata) > 0) {
$frame_frequencystr = getid3_lib::BigEndian2Bin(substr($frame_remainingdata, 0, 2));
$frame_incdec = (bool) substr($frame_frequencystr, 0, 1);
$frame_frequency = bindec(substr($frame_frequencystr, 1, 15));
$parsedFrame[$frame_frequency]['incdec'] = $frame_incdec;
$parsedFrame[$frame_frequency]['adjustment'] = getid3_lib::BigEndian2Int(substr($frame_remainingdata, 2, $frame_adjustmentbytes));
if ($parsedFrame[$frame_frequency]['incdec'] === false) {
$parsedFrame[$frame_frequency]['adjustment'] *= -1;
}
$frame_remainingdata = substr($frame_remainingdata, 2 + $frame_adjustmentbytes);
}
unset($parsedFrame['data']);
} elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'RVRB')) || // 4.13 RVRB Reverb
(($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'REV'))) { // 4.14 REV Reverb
// There may only be one 'RVRB' frame in each tag.
// <Header for 'Reverb', ID: 'RVRB'>
// Reverb left (ms) $xx xx
// Reverb right (ms) $xx xx
// Reverb bounces, left $xx
// Reverb bounces, right $xx
// Reverb feedback, left to left $xx
// Reverb feedback, left to right $xx
// Reverb feedback, right to right $xx
// Reverb feedback, right to left $xx
// Premix left to right $xx
// Premix right to left $xx
$frame_offset = 0;
$parsedFrame['left'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 2));
$frame_offset += 2;
$parsedFrame['right'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 2));
$frame_offset += 2;
$parsedFrame['bouncesL'] = ord(substr($parsedFrame['data'], $frame_offset++, 1));
$parsedFrame['bouncesR'] = ord(substr($parsedFrame['data'], $frame_offset++, 1));
$parsedFrame['feedbackLL'] = ord(substr($parsedFrame['data'], $frame_offset++, 1));
$parsedFrame['feedbackLR'] = ord(substr($parsedFrame['data'], $frame_offset++, 1));
$parsedFrame['feedbackRR'] = ord(substr($parsedFrame['data'], $frame_offset++, 1));
$parsedFrame['feedbackRL'] = ord(substr($parsedFrame['data'], $frame_offset++, 1));
$parsedFrame['premixLR'] = ord(substr($parsedFrame['data'], $frame_offset++, 1));
$parsedFrame['premixRL'] = ord(substr($parsedFrame['data'], $frame_offset++, 1));
unset($parsedFrame['data']);
} elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'APIC')) || // 4.14 APIC Attached picture
(($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'PIC'))) { // 4.15 PIC Attached picture
// There may be several pictures attached to one file,
// each in their individual 'APIC' frame, but only one
// with the same content descriptor
// <Header for 'Attached picture', ID: 'APIC'>
// Text encoding $xx
// ID3v2.3+ => MIME type <text string> $00
// ID3v2.2 => Image format $xx xx xx
// Picture type $xx
// Description <text string according to encoding> $00 (00)
// Picture data <binary data>
$frame_offset = 0;
$frame_textencoding = ord(substr($parsedFrame['data'], $frame_offset++, 1));
if ((($id3v2_majorversion <= 3) && ($frame_textencoding > 1)) || (($id3v2_majorversion == 4) && ($frame_textencoding > 3))) {
$info['warning'][] = 'Invalid text encoding byte ('.$frame_textencoding.') in frame "'.$parsedFrame['frame_name'].'" - defaulting to ISO-8859-1 encoding';
}
if ($id3v2_majorversion == 2 && strlen($parsedFrame['data']) > $frame_offset) {
$frame_imagetype = substr($parsedFrame['data'], $frame_offset, 3);
if (strtolower($frame_imagetype) == 'ima') {
// complete hack for mp3Rage (www.chaoticsoftware.com) that puts ID3v2.3-formatted
// MIME type instead of 3-char ID3v2.2-format image type (thanks xbhoffØpacbell*net)
$frame_terminatorpos = strpos($parsedFrame['data'], "\x00", $frame_offset);
$frame_mimetype = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset);
if (ord($frame_mimetype) === 0) {
$frame_mimetype = '';
}
$frame_imagetype = strtoupper(str_replace('image/', '', strtolower($frame_mimetype)));
if ($frame_imagetype == 'JPEG') {
$frame_imagetype = 'JPG';
}
$frame_offset = $frame_terminatorpos + strlen("\x00");
} else {
$frame_offset += 3;
}
}
if ($id3v2_majorversion > 2 && strlen($parsedFrame['data']) > $frame_offset) {
$frame_terminatorpos = strpos($parsedFrame['data'], "\x00", $frame_offset);
$frame_mimetype = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset);
if (ord($frame_mimetype) === 0) {
$frame_mimetype = '';
}
$frame_offset = $frame_terminatorpos + strlen("\x00");
}
$frame_picturetype = ord(substr($parsedFrame['data'], $frame_offset++, 1));
if ($frame_offset >= $parsedFrame['datalength']) {
$info['warning'][] = 'data portion of APIC frame is missing at offset '.($parsedFrame['dataoffset'] + 8 + $frame_offset);
} else {
$frame_terminatorpos = strpos($parsedFrame['data'], $this->TextEncodingTerminatorLookup($frame_textencoding), $frame_offset);
if (ord(substr($parsedFrame['data'], $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding)), 1)) === 0) {
$frame_terminatorpos++; // strpos() fooled because 2nd byte of Unicode chars are often 0x00
}
$frame_description = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset);
if (ord($frame_description) === 0) {
$frame_description = '';
}
$parsedFrame['encodingid'] = $frame_textencoding;
$parsedFrame['encoding'] = $this->TextEncodingNameLookup($frame_textencoding);
if ($id3v2_majorversion == 2) {
$parsedFrame['imagetype'] = $frame_imagetype;
} else {
$parsedFrame['mime'] = $frame_mimetype;
}
$parsedFrame['picturetypeid'] = $frame_picturetype;
$parsedFrame['picturetype'] = $this->APICPictureTypeLookup($frame_picturetype);
$parsedFrame['description'] = $frame_description;
$parsedFrame['data'] = substr($parsedFrame['data'], $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding)));
$parsedFrame['datalength'] = strlen($parsedFrame['data']);
$parsedFrame['image_mime'] = '';
$imageinfo = array();
$imagechunkcheck = getid3_lib::GetDataImageSize($parsedFrame['data'], $imageinfo);
if (($imagechunkcheck[2] >= 1) && ($imagechunkcheck[2] <= 3)) {
$parsedFrame['image_mime'] = 'image/'.getid3_lib::ImageTypesLookup($imagechunkcheck[2]);
if ($imagechunkcheck[0]) {
$parsedFrame['image_width'] = $imagechunkcheck[0];
}
if ($imagechunkcheck[1]) {
$parsedFrame['image_height'] = $imagechunkcheck[1];
}
}
do {
if ($this->getid3->option_save_attachments === false) {
// skip entirely
unset($parsedFrame['data']);
break;
}
if ($this->getid3->option_save_attachments === true) {
// great
/*
} elseif (is_int($this->getid3->option_save_attachments)) {
if ($this->getid3->option_save_attachments < $parsedFrame['data_length']) {
// too big, skip
$info['warning'][] = 'attachment at '.$frame_offset.' is too large to process inline ('.number_format($parsedFrame['data_length']).' bytes)';
unset($parsedFrame['data']);
break;
}
*/
} elseif (is_string($this->getid3->option_save_attachments)) {
$dir = rtrim(str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $this->getid3->option_save_attachments), DIRECTORY_SEPARATOR);
if (!is_dir($dir) || !is_writable($dir)) {
// cannot write, skip
$info['warning'][] = 'attachment at '.$frame_offset.' cannot be saved to "'.$dir.'" (not writable)';
unset($parsedFrame['data']);
break;
}
}
// if we get this far, must be OK
if (is_string($this->getid3->option_save_attachments)) {
$destination_filename = $dir.DIRECTORY_SEPARATOR.md5($info['filenamepath']).'_'.$frame_offset;
if (!file_exists($destination_filename) || is_writable($destination_filename)) {
file_put_contents($destination_filename, $parsedFrame['data']);
} else {
$info['warning'][] = 'attachment at '.$frame_offset.' cannot be saved to "'.$destination_filename.'" (not writable)';
}
$parsedFrame['data_filename'] = $destination_filename;
unset($parsedFrame['data']);
} else {
if (!empty($parsedFrame['framenameshort']) && !empty($parsedFrame['data'])) {
if (!isset($info['id3v2']['comments']['picture'])) {
$info['id3v2']['comments']['picture'] = array();
}
$info['id3v2']['comments']['picture'][] = array('data'=>$parsedFrame['data'], 'image_mime'=>$parsedFrame['image_mime']);
}
}
} while (false);
}
} elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'GEOB')) || // 4.15 GEOB General encapsulated object
(($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'GEO'))) { // 4.16 GEO General encapsulated object
// There may be more than one 'GEOB' frame in each tag,
// but only one with the same content descriptor
// <Header for 'General encapsulated object', ID: 'GEOB'>
// Text encoding $xx
// MIME type <text string> $00
// Filename <text string according to encoding> $00 (00)
// Content description <text string according to encoding> $00 (00)
// Encapsulated object <binary data>
$frame_offset = 0;
$frame_textencoding = ord(substr($parsedFrame['data'], $frame_offset++, 1));
if ((($id3v2_majorversion <= 3) && ($frame_textencoding > 1)) || (($id3v2_majorversion == 4) && ($frame_textencoding > 3))) {
$info['warning'][] = 'Invalid text encoding byte ('.$frame_textencoding.') in frame "'.$parsedFrame['frame_name'].'" - defaulting to ISO-8859-1 encoding';
}
$frame_terminatorpos = strpos($parsedFrame['data'], "\x00", $frame_offset);
$frame_mimetype = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset);
if (ord($frame_mimetype) === 0) {
$frame_mimetype = '';
}
$frame_offset = $frame_terminatorpos + strlen("\x00");
$frame_terminatorpos = strpos($parsedFrame['data'], $this->TextEncodingTerminatorLookup($frame_textencoding), $frame_offset);
if (ord(substr($parsedFrame['data'], $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding)), 1)) === 0) {
$frame_terminatorpos++; // strpos() fooled because 2nd byte of Unicode chars are often 0x00
}
$frame_filename = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset);
if (ord($frame_filename) === 0) {
$frame_filename = '';
}
$frame_offset = $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding));
$frame_terminatorpos = strpos($parsedFrame['data'], $this->TextEncodingTerminatorLookup($frame_textencoding), $frame_offset);
if (ord(substr($parsedFrame['data'], $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding)), 1)) === 0) {
$frame_terminatorpos++; // strpos() fooled because 2nd byte of Unicode chars are often 0x00
}
$frame_description = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset);
if (ord($frame_description) === 0) {
$frame_description = '';
}
$frame_offset = $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding));
$parsedFrame['objectdata'] = (string) substr($parsedFrame['data'], $frame_offset);
$parsedFrame['encodingid'] = $frame_textencoding;
$parsedFrame['encoding'] = $this->TextEncodingNameLookup($frame_textencoding);
$parsedFrame['mime'] = $frame_mimetype;
$parsedFrame['filename'] = $frame_filename;
$parsedFrame['description'] = $frame_description;
unset($parsedFrame['data']);
} elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'PCNT')) || // 4.16 PCNT Play counter
(($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'CNT'))) { // 4.17 CNT Play counter
// There may only be one 'PCNT' frame in each tag.
// When the counter reaches all one's, one byte is inserted in
// front of the counter thus making the counter eight bits bigger
// <Header for 'Play counter', ID: 'PCNT'>
// Counter $xx xx xx xx (xx ...)
$parsedFrame['data'] = getid3_lib::BigEndian2Int($parsedFrame['data']);
} elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'POPM')) || // 4.17 POPM Popularimeter
(($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'POP'))) { // 4.18 POP Popularimeter
// There may be more than one 'POPM' frame in each tag,
// but only one with the same email address
// <Header for 'Popularimeter', ID: 'POPM'>
// Email to user <text string> $00
// Rating $xx
// Counter $xx xx xx xx (xx ...)
$frame_offset = 0;
$frame_terminatorpos = strpos($parsedFrame['data'], "\x00", $frame_offset);
$frame_emailaddress = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset);
if (ord($frame_emailaddress) === 0) {
$frame_emailaddress = '';
}
$frame_offset = $frame_terminatorpos + strlen("\x00");
$frame_rating = ord(substr($parsedFrame['data'], $frame_offset++, 1));
$parsedFrame['counter'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset));
$parsedFrame['email'] = $frame_emailaddress;
$parsedFrame['rating'] = $frame_rating;
unset($parsedFrame['data']);
} elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'RBUF')) || // 4.18 RBUF Recommended buffer size
(($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'BUF'))) { // 4.19 BUF Recommended buffer size
// There may only be one 'RBUF' frame in each tag
// <Header for 'Recommended buffer size', ID: 'RBUF'>
// Buffer size $xx xx xx
// Embedded info flag %0000000x
// Offset to next tag $xx xx xx xx
$frame_offset = 0;
$parsedFrame['buffersize'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 3));
$frame_offset += 3;
$frame_embeddedinfoflags = getid3_lib::BigEndian2Bin(substr($parsedFrame['data'], $frame_offset++, 1));
$parsedFrame['flags']['embededinfo'] = (bool) substr($frame_embeddedinfoflags, 7, 1);
$parsedFrame['nexttagoffset'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 4));
unset($parsedFrame['data']);
} elseif (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'CRM')) { // 4.20 Encrypted meta frame (ID3v2.2 only)
// There may be more than one 'CRM' frame in a tag,
// but only one with the same 'owner identifier'
// <Header for 'Encrypted meta frame', ID: 'CRM'>
// Owner identifier <textstring> $00 (00)
// Content/explanation <textstring> $00 (00)
// Encrypted datablock <binary data>
$frame_offset = 0;
$frame_terminatorpos = strpos($parsedFrame['data'], "\x00", $frame_offset);
$frame_ownerid = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset);
$frame_offset = $frame_terminatorpos + strlen("\x00");
$frame_terminatorpos = strpos($parsedFrame['data'], "\x00", $frame_offset);
$frame_description = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset);
if (ord($frame_description) === 0) {
$frame_description = '';
}
$frame_offset = $frame_terminatorpos + strlen("\x00");
$parsedFrame['ownerid'] = $frame_ownerid;
$parsedFrame['data'] = (string) substr($parsedFrame['data'], $frame_offset);
$parsedFrame['description'] = $frame_description;
unset($parsedFrame['data']);
} elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'AENC')) || // 4.19 AENC Audio encryption
(($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'CRA'))) { // 4.21 CRA Audio encryption
// There may be more than one 'AENC' frames in a tag,
// but only one with the same 'Owner identifier'
// <Header for 'Audio encryption', ID: 'AENC'>
// Owner identifier <text string> $00
// Preview start $xx xx
// Preview length $xx xx
// Encryption info <binary data>
$frame_offset = 0;
$frame_terminatorpos = strpos($parsedFrame['data'], "\x00", $frame_offset);
$frame_ownerid = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset);
if (ord($frame_ownerid) === 0) {
$frame_ownerid == '';
}
$frame_offset = $frame_terminatorpos + strlen("\x00");
$parsedFrame['ownerid'] = $frame_ownerid;
$parsedFrame['previewstart'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 2));
$frame_offset += 2;
$parsedFrame['previewlength'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 2));
$frame_offset += 2;
$parsedFrame['encryptioninfo'] = (string) substr($parsedFrame['data'], $frame_offset);
unset($parsedFrame['data']);
} elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'LINK')) || // 4.20 LINK Linked information
(($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'LNK'))) { // 4.22 LNK Linked information
// There may be more than one 'LINK' frame in a tag,
// but only one with the same contents
// <Header for 'Linked information', ID: 'LINK'>
// ID3v2.3+ => Frame identifier $xx xx xx xx
// ID3v2.2 => Frame identifier $xx xx xx
// URL <text string> $00
// ID and additional data <text string(s)>
$frame_offset = 0;
if ($id3v2_majorversion == 2) {
$parsedFrame['frameid'] = substr($parsedFrame['data'], $frame_offset, 3);
$frame_offset += 3;
} else {
$parsedFrame['frameid'] = substr($parsedFrame['data'], $frame_offset, 4);
$frame_offset += 4;
}
$frame_terminatorpos = strpos($parsedFrame['data'], "\x00", $frame_offset);
$frame_url = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset);
if (ord($frame_url) === 0) {
$frame_url = '';
}
$frame_offset = $frame_terminatorpos + strlen("\x00");
$parsedFrame['url'] = $frame_url;
$parsedFrame['additionaldata'] = (string) substr($parsedFrame['data'], $frame_offset);
if (!empty($parsedFrame['framenameshort']) && $parsedFrame['url']) {
$info['id3v2']['comments'][$parsedFrame['framenameshort']][] = utf8_encode($parsedFrame['url']);
}
unset($parsedFrame['data']);
} elseif (($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'POSS')) { // 4.21 POSS Position synchronisation frame (ID3v2.3+ only)
// There may only be one 'POSS' frame in each tag
// <Head for 'Position synchronisation', ID: 'POSS'>
// Time stamp format $xx
// Position $xx (xx ...)
$frame_offset = 0;
$parsedFrame['timestampformat'] = ord(substr($parsedFrame['data'], $frame_offset++, 1));
$parsedFrame['position'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset));
unset($parsedFrame['data']);
} elseif (($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'USER')) { // 4.22 USER Terms of use (ID3v2.3+ only)
// There may be more than one 'Terms of use' frame in a tag,
// but only one with the same 'Language'
// <Header for 'Terms of use frame', ID: 'USER'>
// Text encoding $xx
// Language $xx xx xx
// The actual text <text string according to encoding>
$frame_offset = 0;
$frame_textencoding = ord(substr($parsedFrame['data'], $frame_offset++, 1));
if ((($id3v2_majorversion <= 3) && ($frame_textencoding > 1)) || (($id3v2_majorversion == 4) && ($frame_textencoding > 3))) {
$info['warning'][] = 'Invalid text encoding byte ('.$frame_textencoding.') in frame "'.$parsedFrame['frame_name'].'" - defaulting to ISO-8859-1 encoding';
}
$frame_language = substr($parsedFrame['data'], $frame_offset, 3);
$frame_offset += 3;
$parsedFrame['language'] = $frame_language;
$parsedFrame['languagename'] = $this->LanguageLookup($frame_language, false);
$parsedFrame['encodingid'] = $frame_textencoding;
$parsedFrame['encoding'] = $this->TextEncodingNameLookup($frame_textencoding);
$parsedFrame['data'] = (string) substr($parsedFrame['data'], $frame_offset);
if (!empty($parsedFrame['framenameshort']) && !empty($parsedFrame['data'])) {
$info['id3v2']['comments'][$parsedFrame['framenameshort']][] = getid3_lib::iconv_fallback($parsedFrame['encoding'], $info['id3v2']['encoding'], $parsedFrame['data']);
}
unset($parsedFrame['data']);
} elseif (($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'OWNE')) { // 4.23 OWNE Ownership frame (ID3v2.3+ only)
// There may only be one 'OWNE' frame in a tag
// <Header for 'Ownership frame', ID: 'OWNE'>
// Text encoding $xx
// Price paid <text string> $00
// Date of purch. <text string>
// Seller <text string according to encoding>
$frame_offset = 0;
$frame_textencoding = ord(substr($parsedFrame['data'], $frame_offset++, 1));
if ((($id3v2_majorversion <= 3) && ($frame_textencoding > 1)) || (($id3v2_majorversion == 4) && ($frame_textencoding > 3))) {
$info['warning'][] = 'Invalid text encoding byte ('.$frame_textencoding.') in frame "'.$parsedFrame['frame_name'].'" - defaulting to ISO-8859-1 encoding';
}
$parsedFrame['encodingid'] = $frame_textencoding;
$parsedFrame['encoding'] = $this->TextEncodingNameLookup($frame_textencoding);
$frame_terminatorpos = strpos($parsedFrame['data'], "\x00", $frame_offset);
$frame_pricepaid = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset);
$frame_offset = $frame_terminatorpos + strlen("\x00");
$parsedFrame['pricepaid']['currencyid'] = substr($frame_pricepaid, 0, 3);
$parsedFrame['pricepaid']['currency'] = $this->LookupCurrencyUnits($parsedFrame['pricepaid']['currencyid']);
$parsedFrame['pricepaid']['value'] = substr($frame_pricepaid, 3);
$parsedFrame['purchasedate'] = substr($parsedFrame['data'], $frame_offset, 8);
if (!$this->IsValidDateStampString($parsedFrame['purchasedate'])) {
$parsedFrame['purchasedateunix'] = mktime (0, 0, 0, substr($parsedFrame['purchasedate'], 4, 2), substr($parsedFrame['purchasedate'], 6, 2), substr($parsedFrame['purchasedate'], 0, 4));
}
$frame_offset += 8;
$parsedFrame['seller'] = (string) substr($parsedFrame['data'], $frame_offset);
unset($parsedFrame['data']);
} elseif (($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'COMR')) { // 4.24 COMR Commercial frame (ID3v2.3+ only)
// There may be more than one 'commercial frame' in a tag,
// but no two may be identical
// <Header for 'Commercial frame', ID: 'COMR'>
// Text encoding $xx
// Price string <text string> $00
// Valid until <text string>
// Contact URL <text string> $00
// Received as $xx
// Name of seller <text string according to encoding> $00 (00)
// Description <text string according to encoding> $00 (00)
// Picture MIME type <string> $00
// Seller logo <binary data>
$frame_offset = 0;
$frame_textencoding = ord(substr($parsedFrame['data'], $frame_offset++, 1));
if ((($id3v2_majorversion <= 3) && ($frame_textencoding > 1)) || (($id3v2_majorversion == 4) && ($frame_textencoding > 3))) {
$info['warning'][] = 'Invalid text encoding byte ('.$frame_textencoding.') in frame "'.$parsedFrame['frame_name'].'" - defaulting to ISO-8859-1 encoding';
}
$frame_terminatorpos = strpos($parsedFrame['data'], "\x00", $frame_offset);
$frame_pricestring = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset);
$frame_offset = $frame_terminatorpos + strlen("\x00");
$frame_rawpricearray = explode('/', $frame_pricestring);
foreach ($frame_rawpricearray as $key => $val) {
$frame_currencyid = substr($val, 0, 3);
$parsedFrame['price'][$frame_currencyid]['currency'] = $this->LookupCurrencyUnits($frame_currencyid);
$parsedFrame['price'][$frame_currencyid]['value'] = substr($val, 3);
}
$frame_datestring = substr($parsedFrame['data'], $frame_offset, 8);
$frame_offset += 8;
$frame_terminatorpos = strpos($parsedFrame['data'], "\x00", $frame_offset);
$frame_contacturl = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset);
$frame_offset = $frame_terminatorpos + strlen("\x00");
$frame_receivedasid = ord(substr($parsedFrame['data'], $frame_offset++, 1));
$frame_terminatorpos = strpos($parsedFrame['data'], $this->TextEncodingTerminatorLookup($frame_textencoding), $frame_offset);
if (ord(substr($parsedFrame['data'], $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding)), 1)) === 0) {
$frame_terminatorpos++; // strpos() fooled because 2nd byte of Unicode chars are often 0x00
}
$frame_sellername = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset);
if (ord($frame_sellername) === 0) {
$frame_sellername = '';
}
$frame_offset = $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding));
$frame_terminatorpos = strpos($parsedFrame['data'], $this->TextEncodingTerminatorLookup($frame_textencoding), $frame_offset);
if (ord(substr($parsedFrame['data'], $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding)), 1)) === 0) {
$frame_terminatorpos++; // strpos() fooled because 2nd byte of Unicode chars are often 0x00
}
$frame_description = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset);
if (ord($frame_description) === 0) {
$frame_description = '';
}
$frame_offset = $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding));
$frame_terminatorpos = strpos($parsedFrame['data'], "\x00", $frame_offset);
$frame_mimetype = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset);
$frame_offset = $frame_terminatorpos + strlen("\x00");
$frame_sellerlogo = substr($parsedFrame['data'], $frame_offset);
$parsedFrame['encodingid'] = $frame_textencoding;
$parsedFrame['encoding'] = $this->TextEncodingNameLookup($frame_textencoding);
$parsedFrame['pricevaliduntil'] = $frame_datestring;
$parsedFrame['contacturl'] = $frame_contacturl;
$parsedFrame['receivedasid'] = $frame_receivedasid;
$parsedFrame['receivedas'] = $this->COMRReceivedAsLookup($frame_receivedasid);
$parsedFrame['sellername'] = $frame_sellername;
$parsedFrame['description'] = $frame_description;
$parsedFrame['mime'] = $frame_mimetype;
$parsedFrame['logo'] = $frame_sellerlogo;
unset($parsedFrame['data']);
} elseif (($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'ENCR')) { // 4.25 ENCR Encryption method registration (ID3v2.3+ only)
// There may be several 'ENCR' frames in a tag,
// but only one containing the same symbol
// and only one containing the same owner identifier
// <Header for 'Encryption method registration', ID: 'ENCR'>
// Owner identifier <text string> $00
// Method symbol $xx
// Encryption data <binary data>
$frame_offset = 0;
$frame_terminatorpos = strpos($parsedFrame['data'], "\x00", $frame_offset);
$frame_ownerid = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset);
if (ord($frame_ownerid) === 0) {
$frame_ownerid = '';
}
$frame_offset = $frame_terminatorpos + strlen("\x00");
$parsedFrame['ownerid'] = $frame_ownerid;
$parsedFrame['methodsymbol'] = ord(substr($parsedFrame['data'], $frame_offset++, 1));
$parsedFrame['data'] = (string) substr($parsedFrame['data'], $frame_offset);
} elseif (($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'GRID')) { // 4.26 GRID Group identification registration (ID3v2.3+ only)
// There may be several 'GRID' frames in a tag,
// but only one containing the same symbol
// and only one containing the same owner identifier
// <Header for 'Group ID registration', ID: 'GRID'>
// Owner identifier <text string> $00
// Group symbol $xx
// Group dependent data <binary data>
$frame_offset = 0;
$frame_terminatorpos = strpos($parsedFrame['data'], "\x00", $frame_offset);
$frame_ownerid = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset);
if (ord($frame_ownerid) === 0) {
$frame_ownerid = '';
}
$frame_offset = $frame_terminatorpos + strlen("\x00");
$parsedFrame['ownerid'] = $frame_ownerid;
$parsedFrame['groupsymbol'] = ord(substr($parsedFrame['data'], $frame_offset++, 1));
$parsedFrame['data'] = (string) substr($parsedFrame['data'], $frame_offset);
} elseif (($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'PRIV')) { // 4.27 PRIV Private frame (ID3v2.3+ only)
// The tag may contain more than one 'PRIV' frame
// but only with different contents
// <Header for 'Private frame', ID: 'PRIV'>
// Owner identifier <text string> $00
// The private data <binary data>
$frame_offset = 0;
$frame_terminatorpos = strpos($parsedFrame['data'], "\x00", $frame_offset);
$frame_ownerid = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset);
if (ord($frame_ownerid) === 0) {
$frame_ownerid = '';
}
$frame_offset = $frame_terminatorpos + strlen("\x00");
$parsedFrame['ownerid'] = $frame_ownerid;
$parsedFrame['data'] = (string) substr($parsedFrame['data'], $frame_offset);
} elseif (($id3v2_majorversion >= 4) && ($parsedFrame['frame_name'] == 'SIGN')) { // 4.28 SIGN Signature frame (ID3v2.4+ only)
// There may be more than one 'signature frame' in a tag,
// but no two may be identical
// <Header for 'Signature frame', ID: 'SIGN'>
// Group symbol $xx
// Signature <binary data>
$frame_offset = 0;
$parsedFrame['groupsymbol'] = ord(substr($parsedFrame['data'], $frame_offset++, 1));
$parsedFrame['data'] = (string) substr($parsedFrame['data'], $frame_offset);
} elseif (($id3v2_majorversion >= 4) && ($parsedFrame['frame_name'] == 'SEEK')) { // 4.29 SEEK Seek frame (ID3v2.4+ only)
// There may only be one 'seek frame' in a tag
// <Header for 'Seek frame', ID: 'SEEK'>
// Minimum offset to next tag $xx xx xx xx
$frame_offset = 0;
$parsedFrame['data'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 4));
} elseif (($id3v2_majorversion >= 4) && ($parsedFrame['frame_name'] == 'ASPI')) { // 4.30 ASPI Audio seek point index (ID3v2.4+ only)
// There may only be one 'audio seek point index' frame in a tag
// <Header for 'Seek Point Index', ID: 'ASPI'>
// Indexed data start (S) $xx xx xx xx
// Indexed data length (L) $xx xx xx xx
// Number of index points (N) $xx xx
// Bits per index point (b) $xx
// Then for every index point the following data is included:
// Fraction at index (Fi) $xx (xx)
$frame_offset = 0;
$parsedFrame['datastart'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 4));
$frame_offset += 4;
$parsedFrame['indexeddatalength'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 4));
$frame_offset += 4;
$parsedFrame['indexpoints'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 2));
$frame_offset += 2;
$parsedFrame['bitsperpoint'] = ord(substr($parsedFrame['data'], $frame_offset++, 1));
$frame_bytesperpoint = ceil($parsedFrame['bitsperpoint'] / 8);
for ($i = 0; $i < $frame_indexpoints; $i++) {
$parsedFrame['indexes'][$i] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, $frame_bytesperpoint));
$frame_offset += $frame_bytesperpoint;
}
unset($parsedFrame['data']);
} elseif (($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'RGAD')) { // Replay Gain Adjustment
// http://privatewww.essex.ac.uk/~djmrob/replaygain/file_format_id3v2.html
// There may only be one 'RGAD' frame in a tag
// <Header for 'Replay Gain Adjustment', ID: 'RGAD'>
// Peak Amplitude $xx $xx $xx $xx
// Radio Replay Gain Adjustment %aaabbbcd %dddddddd
// Audiophile Replay Gain Adjustment %aaabbbcd %dddddddd
// a - name code
// b - originator code
// c - sign bit
// d - replay gain adjustment
$frame_offset = 0;
$parsedFrame['peakamplitude'] = getid3_lib::BigEndian2Float(substr($parsedFrame['data'], $frame_offset, 4));
$frame_offset += 4;
$rg_track_adjustment = getid3_lib::Dec2Bin(substr($parsedFrame['data'], $frame_offset, 2));
$frame_offset += 2;
$rg_album_adjustment = getid3_lib::Dec2Bin(substr($parsedFrame['data'], $frame_offset, 2));
$frame_offset += 2;
$parsedFrame['raw']['track']['name'] = getid3_lib::Bin2Dec(substr($rg_track_adjustment, 0, 3));
$parsedFrame['raw']['track']['originator'] = getid3_lib::Bin2Dec(substr($rg_track_adjustment, 3, 3));
$parsedFrame['raw']['track']['signbit'] = getid3_lib::Bin2Dec(substr($rg_track_adjustment, 6, 1));
$parsedFrame['raw']['track']['adjustment'] = getid3_lib::Bin2Dec(substr($rg_track_adjustment, 7, 9));
$parsedFrame['raw']['album']['name'] = getid3_lib::Bin2Dec(substr($rg_album_adjustment, 0, 3));
$parsedFrame['raw']['album']['originator'] = getid3_lib::Bin2Dec(substr($rg_album_adjustment, 3, 3));
$parsedFrame['raw']['album']['signbit'] = getid3_lib::Bin2Dec(substr($rg_album_adjustment, 6, 1));
$parsedFrame['raw']['album']['adjustment'] = getid3_lib::Bin2Dec(substr($rg_album_adjustment, 7, 9));
$parsedFrame['track']['name'] = getid3_lib::RGADnameLookup($parsedFrame['raw']['track']['name']);
$parsedFrame['track']['originator'] = getid3_lib::RGADoriginatorLookup($parsedFrame['raw']['track']['originator']);
$parsedFrame['track']['adjustment'] = getid3_lib::RGADadjustmentLookup($parsedFrame['raw']['track']['adjustment'], $parsedFrame['raw']['track']['signbit']);
$parsedFrame['album']['name'] = getid3_lib::RGADnameLookup($parsedFrame['raw']['album']['name']);
$parsedFrame['album']['originator'] = getid3_lib::RGADoriginatorLookup($parsedFrame['raw']['album']['originator']);
$parsedFrame['album']['adjustment'] = getid3_lib::RGADadjustmentLookup($parsedFrame['raw']['album']['adjustment'], $parsedFrame['raw']['album']['signbit']);
$info['replay_gain']['track']['peak'] = $parsedFrame['peakamplitude'];
$info['replay_gain']['track']['originator'] = $parsedFrame['track']['originator'];
$info['replay_gain']['track']['adjustment'] = $parsedFrame['track']['adjustment'];
$info['replay_gain']['album']['originator'] = $parsedFrame['album']['originator'];
$info['replay_gain']['album']['adjustment'] = $parsedFrame['album']['adjustment'];
unset($parsedFrame['data']);
}
return true;
}
public function DeUnsynchronise($data) {
return str_replace("\xFF\x00", "\xFF", $data);
}
public function LookupExtendedHeaderRestrictionsTagSizeLimits($index) {
static $LookupExtendedHeaderRestrictionsTagSizeLimits = array(
0x00 => 'No more than 128 frames and 1 MB total tag size',
0x01 => 'No more than 64 frames and 128 KB total tag size',
0x02 => 'No more than 32 frames and 40 KB total tag size',
0x03 => 'No more than 32 frames and 4 KB total tag size',
);
return (isset($LookupExtendedHeaderRestrictionsTagSizeLimits[$index]) ? $LookupExtendedHeaderRestrictionsTagSizeLimits[$index] : '');
}
public function LookupExtendedHeaderRestrictionsTextEncodings($index) {
static $LookupExtendedHeaderRestrictionsTextEncodings = array(
0x00 => 'No restrictions',
0x01 => 'Strings are only encoded with ISO-8859-1 or UTF-8',
);
return (isset($LookupExtendedHeaderRestrictionsTextEncodings[$index]) ? $LookupExtendedHeaderRestrictionsTextEncodings[$index] : '');
}
public function LookupExtendedHeaderRestrictionsTextFieldSize($index) {
static $LookupExtendedHeaderRestrictionsTextFieldSize = array(
0x00 => 'No restrictions',
0x01 => 'No string is longer than 1024 characters',
0x02 => 'No string is longer than 128 characters',
0x03 => 'No string is longer than 30 characters',
);
return (isset($LookupExtendedHeaderRestrictionsTextFieldSize[$index]) ? $LookupExtendedHeaderRestrictionsTextFieldSize[$index] : '');
}
public function LookupExtendedHeaderRestrictionsImageEncoding($index) {
static $LookupExtendedHeaderRestrictionsImageEncoding = array(
0x00 => 'No restrictions',
0x01 => 'Images are encoded only with PNG or JPEG',
);
return (isset($LookupExtendedHeaderRestrictionsImageEncoding[$index]) ? $LookupExtendedHeaderRestrictionsImageEncoding[$index] : '');
}
public function LookupExtendedHeaderRestrictionsImageSizeSize($index) {
static $LookupExtendedHeaderRestrictionsImageSizeSize = array(
0x00 => 'No restrictions',
0x01 => 'All images are 256x256 pixels or smaller',
0x02 => 'All images are 64x64 pixels or smaller',
0x03 => 'All images are exactly 64x64 pixels, unless required otherwise',
);
return (isset($LookupExtendedHeaderRestrictionsImageSizeSize[$index]) ? $LookupExtendedHeaderRestrictionsImageSizeSize[$index] : '');
}
public function LookupCurrencyUnits($currencyid) {
$begin = __LINE__;
/** This is not a comment!
AED Dirhams
AFA Afghanis
ALL Leke
AMD Drams
ANG Guilders
AOA Kwanza
ARS Pesos
ATS Schillings
AUD Dollars
AWG Guilders
AZM Manats
BAM Convertible Marka
BBD Dollars
BDT Taka
BEF Francs
BGL Leva
BHD Dinars
BIF Francs
BMD Dollars
BND Dollars
BOB Bolivianos
BRL Brazil Real
BSD Dollars
BTN Ngultrum
BWP Pulas
BYR Rubles
BZD Dollars
CAD Dollars
CDF Congolese Francs
CHF Francs
CLP Pesos
CNY Yuan Renminbi
COP Pesos
CRC Colones
CUP Pesos
CVE Escudos
CYP Pounds
CZK Koruny
DEM Deutsche Marks
DJF Francs
DKK Kroner
DOP Pesos
DZD Algeria Dinars
EEK Krooni
EGP Pounds
ERN Nakfa
ESP Pesetas
ETB Birr
EUR Euro
FIM Markkaa
FJD Dollars
FKP Pounds
FRF Francs
GBP Pounds
GEL Lari
GGP Pounds
GHC Cedis
GIP Pounds
GMD Dalasi
GNF Francs
GRD Drachmae
GTQ Quetzales
GYD Dollars
HKD Dollars
HNL Lempiras
HRK Kuna
HTG Gourdes
HUF Forints
IDR Rupiahs
IEP Pounds
ILS New Shekels
IMP Pounds
INR Rupees
IQD Dinars
IRR Rials
ISK Kronur
ITL Lire
JEP Pounds
JMD Dollars
JOD Dinars
JPY Yen
KES Shillings
KGS Soms
KHR Riels
KMF Francs
KPW Won
KWD Dinars
KYD Dollars
KZT Tenge
LAK Kips
LBP Pounds
LKR Rupees
LRD Dollars
LSL Maloti
LTL Litai
LUF Francs
LVL Lati
LYD Dinars
MAD Dirhams
MDL Lei
MGF Malagasy Francs
MKD Denars
MMK Kyats
MNT Tugriks
MOP Patacas
MRO Ouguiyas
MTL Liri
MUR Rupees
MVR Rufiyaa
MWK Kwachas
MXN Pesos
MYR Ringgits
MZM Meticais
NAD Dollars
NGN Nairas
NIO Gold Cordobas
NLG Guilders
NOK Krone
NPR Nepal Rupees
NZD Dollars
OMR Rials
PAB Balboa
PEN Nuevos Soles
PGK Kina
PHP Pesos
PKR Rupees
PLN Zlotych
PTE Escudos
PYG Guarani
QAR Rials
ROL Lei
RUR Rubles
RWF Rwanda Francs
SAR Riyals
SBD Dollars
SCR Rupees
SDD Dinars
SEK Kronor
SGD Dollars
SHP Pounds
SIT Tolars
SKK Koruny
SLL Leones
SOS Shillings
SPL Luigini
SRG Guilders
STD Dobras
SVC Colones
SYP Pounds
SZL Emalangeni
THB Baht
TJR Rubles
TMM Manats
TND Dinars
TOP Pa'anga
TRL Liras
TTD Dollars
TVD Tuvalu Dollars
TWD New Dollars
TZS Shillings
UAH Hryvnia
UGX Shillings
USD Dollars
UYU Pesos
UZS Sums
VAL Lire
VEB Bolivares
VND Dong
VUV Vatu
WST Tala
XAF Francs
XAG Ounces
XAU Ounces
XCD Dollars
XDR Special Drawing Rights
XPD Ounces
XPF Francs
XPT Ounces
YER Rials
YUM New Dinars
ZAR Rand
ZMK Kwacha
ZWD Zimbabwe Dollars
*/
return getid3_lib::EmbeddedLookup($currencyid, $begin, __LINE__, __FILE__, 'id3v2-currency-units');
}
public function LookupCurrencyCountry($currencyid) {
$begin = __LINE__;
/** This is not a comment!
AED United Arab Emirates
AFA Afghanistan
ALL Albania
AMD Armenia
ANG Netherlands Antilles
AOA Angola
ARS Argentina
ATS Austria
AUD Australia
AWG Aruba
AZM Azerbaijan
BAM Bosnia and Herzegovina
BBD Barbados
BDT Bangladesh
BEF Belgium
BGL Bulgaria
BHD Bahrain
BIF Burundi
BMD Bermuda
BND Brunei Darussalam
BOB Bolivia
BRL Brazil
BSD Bahamas
BTN Bhutan
BWP Botswana
BYR Belarus
BZD Belize
CAD Canada
CDF Congo/Kinshasa
CHF Switzerland
CLP Chile
CNY China
COP Colombia
CRC Costa Rica
CUP Cuba
CVE Cape Verde
CYP Cyprus
CZK Czech Republic
DEM Germany
DJF Djibouti
DKK Denmark
DOP Dominican Republic
DZD Algeria
EEK Estonia
EGP Egypt
ERN Eritrea
ESP Spain
ETB Ethiopia
EUR Euro Member Countries
FIM Finland
FJD Fiji
FKP Falkland Islands (Malvinas)
FRF France
GBP United Kingdom
GEL Georgia
GGP Guernsey
GHC Ghana
GIP Gibraltar
GMD Gambia
GNF Guinea
GRD Greece
GTQ Guatemala
GYD Guyana
HKD Hong Kong
HNL Honduras
HRK Croatia
HTG Haiti
HUF Hungary
IDR Indonesia
IEP Ireland (Eire)
ILS Israel
IMP Isle of Man
INR India
IQD Iraq
IRR Iran
ISK Iceland
ITL Italy
JEP Jersey
JMD Jamaica
JOD Jordan
JPY Japan
KES Kenya
KGS Kyrgyzstan
KHR Cambodia
KMF Comoros
KPW Korea
KWD Kuwait
KYD Cayman Islands
KZT Kazakstan
LAK Laos
LBP Lebanon
LKR Sri Lanka
LRD Liberia
LSL Lesotho
LTL Lithuania
LUF Luxembourg
LVL Latvia
LYD Libya
MAD Morocco
MDL Moldova
MGF Madagascar
MKD Macedonia
MMK Myanmar (Burma)
MNT Mongolia
MOP Macau
MRO Mauritania
MTL Malta
MUR Mauritius
MVR Maldives (Maldive Islands)
MWK Malawi
MXN Mexico
MYR Malaysia
MZM Mozambique
NAD Namibia
NGN Nigeria
NIO Nicaragua
NLG Netherlands (Holland)
NOK Norway
NPR Nepal
NZD New Zealand
OMR Oman
PAB Panama
PEN Peru
PGK Papua New Guinea
PHP Philippines
PKR Pakistan
PLN Poland
PTE Portugal
PYG Paraguay
QAR Qatar
ROL Romania
RUR Russia
RWF Rwanda
SAR Saudi Arabia
SBD Solomon Islands
SCR Seychelles
SDD Sudan
SEK Sweden
SGD Singapore
SHP Saint Helena
SIT Slovenia
SKK Slovakia
SLL Sierra Leone
SOS Somalia
SPL Seborga
SRG Suriname
STD São Tome and Principe
SVC El Salvador
SYP Syria
SZL Swaziland
THB Thailand
TJR Tajikistan
TMM Turkmenistan
TND Tunisia
TOP Tonga
TRL Turkey
TTD Trinidad and Tobago
TVD Tuvalu
TWD Taiwan
TZS Tanzania
UAH Ukraine
UGX Uganda
USD United States of America
UYU Uruguay
UZS Uzbekistan
VAL Vatican City
VEB Venezuela
VND Viet Nam
VUV Vanuatu
WST Samoa
XAF Communauté Financière Africaine
XAG Silver
XAU Gold
XCD East Caribbean
XDR International Monetary Fund
XPD Palladium
XPF Comptoirs Français du Pacifique
XPT Platinum
YER Yemen
YUM Yugoslavia
ZAR South Africa
ZMK Zambia
ZWD Zimbabwe
*/
return getid3_lib::EmbeddedLookup($currencyid, $begin, __LINE__, __FILE__, 'id3v2-currency-country');
}
public static function LanguageLookup($languagecode, $casesensitive=false) {
if (!$casesensitive) {
$languagecode = strtolower($languagecode);
}
// http://www.id3.org/id3v2.4.0-structure.txt
// [4. ID3v2 frame overview]
// The three byte language field, present in several frames, is used to
// describe the language of the frame's content, according to ISO-639-2
// [ISO-639-2]. The language should be represented in lower case. If the
// language is not known the string "XXX" should be used.
// ISO 639-2 - http://www.id3.org/iso639-2.html
$begin = __LINE__;
/** This is not a comment!
XXX unknown
xxx unknown
aar Afar
abk Abkhazian
ace Achinese
ach Acoli
ada Adangme
afa Afro-Asiatic (Other)
afh Afrihili
afr Afrikaans
aka Akan
akk Akkadian
alb Albanian
ale Aleut
alg Algonquian Languages
amh Amharic
ang English, Old (ca. 450-1100)
apa Apache Languages
ara Arabic
arc Aramaic
arm Armenian
arn Araucanian
arp Arapaho
art Artificial (Other)
arw Arawak
asm Assamese
ath Athapascan Languages
ava Avaric
ave Avestan
awa Awadhi
aym Aymara
aze Azerbaijani
bad Banda
bai Bamileke Languages
bak Bashkir
bal Baluchi
bam Bambara
ban Balinese
baq Basque
bas Basa
bat Baltic (Other)
bej Beja
bel Byelorussian
bem Bemba
ben Bengali
ber Berber (Other)
bho Bhojpuri
bih Bihari
bik Bikol
bin Bini
bis Bislama
bla Siksika
bnt Bantu (Other)
bod Tibetan
bra Braj
bre Breton
bua Buriat
bug Buginese
bul Bulgarian
bur Burmese
cad Caddo
cai Central American Indian (Other)
car Carib
cat Catalan
cau Caucasian (Other)
ceb Cebuano
cel Celtic (Other)
ces Czech
cha Chamorro
chb Chibcha
che Chechen
chg Chagatai
chi Chinese
chm Mari
chn Chinook jargon
cho Choctaw
chr Cherokee
chu Church Slavic
chv Chuvash
chy Cheyenne
cop Coptic
cor Cornish
cos Corsican
cpe Creoles and Pidgins, English-based (Other)
cpf Creoles and Pidgins, French-based (Other)
cpp Creoles and Pidgins, Portuguese-based (Other)
cre Cree
crp Creoles and Pidgins (Other)
cus Cushitic (Other)
cym Welsh
cze Czech
dak Dakota
dan Danish
del Delaware
deu German
din Dinka
div Divehi
doi Dogri
dra Dravidian (Other)
dua Duala
dum Dutch, Middle (ca. 1050-1350)
dut Dutch
dyu Dyula
dzo Dzongkha
efi Efik
egy Egyptian (Ancient)
eka Ekajuk
ell Greek, Modern (1453-)
elx Elamite
eng English
enm English, Middle (ca. 1100-1500)
epo Esperanto
esk Eskimo (Other)
esl Spanish
est Estonian
eus Basque
ewe Ewe
ewo Ewondo
fan Fang
fao Faroese
fas Persian
fat Fanti
fij Fijian
fin Finnish
fiu Finno-Ugrian (Other)
fon Fon
fra French
fre French
frm French, Middle (ca. 1400-1600)
fro French, Old (842- ca. 1400)
fry Frisian
ful Fulah
gaa Ga
gae Gaelic (Scots)
gai Irish
gay Gayo
gdh Gaelic (Scots)
gem Germanic (Other)
geo Georgian
ger German
gez Geez
gil Gilbertese
glg Gallegan
gmh German, Middle High (ca. 1050-1500)
goh German, Old High (ca. 750-1050)
gon Gondi
got Gothic
grb Grebo
grc Greek, Ancient (to 1453)
gre Greek, Modern (1453-)
grn Guarani
guj Gujarati
hai Haida
hau Hausa
haw Hawaiian
heb Hebrew
her Herero
hil Hiligaynon
him Himachali
hin Hindi
hmo Hiri Motu
hun Hungarian
hup Hupa
hye Armenian
iba Iban
ibo Igbo
ice Icelandic
ijo Ijo
iku Inuktitut
ilo Iloko
ina Interlingua (International Auxiliary language Association)
inc Indic (Other)
ind Indonesian
ine Indo-European (Other)
ine Interlingue
ipk Inupiak
ira Iranian (Other)
iri Irish
iro Iroquoian uages
isl Icelandic
ita Italian
jav Javanese
jaw Javanese
jpn Japanese
jpr Judeo-Persian
jrb Judeo-Arabic
kaa Kara-Kalpak
kab Kabyle
kac Kachin
kal Greenlandic
kam Kamba
kan Kannada
kar Karen
kas Kashmiri
kat Georgian
kau Kanuri
kaw Kawi
kaz Kazakh
kha Khasi
khi Khoisan (Other)
khm Khmer
kho Khotanese
kik Kikuyu
kin Kinyarwanda
kir Kirghiz
kok Konkani
kom Komi
kon Kongo
kor Korean
kpe Kpelle
kro Kru
kru Kurukh
kua Kuanyama
kum Kumyk
kur Kurdish
kus Kusaie
kut Kutenai
lad Ladino
lah Lahnda
lam Lamba
lao Lao
lat Latin
lav Latvian
lez Lezghian
lin Lingala
lit Lithuanian
lol Mongo
loz Lozi
ltz Letzeburgesch
lub Luba-Katanga
lug Ganda
lui Luiseno
lun Lunda
luo Luo (Kenya and Tanzania)
mac Macedonian
mad Madurese
mag Magahi
mah Marshall
mai Maithili
mak Macedonian
mak Makasar
mal Malayalam
man Mandingo
mao Maori
map Austronesian (Other)
mar Marathi
mas Masai
max Manx
may Malay
men Mende
mga Irish, Middle (900 - 1200)
mic Micmac
min Minangkabau
mis Miscellaneous (Other)
mkh Mon-Kmer (Other)
mlg Malagasy
mlt Maltese
mni Manipuri
mno Manobo Languages
moh Mohawk
mol Moldavian
mon Mongolian
mos Mossi
mri Maori
msa Malay
mul Multiple Languages
mun Munda Languages
mus Creek
mwr Marwari
mya Burmese
myn Mayan Languages
nah Aztec
nai North American Indian (Other)
nau Nauru
nav Navajo
nbl Ndebele, South
nde Ndebele, North
ndo Ndongo
nep Nepali
new Newari
nic Niger-Kordofanian (Other)
niu Niuean
nla Dutch
nno Norwegian (Nynorsk)
non Norse, Old
nor Norwegian
nso Sotho, Northern
nub Nubian Languages
nya Nyanja
nym Nyamwezi
nyn Nyankole
nyo Nyoro
nzi Nzima
oci Langue d'Oc (post 1500)
oji Ojibwa
ori Oriya
orm Oromo
osa Osage
oss Ossetic
ota Turkish, Ottoman (1500 - 1928)
oto Otomian Languages
paa Papuan-Australian (Other)
pag Pangasinan
pal Pahlavi
pam Pampanga
pan Panjabi
pap Papiamento
pau Palauan
peo Persian, Old (ca 600 - 400 B.C.)
per Persian
phn Phoenician
pli Pali
pol Polish
pon Ponape
por Portuguese
pra Prakrit uages
pro Provencal, Old (to 1500)
pus Pushto
que Quechua
raj Rajasthani
rar Rarotongan
roa Romance (Other)
roh Rhaeto-Romance
rom Romany
ron Romanian
rum Romanian
run Rundi
rus Russian
sad Sandawe
sag Sango
sah Yakut
sai South American Indian (Other)
sal Salishan Languages
sam Samaritan Aramaic
san Sanskrit
sco Scots
scr Serbo-Croatian
sel Selkup
sem Semitic (Other)
sga Irish, Old (to 900)
shn Shan
sid Sidamo
sin Singhalese
sio Siouan Languages
sit Sino-Tibetan (Other)
sla Slavic (Other)
slk Slovak
slo Slovak
slv Slovenian
smi Sami Languages
smo Samoan
sna Shona
snd Sindhi
sog Sogdian
som Somali
son Songhai
sot Sotho, Southern
spa Spanish
sqi Albanian
srd Sardinian
srr Serer
ssa Nilo-Saharan (Other)
ssw Siswant
ssw Swazi
suk Sukuma
sun Sudanese
sus Susu
sux Sumerian
sve Swedish
swa Swahili
swe Swedish
syr Syriac
tah Tahitian
tam Tamil
tat Tatar
tel Telugu
tem Timne
ter Tereno
tgk Tajik
tgl Tagalog
tha Thai
tib Tibetan
tig Tigre
tir Tigrinya
tiv Tivi
tli Tlingit
tmh Tamashek
tog Tonga (Nyasa)
ton Tonga (Tonga Islands)
tru Truk
tsi Tsimshian
tsn Tswana
tso Tsonga
tuk Turkmen
tum Tumbuka
tur Turkish
tut Altaic (Other)
twi Twi
tyv Tuvinian
uga Ugaritic
uig Uighur
ukr Ukrainian
umb Umbundu
und Undetermined
urd Urdu
uzb Uzbek
vai Vai
ven Venda
vie Vietnamese
vol Volapük
vot Votic
wak Wakashan Languages
wal Walamo
war Waray
was Washo
wel Welsh
wen Sorbian Languages
wol Wolof
xho Xhosa
yao Yao
yap Yap
yid Yiddish
yor Yoruba
zap Zapotec
zen Zenaga
zha Zhuang
zho Chinese
zul Zulu
zun Zuni
*/
return getid3_lib::EmbeddedLookup($languagecode, $begin, __LINE__, __FILE__, 'id3v2-languagecode');
}
public static function ETCOEventLookup($index) {
if (($index >= 0x17) && ($index <= 0xDF)) {
return 'reserved for future use';
}
if (($index >= 0xE0) && ($index <= 0xEF)) {
return 'not predefined synch 0-F';
}
if (($index >= 0xF0) && ($index <= 0xFC)) {
return 'reserved for future use';
}
static $EventLookup = array(
0x00 => 'padding (has no meaning)',
0x01 => 'end of initial silence',
0x02 => 'intro start',
0x03 => 'main part start',
0x04 => 'outro start',
0x05 => 'outro end',
0x06 => 'verse start',
0x07 => 'refrain start',
0x08 => 'interlude start',
0x09 => 'theme start',
0x0A => 'variation start',
0x0B => 'key change',
0x0C => 'time change',
0x0D => 'momentary unwanted noise (Snap, Crackle & Pop)',
0x0E => 'sustained noise',
0x0F => 'sustained noise end',
0x10 => 'intro end',
0x11 => 'main part end',
0x12 => 'verse end',
0x13 => 'refrain end',
0x14 => 'theme end',
0x15 => 'profanity',
0x16 => 'profanity end',
0xFD => 'audio end (start of silence)',
0xFE => 'audio file ends',
0xFF => 'one more byte of events follows'
);
return (isset($EventLookup[$index]) ? $EventLookup[$index] : '');
}
public static function SYTLContentTypeLookup($index) {
static $SYTLContentTypeLookup = array(
0x00 => 'other',
0x01 => 'lyrics',
0x02 => 'text transcription',
0x03 => 'movement/part name', // (e.g. 'Adagio')
0x04 => 'events', // (e.g. 'Don Quijote enters the stage')
0x05 => 'chord', // (e.g. 'Bb F Fsus')
0x06 => 'trivia/\'pop up\' information',
0x07 => 'URLs to webpages',
0x08 => 'URLs to images'
);
return (isset($SYTLContentTypeLookup[$index]) ? $SYTLContentTypeLookup[$index] : '');
}
public static function APICPictureTypeLookup($index, $returnarray=false) {
static $APICPictureTypeLookup = array(
0x00 => 'Other',
0x01 => '32x32 pixels \'file icon\' (PNG only)',
0x02 => 'Other file icon',
0x03 => 'Cover (front)',
0x04 => 'Cover (back)',
0x05 => 'Leaflet page',
0x06 => 'Media (e.g. label side of CD)',
0x07 => 'Lead artist/lead performer/soloist',
0x08 => 'Artist/performer',
0x09 => 'Conductor',
0x0A => 'Band/Orchestra',
0x0B => 'Composer',
0x0C => 'Lyricist/text writer',
0x0D => 'Recording Location',
0x0E => 'During recording',
0x0F => 'During performance',
0x10 => 'Movie/video screen capture',
0x11 => 'A bright coloured fish',
0x12 => 'Illustration',
0x13 => 'Band/artist logotype',
0x14 => 'Publisher/Studio logotype'
);
if ($returnarray) {
return $APICPictureTypeLookup;
}
return (isset($APICPictureTypeLookup[$index]) ? $APICPictureTypeLookup[$index] : '');
}
public static function COMRReceivedAsLookup($index) {
static $COMRReceivedAsLookup = array(
0x00 => 'Other',
0x01 => 'Standard CD album with other songs',
0x02 => 'Compressed audio on CD',
0x03 => 'File over the Internet',
0x04 => 'Stream over the Internet',
0x05 => 'As note sheets',
0x06 => 'As note sheets in a book with other sheets',
0x07 => 'Music on other media',
0x08 => 'Non-musical merchandise'
);
return (isset($COMRReceivedAsLookup[$index]) ? $COMRReceivedAsLookup[$index] : '');
}
public static function RVA2ChannelTypeLookup($index) {
static $RVA2ChannelTypeLookup = array(
0x00 => 'Other',
0x01 => 'Master volume',
0x02 => 'Front right',
0x03 => 'Front left',
0x04 => 'Back right',
0x05 => 'Back left',
0x06 => 'Front centre',
0x07 => 'Back centre',
0x08 => 'Subwoofer'
);
return (isset($RVA2ChannelTypeLookup[$index]) ? $RVA2ChannelTypeLookup[$index] : '');
}
public static function FrameNameLongLookup($framename) {
$begin = __LINE__;
/** This is not a comment!
AENC Audio encryption
APIC Attached picture
ASPI Audio seek point index
BUF Recommended buffer size
CNT Play counter
COM Comments
COMM Comments
COMR Commercial frame
CRA Audio encryption
CRM Encrypted meta frame
ENCR Encryption method registration
EQU Equalisation
EQU2 Equalisation (2)
EQUA Equalisation
ETC Event timing codes
ETCO Event timing codes
GEO General encapsulated object
GEOB General encapsulated object
GRID Group identification registration
IPL Involved people list
IPLS Involved people list
LINK Linked information
LNK Linked information
MCDI Music CD identifier
MCI Music CD Identifier
MLL MPEG location lookup table
MLLT MPEG location lookup table
OWNE Ownership frame
PCNT Play counter
PIC Attached picture
POP Popularimeter
POPM Popularimeter
POSS Position synchronisation frame
PRIV Private frame
RBUF Recommended buffer size
REV Reverb
RVA Relative volume adjustment
RVA2 Relative volume adjustment (2)
RVAD Relative volume adjustment
RVRB Reverb
SEEK Seek frame
SIGN Signature frame
SLT Synchronised lyric/text
STC Synced tempo codes
SYLT Synchronised lyric/text
SYTC Synchronised tempo codes
TAL Album/Movie/Show title
TALB Album/Movie/Show title
TBP BPM (Beats Per Minute)
TBPM BPM (beats per minute)
TCM Composer
TCMP Part of a compilation
TCO Content type
TCOM Composer
TCON Content type
TCOP Copyright message
TCP Part of a compilation
TCR Copyright message
TDA Date
TDAT Date
TDEN Encoding time
TDLY Playlist delay
TDOR Original release time
TDRC Recording time
TDRL Release time
TDTG Tagging time
TDY Playlist delay
TEN Encoded by
TENC Encoded by
TEXT Lyricist/Text writer
TFLT File type
TFT File type
TIM Time
TIME Time
TIPL Involved people list
TIT1 Content group description
TIT2 Title/songname/content description
TIT3 Subtitle/Description refinement
TKE Initial key
TKEY Initial key
TLA Language(s)
TLAN Language(s)
TLE Length
TLEN Length
TMCL Musician credits list
TMED Media type
TMOO Mood
TMT Media type
TOA Original artist(s)/performer(s)
TOAL Original album/movie/show title
TOF Original filename
TOFN Original filename
TOL Original Lyricist(s)/text writer(s)
TOLY Original lyricist(s)/text writer(s)
TOPE Original artist(s)/performer(s)
TOR Original release year
TORY Original release year
TOT Original album/Movie/Show title
TOWN File owner/licensee
TP1 Lead artist(s)/Lead performer(s)/Soloist(s)/Performing group
TP2 Band/Orchestra/Accompaniment
TP3 Conductor/Performer refinement
TP4 Interpreted, remixed, or otherwise modified by
TPA Part of a set
TPB Publisher
TPE1 Lead performer(s)/Soloist(s)
TPE2 Band/orchestra/accompaniment
TPE3 Conductor/performer refinement
TPE4 Interpreted, remixed, or otherwise modified by
TPOS Part of a set
TPRO Produced notice
TPUB Publisher
TRC ISRC (International Standard Recording Code)
TRCK Track number/Position in set
TRD Recording dates
TRDA Recording dates
TRK Track number/Position in set
TRSN Internet radio station name
TRSO Internet radio station owner
TS2 Album-Artist sort order
TSA Album sort order
TSC Composer sort order
TSI Size
TSIZ Size
TSO2 Album-Artist sort order
TSOA Album sort order
TSOC Composer sort order
TSOP Performer sort order
TSOT Title sort order
TSP Performer sort order
TSRC ISRC (international standard recording code)
TSS Software/hardware and settings used for encoding
TSSE Software/Hardware and settings used for encoding
TSST Set subtitle
TST Title sort order
TT1 Content group description
TT2 Title/Songname/Content description
TT3 Subtitle/Description refinement
TXT Lyricist/text writer
TXX User defined text information frame
TXXX User defined text information frame
TYE Year
TYER Year
UFI Unique file identifier
UFID Unique file identifier
ULT Unsychronised lyric/text transcription
USER Terms of use
USLT Unsynchronised lyric/text transcription
WAF Official audio file webpage
WAR Official artist/performer webpage
WAS Official audio source webpage
WCM Commercial information
WCOM Commercial information
WCOP Copyright/Legal information
WCP Copyright/Legal information
WOAF Official audio file webpage
WOAR Official artist/performer webpage
WOAS Official audio source webpage
WORS Official Internet radio station homepage
WPAY Payment
WPB Publishers official webpage
WPUB Publishers official webpage
WXX User defined URL link frame
WXXX User defined URL link frame
TFEA Featured Artist
TSTU Recording Studio
rgad Replay Gain Adjustment
*/
return getid3_lib::EmbeddedLookup($framename, $begin, __LINE__, __FILE__, 'id3v2-framename_long');
// Last three:
// from Helium2 [www.helium2.com]
// from http://privatewww.essex.ac.uk/~djmrob/replaygain/file_format_id3v2.html
}
public static function FrameNameShortLookup($framename) {
$begin = __LINE__;
/** This is not a comment!
AENC audio_encryption
APIC attached_picture
ASPI audio_seek_point_index
BUF recommended_buffer_size
CNT play_counter
COM comment
COMM comment
COMR commercial_frame
CRA audio_encryption
CRM encrypted_meta_frame
ENCR encryption_method_registration
EQU equalisation
EQU2 equalisation
EQUA equalisation
ETC event_timing_codes
ETCO event_timing_codes
GEO general_encapsulated_object
GEOB general_encapsulated_object
GRID group_identification_registration
IPL involved_people_list
IPLS involved_people_list
LINK linked_information
LNK linked_information
MCDI music_cd_identifier
MCI music_cd_identifier
MLL mpeg_location_lookup_table
MLLT mpeg_location_lookup_table
OWNE ownership_frame
PCNT play_counter
PIC attached_picture
POP popularimeter
POPM popularimeter
POSS position_synchronisation_frame
PRIV private_frame
RBUF recommended_buffer_size
REV reverb
RVA relative_volume_adjustment
RVA2 relative_volume_adjustment
RVAD relative_volume_adjustment
RVRB reverb
SEEK seek_frame
SIGN signature_frame
SLT synchronised_lyric
STC synced_tempo_codes
SYLT synchronised_lyric
SYTC synchronised_tempo_codes
TAL album
TALB album
TBP bpm
TBPM bpm
TCM composer
TCMP part_of_a_compilation
TCO genre
TCOM composer
TCON genre
TCOP copyright_message
TCP part_of_a_compilation
TCR copyright_message
TDA date
TDAT date
TDEN encoding_time
TDLY playlist_delay
TDOR original_release_time
TDRC recording_time
TDRL release_time
TDTG tagging_time
TDY playlist_delay
TEN encoded_by
TENC encoded_by
TEXT lyricist
TFLT file_type
TFT file_type
TIM time
TIME time
TIPL involved_people_list
TIT1 content_group_description
TIT2 title
TIT3 subtitle
TKE initial_key
TKEY initial_key
TLA language
TLAN language
TLE length
TLEN length
TMCL musician_credits_list
TMED media_type
TMOO mood
TMT media_type
TOA original_artist
TOAL original_album
TOF original_filename
TOFN original_filename
TOL original_lyricist
TOLY original_lyricist
TOPE original_artist
TOR original_year
TORY original_year
TOT original_album
TOWN file_owner
TP1 artist
TP2 band
TP3 conductor
TP4 remixer
TPA part_of_a_set
TPB publisher
TPE1 artist
TPE2 band
TPE3 conductor
TPE4 remixer
TPOS part_of_a_set
TPRO produced_notice
TPUB publisher
TRC isrc
TRCK track_number
TRD recording_dates
TRDA recording_dates
TRK track_number
TRSN internet_radio_station_name
TRSO internet_radio_station_owner
TS2 album_artist_sort_order
TSA album_sort_order
TSC composer_sort_order
TSI size
TSIZ size
TSO2 album_artist_sort_order
TSOA album_sort_order
TSOC composer_sort_order
TSOP performer_sort_order
TSOT title_sort_order
TSP performer_sort_order
TSRC isrc
TSS encoder_settings
TSSE encoder_settings
TSST set_subtitle
TST title_sort_order
TT1 content_group_description
TT2 title
TT3 subtitle
TXT lyricist
TXX text
TXXX text
TYE year
TYER year
UFI unique_file_identifier
UFID unique_file_identifier
ULT unsychronised_lyric
USER terms_of_use
USLT unsynchronised_lyric
WAF url_file
WAR url_artist
WAS url_source
WCM commercial_information
WCOM commercial_information
WCOP copyright
WCP copyright
WOAF url_file
WOAR url_artist
WOAS url_source
WORS url_station
WPAY url_payment
WPB url_publisher
WPUB url_publisher
WXX url_user
WXXX url_user
TFEA featured_artist
TSTU recording_studio
rgad replay_gain_adjustment
*/
return getid3_lib::EmbeddedLookup($framename, $begin, __LINE__, __FILE__, 'id3v2-framename_short');
}
public static function TextEncodingTerminatorLookup($encoding) {
// http://www.id3.org/id3v2.4.0-structure.txt
// Frames that allow different types of text encoding contains a text encoding description byte. Possible encodings:
static $TextEncodingTerminatorLookup = array(
0 => "\x00", // $00 ISO-8859-1. Terminated with $00.
1 => "\x00\x00", // $01 UTF-16 encoded Unicode with BOM. All strings in the same frame SHALL have the same byteorder. Terminated with $00 00.
2 => "\x00\x00", // $02 UTF-16BE encoded Unicode without BOM. Terminated with $00 00.
3 => "\x00", // $03 UTF-8 encoded Unicode. Terminated with $00.
255 => "\x00\x00"
);
return (isset($TextEncodingTerminatorLookup[$encoding]) ? $TextEncodingTerminatorLookup[$encoding] : '');
}
public static function TextEncodingNameLookup($encoding) {
// http://www.id3.org/id3v2.4.0-structure.txt
// Frames that allow different types of text encoding contains a text encoding description byte. Possible encodings:
static $TextEncodingNameLookup = array(
0 => 'ISO-8859-1', // $00 ISO-8859-1. Terminated with $00.
1 => 'UTF-16', // $01 UTF-16 encoded Unicode with BOM. All strings in the same frame SHALL have the same byteorder. Terminated with $00 00.
2 => 'UTF-16BE', // $02 UTF-16BE encoded Unicode without BOM. Terminated with $00 00.
3 => 'UTF-8', // $03 UTF-8 encoded Unicode. Terminated with $00.
255 => 'UTF-16BE'
);
return (isset($TextEncodingNameLookup[$encoding]) ? $TextEncodingNameLookup[$encoding] : 'ISO-8859-1');
}
public static function IsValidID3v2FrameName($framename, $id3v2majorversion) {
switch ($id3v2majorversion) {
case 2:
return preg_match('#[A-Z][A-Z0-9]{2}#', $framename);
break;
case 3:
case 4:
return preg_match('#[A-Z][A-Z0-9]{3}#', $framename);
break;
}
return false;
}
public static function IsANumber($numberstring, $allowdecimal=false, $allownegative=false) {
for ($i = 0; $i < strlen($numberstring); $i++) {
if ((chr($numberstring{$i}) < chr('0')) || (chr($numberstring{$i}) > chr('9'))) {
if (($numberstring{$i} == '.') && $allowdecimal) {
// allowed
} elseif (($numberstring{$i} == '-') && $allownegative && ($i == 0)) {
// allowed
} else {
return false;
}
}
}
return true;
}
public static function IsValidDateStampString($datestamp) {
if (strlen($datestamp) != 8) {
return false;
}
if (!self::IsANumber($datestamp, false)) {
return false;
}
$year = substr($datestamp, 0, 4);
$month = substr($datestamp, 4, 2);
$day = substr($datestamp, 6, 2);
if (($year == 0) || ($month == 0) || ($day == 0)) {
return false;
}
if ($month > 12) {
return false;
}
if ($day > 31) {
return false;
}
if (($day > 30) && (($month == 4) || ($month == 6) || ($month == 9) || ($month == 11))) {
return false;
}
if (($day > 29) && ($month == 2)) {
return false;
}
return true;
}
public static function ID3v2HeaderLength($majorversion) {
return (($majorversion == 2) ? 6 : 10);
}
}
| PHP |
<?php
/////////////////////////////////////////////////////////////////
/// getID3() by James Heinrich <info@getid3.org> //
// available at http://getid3.sourceforge.net //
// or http://www.getid3.org //
/////////////////////////////////////////////////////////////////
// See readme.txt for more details //
/////////////////////////////////////////////////////////////////
// //
// module.audio-video.riff.php //
// module for analyzing RIFF files //
// multiple formats supported by this module: //
// Wave, AVI, AIFF/AIFC, (MP3,AC3)/RIFF, Wavpack v3, 8SVX //
// dependencies: module.audio.mp3.php //
// module.audio.ac3.php //
// module.audio.dts.php //
// ///
/////////////////////////////////////////////////////////////////
/**
* @todo Parse AC-3/DTS audio inside WAVE correctly
* @todo Rewrite RIFF parser totally
*/
getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.audio.mp3.php', __FILE__, true);
getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.audio.ac3.php', __FILE__, true);
getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.audio.dts.php', __FILE__, true);
class getid3_riff extends getid3_handler
{
public function Analyze() {
$info = &$this->getid3->info;
// initialize these values to an empty array, otherwise they default to NULL
// and you can't append array values to a NULL value
$info['riff'] = array('raw'=>array());
// Shortcuts
$thisfile_riff = &$info['riff'];
$thisfile_riff_raw = &$thisfile_riff['raw'];
$thisfile_audio = &$info['audio'];
$thisfile_video = &$info['video'];
$thisfile_audio_dataformat = &$thisfile_audio['dataformat'];
$thisfile_riff_audio = &$thisfile_riff['audio'];
$thisfile_riff_video = &$thisfile_riff['video'];
$Original['avdataoffset'] = $info['avdataoffset'];
$Original['avdataend'] = $info['avdataend'];
$this->fseek($info['avdataoffset']);
$RIFFheader = $this->fread(12);
$offset = $this->ftell();
$RIFFtype = substr($RIFFheader, 0, 4);
$RIFFsize = substr($RIFFheader, 4, 4);
$RIFFsubtype = substr($RIFFheader, 8, 4);
switch ($RIFFtype) {
case 'FORM': // AIFF, AIFC
$info['fileformat'] = 'aiff';
$thisfile_riff['header_size'] = $this->EitherEndian2Int($RIFFsize);
$thisfile_riff[$RIFFsubtype] = $this->ParseRIFF($offset, ($offset + $thisfile_riff['header_size'] - 4));
break;
case 'RIFF': // AVI, WAV, etc
case 'SDSS': // SDSS is identical to RIFF, just renamed. Used by SmartSound QuickTracks (www.smartsound.com)
case 'RMP3': // RMP3 is identical to RIFF, just renamed. Used by [unknown program] when creating RIFF-MP3s
$info['fileformat'] = 'riff';
$thisfile_riff['header_size'] = $this->EitherEndian2Int($RIFFsize);
if ($RIFFsubtype == 'RMP3') {
// RMP3 is identical to WAVE, just renamed. Used by [unknown program] when creating RIFF-MP3s
$RIFFsubtype = 'WAVE';
}
$thisfile_riff[$RIFFsubtype] = $this->ParseRIFF($offset, ($offset + $thisfile_riff['header_size'] - 4));
if (($info['avdataend'] - $info['filesize']) == 1) {
// LiteWave appears to incorrectly *not* pad actual output file
// to nearest WORD boundary so may appear to be short by one
// byte, in which case - skip warning
$info['avdataend'] = $info['filesize'];
}
$nextRIFFoffset = $Original['avdataoffset'] + 8 + $thisfile_riff['header_size']; // 8 = "RIFF" + 32-bit offset
while ($nextRIFFoffset < min($info['filesize'], $info['avdataend'])) {
try {
$this->fseek($nextRIFFoffset);
} catch (getid3_exception $e) {
if ($e->getCode() == 10) {
//$this->warning('RIFF parser: '.$e->getMessage());
$this->error('AVI extends beyond '.round(PHP_INT_MAX / 1073741824).'GB and PHP filesystem functions cannot read that far, playtime may be wrong');
$this->warning('[avdataend] value may be incorrect, multiple AVIX chunks may be present');
break;
} else {
throw $e;
}
}
$nextRIFFheader = $this->fread(12);
if ($nextRIFFoffset == ($info['avdataend'] - 1)) {
if (substr($nextRIFFheader, 0, 1) == "\x00") {
// RIFF padded to WORD boundary, we're actually already at the end
break;
}
}
$nextRIFFheaderID = substr($nextRIFFheader, 0, 4);
$nextRIFFsize = $this->EitherEndian2Int(substr($nextRIFFheader, 4, 4));
$nextRIFFtype = substr($nextRIFFheader, 8, 4);
$chunkdata = array();
$chunkdata['offset'] = $nextRIFFoffset + 8;
$chunkdata['size'] = $nextRIFFsize;
$nextRIFFoffset = $chunkdata['offset'] + $chunkdata['size'];
switch ($nextRIFFheaderID) {
case 'RIFF':
$chunkdata['chunks'] = $this->ParseRIFF($chunkdata['offset'] + 4, $nextRIFFoffset);
if (!isset($thisfile_riff[$nextRIFFtype])) {
$thisfile_riff[$nextRIFFtype] = array();
}
$thisfile_riff[$nextRIFFtype][] = $chunkdata;
break;
case 'JUNK':
// ignore
$thisfile_riff[$nextRIFFheaderID][] = $chunkdata;
break;
case 'IDVX':
$info['divxtag']['comments'] = self::ParseDIVXTAG($this->fread($chunkdata['size']));
break;
default:
if ($info['filesize'] == ($chunkdata['offset'] - 8 + 128)) {
$DIVXTAG = $nextRIFFheader.$this->fread(128 - 12);
if (substr($DIVXTAG, -7) == 'DIVXTAG') {
// DIVXTAG is supposed to be inside an IDVX chunk in a LIST chunk, but some bad encoders just slap it on the end of a file
$this->warning('Found wrongly-structured DIVXTAG at offset '.($this->ftell() - 128).', parsing anyway');
$info['divxtag']['comments'] = self::ParseDIVXTAG($DIVXTAG);
break 2;
}
}
$this->warning('Expecting "RIFF|JUNK|IDVX" at '.$nextRIFFoffset.', found "'.$nextRIFFheaderID.'" ('.getid3_lib::PrintHexBytes($nextRIFFheaderID).') - skipping rest of file');
break 2;
}
}
if ($RIFFsubtype == 'WAVE') {
$thisfile_riff_WAVE = &$thisfile_riff['WAVE'];
}
break;
default:
$this->error('Cannot parse RIFF (this is maybe not a RIFF / WAV / AVI file?) - expecting "FORM|RIFF|SDSS|RMP3" found "'.$RIFFsubtype.'" instead');
unset($info['fileformat']);
return false;
}
$streamindex = 0;
switch ($RIFFsubtype) {
case 'WAVE':
if (empty($thisfile_audio['bitrate_mode'])) {
$thisfile_audio['bitrate_mode'] = 'cbr';
}
if (empty($thisfile_audio_dataformat)) {
$thisfile_audio_dataformat = 'wav';
}
if (isset($thisfile_riff_WAVE['data'][0]['offset'])) {
$info['avdataoffset'] = $thisfile_riff_WAVE['data'][0]['offset'] + 8;
$info['avdataend'] = $info['avdataoffset'] + $thisfile_riff_WAVE['data'][0]['size'];
}
if (isset($thisfile_riff_WAVE['fmt '][0]['data'])) {
$thisfile_riff_audio[$streamindex] = self::parseWAVEFORMATex($thisfile_riff_WAVE['fmt '][0]['data']);
$thisfile_audio['wformattag'] = $thisfile_riff_audio[$streamindex]['raw']['wFormatTag'];
if (!isset($thisfile_riff_audio[$streamindex]['bitrate']) || ($thisfile_riff_audio[$streamindex]['bitrate'] == 0)) {
$info['error'][] = 'Corrupt RIFF file: bitrate_audio == zero';
return false;
}
$thisfile_riff_raw['fmt '] = $thisfile_riff_audio[$streamindex]['raw'];
unset($thisfile_riff_audio[$streamindex]['raw']);
$thisfile_audio['streams'][$streamindex] = $thisfile_riff_audio[$streamindex];
$thisfile_audio = getid3_lib::array_merge_noclobber($thisfile_audio, $thisfile_riff_audio[$streamindex]);
if (substr($thisfile_audio['codec'], 0, strlen('unknown: 0x')) == 'unknown: 0x') {
$info['warning'][] = 'Audio codec = '.$thisfile_audio['codec'];
}
$thisfile_audio['bitrate'] = $thisfile_riff_audio[$streamindex]['bitrate'];
if (empty($info['playtime_seconds'])) { // may already be set (e.g. DTS-WAV)
$info['playtime_seconds'] = (float) ((($info['avdataend'] - $info['avdataoffset']) * 8) / $thisfile_audio['bitrate']);
}
$thisfile_audio['lossless'] = false;
if (isset($thisfile_riff_WAVE['data'][0]['offset']) && isset($thisfile_riff_raw['fmt ']['wFormatTag'])) {
switch ($thisfile_riff_raw['fmt ']['wFormatTag']) {
case 0x0001: // PCM
$thisfile_audio['lossless'] = true;
break;
case 0x2000: // AC-3
$thisfile_audio_dataformat = 'ac3';
break;
default:
// do nothing
break;
}
}
$thisfile_audio['streams'][$streamindex]['wformattag'] = $thisfile_audio['wformattag'];
$thisfile_audio['streams'][$streamindex]['bitrate_mode'] = $thisfile_audio['bitrate_mode'];
$thisfile_audio['streams'][$streamindex]['lossless'] = $thisfile_audio['lossless'];
$thisfile_audio['streams'][$streamindex]['dataformat'] = $thisfile_audio_dataformat;
}
if (isset($thisfile_riff_WAVE['rgad'][0]['data'])) {
// shortcuts
$rgadData = &$thisfile_riff_WAVE['rgad'][0]['data'];
$thisfile_riff_raw['rgad'] = array('track'=>array(), 'album'=>array());
$thisfile_riff_raw_rgad = &$thisfile_riff_raw['rgad'];
$thisfile_riff_raw_rgad_track = &$thisfile_riff_raw_rgad['track'];
$thisfile_riff_raw_rgad_album = &$thisfile_riff_raw_rgad['album'];
$thisfile_riff_raw_rgad['fPeakAmplitude'] = getid3_lib::LittleEndian2Float(substr($rgadData, 0, 4));
$thisfile_riff_raw_rgad['nRadioRgAdjust'] = $this->EitherEndian2Int(substr($rgadData, 4, 2));
$thisfile_riff_raw_rgad['nAudiophileRgAdjust'] = $this->EitherEndian2Int(substr($rgadData, 6, 2));
$nRadioRgAdjustBitstring = str_pad(getid3_lib::Dec2Bin($thisfile_riff_raw_rgad['nRadioRgAdjust']), 16, '0', STR_PAD_LEFT);
$nAudiophileRgAdjustBitstring = str_pad(getid3_lib::Dec2Bin($thisfile_riff_raw_rgad['nAudiophileRgAdjust']), 16, '0', STR_PAD_LEFT);
$thisfile_riff_raw_rgad_track['name'] = getid3_lib::Bin2Dec(substr($nRadioRgAdjustBitstring, 0, 3));
$thisfile_riff_raw_rgad_track['originator'] = getid3_lib::Bin2Dec(substr($nRadioRgAdjustBitstring, 3, 3));
$thisfile_riff_raw_rgad_track['signbit'] = getid3_lib::Bin2Dec(substr($nRadioRgAdjustBitstring, 6, 1));
$thisfile_riff_raw_rgad_track['adjustment'] = getid3_lib::Bin2Dec(substr($nRadioRgAdjustBitstring, 7, 9));
$thisfile_riff_raw_rgad_album['name'] = getid3_lib::Bin2Dec(substr($nAudiophileRgAdjustBitstring, 0, 3));
$thisfile_riff_raw_rgad_album['originator'] = getid3_lib::Bin2Dec(substr($nAudiophileRgAdjustBitstring, 3, 3));
$thisfile_riff_raw_rgad_album['signbit'] = getid3_lib::Bin2Dec(substr($nAudiophileRgAdjustBitstring, 6, 1));
$thisfile_riff_raw_rgad_album['adjustment'] = getid3_lib::Bin2Dec(substr($nAudiophileRgAdjustBitstring, 7, 9));
$thisfile_riff['rgad']['peakamplitude'] = $thisfile_riff_raw_rgad['fPeakAmplitude'];
if (($thisfile_riff_raw_rgad_track['name'] != 0) && ($thisfile_riff_raw_rgad_track['originator'] != 0)) {
$thisfile_riff['rgad']['track']['name'] = getid3_lib::RGADnameLookup($thisfile_riff_raw_rgad_track['name']);
$thisfile_riff['rgad']['track']['originator'] = getid3_lib::RGADoriginatorLookup($thisfile_riff_raw_rgad_track['originator']);
$thisfile_riff['rgad']['track']['adjustment'] = getid3_lib::RGADadjustmentLookup($thisfile_riff_raw_rgad_track['adjustment'], $thisfile_riff_raw_rgad_track['signbit']);
}
if (($thisfile_riff_raw_rgad_album['name'] != 0) && ($thisfile_riff_raw_rgad_album['originator'] != 0)) {
$thisfile_riff['rgad']['album']['name'] = getid3_lib::RGADnameLookup($thisfile_riff_raw_rgad_album['name']);
$thisfile_riff['rgad']['album']['originator'] = getid3_lib::RGADoriginatorLookup($thisfile_riff_raw_rgad_album['originator']);
$thisfile_riff['rgad']['album']['adjustment'] = getid3_lib::RGADadjustmentLookup($thisfile_riff_raw_rgad_album['adjustment'], $thisfile_riff_raw_rgad_album['signbit']);
}
}
if (isset($thisfile_riff_WAVE['fact'][0]['data'])) {
$thisfile_riff_raw['fact']['NumberOfSamples'] = $this->EitherEndian2Int(substr($thisfile_riff_WAVE['fact'][0]['data'], 0, 4));
// This should be a good way of calculating exact playtime,
// but some sample files have had incorrect number of samples,
// so cannot use this method
// if (!empty($thisfile_riff_raw['fmt ']['nSamplesPerSec'])) {
// $info['playtime_seconds'] = (float) $thisfile_riff_raw['fact']['NumberOfSamples'] / $thisfile_riff_raw['fmt ']['nSamplesPerSec'];
// }
}
if (!empty($thisfile_riff_raw['fmt ']['nAvgBytesPerSec'])) {
$thisfile_audio['bitrate'] = getid3_lib::CastAsInt($thisfile_riff_raw['fmt ']['nAvgBytesPerSec'] * 8);
}
if (isset($thisfile_riff_WAVE['bext'][0]['data'])) {
// shortcut
$thisfile_riff_WAVE_bext_0 = &$thisfile_riff_WAVE['bext'][0];
$thisfile_riff_WAVE_bext_0['title'] = trim(substr($thisfile_riff_WAVE_bext_0['data'], 0, 256));
$thisfile_riff_WAVE_bext_0['author'] = trim(substr($thisfile_riff_WAVE_bext_0['data'], 256, 32));
$thisfile_riff_WAVE_bext_0['reference'] = trim(substr($thisfile_riff_WAVE_bext_0['data'], 288, 32));
$thisfile_riff_WAVE_bext_0['origin_date'] = substr($thisfile_riff_WAVE_bext_0['data'], 320, 10);
$thisfile_riff_WAVE_bext_0['origin_time'] = substr($thisfile_riff_WAVE_bext_0['data'], 330, 8);
$thisfile_riff_WAVE_bext_0['time_reference'] = getid3_lib::LittleEndian2Int(substr($thisfile_riff_WAVE_bext_0['data'], 338, 8));
$thisfile_riff_WAVE_bext_0['bwf_version'] = getid3_lib::LittleEndian2Int(substr($thisfile_riff_WAVE_bext_0['data'], 346, 1));
$thisfile_riff_WAVE_bext_0['reserved'] = substr($thisfile_riff_WAVE_bext_0['data'], 347, 254);
$thisfile_riff_WAVE_bext_0['coding_history'] = explode("\r\n", trim(substr($thisfile_riff_WAVE_bext_0['data'], 601)));
if (preg_match('#^([0-9]{4}).([0-9]{2}).([0-9]{2})$#', $thisfile_riff_WAVE_bext_0['origin_date'], $matches_bext_date)) {
if (preg_match('#^([0-9]{2}).([0-9]{2}).([0-9]{2})$#', $thisfile_riff_WAVE_bext_0['origin_time'], $matches_bext_time)) {
list($dummy, $bext_timestamp['year'], $bext_timestamp['month'], $bext_timestamp['day']) = $matches_bext_date;
list($dummy, $bext_timestamp['hour'], $bext_timestamp['minute'], $bext_timestamp['second']) = $matches_bext_time;
$thisfile_riff_WAVE_bext_0['origin_date_unix'] = gmmktime($bext_timestamp['hour'], $bext_timestamp['minute'], $bext_timestamp['second'], $bext_timestamp['month'], $bext_timestamp['day'], $bext_timestamp['year']);
} else {
$info['warning'][] = 'RIFF.WAVE.BEXT.origin_time is invalid';
}
} else {
$info['warning'][] = 'RIFF.WAVE.BEXT.origin_date is invalid';
}
$thisfile_riff['comments']['author'][] = $thisfile_riff_WAVE_bext_0['author'];
$thisfile_riff['comments']['title'][] = $thisfile_riff_WAVE_bext_0['title'];
}
if (isset($thisfile_riff_WAVE['MEXT'][0]['data'])) {
// shortcut
$thisfile_riff_WAVE_MEXT_0 = &$thisfile_riff_WAVE['MEXT'][0];
$thisfile_riff_WAVE_MEXT_0['raw']['sound_information'] = getid3_lib::LittleEndian2Int(substr($thisfile_riff_WAVE_MEXT_0['data'], 0, 2));
$thisfile_riff_WAVE_MEXT_0['flags']['homogenous'] = (bool) ($thisfile_riff_WAVE_MEXT_0['raw']['sound_information'] & 0x0001);
if ($thisfile_riff_WAVE_MEXT_0['flags']['homogenous']) {
$thisfile_riff_WAVE_MEXT_0['flags']['padding'] = ($thisfile_riff_WAVE_MEXT_0['raw']['sound_information'] & 0x0002) ? false : true;
$thisfile_riff_WAVE_MEXT_0['flags']['22_or_44'] = (bool) ($thisfile_riff_WAVE_MEXT_0['raw']['sound_information'] & 0x0004);
$thisfile_riff_WAVE_MEXT_0['flags']['free_format'] = (bool) ($thisfile_riff_WAVE_MEXT_0['raw']['sound_information'] & 0x0008);
$thisfile_riff_WAVE_MEXT_0['nominal_frame_size'] = getid3_lib::LittleEndian2Int(substr($thisfile_riff_WAVE_MEXT_0['data'], 2, 2));
}
$thisfile_riff_WAVE_MEXT_0['anciliary_data_length'] = getid3_lib::LittleEndian2Int(substr($thisfile_riff_WAVE_MEXT_0['data'], 6, 2));
$thisfile_riff_WAVE_MEXT_0['raw']['anciliary_data_def'] = getid3_lib::LittleEndian2Int(substr($thisfile_riff_WAVE_MEXT_0['data'], 8, 2));
$thisfile_riff_WAVE_MEXT_0['flags']['anciliary_data_left'] = (bool) ($thisfile_riff_WAVE_MEXT_0['raw']['anciliary_data_def'] & 0x0001);
$thisfile_riff_WAVE_MEXT_0['flags']['anciliary_data_free'] = (bool) ($thisfile_riff_WAVE_MEXT_0['raw']['anciliary_data_def'] & 0x0002);
$thisfile_riff_WAVE_MEXT_0['flags']['anciliary_data_right'] = (bool) ($thisfile_riff_WAVE_MEXT_0['raw']['anciliary_data_def'] & 0x0004);
}
if (isset($thisfile_riff_WAVE['cart'][0]['data'])) {
// shortcut
$thisfile_riff_WAVE_cart_0 = &$thisfile_riff_WAVE['cart'][0];
$thisfile_riff_WAVE_cart_0['version'] = substr($thisfile_riff_WAVE_cart_0['data'], 0, 4);
$thisfile_riff_WAVE_cart_0['title'] = trim(substr($thisfile_riff_WAVE_cart_0['data'], 4, 64));
$thisfile_riff_WAVE_cart_0['artist'] = trim(substr($thisfile_riff_WAVE_cart_0['data'], 68, 64));
$thisfile_riff_WAVE_cart_0['cut_id'] = trim(substr($thisfile_riff_WAVE_cart_0['data'], 132, 64));
$thisfile_riff_WAVE_cart_0['client_id'] = trim(substr($thisfile_riff_WAVE_cart_0['data'], 196, 64));
$thisfile_riff_WAVE_cart_0['category'] = trim(substr($thisfile_riff_WAVE_cart_0['data'], 260, 64));
$thisfile_riff_WAVE_cart_0['classification'] = trim(substr($thisfile_riff_WAVE_cart_0['data'], 324, 64));
$thisfile_riff_WAVE_cart_0['out_cue'] = trim(substr($thisfile_riff_WAVE_cart_0['data'], 388, 64));
$thisfile_riff_WAVE_cart_0['start_date'] = trim(substr($thisfile_riff_WAVE_cart_0['data'], 452, 10));
$thisfile_riff_WAVE_cart_0['start_time'] = trim(substr($thisfile_riff_WAVE_cart_0['data'], 462, 8));
$thisfile_riff_WAVE_cart_0['end_date'] = trim(substr($thisfile_riff_WAVE_cart_0['data'], 470, 10));
$thisfile_riff_WAVE_cart_0['end_time'] = trim(substr($thisfile_riff_WAVE_cart_0['data'], 480, 8));
$thisfile_riff_WAVE_cart_0['producer_app_id'] = trim(substr($thisfile_riff_WAVE_cart_0['data'], 488, 64));
$thisfile_riff_WAVE_cart_0['producer_app_version'] = trim(substr($thisfile_riff_WAVE_cart_0['data'], 552, 64));
$thisfile_riff_WAVE_cart_0['user_defined_text'] = trim(substr($thisfile_riff_WAVE_cart_0['data'], 616, 64));
$thisfile_riff_WAVE_cart_0['zero_db_reference'] = getid3_lib::LittleEndian2Int(substr($thisfile_riff_WAVE_cart_0['data'], 680, 4), true);
for ($i = 0; $i < 8; $i++) {
$thisfile_riff_WAVE_cart_0['post_time'][$i]['usage_fourcc'] = substr($thisfile_riff_WAVE_cart_0['data'], 684 + ($i * 8), 4);
$thisfile_riff_WAVE_cart_0['post_time'][$i]['timer_value'] = getid3_lib::LittleEndian2Int(substr($thisfile_riff_WAVE_cart_0['data'], 684 + ($i * 8) + 4, 4));
}
$thisfile_riff_WAVE_cart_0['url'] = trim(substr($thisfile_riff_WAVE_cart_0['data'], 748, 1024));
$thisfile_riff_WAVE_cart_0['tag_text'] = explode("\r\n", trim(substr($thisfile_riff_WAVE_cart_0['data'], 1772)));
$thisfile_riff['comments']['artist'][] = $thisfile_riff_WAVE_cart_0['artist'];
$thisfile_riff['comments']['title'][] = $thisfile_riff_WAVE_cart_0['title'];
}
if (isset($thisfile_riff_WAVE['SNDM'][0]['data'])) {
// SoundMiner metadata
// shortcuts
$thisfile_riff_WAVE_SNDM_0 = &$thisfile_riff_WAVE['SNDM'][0];
$thisfile_riff_WAVE_SNDM_0_data = &$thisfile_riff_WAVE_SNDM_0['data'];
$SNDM_startoffset = 0;
$SNDM_endoffset = $thisfile_riff_WAVE_SNDM_0['size'];
while ($SNDM_startoffset < $SNDM_endoffset) {
$SNDM_thisTagOffset = 0;
$SNDM_thisTagSize = getid3_lib::BigEndian2Int(substr($thisfile_riff_WAVE_SNDM_0_data, $SNDM_startoffset + $SNDM_thisTagOffset, 4));
$SNDM_thisTagOffset += 4;
$SNDM_thisTagKey = substr($thisfile_riff_WAVE_SNDM_0_data, $SNDM_startoffset + $SNDM_thisTagOffset, 4);
$SNDM_thisTagOffset += 4;
$SNDM_thisTagDataSize = getid3_lib::BigEndian2Int(substr($thisfile_riff_WAVE_SNDM_0_data, $SNDM_startoffset + $SNDM_thisTagOffset, 2));
$SNDM_thisTagOffset += 2;
$SNDM_thisTagDataFlags = getid3_lib::BigEndian2Int(substr($thisfile_riff_WAVE_SNDM_0_data, $SNDM_startoffset + $SNDM_thisTagOffset, 2));
$SNDM_thisTagOffset += 2;
$SNDM_thisTagDataText = substr($thisfile_riff_WAVE_SNDM_0_data, $SNDM_startoffset + $SNDM_thisTagOffset, $SNDM_thisTagDataSize);
$SNDM_thisTagOffset += $SNDM_thisTagDataSize;
if ($SNDM_thisTagSize != (4 + 4 + 2 + 2 + $SNDM_thisTagDataSize)) {
$info['warning'][] = 'RIFF.WAVE.SNDM.data contains tag not expected length (expected: '.$SNDM_thisTagSize.', found: '.(4 + 4 + 2 + 2 + $SNDM_thisTagDataSize).') at offset '.$SNDM_startoffset.' (file offset '.($thisfile_riff_WAVE_SNDM_0['offset'] + $SNDM_startoffset).')';
break;
} elseif ($SNDM_thisTagSize <= 0) {
$info['warning'][] = 'RIFF.WAVE.SNDM.data contains zero-size tag at offset '.$SNDM_startoffset.' (file offset '.($thisfile_riff_WAVE_SNDM_0['offset'] + $SNDM_startoffset).')';
break;
}
$SNDM_startoffset += $SNDM_thisTagSize;
$thisfile_riff_WAVE_SNDM_0['parsed_raw'][$SNDM_thisTagKey] = $SNDM_thisTagDataText;
if ($parsedkey = self::waveSNDMtagLookup($SNDM_thisTagKey)) {
$thisfile_riff_WAVE_SNDM_0['parsed'][$parsedkey] = $SNDM_thisTagDataText;
} else {
$info['warning'][] = 'RIFF.WAVE.SNDM contains unknown tag "'.$SNDM_thisTagKey.'" at offset '.$SNDM_startoffset.' (file offset '.($thisfile_riff_WAVE_SNDM_0['offset'] + $SNDM_startoffset).')';
}
}
$tagmapping = array(
'tracktitle'=>'title',
'category' =>'genre',
'cdtitle' =>'album',
'tracktitle'=>'title',
);
foreach ($tagmapping as $fromkey => $tokey) {
if (isset($thisfile_riff_WAVE_SNDM_0['parsed'][$fromkey])) {
$thisfile_riff['comments'][$tokey][] = $thisfile_riff_WAVE_SNDM_0['parsed'][$fromkey];
}
}
}
if (isset($thisfile_riff_WAVE['iXML'][0]['data'])) {
// requires functions simplexml_load_string and get_object_vars
if ($parsedXML = getid3_lib::XML2array($thisfile_riff_WAVE['iXML'][0]['data'])) {
$thisfile_riff_WAVE['iXML'][0]['parsed'] = $parsedXML;
if (isset($parsedXML['SPEED']['MASTER_SPEED'])) {
@list($numerator, $denominator) = explode('/', $parsedXML['SPEED']['MASTER_SPEED']);
$thisfile_riff_WAVE['iXML'][0]['master_speed'] = $numerator / ($denominator ? $denominator : 1000);
}
if (isset($parsedXML['SPEED']['TIMECODE_RATE'])) {
@list($numerator, $denominator) = explode('/', $parsedXML['SPEED']['TIMECODE_RATE']);
$thisfile_riff_WAVE['iXML'][0]['timecode_rate'] = $numerator / ($denominator ? $denominator : 1000);
}
if (isset($parsedXML['SPEED']['TIMESTAMP_SAMPLES_SINCE_MIDNIGHT_LO']) && !empty($parsedXML['SPEED']['TIMESTAMP_SAMPLE_RATE']) && !empty($thisfile_riff_WAVE['iXML'][0]['timecode_rate'])) {
$samples_since_midnight = floatval(ltrim($parsedXML['SPEED']['TIMESTAMP_SAMPLES_SINCE_MIDNIGHT_HI'].$parsedXML['SPEED']['TIMESTAMP_SAMPLES_SINCE_MIDNIGHT_LO'], '0'));
$thisfile_riff_WAVE['iXML'][0]['timecode_seconds'] = $samples_since_midnight / $parsedXML['SPEED']['TIMESTAMP_SAMPLE_RATE'];
$h = floor( $thisfile_riff_WAVE['iXML'][0]['timecode_seconds'] / 3600);
$m = floor(($thisfile_riff_WAVE['iXML'][0]['timecode_seconds'] - ($h * 3600)) / 60);
$s = floor( $thisfile_riff_WAVE['iXML'][0]['timecode_seconds'] - ($h * 3600) - ($m * 60));
$f = ($thisfile_riff_WAVE['iXML'][0]['timecode_seconds'] - ($h * 3600) - ($m * 60) - $s) * $thisfile_riff_WAVE['iXML'][0]['timecode_rate'];
$thisfile_riff_WAVE['iXML'][0]['timecode_string'] = sprintf('%02d:%02d:%02d:%05.2f', $h, $m, $s, $f);
$thisfile_riff_WAVE['iXML'][0]['timecode_string_round'] = sprintf('%02d:%02d:%02d:%02d', $h, $m, $s, round($f));
}
unset($parsedXML);
}
}
if (!isset($thisfile_audio['bitrate']) && isset($thisfile_riff_audio[$streamindex]['bitrate'])) {
$thisfile_audio['bitrate'] = $thisfile_riff_audio[$streamindex]['bitrate'];
$info['playtime_seconds'] = (float) ((($info['avdataend'] - $info['avdataoffset']) * 8) / $thisfile_audio['bitrate']);
}
if (!empty($info['wavpack'])) {
$thisfile_audio_dataformat = 'wavpack';
$thisfile_audio['bitrate_mode'] = 'vbr';
$thisfile_audio['encoder'] = 'WavPack v'.$info['wavpack']['version'];
// Reset to the way it was - RIFF parsing will have messed this up
$info['avdataend'] = $Original['avdataend'];
$thisfile_audio['bitrate'] = (($info['avdataend'] - $info['avdataoffset']) * 8) / $info['playtime_seconds'];
$this->fseek($info['avdataoffset'] - 44);
$RIFFdata = $this->fread(44);
$OrignalRIFFheaderSize = getid3_lib::LittleEndian2Int(substr($RIFFdata, 4, 4)) + 8;
$OrignalRIFFdataSize = getid3_lib::LittleEndian2Int(substr($RIFFdata, 40, 4)) + 44;
if ($OrignalRIFFheaderSize > $OrignalRIFFdataSize) {
$info['avdataend'] -= ($OrignalRIFFheaderSize - $OrignalRIFFdataSize);
$this->fseek($info['avdataend']);
$RIFFdata .= $this->fread($OrignalRIFFheaderSize - $OrignalRIFFdataSize);
}
// move the data chunk after all other chunks (if any)
// so that the RIFF parser doesn't see EOF when trying
// to skip over the data chunk
$RIFFdata = substr($RIFFdata, 0, 36).substr($RIFFdata, 44).substr($RIFFdata, 36, 8);
$getid3_riff = new getid3_riff($this->getid3);
$getid3_riff->ParseRIFFdata($RIFFdata);
unset($getid3_riff);
}
if (isset($thisfile_riff_raw['fmt ']['wFormatTag'])) {
switch ($thisfile_riff_raw['fmt ']['wFormatTag']) {
case 0x0001: // PCM
if (!empty($info['ac3'])) {
// Dolby Digital WAV files masquerade as PCM-WAV, but they're not
$thisfile_audio['wformattag'] = 0x2000;
$thisfile_audio['codec'] = self::wFormatTagLookup($thisfile_audio['wformattag']);
$thisfile_audio['lossless'] = false;
$thisfile_audio['bitrate'] = $info['ac3']['bitrate'];
$thisfile_audio['sample_rate'] = $info['ac3']['sample_rate'];
}
if (!empty($info['dts'])) {
// Dolby DTS files masquerade as PCM-WAV, but they're not
$thisfile_audio['wformattag'] = 0x2001;
$thisfile_audio['codec'] = self::wFormatTagLookup($thisfile_audio['wformattag']);
$thisfile_audio['lossless'] = false;
$thisfile_audio['bitrate'] = $info['dts']['bitrate'];
$thisfile_audio['sample_rate'] = $info['dts']['sample_rate'];
}
break;
case 0x08AE: // ClearJump LiteWave
$thisfile_audio['bitrate_mode'] = 'vbr';
$thisfile_audio_dataformat = 'litewave';
//typedef struct tagSLwFormat {
// WORD m_wCompFormat; // low byte defines compression method, high byte is compression flags
// DWORD m_dwScale; // scale factor for lossy compression
// DWORD m_dwBlockSize; // number of samples in encoded blocks
// WORD m_wQuality; // alias for the scale factor
// WORD m_wMarkDistance; // distance between marks in bytes
// WORD m_wReserved;
//
// //following paramters are ignored if CF_FILESRC is not set
// DWORD m_dwOrgSize; // original file size in bytes
// WORD m_bFactExists; // indicates if 'fact' chunk exists in the original file
// DWORD m_dwRiffChunkSize; // riff chunk size in the original file
//
// PCMWAVEFORMAT m_OrgWf; // original wave format
// }SLwFormat, *PSLwFormat;
// shortcut
$thisfile_riff['litewave']['raw'] = array();
$riff_litewave = &$thisfile_riff['litewave'];
$riff_litewave_raw = &$riff_litewave['raw'];
$flags = array(
'compression_method' => 1,
'compression_flags' => 1,
'm_dwScale' => 4,
'm_dwBlockSize' => 4,
'm_wQuality' => 2,
'm_wMarkDistance' => 2,
'm_wReserved' => 2,
'm_dwOrgSize' => 4,
'm_bFactExists' => 2,
'm_dwRiffChunkSize' => 4,
);
$litewave_offset = 18;
foreach ($flags as $flag => $length) {
$riff_litewave_raw[$flag] = getid3_lib::LittleEndian2Int(substr($thisfile_riff_WAVE['fmt '][0]['data'], $litewave_offset, $length));
$litewave_offset += $length;
}
//$riff_litewave['quality_factor'] = intval(round((2000 - $riff_litewave_raw['m_dwScale']) / 20));
$riff_litewave['quality_factor'] = $riff_litewave_raw['m_wQuality'];
$riff_litewave['flags']['raw_source'] = ($riff_litewave_raw['compression_flags'] & 0x01) ? false : true;
$riff_litewave['flags']['vbr_blocksize'] = ($riff_litewave_raw['compression_flags'] & 0x02) ? false : true;
$riff_litewave['flags']['seekpoints'] = (bool) ($riff_litewave_raw['compression_flags'] & 0x04);
$thisfile_audio['lossless'] = (($riff_litewave_raw['m_wQuality'] == 100) ? true : false);
$thisfile_audio['encoder_options'] = '-q'.$riff_litewave['quality_factor'];
break;
default:
break;
}
}
if ($info['avdataend'] > $info['filesize']) {
switch (!empty($thisfile_audio_dataformat) ? $thisfile_audio_dataformat : '') {
case 'wavpack': // WavPack
case 'lpac': // LPAC
case 'ofr': // OptimFROG
case 'ofs': // OptimFROG DualStream
// lossless compressed audio formats that keep original RIFF headers - skip warning
break;
case 'litewave':
if (($info['avdataend'] - $info['filesize']) == 1) {
// LiteWave appears to incorrectly *not* pad actual output file
// to nearest WORD boundary so may appear to be short by one
// byte, in which case - skip warning
} else {
// Short by more than one byte, throw warning
$info['warning'][] = 'Probably truncated file - expecting '.$thisfile_riff[$RIFFsubtype]['data'][0]['size'].' bytes of data, only found '.($info['filesize'] - $info['avdataoffset']).' (short by '.($thisfile_riff[$RIFFsubtype]['data'][0]['size'] - ($info['filesize'] - $info['avdataoffset'])).' bytes)';
$info['avdataend'] = $info['filesize'];
}
break;
default:
if ((($info['avdataend'] - $info['filesize']) == 1) && (($thisfile_riff[$RIFFsubtype]['data'][0]['size'] % 2) == 0) && ((($info['filesize'] - $info['avdataoffset']) % 2) == 1)) {
// output file appears to be incorrectly *not* padded to nearest WORD boundary
// Output less severe warning
$info['warning'][] = 'File should probably be padded to nearest WORD boundary, but it is not (expecting '.$thisfile_riff[$RIFFsubtype]['data'][0]['size'].' bytes of data, only found '.($info['filesize'] - $info['avdataoffset']).' therefore short by '.($thisfile_riff[$RIFFsubtype]['data'][0]['size'] - ($info['filesize'] - $info['avdataoffset'])).' bytes)';
$info['avdataend'] = $info['filesize'];
} else {
// Short by more than one byte, throw warning
$info['warning'][] = 'Probably truncated file - expecting '.$thisfile_riff[$RIFFsubtype]['data'][0]['size'].' bytes of data, only found '.($info['filesize'] - $info['avdataoffset']).' (short by '.($thisfile_riff[$RIFFsubtype]['data'][0]['size'] - ($info['filesize'] - $info['avdataoffset'])).' bytes)';
$info['avdataend'] = $info['filesize'];
}
break;
}
}
if (!empty($info['mpeg']['audio']['LAME']['audio_bytes'])) {
if ((($info['avdataend'] - $info['avdataoffset']) - $info['mpeg']['audio']['LAME']['audio_bytes']) == 1) {
$info['avdataend']--;
$info['warning'][] = 'Extra null byte at end of MP3 data assumed to be RIFF padding and therefore ignored';
}
}
if (isset($thisfile_audio_dataformat) && ($thisfile_audio_dataformat == 'ac3')) {
unset($thisfile_audio['bits_per_sample']);
if (!empty($info['ac3']['bitrate']) && ($info['ac3']['bitrate'] != $thisfile_audio['bitrate'])) {
$thisfile_audio['bitrate'] = $info['ac3']['bitrate'];
}
}
break;
case 'AVI ':
$thisfile_video['bitrate_mode'] = 'vbr'; // maybe not, but probably
$thisfile_video['dataformat'] = 'avi';
$info['mime_type'] = 'video/avi';
if (isset($thisfile_riff[$RIFFsubtype]['movi']['offset'])) {
$info['avdataoffset'] = $thisfile_riff[$RIFFsubtype]['movi']['offset'] + 8;
if (isset($thisfile_riff['AVIX'])) {
$info['avdataend'] = $thisfile_riff['AVIX'][(count($thisfile_riff['AVIX']) - 1)]['chunks']['movi']['offset'] + $thisfile_riff['AVIX'][(count($thisfile_riff['AVIX']) - 1)]['chunks']['movi']['size'];
} else {
$info['avdataend'] = $thisfile_riff['AVI ']['movi']['offset'] + $thisfile_riff['AVI ']['movi']['size'];
}
if ($info['avdataend'] > $info['filesize']) {
$info['warning'][] = 'Probably truncated file - expecting '.($info['avdataend'] - $info['avdataoffset']).' bytes of data, only found '.($info['filesize'] - $info['avdataoffset']).' (short by '.($info['avdataend'] - $info['filesize']).' bytes)';
$info['avdataend'] = $info['filesize'];
}
}
if (isset($thisfile_riff['AVI ']['hdrl']['strl']['indx'])) {
//$bIndexType = array(
// 0x00 => 'AVI_INDEX_OF_INDEXES',
// 0x01 => 'AVI_INDEX_OF_CHUNKS',
// 0x80 => 'AVI_INDEX_IS_DATA',
//);
//$bIndexSubtype = array(
// 0x01 => array(
// 0x01 => 'AVI_INDEX_2FIELD',
// ),
//);
foreach ($thisfile_riff['AVI ']['hdrl']['strl']['indx'] as $streamnumber => $steamdataarray) {
$ahsisd = &$thisfile_riff['AVI ']['hdrl']['strl']['indx'][$streamnumber]['data'];
$thisfile_riff_raw['indx'][$streamnumber]['wLongsPerEntry'] = $this->EitherEndian2Int(substr($ahsisd, 0, 2));
$thisfile_riff_raw['indx'][$streamnumber]['bIndexSubType'] = $this->EitherEndian2Int(substr($ahsisd, 2, 1));
$thisfile_riff_raw['indx'][$streamnumber]['bIndexType'] = $this->EitherEndian2Int(substr($ahsisd, 3, 1));
$thisfile_riff_raw['indx'][$streamnumber]['nEntriesInUse'] = $this->EitherEndian2Int(substr($ahsisd, 4, 4));
$thisfile_riff_raw['indx'][$streamnumber]['dwChunkId'] = substr($ahsisd, 8, 4);
$thisfile_riff_raw['indx'][$streamnumber]['dwReserved'] = $this->EitherEndian2Int(substr($ahsisd, 12, 4));
//$thisfile_riff_raw['indx'][$streamnumber]['bIndexType_name'] = $bIndexType[$thisfile_riff_raw['indx'][$streamnumber]['bIndexType']];
//$thisfile_riff_raw['indx'][$streamnumber]['bIndexSubType_name'] = $bIndexSubtype[$thisfile_riff_raw['indx'][$streamnumber]['bIndexType']][$thisfile_riff_raw['indx'][$streamnumber]['bIndexSubType']];
unset($ahsisd);
}
}
if (isset($thisfile_riff['AVI ']['hdrl']['avih'][$streamindex]['data'])) {
$avihData = $thisfile_riff['AVI ']['hdrl']['avih'][$streamindex]['data'];
// shortcut
$thisfile_riff_raw['avih'] = array();
$thisfile_riff_raw_avih = &$thisfile_riff_raw['avih'];
$thisfile_riff_raw_avih['dwMicroSecPerFrame'] = $this->EitherEndian2Int(substr($avihData, 0, 4)); // frame display rate (or 0L)
if ($thisfile_riff_raw_avih['dwMicroSecPerFrame'] == 0) {
$info['error'][] = 'Corrupt RIFF file: avih.dwMicroSecPerFrame == zero';
return false;
}
$flags = array(
'dwMaxBytesPerSec', // max. transfer rate
'dwPaddingGranularity', // pad to multiples of this size; normally 2K.
'dwFlags', // the ever-present flags
'dwTotalFrames', // # frames in file
'dwInitialFrames', //
'dwStreams', //
'dwSuggestedBufferSize', //
'dwWidth', //
'dwHeight', //
'dwScale', //
'dwRate', //
'dwStart', //
'dwLength', //
);
$avih_offset = 4;
foreach ($flags as $flag) {
$thisfile_riff_raw_avih[$flag] = $this->EitherEndian2Int(substr($avihData, $avih_offset, 4));
$avih_offset += 4;
}
$flags = array(
'hasindex' => 0x00000010,
'mustuseindex' => 0x00000020,
'interleaved' => 0x00000100,
'trustcktype' => 0x00000800,
'capturedfile' => 0x00010000,
'copyrighted' => 0x00020010,
);
foreach ($flags as $flag => $value) {
$thisfile_riff_raw_avih['flags'][$flag] = (bool) ($thisfile_riff_raw_avih['dwFlags'] & $value);
}
// shortcut
$thisfile_riff_video[$streamindex] = array();
$thisfile_riff_video_current = &$thisfile_riff_video[$streamindex];
if ($thisfile_riff_raw_avih['dwWidth'] > 0) {
$thisfile_riff_video_current['frame_width'] = $thisfile_riff_raw_avih['dwWidth'];
$thisfile_video['resolution_x'] = $thisfile_riff_video_current['frame_width'];
}
if ($thisfile_riff_raw_avih['dwHeight'] > 0) {
$thisfile_riff_video_current['frame_height'] = $thisfile_riff_raw_avih['dwHeight'];
$thisfile_video['resolution_y'] = $thisfile_riff_video_current['frame_height'];
}
if ($thisfile_riff_raw_avih['dwTotalFrames'] > 0) {
$thisfile_riff_video_current['total_frames'] = $thisfile_riff_raw_avih['dwTotalFrames'];
$thisfile_video['total_frames'] = $thisfile_riff_video_current['total_frames'];
}
$thisfile_riff_video_current['frame_rate'] = round(1000000 / $thisfile_riff_raw_avih['dwMicroSecPerFrame'], 3);
$thisfile_video['frame_rate'] = $thisfile_riff_video_current['frame_rate'];
}
if (isset($thisfile_riff['AVI ']['hdrl']['strl']['strh'][0]['data'])) {
if (is_array($thisfile_riff['AVI ']['hdrl']['strl']['strh'])) {
for ($i = 0; $i < count($thisfile_riff['AVI ']['hdrl']['strl']['strh']); $i++) {
if (isset($thisfile_riff['AVI ']['hdrl']['strl']['strh'][$i]['data'])) {
$strhData = $thisfile_riff['AVI ']['hdrl']['strl']['strh'][$i]['data'];
$strhfccType = substr($strhData, 0, 4);
if (isset($thisfile_riff['AVI ']['hdrl']['strl']['strf'][$i]['data'])) {
$strfData = $thisfile_riff['AVI ']['hdrl']['strl']['strf'][$i]['data'];
// shortcut
$thisfile_riff_raw_strf_strhfccType_streamindex = &$thisfile_riff_raw['strf'][$strhfccType][$streamindex];
switch ($strhfccType) {
case 'auds':
$thisfile_audio['bitrate_mode'] = 'cbr';
$thisfile_audio_dataformat = 'wav';
if (isset($thisfile_riff_audio) && is_array($thisfile_riff_audio)) {
$streamindex = count($thisfile_riff_audio);
}
$thisfile_riff_audio[$streamindex] = self::parseWAVEFORMATex($strfData);
$thisfile_audio['wformattag'] = $thisfile_riff_audio[$streamindex]['raw']['wFormatTag'];
// shortcut
$thisfile_audio['streams'][$streamindex] = $thisfile_riff_audio[$streamindex];
$thisfile_audio_streams_currentstream = &$thisfile_audio['streams'][$streamindex];
if ($thisfile_audio_streams_currentstream['bits_per_sample'] == 0) {
unset($thisfile_audio_streams_currentstream['bits_per_sample']);
}
$thisfile_audio_streams_currentstream['wformattag'] = $thisfile_audio_streams_currentstream['raw']['wFormatTag'];
unset($thisfile_audio_streams_currentstream['raw']);
// shortcut
$thisfile_riff_raw['strf'][$strhfccType][$streamindex] = $thisfile_riff_audio[$streamindex]['raw'];
unset($thisfile_riff_audio[$streamindex]['raw']);
$thisfile_audio = getid3_lib::array_merge_noclobber($thisfile_audio, $thisfile_riff_audio[$streamindex]);
$thisfile_audio['lossless'] = false;
switch ($thisfile_riff_raw_strf_strhfccType_streamindex['wFormatTag']) {
case 0x0001: // PCM
$thisfile_audio_dataformat = 'wav';
$thisfile_audio['lossless'] = true;
break;
case 0x0050: // MPEG Layer 2 or Layer 1
$thisfile_audio_dataformat = 'mp2'; // Assume Layer-2
break;
case 0x0055: // MPEG Layer 3
$thisfile_audio_dataformat = 'mp3';
break;
case 0x00FF: // AAC
$thisfile_audio_dataformat = 'aac';
break;
case 0x0161: // Windows Media v7 / v8 / v9
case 0x0162: // Windows Media Professional v9
case 0x0163: // Windows Media Lossess v9
$thisfile_audio_dataformat = 'wma';
break;
case 0x2000: // AC-3
$thisfile_audio_dataformat = 'ac3';
break;
case 0x2001: // DTS
$thisfile_audio_dataformat = 'dts';
break;
default:
$thisfile_audio_dataformat = 'wav';
break;
}
$thisfile_audio_streams_currentstream['dataformat'] = $thisfile_audio_dataformat;
$thisfile_audio_streams_currentstream['lossless'] = $thisfile_audio['lossless'];
$thisfile_audio_streams_currentstream['bitrate_mode'] = $thisfile_audio['bitrate_mode'];
break;
case 'iavs':
case 'vids':
// shortcut
$thisfile_riff_raw['strh'][$i] = array();
$thisfile_riff_raw_strh_current = &$thisfile_riff_raw['strh'][$i];
$thisfile_riff_raw_strh_current['fccType'] = substr($strhData, 0, 4); // same as $strhfccType;
$thisfile_riff_raw_strh_current['fccHandler'] = substr($strhData, 4, 4);
$thisfile_riff_raw_strh_current['dwFlags'] = $this->EitherEndian2Int(substr($strhData, 8, 4)); // Contains AVITF_* flags
$thisfile_riff_raw_strh_current['wPriority'] = $this->EitherEndian2Int(substr($strhData, 12, 2));
$thisfile_riff_raw_strh_current['wLanguage'] = $this->EitherEndian2Int(substr($strhData, 14, 2));
$thisfile_riff_raw_strh_current['dwInitialFrames'] = $this->EitherEndian2Int(substr($strhData, 16, 4));
$thisfile_riff_raw_strh_current['dwScale'] = $this->EitherEndian2Int(substr($strhData, 20, 4));
$thisfile_riff_raw_strh_current['dwRate'] = $this->EitherEndian2Int(substr($strhData, 24, 4));
$thisfile_riff_raw_strh_current['dwStart'] = $this->EitherEndian2Int(substr($strhData, 28, 4));
$thisfile_riff_raw_strh_current['dwLength'] = $this->EitherEndian2Int(substr($strhData, 32, 4));
$thisfile_riff_raw_strh_current['dwSuggestedBufferSize'] = $this->EitherEndian2Int(substr($strhData, 36, 4));
$thisfile_riff_raw_strh_current['dwQuality'] = $this->EitherEndian2Int(substr($strhData, 40, 4));
$thisfile_riff_raw_strh_current['dwSampleSize'] = $this->EitherEndian2Int(substr($strhData, 44, 4));
$thisfile_riff_raw_strh_current['rcFrame'] = $this->EitherEndian2Int(substr($strhData, 48, 4));
$thisfile_riff_video_current['codec'] = self::fourccLookup($thisfile_riff_raw_strh_current['fccHandler']);
$thisfile_video['fourcc'] = $thisfile_riff_raw_strh_current['fccHandler'];
if (!$thisfile_riff_video_current['codec'] && isset($thisfile_riff_raw_strf_strhfccType_streamindex['fourcc']) && self::fourccLookup($thisfile_riff_raw_strf_strhfccType_streamindex['fourcc'])) {
$thisfile_riff_video_current['codec'] = self::fourccLookup($thisfile_riff_raw_strf_strhfccType_streamindex['fourcc']);
$thisfile_video['fourcc'] = $thisfile_riff_raw_strf_strhfccType_streamindex['fourcc'];
}
$thisfile_video['codec'] = $thisfile_riff_video_current['codec'];
$thisfile_video['pixel_aspect_ratio'] = (float) 1;
switch ($thisfile_riff_raw_strh_current['fccHandler']) {
case 'HFYU': // Huffman Lossless Codec
case 'IRAW': // Intel YUV Uncompressed
case 'YUY2': // Uncompressed YUV 4:2:2
$thisfile_video['lossless'] = true;
break;
default:
$thisfile_video['lossless'] = false;
break;
}
switch ($strhfccType) {
case 'vids':
$thisfile_riff_raw_strf_strhfccType_streamindex = self::ParseBITMAPINFOHEADER(substr($strfData, 0, 40), ($info['fileformat'] == 'riff'));
$thisfile_video['bits_per_sample'] = $thisfile_riff_raw_strf_strhfccType_streamindex['biBitCount'];
if ($thisfile_riff_video_current['codec'] == 'DV') {
$thisfile_riff_video_current['dv_type'] = 2;
}
break;
case 'iavs':
$thisfile_riff_video_current['dv_type'] = 1;
break;
}
break;
default:
$info['warning'][] = 'Unhandled fccType for stream ('.$i.'): "'.$strhfccType.'"';
break;
}
}
}
if (isset($thisfile_riff_raw_strf_strhfccType_streamindex['fourcc'])) {
$thisfile_video['fourcc'] = $thisfile_riff_raw_strf_strhfccType_streamindex['fourcc'];
if (self::fourccLookup($thisfile_video['fourcc'])) {
$thisfile_riff_video_current['codec'] = self::fourccLookup($thisfile_video['fourcc']);
$thisfile_video['codec'] = $thisfile_riff_video_current['codec'];
}
switch ($thisfile_riff_raw_strf_strhfccType_streamindex['fourcc']) {
case 'HFYU': // Huffman Lossless Codec
case 'IRAW': // Intel YUV Uncompressed
case 'YUY2': // Uncompressed YUV 4:2:2
$thisfile_video['lossless'] = true;
//$thisfile_video['bits_per_sample'] = 24;
break;
default:
$thisfile_video['lossless'] = false;
//$thisfile_video['bits_per_sample'] = 24;
break;
}
}
}
}
}
break;
case 'CDDA':
$thisfile_audio['bitrate_mode'] = 'cbr';
$thisfile_audio_dataformat = 'cda';
$thisfile_audio['lossless'] = true;
unset($info['mime_type']);
$info['avdataoffset'] = 44;
if (isset($thisfile_riff['CDDA']['fmt '][0]['data'])) {
// shortcut
$thisfile_riff_CDDA_fmt_0 = &$thisfile_riff['CDDA']['fmt '][0];
$thisfile_riff_CDDA_fmt_0['unknown1'] = $this->EitherEndian2Int(substr($thisfile_riff_CDDA_fmt_0['data'], 0, 2));
$thisfile_riff_CDDA_fmt_0['track_num'] = $this->EitherEndian2Int(substr($thisfile_riff_CDDA_fmt_0['data'], 2, 2));
$thisfile_riff_CDDA_fmt_0['disc_id'] = $this->EitherEndian2Int(substr($thisfile_riff_CDDA_fmt_0['data'], 4, 4));
$thisfile_riff_CDDA_fmt_0['start_offset_frame'] = $this->EitherEndian2Int(substr($thisfile_riff_CDDA_fmt_0['data'], 8, 4));
$thisfile_riff_CDDA_fmt_0['playtime_frames'] = $this->EitherEndian2Int(substr($thisfile_riff_CDDA_fmt_0['data'], 12, 4));
$thisfile_riff_CDDA_fmt_0['unknown6'] = $this->EitherEndian2Int(substr($thisfile_riff_CDDA_fmt_0['data'], 16, 4));
$thisfile_riff_CDDA_fmt_0['unknown7'] = $this->EitherEndian2Int(substr($thisfile_riff_CDDA_fmt_0['data'], 20, 4));
$thisfile_riff_CDDA_fmt_0['start_offset_seconds'] = (float) $thisfile_riff_CDDA_fmt_0['start_offset_frame'] / 75;
$thisfile_riff_CDDA_fmt_0['playtime_seconds'] = (float) $thisfile_riff_CDDA_fmt_0['playtime_frames'] / 75;
$info['comments']['track'] = $thisfile_riff_CDDA_fmt_0['track_num'];
$info['playtime_seconds'] = $thisfile_riff_CDDA_fmt_0['playtime_seconds'];
// hardcoded data for CD-audio
$thisfile_audio['sample_rate'] = 44100;
$thisfile_audio['channels'] = 2;
$thisfile_audio['bits_per_sample'] = 16;
$thisfile_audio['bitrate'] = $thisfile_audio['sample_rate'] * $thisfile_audio['channels'] * $thisfile_audio['bits_per_sample'];
$thisfile_audio['bitrate_mode'] = 'cbr';
}
break;
case 'AIFF':
case 'AIFC':
$thisfile_audio['bitrate_mode'] = 'cbr';
$thisfile_audio_dataformat = 'aiff';
$thisfile_audio['lossless'] = true;
$info['mime_type'] = 'audio/x-aiff';
if (isset($thisfile_riff[$RIFFsubtype]['SSND'][0]['offset'])) {
$info['avdataoffset'] = $thisfile_riff[$RIFFsubtype]['SSND'][0]['offset'] + 8;
$info['avdataend'] = $info['avdataoffset'] + $thisfile_riff[$RIFFsubtype]['SSND'][0]['size'];
if ($info['avdataend'] > $info['filesize']) {
if (($info['avdataend'] == ($info['filesize'] + 1)) && (($info['filesize'] % 2) == 1)) {
// structures rounded to 2-byte boundary, but dumb encoders
// forget to pad end of file to make this actually work
} else {
$info['warning'][] = 'Probable truncated AIFF file: expecting '.$thisfile_riff[$RIFFsubtype]['SSND'][0]['size'].' bytes of audio data, only '.($info['filesize'] - $info['avdataoffset']).' bytes found';
}
$info['avdataend'] = $info['filesize'];
}
}
if (isset($thisfile_riff[$RIFFsubtype]['COMM'][0]['data'])) {
// shortcut
$thisfile_riff_RIFFsubtype_COMM_0_data = &$thisfile_riff[$RIFFsubtype]['COMM'][0]['data'];
$thisfile_riff_audio['channels'] = getid3_lib::BigEndian2Int(substr($thisfile_riff_RIFFsubtype_COMM_0_data, 0, 2), true);
$thisfile_riff_audio['total_samples'] = getid3_lib::BigEndian2Int(substr($thisfile_riff_RIFFsubtype_COMM_0_data, 2, 4), false);
$thisfile_riff_audio['bits_per_sample'] = getid3_lib::BigEndian2Int(substr($thisfile_riff_RIFFsubtype_COMM_0_data, 6, 2), true);
$thisfile_riff_audio['sample_rate'] = (int) getid3_lib::BigEndian2Float(substr($thisfile_riff_RIFFsubtype_COMM_0_data, 8, 10));
if ($thisfile_riff[$RIFFsubtype]['COMM'][0]['size'] > 18) {
$thisfile_riff_audio['codec_fourcc'] = substr($thisfile_riff_RIFFsubtype_COMM_0_data, 18, 4);
$CodecNameSize = getid3_lib::BigEndian2Int(substr($thisfile_riff_RIFFsubtype_COMM_0_data, 22, 1), false);
$thisfile_riff_audio['codec_name'] = substr($thisfile_riff_RIFFsubtype_COMM_0_data, 23, $CodecNameSize);
switch ($thisfile_riff_audio['codec_name']) {
case 'NONE':
$thisfile_audio['codec'] = 'Pulse Code Modulation (PCM)';
$thisfile_audio['lossless'] = true;
break;
case '':
switch ($thisfile_riff_audio['codec_fourcc']) {
// http://developer.apple.com/qa/snd/snd07.html
case 'sowt':
$thisfile_riff_audio['codec_name'] = 'Two\'s Compliment Little-Endian PCM';
$thisfile_audio['lossless'] = true;
break;
case 'twos':
$thisfile_riff_audio['codec_name'] = 'Two\'s Compliment Big-Endian PCM';
$thisfile_audio['lossless'] = true;
break;
default:
break;
}
break;
default:
$thisfile_audio['codec'] = $thisfile_riff_audio['codec_name'];
$thisfile_audio['lossless'] = false;
break;
}
}
$thisfile_audio['channels'] = $thisfile_riff_audio['channels'];
if ($thisfile_riff_audio['bits_per_sample'] > 0) {
$thisfile_audio['bits_per_sample'] = $thisfile_riff_audio['bits_per_sample'];
}
$thisfile_audio['sample_rate'] = $thisfile_riff_audio['sample_rate'];
if ($thisfile_audio['sample_rate'] == 0) {
$info['error'][] = 'Corrupted AIFF file: sample_rate == zero';
return false;
}
$info['playtime_seconds'] = $thisfile_riff_audio['total_samples'] / $thisfile_audio['sample_rate'];
}
if (isset($thisfile_riff[$RIFFsubtype]['COMT'])) {
$offset = 0;
$CommentCount = getid3_lib::BigEndian2Int(substr($thisfile_riff[$RIFFsubtype]['COMT'][0]['data'], $offset, 2), false);
$offset += 2;
for ($i = 0; $i < $CommentCount; $i++) {
$info['comments_raw'][$i]['timestamp'] = getid3_lib::BigEndian2Int(substr($thisfile_riff[$RIFFsubtype]['COMT'][0]['data'], $offset, 4), false);
$offset += 4;
$info['comments_raw'][$i]['marker_id'] = getid3_lib::BigEndian2Int(substr($thisfile_riff[$RIFFsubtype]['COMT'][0]['data'], $offset, 2), true);
$offset += 2;
$CommentLength = getid3_lib::BigEndian2Int(substr($thisfile_riff[$RIFFsubtype]['COMT'][0]['data'], $offset, 2), false);
$offset += 2;
$info['comments_raw'][$i]['comment'] = substr($thisfile_riff[$RIFFsubtype]['COMT'][0]['data'], $offset, $CommentLength);
$offset += $CommentLength;
$info['comments_raw'][$i]['timestamp_unix'] = getid3_lib::DateMac2Unix($info['comments_raw'][$i]['timestamp']);
$thisfile_riff['comments']['comment'][] = $info['comments_raw'][$i]['comment'];
}
}
$CommentsChunkNames = array('NAME'=>'title', 'author'=>'artist', '(c) '=>'copyright', 'ANNO'=>'comment');
foreach ($CommentsChunkNames as $key => $value) {
if (isset($thisfile_riff[$RIFFsubtype][$key][0]['data'])) {
$thisfile_riff['comments'][$value][] = $thisfile_riff[$RIFFsubtype][$key][0]['data'];
}
}
/*
if (isset($thisfile_riff[$RIFFsubtype]['ID3 '])) {
getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.tag.id3v2.php', __FILE__, true);
$getid3_temp = new getID3();
$getid3_temp->openfile($this->getid3->filename);
$getid3_id3v2 = new getid3_id3v2($getid3_temp);
$getid3_id3v2->StartingOffset = $thisfile_riff[$RIFFsubtype]['ID3 '][0]['offset'] + 8;
if ($thisfile_riff[$RIFFsubtype]['ID3 '][0]['valid'] = $getid3_id3v2->Analyze()) {
$info['id3v2'] = $getid3_temp->info['id3v2'];
}
unset($getid3_temp, $getid3_id3v2);
}
*/
break;
case '8SVX':
$thisfile_audio['bitrate_mode'] = 'cbr';
$thisfile_audio_dataformat = '8svx';
$thisfile_audio['bits_per_sample'] = 8;
$thisfile_audio['channels'] = 1; // overridden below, if need be
$info['mime_type'] = 'audio/x-aiff';
if (isset($thisfile_riff[$RIFFsubtype]['BODY'][0]['offset'])) {
$info['avdataoffset'] = $thisfile_riff[$RIFFsubtype]['BODY'][0]['offset'] + 8;
$info['avdataend'] = $info['avdataoffset'] + $thisfile_riff[$RIFFsubtype]['BODY'][0]['size'];
if ($info['avdataend'] > $info['filesize']) {
$info['warning'][] = 'Probable truncated AIFF file: expecting '.$thisfile_riff[$RIFFsubtype]['BODY'][0]['size'].' bytes of audio data, only '.($info['filesize'] - $info['avdataoffset']).' bytes found';
}
}
if (isset($thisfile_riff[$RIFFsubtype]['VHDR'][0]['offset'])) {
// shortcut
$thisfile_riff_RIFFsubtype_VHDR_0 = &$thisfile_riff[$RIFFsubtype]['VHDR'][0];
$thisfile_riff_RIFFsubtype_VHDR_0['oneShotHiSamples'] = getid3_lib::BigEndian2Int(substr($thisfile_riff_RIFFsubtype_VHDR_0['data'], 0, 4));
$thisfile_riff_RIFFsubtype_VHDR_0['repeatHiSamples'] = getid3_lib::BigEndian2Int(substr($thisfile_riff_RIFFsubtype_VHDR_0['data'], 4, 4));
$thisfile_riff_RIFFsubtype_VHDR_0['samplesPerHiCycle'] = getid3_lib::BigEndian2Int(substr($thisfile_riff_RIFFsubtype_VHDR_0['data'], 8, 4));
$thisfile_riff_RIFFsubtype_VHDR_0['samplesPerSec'] = getid3_lib::BigEndian2Int(substr($thisfile_riff_RIFFsubtype_VHDR_0['data'], 12, 2));
$thisfile_riff_RIFFsubtype_VHDR_0['ctOctave'] = getid3_lib::BigEndian2Int(substr($thisfile_riff_RIFFsubtype_VHDR_0['data'], 14, 1));
$thisfile_riff_RIFFsubtype_VHDR_0['sCompression'] = getid3_lib::BigEndian2Int(substr($thisfile_riff_RIFFsubtype_VHDR_0['data'], 15, 1));
$thisfile_riff_RIFFsubtype_VHDR_0['Volume'] = getid3_lib::FixedPoint16_16(substr($thisfile_riff_RIFFsubtype_VHDR_0['data'], 16, 4));
$thisfile_audio['sample_rate'] = $thisfile_riff_RIFFsubtype_VHDR_0['samplesPerSec'];
switch ($thisfile_riff_RIFFsubtype_VHDR_0['sCompression']) {
case 0:
$thisfile_audio['codec'] = 'Pulse Code Modulation (PCM)';
$thisfile_audio['lossless'] = true;
$ActualBitsPerSample = 8;
break;
case 1:
$thisfile_audio['codec'] = 'Fibonacci-delta encoding';
$thisfile_audio['lossless'] = false;
$ActualBitsPerSample = 4;
break;
default:
$info['warning'][] = 'Unexpected sCompression value in 8SVX.VHDR chunk - expecting 0 or 1, found "'.sCompression.'"';
break;
}
}
if (isset($thisfile_riff[$RIFFsubtype]['CHAN'][0]['data'])) {
$ChannelsIndex = getid3_lib::BigEndian2Int(substr($thisfile_riff[$RIFFsubtype]['CHAN'][0]['data'], 0, 4));
switch ($ChannelsIndex) {
case 6: // Stereo
$thisfile_audio['channels'] = 2;
break;
case 2: // Left channel only
case 4: // Right channel only
$thisfile_audio['channels'] = 1;
break;
default:
$info['warning'][] = 'Unexpected value in 8SVX.CHAN chunk - expecting 2 or 4 or 6, found "'.$ChannelsIndex.'"';
break;
}
}
$CommentsChunkNames = array('NAME'=>'title', 'author'=>'artist', '(c) '=>'copyright', 'ANNO'=>'comment');
foreach ($CommentsChunkNames as $key => $value) {
if (isset($thisfile_riff[$RIFFsubtype][$key][0]['data'])) {
$thisfile_riff['comments'][$value][] = $thisfile_riff[$RIFFsubtype][$key][0]['data'];
}
}
$thisfile_audio['bitrate'] = $thisfile_audio['sample_rate'] * $ActualBitsPerSample * $thisfile_audio['channels'];
if (!empty($thisfile_audio['bitrate'])) {
$info['playtime_seconds'] = ($info['avdataend'] - $info['avdataoffset']) / ($thisfile_audio['bitrate'] / 8);
}
break;
case 'CDXA':
$info['mime_type'] = 'video/mpeg';
if (!empty($thisfile_riff['CDXA']['data'][0]['size'])) {
if (getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.audio-video.mpeg.php', __FILE__, false)) {
$getid3_temp = new getID3();
$getid3_temp->openfile($this->getid3->filename);
$getid3_mpeg = new getid3_mpeg($getid3_temp);
$getid3_mpeg->Analyze();
if (empty($getid3_temp->info['error'])) {
$info['audio'] = $getid3_temp->info['audio'];
$info['video'] = $getid3_temp->info['video'];
$info['mpeg'] = $getid3_temp->info['mpeg'];
$info['warning'] = $getid3_temp->info['warning'];
}
unset($getid3_temp, $getid3_mpeg);
}
}
break;
default:
$info['error'][] = 'Unknown RIFF type: expecting one of (WAVE|RMP3|AVI |CDDA|AIFF|AIFC|8SVX|CDXA), found "'.$RIFFsubtype.'" instead';
unset($info['fileformat']);
break;
}
switch ($RIFFsubtype) {
case 'WAVE':
case 'AIFF':
case 'AIFC':
$ID3v2_key_good = 'id3 ';
$ID3v2_keys_bad = array('ID3 ', 'tag ');
foreach ($ID3v2_keys_bad as $ID3v2_key_bad) {
if (isset($thisfile_riff[$RIFFsubtype][$ID3v2_key_bad]) && !array_key_exists($ID3v2_key_good, $thisfile_riff[$RIFFsubtype])) {
$thisfile_riff[$RIFFsubtype][$ID3v2_key_good] = $thisfile_riff[$RIFFsubtype][$ID3v2_key_bad];
$info['warning'][] = 'mapping "'.$ID3v2_key_bad.'" chunk to "'.$ID3v2_key_good.'"';
}
}
if (isset($thisfile_riff[$RIFFsubtype]['id3 '])) {
getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.tag.id3v2.php', __FILE__, true);
$getid3_temp = new getID3();
$getid3_temp->openfile($this->getid3->filename);
$getid3_id3v2 = new getid3_id3v2($getid3_temp);
$getid3_id3v2->StartingOffset = $thisfile_riff[$RIFFsubtype]['id3 '][0]['offset'] + 8;
if ($thisfile_riff[$RIFFsubtype]['id3 '][0]['valid'] = $getid3_id3v2->Analyze()) {
$info['id3v2'] = $getid3_temp->info['id3v2'];
}
unset($getid3_temp, $getid3_id3v2);
}
break;
}
if (isset($thisfile_riff_WAVE['DISP']) && is_array($thisfile_riff_WAVE['DISP'])) {
$thisfile_riff['comments']['title'][] = trim(substr($thisfile_riff_WAVE['DISP'][count($thisfile_riff_WAVE['DISP']) - 1]['data'], 4));
}
if (isset($thisfile_riff_WAVE['INFO']) && is_array($thisfile_riff_WAVE['INFO'])) {
self::parseComments($thisfile_riff_WAVE['INFO'], $thisfile_riff['comments']);
}
if (isset($thisfile_riff['AVI ']['INFO']) && is_array($thisfile_riff['AVI ']['INFO'])) {
self::parseComments($thisfile_riff['AVI ']['INFO'], $thisfile_riff['comments']);
}
if (empty($thisfile_audio['encoder']) && !empty($info['mpeg']['audio']['LAME']['short_version'])) {
$thisfile_audio['encoder'] = $info['mpeg']['audio']['LAME']['short_version'];
}
if (!isset($info['playtime_seconds'])) {
$info['playtime_seconds'] = 0;
}
if (isset($thisfile_riff_raw['strh'][0]['dwLength']) && isset($thisfile_riff_raw['avih']['dwMicroSecPerFrame'])) {
// needed for >2GB AVIs where 'avih' chunk only lists number of frames in that chunk, not entire movie
$info['playtime_seconds'] = $thisfile_riff_raw['strh'][0]['dwLength'] * ($thisfile_riff_raw['avih']['dwMicroSecPerFrame'] / 1000000);
} elseif (isset($thisfile_riff_raw['avih']['dwTotalFrames']) && isset($thisfile_riff_raw['avih']['dwMicroSecPerFrame'])) {
$info['playtime_seconds'] = $thisfile_riff_raw['avih']['dwTotalFrames'] * ($thisfile_riff_raw['avih']['dwMicroSecPerFrame'] / 1000000);
}
if ($info['playtime_seconds'] > 0) {
if (isset($thisfile_riff_audio) && isset($thisfile_riff_video)) {
if (!isset($info['bitrate'])) {
$info['bitrate'] = ((($info['avdataend'] - $info['avdataoffset']) / $info['playtime_seconds']) * 8);
}
} elseif (isset($thisfile_riff_audio) && !isset($thisfile_riff_video)) {
if (!isset($thisfile_audio['bitrate'])) {
$thisfile_audio['bitrate'] = ((($info['avdataend'] - $info['avdataoffset']) / $info['playtime_seconds']) * 8);
}
} elseif (!isset($thisfile_riff_audio) && isset($thisfile_riff_video)) {
if (!isset($thisfile_video['bitrate'])) {
$thisfile_video['bitrate'] = ((($info['avdataend'] - $info['avdataoffset']) / $info['playtime_seconds']) * 8);
}
}
}
if (isset($thisfile_riff_video) && isset($thisfile_audio['bitrate']) && ($thisfile_audio['bitrate'] > 0) && ($info['playtime_seconds'] > 0)) {
$info['bitrate'] = ((($info['avdataend'] - $info['avdataoffset']) / $info['playtime_seconds']) * 8);
$thisfile_audio['bitrate'] = 0;
$thisfile_video['bitrate'] = $info['bitrate'];
foreach ($thisfile_riff_audio as $channelnumber => $audioinfoarray) {
$thisfile_video['bitrate'] -= $audioinfoarray['bitrate'];
$thisfile_audio['bitrate'] += $audioinfoarray['bitrate'];
}
if ($thisfile_video['bitrate'] <= 0) {
unset($thisfile_video['bitrate']);
}
if ($thisfile_audio['bitrate'] <= 0) {
unset($thisfile_audio['bitrate']);
}
}
if (isset($info['mpeg']['audio'])) {
$thisfile_audio_dataformat = 'mp'.$info['mpeg']['audio']['layer'];
$thisfile_audio['sample_rate'] = $info['mpeg']['audio']['sample_rate'];
$thisfile_audio['channels'] = $info['mpeg']['audio']['channels'];
$thisfile_audio['bitrate'] = $info['mpeg']['audio']['bitrate'];
$thisfile_audio['bitrate_mode'] = strtolower($info['mpeg']['audio']['bitrate_mode']);
if (!empty($info['mpeg']['audio']['codec'])) {
$thisfile_audio['codec'] = $info['mpeg']['audio']['codec'].' '.$thisfile_audio['codec'];
}
if (!empty($thisfile_audio['streams'])) {
foreach ($thisfile_audio['streams'] as $streamnumber => $streamdata) {
if ($streamdata['dataformat'] == $thisfile_audio_dataformat) {
$thisfile_audio['streams'][$streamnumber]['sample_rate'] = $thisfile_audio['sample_rate'];
$thisfile_audio['streams'][$streamnumber]['channels'] = $thisfile_audio['channels'];
$thisfile_audio['streams'][$streamnumber]['bitrate'] = $thisfile_audio['bitrate'];
$thisfile_audio['streams'][$streamnumber]['bitrate_mode'] = $thisfile_audio['bitrate_mode'];
$thisfile_audio['streams'][$streamnumber]['codec'] = $thisfile_audio['codec'];
}
}
}
$getid3_mp3 = new getid3_mp3($this->getid3);
$thisfile_audio['encoder_options'] = $getid3_mp3->GuessEncoderOptions();
unset($getid3_mp3);
}
if (!empty($thisfile_riff_raw['fmt ']['wBitsPerSample']) && ($thisfile_riff_raw['fmt ']['wBitsPerSample'] > 0)) {
switch ($thisfile_audio_dataformat) {
case 'ac3':
// ignore bits_per_sample
break;
default:
$thisfile_audio['bits_per_sample'] = $thisfile_riff_raw['fmt ']['wBitsPerSample'];
break;
}
}
if (empty($thisfile_riff_raw)) {
unset($thisfile_riff['raw']);
}
if (empty($thisfile_riff_audio)) {
unset($thisfile_riff['audio']);
}
if (empty($thisfile_riff_video)) {
unset($thisfile_riff['video']);
}
return true;
}
public function ParseRIFF($startoffset, $maxoffset) {
$info = &$this->getid3->info;
$RIFFchunk = false;
$FoundAllChunksWeNeed = false;
try {
$this->fseek($startoffset);
$maxoffset = min($maxoffset, $info['avdataend']);
while ($this->ftell() < $maxoffset) {
$chunknamesize = $this->fread(8);
//$chunkname = substr($chunknamesize, 0, 4);
$chunkname = str_replace("\x00", '_', substr($chunknamesize, 0, 4)); // note: chunk names of 4 null bytes do appear to be legal (has been observed inside INFO and PRMI chunks, for example), but makes traversing array keys more difficult
$chunksize = $this->EitherEndian2Int(substr($chunknamesize, 4, 4));
//if (strlen(trim($chunkname, "\x00")) < 4) {
if (strlen($chunkname) < 4) {
$this->error('Expecting chunk name at offset '.($this->ftell() - 8).' but found nothing. Aborting RIFF parsing.');
break;
}
if (($chunksize == 0) && ($chunkname != 'JUNK')) {
$this->warning('Chunk ('.$chunkname.') size at offset '.($this->ftell() - 4).' is zero. Aborting RIFF parsing.');
break;
}
if (($chunksize % 2) != 0) {
// all structures are packed on word boundaries
$chunksize++;
}
switch ($chunkname) {
case 'LIST':
$listname = $this->fread(4);
if (preg_match('#^(movi|rec )$#i', $listname)) {
$RIFFchunk[$listname]['offset'] = $this->ftell() - 4;
$RIFFchunk[$listname]['size'] = $chunksize;
if (!$FoundAllChunksWeNeed) {
$WhereWeWere = $this->ftell();
$AudioChunkHeader = $this->fread(12);
$AudioChunkStreamNum = substr($AudioChunkHeader, 0, 2);
$AudioChunkStreamType = substr($AudioChunkHeader, 2, 2);
$AudioChunkSize = getid3_lib::LittleEndian2Int(substr($AudioChunkHeader, 4, 4));
if ($AudioChunkStreamType == 'wb') {
$FirstFourBytes = substr($AudioChunkHeader, 8, 4);
if (preg_match('/^\xFF[\xE2-\xE7\xF2-\xF7\xFA-\xFF][\x00-\xEB]/s', $FirstFourBytes)) {
// MP3
if (getid3_mp3::MPEGaudioHeaderBytesValid($FirstFourBytes)) {
$getid3_temp = new getID3();
$getid3_temp->openfile($this->getid3->filename);
$getid3_temp->info['avdataoffset'] = $this->ftell() - 4;
$getid3_temp->info['avdataend'] = $this->ftell() + $AudioChunkSize;
$getid3_mp3 = new getid3_mp3($getid3_temp);
$getid3_mp3->getOnlyMPEGaudioInfo($getid3_temp->info['avdataoffset'], false);
if (isset($getid3_temp->info['mpeg']['audio'])) {
$info['mpeg']['audio'] = $getid3_temp->info['mpeg']['audio'];
$info['audio'] = $getid3_temp->info['audio'];
$info['audio']['dataformat'] = 'mp'.$info['mpeg']['audio']['layer'];
$info['audio']['sample_rate'] = $info['mpeg']['audio']['sample_rate'];
$info['audio']['channels'] = $info['mpeg']['audio']['channels'];
$info['audio']['bitrate'] = $info['mpeg']['audio']['bitrate'];
$info['audio']['bitrate_mode'] = strtolower($info['mpeg']['audio']['bitrate_mode']);
//$info['bitrate'] = $info['audio']['bitrate'];
}
unset($getid3_temp, $getid3_mp3);
}
} elseif (strpos($FirstFourBytes, getid3_ac3::syncword) === 0) {
// AC3
$getid3_temp = new getID3();
$getid3_temp->openfile($this->getid3->filename);
$getid3_temp->info['avdataoffset'] = $this->ftell() - 4;
$getid3_temp->info['avdataend'] = $this->ftell() + $AudioChunkSize;
$getid3_ac3 = new getid3_ac3($getid3_temp);
$getid3_ac3->Analyze();
if (empty($getid3_temp->info['error'])) {
$info['audio'] = $getid3_temp->info['audio'];
$info['ac3'] = $getid3_temp->info['ac3'];
if (!empty($getid3_temp->info['warning'])) {
foreach ($getid3_temp->info['warning'] as $key => $value) {
$info['warning'][] = $value;
}
}
}
unset($getid3_temp, $getid3_ac3);
}
}
$FoundAllChunksWeNeed = true;
$this->fseek($WhereWeWere);
}
$this->fseek($chunksize - 4, SEEK_CUR);
} else {
if (!isset($RIFFchunk[$listname])) {
$RIFFchunk[$listname] = array();
}
$LISTchunkParent = $listname;
$LISTchunkMaxOffset = $this->ftell() - 4 + $chunksize;
if ($parsedChunk = $this->ParseRIFF($this->ftell(), $LISTchunkMaxOffset)) {
$RIFFchunk[$listname] = array_merge_recursive($RIFFchunk[$listname], $parsedChunk);
}
}
break;
default:
if (preg_match('#^[0-9]{2}(wb|pc|dc|db)$#', $chunkname)) {
$this->fseek($chunksize, SEEK_CUR);
break;
}
$thisindex = 0;
if (isset($RIFFchunk[$chunkname]) && is_array($RIFFchunk[$chunkname])) {
$thisindex = count($RIFFchunk[$chunkname]);
}
$RIFFchunk[$chunkname][$thisindex]['offset'] = $this->ftell() - 8;
$RIFFchunk[$chunkname][$thisindex]['size'] = $chunksize;
switch ($chunkname) {
case 'data':
$info['avdataoffset'] = $this->ftell();
$info['avdataend'] = $info['avdataoffset'] + $chunksize;
$testData = $this->fread(36);
if ($testData === '') {
break;
}
if (preg_match('/^\xFF[\xE2-\xE7\xF2-\xF7\xFA-\xFF][\x00-\xEB]/s', substr($testData, 0, 4))) {
// Probably is MP3 data
if (getid3_mp3::MPEGaudioHeaderBytesValid(substr($testData, 0, 4))) {
$getid3_temp = new getID3();
$getid3_temp->openfile($this->getid3->filename);
$getid3_temp->info['avdataoffset'] = $info['avdataoffset'];
$getid3_temp->info['avdataend'] = $info['avdataend'];
$getid3_mp3 = new getid3_mp3($getid3_temp);
$getid3_mp3->getOnlyMPEGaudioInfo($info['avdataoffset'], false);
if (empty($getid3_temp->info['error'])) {
$info['audio'] = $getid3_temp->info['audio'];
$info['mpeg'] = $getid3_temp->info['mpeg'];
}
unset($getid3_temp, $getid3_mp3);
}
} elseif (($isRegularAC3 = (substr($testData, 0, 2) == getid3_ac3::syncword)) || substr($testData, 8, 2) == strrev(getid3_ac3::syncword)) {
// This is probably AC-3 data
$getid3_temp = new getID3();
if ($isRegularAC3) {
$getid3_temp->openfile($this->getid3->filename);
$getid3_temp->info['avdataoffset'] = $info['avdataoffset'];
$getid3_temp->info['avdataend'] = $info['avdataend'];
}
$getid3_ac3 = new getid3_ac3($getid3_temp);
if ($isRegularAC3) {
$getid3_ac3->Analyze();
} else {
// Dolby Digital WAV
// AC-3 content, but not encoded in same format as normal AC-3 file
// For one thing, byte order is swapped
$ac3_data = '';
for ($i = 0; $i < 28; $i += 2) {
$ac3_data .= substr($testData, 8 + $i + 1, 1);
$ac3_data .= substr($testData, 8 + $i + 0, 1);
}
$getid3_ac3->AnalyzeString($ac3_data);
}
if (empty($getid3_temp->info['error'])) {
$info['audio'] = $getid3_temp->info['audio'];
$info['ac3'] = $getid3_temp->info['ac3'];
if (!empty($getid3_temp->info['warning'])) {
foreach ($getid3_temp->info['warning'] as $newerror) {
$this->warning('getid3_ac3() says: ['.$newerror.']');
}
}
}
unset($getid3_temp, $getid3_ac3);
} elseif (preg_match('/^('.implode('|', array_map('preg_quote', getid3_dts::$syncwords)).')/', $testData)) {
// This is probably DTS data
$getid3_temp = new getID3();
$getid3_temp->openfile($this->getid3->filename);
$getid3_temp->info['avdataoffset'] = $info['avdataoffset'];
$getid3_dts = new getid3_dts($getid3_temp);
$getid3_dts->Analyze();
if (empty($getid3_temp->info['error'])) {
$info['audio'] = $getid3_temp->info['audio'];
$info['dts'] = $getid3_temp->info['dts'];
$info['playtime_seconds'] = $getid3_temp->info['playtime_seconds']; // may not match RIFF calculations since DTS-WAV often used 14/16 bit-word packing
if (!empty($getid3_temp->info['warning'])) {
foreach ($getid3_temp->info['warning'] as $newerror) {
$this->warning('getid3_dts() says: ['.$newerror.']');
}
}
}
unset($getid3_temp, $getid3_dts);
} elseif (substr($testData, 0, 4) == 'wvpk') {
// This is WavPack data
$info['wavpack']['offset'] = $info['avdataoffset'];
$info['wavpack']['size'] = getid3_lib::LittleEndian2Int(substr($testData, 4, 4));
$this->parseWavPackHeader(substr($testData, 8, 28));
} else {
// This is some other kind of data (quite possibly just PCM)
// do nothing special, just skip it
}
$nextoffset = $info['avdataend'];
$this->fseek($nextoffset);
break;
case 'iXML':
case 'bext':
case 'cart':
case 'fmt ':
case 'strh':
case 'strf':
case 'indx':
case 'MEXT':
case 'DISP':
// always read data in
case 'JUNK':
// should be: never read data in
// but some programs write their version strings in a JUNK chunk (e.g. VirtualDub, AVIdemux, etc)
if ($chunksize < 1048576) {
if ($chunksize > 0) {
$RIFFchunk[$chunkname][$thisindex]['data'] = $this->fread($chunksize);
if ($chunkname == 'JUNK') {
if (preg_match('#^([\\x20-\\x7F]+)#', $RIFFchunk[$chunkname][$thisindex]['data'], $matches)) {
// only keep text characters [chr(32)-chr(127)]
$info['riff']['comments']['junk'][] = trim($matches[1]);
}
// but if nothing there, ignore
// remove the key in either case
unset($RIFFchunk[$chunkname][$thisindex]['data']);
}
}
} else {
$this->warning('Chunk "'.$chunkname.'" at offset '.$this->ftell().' is unexpectedly larger than 1MB (claims to be '.number_format($chunksize).' bytes), skipping data');
$this->fseek($chunksize, SEEK_CUR);
}
break;
//case 'IDVX':
// $info['divxtag']['comments'] = self::ParseDIVXTAG($this->fread($chunksize));
// break;
default:
if (!empty($LISTchunkParent) && (($RIFFchunk[$chunkname][$thisindex]['offset'] + $RIFFchunk[$chunkname][$thisindex]['size']) <= $LISTchunkMaxOffset)) {
$RIFFchunk[$LISTchunkParent][$chunkname][$thisindex]['offset'] = $RIFFchunk[$chunkname][$thisindex]['offset'];
$RIFFchunk[$LISTchunkParent][$chunkname][$thisindex]['size'] = $RIFFchunk[$chunkname][$thisindex]['size'];
unset($RIFFchunk[$chunkname][$thisindex]['offset']);
unset($RIFFchunk[$chunkname][$thisindex]['size']);
if (isset($RIFFchunk[$chunkname][$thisindex]) && empty($RIFFchunk[$chunkname][$thisindex])) {
unset($RIFFchunk[$chunkname][$thisindex]);
}
if (isset($RIFFchunk[$chunkname]) && empty($RIFFchunk[$chunkname])) {
unset($RIFFchunk[$chunkname]);
}
$RIFFchunk[$LISTchunkParent][$chunkname][$thisindex]['data'] = $this->fread($chunksize);
} elseif ($chunksize < 2048) {
// only read data in if smaller than 2kB
$RIFFchunk[$chunkname][$thisindex]['data'] = $this->fread($chunksize);
} else {
$this->fseek($chunksize, SEEK_CUR);
}
break;
}
break;
}
}
} catch (getid3_exception $e) {
if ($e->getCode() == 10) {
$this->warning('RIFF parser: '.$e->getMessage());
} else {
throw $e;
}
}
return $RIFFchunk;
}
public function ParseRIFFdata(&$RIFFdata) {
$info = &$this->getid3->info;
if ($RIFFdata) {
$tempfile = tempnam(GETID3_TEMP_DIR, 'getID3');
$fp_temp = fopen($tempfile, 'wb');
$RIFFdataLength = strlen($RIFFdata);
$NewLengthString = getid3_lib::LittleEndian2String($RIFFdataLength, 4);
for ($i = 0; $i < 4; $i++) {
$RIFFdata[($i + 4)] = $NewLengthString[$i];
}
fwrite($fp_temp, $RIFFdata);
fclose($fp_temp);
$getid3_temp = new getID3();
$getid3_temp->openfile($tempfile);
$getid3_temp->info['filesize'] = $RIFFdataLength;
$getid3_temp->info['filenamepath'] = $info['filenamepath'];
$getid3_temp->info['tags'] = $info['tags'];
$getid3_temp->info['warning'] = $info['warning'];
$getid3_temp->info['error'] = $info['error'];
$getid3_temp->info['comments'] = $info['comments'];
$getid3_temp->info['audio'] = (isset($info['audio']) ? $info['audio'] : array());
$getid3_temp->info['video'] = (isset($info['video']) ? $info['video'] : array());
$getid3_riff = new getid3_riff($getid3_temp);
$getid3_riff->Analyze();
$info['riff'] = $getid3_temp->info['riff'];
$info['warning'] = $getid3_temp->info['warning'];
$info['error'] = $getid3_temp->info['error'];
$info['tags'] = $getid3_temp->info['tags'];
$info['comments'] = $getid3_temp->info['comments'];
unset($getid3_riff, $getid3_temp);
unlink($tempfile);
}
return false;
}
public static function parseComments(&$RIFFinfoArray, &$CommentsTargetArray) {
$RIFFinfoKeyLookup = array(
'IARL'=>'archivallocation',
'IART'=>'artist',
'ICDS'=>'costumedesigner',
'ICMS'=>'commissionedby',
'ICMT'=>'comment',
'ICNT'=>'country',
'ICOP'=>'copyright',
'ICRD'=>'creationdate',
'IDIM'=>'dimensions',
'IDIT'=>'digitizationdate',
'IDPI'=>'resolution',
'IDST'=>'distributor',
'IEDT'=>'editor',
'IENG'=>'engineers',
'IFRM'=>'accountofparts',
'IGNR'=>'genre',
'IKEY'=>'keywords',
'ILGT'=>'lightness',
'ILNG'=>'language',
'IMED'=>'orignalmedium',
'IMUS'=>'composer',
'INAM'=>'title',
'IPDS'=>'productiondesigner',
'IPLT'=>'palette',
'IPRD'=>'product',
'IPRO'=>'producer',
'IPRT'=>'part',
'IRTD'=>'rating',
'ISBJ'=>'subject',
'ISFT'=>'software',
'ISGN'=>'secondarygenre',
'ISHP'=>'sharpness',
'ISRC'=>'sourcesupplier',
'ISRF'=>'digitizationsource',
'ISTD'=>'productionstudio',
'ISTR'=>'starring',
'ITCH'=>'encoded_by',
'IWEB'=>'url',
'IWRI'=>'writer',
'____'=>'comment',
);
foreach ($RIFFinfoKeyLookup as $key => $value) {
if (isset($RIFFinfoArray[$key])) {
foreach ($RIFFinfoArray[$key] as $commentid => $commentdata) {
if (trim($commentdata['data']) != '') {
if (isset($CommentsTargetArray[$value])) {
$CommentsTargetArray[$value][] = trim($commentdata['data']);
} else {
$CommentsTargetArray[$value] = array(trim($commentdata['data']));
}
}
}
}
}
return true;
}
public static function parseWAVEFORMATex($WaveFormatExData) {
// shortcut
$WaveFormatEx['raw'] = array();
$WaveFormatEx_raw = &$WaveFormatEx['raw'];
$WaveFormatEx_raw['wFormatTag'] = substr($WaveFormatExData, 0, 2);
$WaveFormatEx_raw['nChannels'] = substr($WaveFormatExData, 2, 2);
$WaveFormatEx_raw['nSamplesPerSec'] = substr($WaveFormatExData, 4, 4);
$WaveFormatEx_raw['nAvgBytesPerSec'] = substr($WaveFormatExData, 8, 4);
$WaveFormatEx_raw['nBlockAlign'] = substr($WaveFormatExData, 12, 2);
$WaveFormatEx_raw['wBitsPerSample'] = substr($WaveFormatExData, 14, 2);
if (strlen($WaveFormatExData) > 16) {
$WaveFormatEx_raw['cbSize'] = substr($WaveFormatExData, 16, 2);
}
$WaveFormatEx_raw = array_map('getid3_lib::LittleEndian2Int', $WaveFormatEx_raw);
$WaveFormatEx['codec'] = self::wFormatTagLookup($WaveFormatEx_raw['wFormatTag']);
$WaveFormatEx['channels'] = $WaveFormatEx_raw['nChannels'];
$WaveFormatEx['sample_rate'] = $WaveFormatEx_raw['nSamplesPerSec'];
$WaveFormatEx['bitrate'] = $WaveFormatEx_raw['nAvgBytesPerSec'] * 8;
$WaveFormatEx['bits_per_sample'] = $WaveFormatEx_raw['wBitsPerSample'];
return $WaveFormatEx;
}
public function parseWavPackHeader($WavPackChunkData) {
// typedef struct {
// char ckID [4];
// long ckSize;
// short version;
// short bits; // added for version 2.00
// short flags, shift; // added for version 3.00
// long total_samples, crc, crc2;
// char extension [4], extra_bc, extras [3];
// } WavpackHeader;
// shortcut
$info = &$this->getid3->info;
$info['wavpack'] = array();
$thisfile_wavpack = &$info['wavpack'];
$thisfile_wavpack['version'] = getid3_lib::LittleEndian2Int(substr($WavPackChunkData, 0, 2));
if ($thisfile_wavpack['version'] >= 2) {
$thisfile_wavpack['bits'] = getid3_lib::LittleEndian2Int(substr($WavPackChunkData, 2, 2));
}
if ($thisfile_wavpack['version'] >= 3) {
$thisfile_wavpack['flags_raw'] = getid3_lib::LittleEndian2Int(substr($WavPackChunkData, 4, 2));
$thisfile_wavpack['shift'] = getid3_lib::LittleEndian2Int(substr($WavPackChunkData, 6, 2));
$thisfile_wavpack['total_samples'] = getid3_lib::LittleEndian2Int(substr($WavPackChunkData, 8, 4));
$thisfile_wavpack['crc1'] = getid3_lib::LittleEndian2Int(substr($WavPackChunkData, 12, 4));
$thisfile_wavpack['crc2'] = getid3_lib::LittleEndian2Int(substr($WavPackChunkData, 16, 4));
$thisfile_wavpack['extension'] = substr($WavPackChunkData, 20, 4);
$thisfile_wavpack['extra_bc'] = getid3_lib::LittleEndian2Int(substr($WavPackChunkData, 24, 1));
for ($i = 0; $i <= 2; $i++) {
$thisfile_wavpack['extras'][] = getid3_lib::LittleEndian2Int(substr($WavPackChunkData, 25 + $i, 1));
}
// shortcut
$thisfile_wavpack['flags'] = array();
$thisfile_wavpack_flags = &$thisfile_wavpack['flags'];
$thisfile_wavpack_flags['mono'] = (bool) ($thisfile_wavpack['flags_raw'] & 0x000001);
$thisfile_wavpack_flags['fast_mode'] = (bool) ($thisfile_wavpack['flags_raw'] & 0x000002);
$thisfile_wavpack_flags['raw_mode'] = (bool) ($thisfile_wavpack['flags_raw'] & 0x000004);
$thisfile_wavpack_flags['calc_noise'] = (bool) ($thisfile_wavpack['flags_raw'] & 0x000008);
$thisfile_wavpack_flags['high_quality'] = (bool) ($thisfile_wavpack['flags_raw'] & 0x000010);
$thisfile_wavpack_flags['3_byte_samples'] = (bool) ($thisfile_wavpack['flags_raw'] & 0x000020);
$thisfile_wavpack_flags['over_20_bits'] = (bool) ($thisfile_wavpack['flags_raw'] & 0x000040);
$thisfile_wavpack_flags['use_wvc'] = (bool) ($thisfile_wavpack['flags_raw'] & 0x000080);
$thisfile_wavpack_flags['noiseshaping'] = (bool) ($thisfile_wavpack['flags_raw'] & 0x000100);
$thisfile_wavpack_flags['very_fast_mode'] = (bool) ($thisfile_wavpack['flags_raw'] & 0x000200);
$thisfile_wavpack_flags['new_high_quality'] = (bool) ($thisfile_wavpack['flags_raw'] & 0x000400);
$thisfile_wavpack_flags['cancel_extreme'] = (bool) ($thisfile_wavpack['flags_raw'] & 0x000800);
$thisfile_wavpack_flags['cross_decorrelation'] = (bool) ($thisfile_wavpack['flags_raw'] & 0x001000);
$thisfile_wavpack_flags['new_decorrelation'] = (bool) ($thisfile_wavpack['flags_raw'] & 0x002000);
$thisfile_wavpack_flags['joint_stereo'] = (bool) ($thisfile_wavpack['flags_raw'] & 0x004000);
$thisfile_wavpack_flags['extra_decorrelation'] = (bool) ($thisfile_wavpack['flags_raw'] & 0x008000);
$thisfile_wavpack_flags['override_noiseshape'] = (bool) ($thisfile_wavpack['flags_raw'] & 0x010000);
$thisfile_wavpack_flags['override_jointstereo'] = (bool) ($thisfile_wavpack['flags_raw'] & 0x020000);
$thisfile_wavpack_flags['copy_source_filetime'] = (bool) ($thisfile_wavpack['flags_raw'] & 0x040000);
$thisfile_wavpack_flags['create_exe'] = (bool) ($thisfile_wavpack['flags_raw'] & 0x080000);
}
return true;
}
public static function ParseBITMAPINFOHEADER($BITMAPINFOHEADER, $littleEndian=true) {
$parsed['biSize'] = substr($BITMAPINFOHEADER, 0, 4); // number of bytes required by the BITMAPINFOHEADER structure
$parsed['biWidth'] = substr($BITMAPINFOHEADER, 4, 4); // width of the bitmap in pixels
$parsed['biHeight'] = substr($BITMAPINFOHEADER, 8, 4); // height of the bitmap in pixels. If biHeight is positive, the bitmap is a 'bottom-up' DIB and its origin is the lower left corner. If biHeight is negative, the bitmap is a 'top-down' DIB and its origin is the upper left corner
$parsed['biPlanes'] = substr($BITMAPINFOHEADER, 12, 2); // number of color planes on the target device. In most cases this value must be set to 1
$parsed['biBitCount'] = substr($BITMAPINFOHEADER, 14, 2); // Specifies the number of bits per pixels
$parsed['biSizeImage'] = substr($BITMAPINFOHEADER, 20, 4); // size of the bitmap data section of the image (the actual pixel data, excluding BITMAPINFOHEADER and RGBQUAD structures)
$parsed['biXPelsPerMeter'] = substr($BITMAPINFOHEADER, 24, 4); // horizontal resolution, in pixels per metre, of the target device
$parsed['biYPelsPerMeter'] = substr($BITMAPINFOHEADER, 28, 4); // vertical resolution, in pixels per metre, of the target device
$parsed['biClrUsed'] = substr($BITMAPINFOHEADER, 32, 4); // actual number of color indices in the color table used by the bitmap. If this value is zero, the bitmap uses the maximum number of colors corresponding to the value of the biBitCount member for the compression mode specified by biCompression
$parsed['biClrImportant'] = substr($BITMAPINFOHEADER, 36, 4); // number of color indices that are considered important for displaying the bitmap. If this value is zero, all colors are important
$parsed = array_map('getid3_lib::'.($littleEndian ? 'Little' : 'Big').'Endian2Int', $parsed);
$parsed['fourcc'] = substr($BITMAPINFOHEADER, 16, 4); // compression identifier
return $parsed;
}
public static function ParseDIVXTAG($DIVXTAG, $raw=false) {
// structure from "IDivX" source, Form1.frm, by "Greg Frazier of Daemonic Software Group", email: gfrazier@icestorm.net, web: http://dsg.cjb.net/
// source available at http://files.divx-digest.com/download/c663efe7ef8ad2e90bf4af4d3ea6188a/on0SWN2r/edit/IDivX.zip
// 'Byte Layout: '1111111111111111
// '32 for Movie - 1 '1111111111111111
// '28 for Author - 6 '6666666666666666
// '4 for year - 2 '6666666666662222
// '3 for genre - 3 '7777777777777777
// '48 for Comments - 7 '7777777777777777
// '1 for Rating - 4 '7777777777777777
// '5 for Future Additions - 0 '333400000DIVXTAG
// '128 bytes total
static $DIVXTAGgenre = array(
0 => 'Action',
1 => 'Action/Adventure',
2 => 'Adventure',
3 => 'Adult',
4 => 'Anime',
5 => 'Cartoon',
6 => 'Claymation',
7 => 'Comedy',
8 => 'Commercial',
9 => 'Documentary',
10 => 'Drama',
11 => 'Home Video',
12 => 'Horror',
13 => 'Infomercial',
14 => 'Interactive',
15 => 'Mystery',
16 => 'Music Video',
17 => 'Other',
18 => 'Religion',
19 => 'Sci Fi',
20 => 'Thriller',
21 => 'Western',
),
$DIVXTAGrating = array(
0 => 'Unrated',
1 => 'G',
2 => 'PG',
3 => 'PG-13',
4 => 'R',
5 => 'NC-17',
);
$parsed['title'] = trim(substr($DIVXTAG, 0, 32));
$parsed['artist'] = trim(substr($DIVXTAG, 32, 28));
$parsed['year'] = intval(trim(substr($DIVXTAG, 60, 4)));
$parsed['comment'] = trim(substr($DIVXTAG, 64, 48));
$parsed['genre_id'] = intval(trim(substr($DIVXTAG, 112, 3)));
$parsed['rating_id'] = ord(substr($DIVXTAG, 115, 1));
//$parsed['padding'] = substr($DIVXTAG, 116, 5); // 5-byte null
//$parsed['magic'] = substr($DIVXTAG, 121, 7); // "DIVXTAG"
$parsed['genre'] = (isset($DIVXTAGgenre[$parsed['genre_id']]) ? $DIVXTAGgenre[$parsed['genre_id']] : $parsed['genre_id']);
$parsed['rating'] = (isset($DIVXTAGrating[$parsed['rating_id']]) ? $DIVXTAGrating[$parsed['rating_id']] : $parsed['rating_id']);
if (!$raw) {
unset($parsed['genre_id'], $parsed['rating_id']);
foreach ($parsed as $key => $value) {
if (!$value === '') {
unset($parsed['key']);
}
}
}
foreach ($parsed as $tag => $value) {
$parsed[$tag] = array($value);
}
return $parsed;
}
public static function waveSNDMtagLookup($tagshortname) {
$begin = __LINE__;
/** This is not a comment!
©kwd keywords
©BPM bpm
©trt tracktitle
©des description
©gen category
©fin featuredinstrument
©LID longid
©bex bwdescription
©pub publisher
©cdt cdtitle
©alb library
©com composer
*/
return getid3_lib::EmbeddedLookup($tagshortname, $begin, __LINE__, __FILE__, 'riff-sndm');
}
public static function wFormatTagLookup($wFormatTag) {
$begin = __LINE__;
/** This is not a comment!
0x0000 Microsoft Unknown Wave Format
0x0001 Pulse Code Modulation (PCM)
0x0002 Microsoft ADPCM
0x0003 IEEE Float
0x0004 Compaq Computer VSELP
0x0005 IBM CVSD
0x0006 Microsoft A-Law
0x0007 Microsoft mu-Law
0x0008 Microsoft DTS
0x0010 OKI ADPCM
0x0011 Intel DVI/IMA ADPCM
0x0012 Videologic MediaSpace ADPCM
0x0013 Sierra Semiconductor ADPCM
0x0014 Antex Electronics G.723 ADPCM
0x0015 DSP Solutions DigiSTD
0x0016 DSP Solutions DigiFIX
0x0017 Dialogic OKI ADPCM
0x0018 MediaVision ADPCM
0x0019 Hewlett-Packard CU
0x0020 Yamaha ADPCM
0x0021 Speech Compression Sonarc
0x0022 DSP Group TrueSpeech
0x0023 Echo Speech EchoSC1
0x0024 Audiofile AF36
0x0025 Audio Processing Technology APTX
0x0026 AudioFile AF10
0x0027 Prosody 1612
0x0028 LRC
0x0030 Dolby AC2
0x0031 Microsoft GSM 6.10
0x0032 MSNAudio
0x0033 Antex Electronics ADPCME
0x0034 Control Resources VQLPC
0x0035 DSP Solutions DigiREAL
0x0036 DSP Solutions DigiADPCM
0x0037 Control Resources CR10
0x0038 Natural MicroSystems VBXADPCM
0x0039 Crystal Semiconductor IMA ADPCM
0x003A EchoSC3
0x003B Rockwell ADPCM
0x003C Rockwell Digit LK
0x003D Xebec
0x0040 Antex Electronics G.721 ADPCM
0x0041 G.728 CELP
0x0042 MSG723
0x0050 MPEG Layer-2 or Layer-1
0x0052 RT24
0x0053 PAC
0x0055 MPEG Layer-3
0x0059 Lucent G.723
0x0060 Cirrus
0x0061 ESPCM
0x0062 Voxware
0x0063 Canopus Atrac
0x0064 G.726 ADPCM
0x0065 G.722 ADPCM
0x0066 DSAT
0x0067 DSAT Display
0x0069 Voxware Byte Aligned
0x0070 Voxware AC8
0x0071 Voxware AC10
0x0072 Voxware AC16
0x0073 Voxware AC20
0x0074 Voxware MetaVoice
0x0075 Voxware MetaSound
0x0076 Voxware RT29HW
0x0077 Voxware VR12
0x0078 Voxware VR18
0x0079 Voxware TQ40
0x0080 Softsound
0x0081 Voxware TQ60
0x0082 MSRT24
0x0083 G.729A
0x0084 MVI MV12
0x0085 DF G.726
0x0086 DF GSM610
0x0088 ISIAudio
0x0089 Onlive
0x0091 SBC24
0x0092 Dolby AC3 SPDIF
0x0093 MediaSonic G.723
0x0094 Aculab PLC Prosody 8kbps
0x0097 ZyXEL ADPCM
0x0098 Philips LPCBB
0x0099 Packed
0x00FF AAC
0x0100 Rhetorex ADPCM
0x0101 IBM mu-law
0x0102 IBM A-law
0x0103 IBM AVC Adaptive Differential Pulse Code Modulation (ADPCM)
0x0111 Vivo G.723
0x0112 Vivo Siren
0x0123 Digital G.723
0x0125 Sanyo LD ADPCM
0x0130 Sipro Lab Telecom ACELP NET
0x0131 Sipro Lab Telecom ACELP 4800
0x0132 Sipro Lab Telecom ACELP 8V3
0x0133 Sipro Lab Telecom G.729
0x0134 Sipro Lab Telecom G.729A
0x0135 Sipro Lab Telecom Kelvin
0x0140 Windows Media Video V8
0x0150 Qualcomm PureVoice
0x0151 Qualcomm HalfRate
0x0155 Ring Zero Systems TUB GSM
0x0160 Microsoft Audio 1
0x0161 Windows Media Audio V7 / V8 / V9
0x0162 Windows Media Audio Professional V9
0x0163 Windows Media Audio Lossless V9
0x0200 Creative Labs ADPCM
0x0202 Creative Labs Fastspeech8
0x0203 Creative Labs Fastspeech10
0x0210 UHER Informatic GmbH ADPCM
0x0220 Quarterdeck
0x0230 I-link Worldwide VC
0x0240 Aureal RAW Sport
0x0250 Interactive Products HSX
0x0251 Interactive Products RPELP
0x0260 Consistent Software CS2
0x0270 Sony SCX
0x0300 Fujitsu FM Towns Snd
0x0400 BTV Digital
0x0401 Intel Music Coder
0x0450 QDesign Music
0x0680 VME VMPCM
0x0681 AT&T Labs TPC
0x08AE ClearJump LiteWave
0x1000 Olivetti GSM
0x1001 Olivetti ADPCM
0x1002 Olivetti CELP
0x1003 Olivetti SBC
0x1004 Olivetti OPR
0x1100 Lernout & Hauspie Codec (0x1100)
0x1101 Lernout & Hauspie CELP Codec (0x1101)
0x1102 Lernout & Hauspie SBC Codec (0x1102)
0x1103 Lernout & Hauspie SBC Codec (0x1103)
0x1104 Lernout & Hauspie SBC Codec (0x1104)
0x1400 Norris
0x1401 AT&T ISIAudio
0x1500 Soundspace Music Compression
0x181C VoxWare RT24 Speech
0x1FC4 NCT Soft ALF2CD (www.nctsoft.com)
0x2000 Dolby AC3
0x2001 Dolby DTS
0x2002 WAVE_FORMAT_14_4
0x2003 WAVE_FORMAT_28_8
0x2004 WAVE_FORMAT_COOK
0x2005 WAVE_FORMAT_DNET
0x674F Ogg Vorbis 1
0x6750 Ogg Vorbis 2
0x6751 Ogg Vorbis 3
0x676F Ogg Vorbis 1+
0x6770 Ogg Vorbis 2+
0x6771 Ogg Vorbis 3+
0x7A21 GSM-AMR (CBR, no SID)
0x7A22 GSM-AMR (VBR, including SID)
0xFFFE WAVE_FORMAT_EXTENSIBLE
0xFFFF WAVE_FORMAT_DEVELOPMENT
*/
return getid3_lib::EmbeddedLookup('0x'.str_pad(strtoupper(dechex($wFormatTag)), 4, '0', STR_PAD_LEFT), $begin, __LINE__, __FILE__, 'riff-wFormatTag');
}
public static function fourccLookup($fourcc) {
$begin = __LINE__;
/** This is not a comment!
swot http://developer.apple.com/qa/snd/snd07.html
____ No Codec (____)
_BIT BI_BITFIELDS (Raw RGB)
_JPG JPEG compressed
_PNG PNG compressed W3C/ISO/IEC (RFC-2083)
_RAW Full Frames (Uncompressed)
_RGB Raw RGB Bitmap
_RL4 RLE 4bpp RGB
_RL8 RLE 8bpp RGB
3IV1 3ivx MPEG-4 v1
3IV2 3ivx MPEG-4 v2
3IVX 3ivx MPEG-4
AASC Autodesk Animator
ABYR Kensington ?ABYR?
AEMI Array Microsystems VideoONE MPEG1-I Capture
AFLC Autodesk Animator FLC
AFLI Autodesk Animator FLI
AMPG Array Microsystems VideoONE MPEG
ANIM Intel RDX (ANIM)
AP41 AngelPotion Definitive
ASV1 Asus Video v1
ASV2 Asus Video v2
ASVX Asus Video 2.0 (audio)
AUR2 AuraVision Aura 2 Codec - YUV 4:2:2
AURA AuraVision Aura 1 Codec - YUV 4:1:1
AVDJ Independent JPEG Group\'s codec (AVDJ)
AVRN Independent JPEG Group\'s codec (AVRN)
AYUV 4:4:4 YUV (AYUV)
AZPR Quicktime Apple Video (AZPR)
BGR Raw RGB32
BLZ0 Blizzard DivX MPEG-4
BTVC Conexant Composite Video
BINK RAD Game Tools Bink Video
BT20 Conexant Prosumer Video
BTCV Conexant Composite Video Codec
BW10 Data Translation Broadway MPEG Capture
CC12 Intel YUV12
CDVC Canopus DV
CFCC Digital Processing Systems DPS Perception
CGDI Microsoft Office 97 Camcorder Video
CHAM Winnov Caviara Champagne
CJPG Creative WebCam JPEG
CLJR Cirrus Logic YUV 4:1:1
CMYK Common Data Format in Printing (Colorgraph)
CPLA Weitek 4:2:0 YUV Planar
CRAM Microsoft Video 1 (CRAM)
cvid Radius Cinepak
CVID Radius Cinepak
CWLT Microsoft Color WLT DIB
CYUV Creative Labs YUV
CYUY ATI YUV
D261 H.261
D263 H.263
DIB Device Independent Bitmap
DIV1 FFmpeg OpenDivX
DIV2 Microsoft MPEG-4 v1/v2
DIV3 DivX ;-) MPEG-4 v3.x Low-Motion
DIV4 DivX ;-) MPEG-4 v3.x Fast-Motion
DIV5 DivX MPEG-4 v5.x
DIV6 DivX ;-) (MS MPEG-4 v3.x)
DIVX DivX MPEG-4 v4 (OpenDivX / Project Mayo)
divx DivX MPEG-4
DMB1 Matrox Rainbow Runner hardware MJPEG
DMB2 Paradigm MJPEG
DSVD ?DSVD?
DUCK Duck TrueMotion 1.0
DPS0 DPS/Leitch Reality Motion JPEG
DPSC DPS/Leitch PAR Motion JPEG
DV25 Matrox DVCPRO codec
DV50 Matrox DVCPRO50 codec
DVC IEC 61834 and SMPTE 314M (DVC/DV Video)
DVCP IEC 61834 and SMPTE 314M (DVC/DV Video)
DVHD IEC Standard DV 1125 lines @ 30fps / 1250 lines @ 25fps
DVMA Darim Vision DVMPEG (dummy for MPEG compressor) (www.darvision.com)
DVSL IEC Standard DV compressed in SD (SDL)
DVAN ?DVAN?
DVE2 InSoft DVE-2 Videoconferencing
dvsd IEC 61834 and SMPTE 314M DVC/DV Video
DVSD IEC 61834 and SMPTE 314M DVC/DV Video
DVX1 Lucent DVX1000SP Video Decoder
DVX2 Lucent DVX2000S Video Decoder
DVX3 Lucent DVX3000S Video Decoder
DX50 DivX v5
DXT1 Microsoft DirectX Compressed Texture (DXT1)
DXT2 Microsoft DirectX Compressed Texture (DXT2)
DXT3 Microsoft DirectX Compressed Texture (DXT3)
DXT4 Microsoft DirectX Compressed Texture (DXT4)
DXT5 Microsoft DirectX Compressed Texture (DXT5)
DXTC Microsoft DirectX Compressed Texture (DXTC)
DXTn Microsoft DirectX Compressed Texture (DXTn)
EM2V Etymonix MPEG-2 I-frame (www.etymonix.com)
EKQ0 Elsa ?EKQ0?
ELK0 Elsa ?ELK0?
ESCP Eidos Escape
ETV1 eTreppid Video ETV1
ETV2 eTreppid Video ETV2
ETVC eTreppid Video ETVC
FLIC Autodesk FLI/FLC Animation
FLV1 Sorenson Spark
FLV4 On2 TrueMotion VP6
FRWT Darim Vision Forward Motion JPEG (www.darvision.com)
FRWU Darim Vision Forward Uncompressed (www.darvision.com)
FLJP D-Vision Field Encoded Motion JPEG
FPS1 FRAPS v1
FRWA SoftLab-Nsk Forward Motion JPEG w/ alpha channel
FRWD SoftLab-Nsk Forward Motion JPEG
FVF1 Iterated Systems Fractal Video Frame
GLZW Motion LZW (gabest@freemail.hu)
GPEG Motion JPEG (gabest@freemail.hu)
GWLT Microsoft Greyscale WLT DIB
H260 Intel ITU H.260 Videoconferencing
H261 Intel ITU H.261 Videoconferencing
H262 Intel ITU H.262 Videoconferencing
H263 Intel ITU H.263 Videoconferencing
H264 Intel ITU H.264 Videoconferencing
H265 Intel ITU H.265 Videoconferencing
H266 Intel ITU H.266 Videoconferencing
H267 Intel ITU H.267 Videoconferencing
H268 Intel ITU H.268 Videoconferencing
H269 Intel ITU H.269 Videoconferencing
HFYU Huffman Lossless Codec
HMCR Rendition Motion Compensation Format (HMCR)
HMRR Rendition Motion Compensation Format (HMRR)
I263 FFmpeg I263 decoder
IF09 Indeo YVU9 ("YVU9 with additional delta-frame info after the U plane")
IUYV Interlaced version of UYVY (www.leadtools.com)
IY41 Interlaced version of Y41P (www.leadtools.com)
IYU1 12 bit format used in mode 2 of the IEEE 1394 Digital Camera 1.04 spec IEEE standard
IYU2 24 bit format used in mode 2 of the IEEE 1394 Digital Camera 1.04 spec IEEE standard
IYUV Planar YUV format (8-bpp Y plane, followed by 8-bpp 2×2 U and V planes)
i263 Intel ITU H.263 Videoconferencing (i263)
I420 Intel Indeo 4
IAN Intel Indeo 4 (RDX)
ICLB InSoft CellB Videoconferencing
IGOR Power DVD
IJPG Intergraph JPEG
ILVC Intel Layered Video
ILVR ITU-T H.263+
IPDV I-O Data Device Giga AVI DV Codec
IR21 Intel Indeo 2.1
IRAW Intel YUV Uncompressed
IV30 Intel Indeo 3.0
IV31 Intel Indeo 3.1
IV32 Ligos Indeo 3.2
IV33 Ligos Indeo 3.3
IV34 Ligos Indeo 3.4
IV35 Ligos Indeo 3.5
IV36 Ligos Indeo 3.6
IV37 Ligos Indeo 3.7
IV38 Ligos Indeo 3.8
IV39 Ligos Indeo 3.9
IV40 Ligos Indeo Interactive 4.0
IV41 Ligos Indeo Interactive 4.1
IV42 Ligos Indeo Interactive 4.2
IV43 Ligos Indeo Interactive 4.3
IV44 Ligos Indeo Interactive 4.4
IV45 Ligos Indeo Interactive 4.5
IV46 Ligos Indeo Interactive 4.6
IV47 Ligos Indeo Interactive 4.7
IV48 Ligos Indeo Interactive 4.8
IV49 Ligos Indeo Interactive 4.9
IV50 Ligos Indeo Interactive 5.0
JBYR Kensington ?JBYR?
JPEG Still Image JPEG DIB
JPGL Pegasus Lossless Motion JPEG
KMVC Team17 Software Karl Morton\'s Video Codec
LSVM Vianet Lighting Strike Vmail (Streaming) (www.vianet.com)
LEAD LEAD Video Codec
Ljpg LEAD MJPEG Codec
MDVD Alex MicroDVD Video (hacked MS MPEG-4) (www.tiasoft.de)
MJPA Morgan Motion JPEG (MJPA) (www.morgan-multimedia.com)
MJPB Morgan Motion JPEG (MJPB) (www.morgan-multimedia.com)
MMES Matrox MPEG-2 I-frame
MP2v Microsoft S-Mpeg 4 version 1 (MP2v)
MP42 Microsoft S-Mpeg 4 version 2 (MP42)
MP43 Microsoft S-Mpeg 4 version 3 (MP43)
MP4S Microsoft S-Mpeg 4 version 3 (MP4S)
MP4V FFmpeg MPEG-4
MPG1 FFmpeg MPEG 1/2
MPG2 FFmpeg MPEG 1/2
MPG3 FFmpeg DivX ;-) (MS MPEG-4 v3)
MPG4 Microsoft MPEG-4
MPGI Sigma Designs MPEG
MPNG PNG images decoder
MSS1 Microsoft Windows Screen Video
MSZH LCL (Lossless Codec Library) (www.geocities.co.jp/Playtown-Denei/2837/LRC.htm)
M261 Microsoft H.261
M263 Microsoft H.263
M4S2 Microsoft Fully Compliant MPEG-4 v2 simple profile (M4S2)
m4s2 Microsoft Fully Compliant MPEG-4 v2 simple profile (m4s2)
MC12 ATI Motion Compensation Format (MC12)
MCAM ATI Motion Compensation Format (MCAM)
MJ2C Morgan Multimedia Motion JPEG2000
mJPG IBM Motion JPEG w/ Huffman Tables
MJPG Microsoft Motion JPEG DIB
MP42 Microsoft MPEG-4 (low-motion)
MP43 Microsoft MPEG-4 (fast-motion)
MP4S Microsoft MPEG-4 (MP4S)
mp4s Microsoft MPEG-4 (mp4s)
MPEG Chromatic Research MPEG-1 Video I-Frame
MPG4 Microsoft MPEG-4 Video High Speed Compressor
MPGI Sigma Designs MPEG
MRCA FAST Multimedia Martin Regen Codec
MRLE Microsoft Run Length Encoding
MSVC Microsoft Video 1
MTX1 Matrox ?MTX1?
MTX2 Matrox ?MTX2?
MTX3 Matrox ?MTX3?
MTX4 Matrox ?MTX4?
MTX5 Matrox ?MTX5?
MTX6 Matrox ?MTX6?
MTX7 Matrox ?MTX7?
MTX8 Matrox ?MTX8?
MTX9 Matrox ?MTX9?
MV12 Motion Pixels Codec (old)
MWV1 Aware Motion Wavelets
nAVI SMR Codec (hack of Microsoft MPEG-4) (IRC #shadowrealm)
NT00 NewTek LightWave HDTV YUV w/ Alpha (www.newtek.com)
NUV1 NuppelVideo
NTN1 Nogatech Video Compression 1
NVS0 nVidia GeForce Texture (NVS0)
NVS1 nVidia GeForce Texture (NVS1)
NVS2 nVidia GeForce Texture (NVS2)
NVS3 nVidia GeForce Texture (NVS3)
NVS4 nVidia GeForce Texture (NVS4)
NVS5 nVidia GeForce Texture (NVS5)
NVT0 nVidia GeForce Texture (NVT0)
NVT1 nVidia GeForce Texture (NVT1)
NVT2 nVidia GeForce Texture (NVT2)
NVT3 nVidia GeForce Texture (NVT3)
NVT4 nVidia GeForce Texture (NVT4)
NVT5 nVidia GeForce Texture (NVT5)
PIXL MiroXL, Pinnacle PCTV
PDVC I-O Data Device Digital Video Capture DV codec
PGVV Radius Video Vision
PHMO IBM Photomotion
PIM1 MPEG Realtime (Pinnacle Cards)
PIM2 Pegasus Imaging ?PIM2?
PIMJ Pegasus Imaging Lossless JPEG
PVEZ Horizons Technology PowerEZ
PVMM PacketVideo Corporation MPEG-4
PVW2 Pegasus Imaging Wavelet Compression
Q1.0 Q-Team\'s QPEG 1.0 (www.q-team.de)
Q1.1 Q-Team\'s QPEG 1.1 (www.q-team.de)
QPEG Q-Team QPEG 1.0
qpeq Q-Team QPEG 1.1
RGB Raw BGR32
RGBA Raw RGB w/ Alpha
RMP4 REALmagic MPEG-4 (unauthorized XVID copy) (www.sigmadesigns.com)
ROQV Id RoQ File Video Decoder
RPZA Quicktime Apple Video (RPZA)
RUD0 Rududu video codec (http://rududu.ifrance.com/rududu/)
RV10 RealVideo 1.0 (aka RealVideo 5.0)
RV13 RealVideo 1.0 (RV13)
RV20 RealVideo G2
RV30 RealVideo 8
RV40 RealVideo 9
RGBT Raw RGB w/ Transparency
RLE Microsoft Run Length Encoder
RLE4 Run Length Encoded (4bpp, 16-color)
RLE8 Run Length Encoded (8bpp, 256-color)
RT21 Intel Indeo RealTime Video 2.1
rv20 RealVideo G2
rv30 RealVideo 8
RVX Intel RDX (RVX )
SMC Apple Graphics (SMC )
SP54 Logitech Sunplus Sp54 Codec for Mustek GSmart Mini 2
SPIG Radius Spigot
SVQ3 Sorenson Video 3 (Apple Quicktime 5)
s422 Tekram VideoCap C210 YUV 4:2:2
SDCC Sun Communication Digital Camera Codec
SFMC CrystalNet Surface Fitting Method
SMSC Radius SMSC
SMSD Radius SMSD
smsv WorldConnect Wavelet Video
SPIG Radius Spigot
SPLC Splash Studios ACM Audio Codec (www.splashstudios.net)
SQZ2 Microsoft VXTreme Video Codec V2
STVA ST Microelectronics CMOS Imager Data (Bayer)
STVB ST Microelectronics CMOS Imager Data (Nudged Bayer)
STVC ST Microelectronics CMOS Imager Data (Bunched)
STVX ST Microelectronics CMOS Imager Data (Extended CODEC Data Format)
STVY ST Microelectronics CMOS Imager Data (Extended CODEC Data Format with Correction Data)
SV10 Sorenson Video R1
SVQ1 Sorenson Video
T420 Toshiba YUV 4:2:0
TM2A Duck TrueMotion Archiver 2.0 (www.duck.com)
TVJP Pinnacle/Truevision Targa 2000 board (TVJP)
TVMJ Pinnacle/Truevision Targa 2000 board (TVMJ)
TY0N Tecomac Low-Bit Rate Codec (www.tecomac.com)
TY2C Trident Decompression Driver
TLMS TeraLogic Motion Intraframe Codec (TLMS)
TLST TeraLogic Motion Intraframe Codec (TLST)
TM20 Duck TrueMotion 2.0
TM2X Duck TrueMotion 2X
TMIC TeraLogic Motion Intraframe Codec (TMIC)
TMOT Horizons Technology TrueMotion S
tmot Horizons TrueMotion Video Compression
TR20 Duck TrueMotion RealTime 2.0
TSCC TechSmith Screen Capture Codec
TV10 Tecomac Low-Bit Rate Codec
TY2N Trident ?TY2N?
U263 UB Video H.263/H.263+/H.263++ Decoder
UMP4 UB Video MPEG 4 (www.ubvideo.com)
UYNV Nvidia UYVY packed 4:2:2
UYVP Evans & Sutherland YCbCr 4:2:2 extended precision
UCOD eMajix.com ClearVideo
ULTI IBM Ultimotion
UYVY UYVY packed 4:2:2
V261 Lucent VX2000S
VIFP VFAPI Reader Codec (www.yks.ne.jp/~hori/)
VIV1 FFmpeg H263+ decoder
VIV2 Vivo H.263
VQC2 Vector-quantised codec 2 (research) http://eprints.ecs.soton.ac.uk/archive/00001310/01/VTC97-js.pdf)
VTLP Alaris VideoGramPiX
VYU9 ATI YUV (VYU9)
VYUY ATI YUV (VYUY)
V261 Lucent VX2000S
V422 Vitec Multimedia 24-bit YUV 4:2:2 Format
V655 Vitec Multimedia 16-bit YUV 4:2:2 Format
VCR1 ATI Video Codec 1
VCR2 ATI Video Codec 2
VCR3 ATI VCR 3.0
VCR4 ATI VCR 4.0
VCR5 ATI VCR 5.0
VCR6 ATI VCR 6.0
VCR7 ATI VCR 7.0
VCR8 ATI VCR 8.0
VCR9 ATI VCR 9.0
VDCT Vitec Multimedia Video Maker Pro DIB
VDOM VDOnet VDOWave
VDOW VDOnet VDOLive (H.263)
VDTZ Darim Vison VideoTizer YUV
VGPX Alaris VideoGramPiX
VIDS Vitec Multimedia YUV 4:2:2 CCIR 601 for V422
VIVO Vivo H.263 v2.00
vivo Vivo H.263
VIXL Miro/Pinnacle Video XL
VLV1 VideoLogic/PURE Digital Videologic Capture
VP30 On2 VP3.0
VP31 On2 VP3.1
VP6F On2 TrueMotion VP6
VX1K Lucent VX1000S Video Codec
VX2K Lucent VX2000S Video Codec
VXSP Lucent VX1000SP Video Codec
WBVC Winbond W9960
WHAM Microsoft Video 1 (WHAM)
WINX Winnov Software Compression
WJPG AverMedia Winbond JPEG
WMV1 Windows Media Video V7
WMV2 Windows Media Video V8
WMV3 Windows Media Video V9
WNV1 Winnov Hardware Compression
XYZP Extended PAL format XYZ palette (www.riff.org)
x263 Xirlink H.263
XLV0 NetXL Video Decoder
XMPG Xing MPEG (I-Frame only)
XVID XviD MPEG-4 (www.xvid.org)
XXAN ?XXAN?
YU92 Intel YUV (YU92)
YUNV Nvidia Uncompressed YUV 4:2:2
YUVP Extended PAL format YUV palette (www.riff.org)
Y211 YUV 2:1:1 Packed
Y411 YUV 4:1:1 Packed
Y41B Weitek YUV 4:1:1 Planar
Y41P Brooktree PC1 YUV 4:1:1 Packed
Y41T Brooktree PC1 YUV 4:1:1 with transparency
Y42B Weitek YUV 4:2:2 Planar
Y42T Brooktree UYUV 4:2:2 with transparency
Y422 ADS Technologies Copy of UYVY used in Pyro WebCam firewire camera
Y800 Simple, single Y plane for monochrome images
Y8 Grayscale video
YC12 Intel YUV 12 codec
YUV8 Winnov Caviar YUV8
YUV9 Intel YUV9
YUY2 Uncompressed YUV 4:2:2
YUYV Canopus YUV
YV12 YVU12 Planar
YVU9 Intel YVU9 Planar (8-bpp Y plane, followed by 8-bpp 4x4 U and V planes)
YVYU YVYU 4:2:2 Packed
ZLIB Lossless Codec Library zlib compression (www.geocities.co.jp/Playtown-Denei/2837/LRC.htm)
ZPEG Metheus Video Zipper
*/
return getid3_lib::EmbeddedLookup($fourcc, $begin, __LINE__, __FILE__, 'riff-fourcc');
}
private function EitherEndian2Int($byteword, $signed=false) {
if ($this->getid3->info['fileformat'] == 'riff') {
return getid3_lib::LittleEndian2Int($byteword, $signed);
}
return getid3_lib::BigEndian2Int($byteword, false, $signed);
}
}
| PHP |
<?php
/////////////////////////////////////////////////////////////////
/// getID3() by James Heinrich <info@getid3.org> //
// available at http://getid3.sourceforge.net //
// or http://www.getid3.org //
/////////////////////////////////////////////////////////////////
// See readme.txt for more details //
/////////////////////////////////////////////////////////////////
// //
// module.audio.dts.php //
// module for analyzing DTS Audio files //
// dependencies: NONE //
// //
/////////////////////////////////////////////////////////////////
/**
* @tutorial http://wiki.multimedia.cx/index.php?title=DTS
*/
class getid3_dts extends getid3_handler
{
/**
* Default DTS syncword used in native .cpt or .dts formats
*/
const syncword = "\x7F\xFE\x80\x01";
private $readBinDataOffset = 0;
/**
* Possible syncwords indicating bitstream encoding
*/
public static $syncwords = array(
0 => "\x7F\xFE\x80\x01", // raw big-endian
1 => "\xFE\x7F\x01\x80", // raw little-endian
2 => "\x1F\xFF\xE8\x00", // 14-bit big-endian
3 => "\xFF\x1F\x00\xE8"); // 14-bit little-endian
public function Analyze() {
$info = &$this->getid3->info;
$info['fileformat'] = 'dts';
$this->fseek($info['avdataoffset']);
$DTSheader = $this->fread(20); // we only need 2 words magic + 6 words frame header, but these words may be normal 16-bit words OR 14-bit words with 2 highest bits set to zero, so 8 words can be either 8*16/8 = 16 bytes OR 8*16*(16/14)/8 = 18.3 bytes
// check syncword
$sync = substr($DTSheader, 0, 4);
if (($encoding = array_search($sync, self::$syncwords)) !== false) {
$info['dts']['raw']['magic'] = $sync;
$this->readBinDataOffset = 32;
} elseif ($this->isDependencyFor('matroska')) {
// Matroska contains DTS without syncword encoded as raw big-endian format
$encoding = 0;
$this->readBinDataOffset = 0;
} else {
unset($info['fileformat']);
return $this->error('Expecting "'.implode('| ', array_map('getid3_lib::PrintHexBytes', self::$syncwords)).'" at offset '.$info['avdataoffset'].', found "'.getid3_lib::PrintHexBytes($sync).'"');
}
// decode header
$fhBS = '';
for ($word_offset = 0; $word_offset <= strlen($DTSheader); $word_offset += 2) {
switch ($encoding) {
case 0: // raw big-endian
$fhBS .= getid3_lib::BigEndian2Bin( substr($DTSheader, $word_offset, 2) );
break;
case 1: // raw little-endian
$fhBS .= getid3_lib::BigEndian2Bin(strrev(substr($DTSheader, $word_offset, 2)));
break;
case 2: // 14-bit big-endian
$fhBS .= substr(getid3_lib::BigEndian2Bin( substr($DTSheader, $word_offset, 2) ), 2, 14);
break;
case 3: // 14-bit little-endian
$fhBS .= substr(getid3_lib::BigEndian2Bin(strrev(substr($DTSheader, $word_offset, 2))), 2, 14);
break;
}
}
$info['dts']['raw']['frame_type'] = $this->readBinData($fhBS, 1);
$info['dts']['raw']['deficit_samples'] = $this->readBinData($fhBS, 5);
$info['dts']['flags']['crc_present'] = (bool) $this->readBinData($fhBS, 1);
$info['dts']['raw']['pcm_sample_blocks'] = $this->readBinData($fhBS, 7);
$info['dts']['raw']['frame_byte_size'] = $this->readBinData($fhBS, 14);
$info['dts']['raw']['channel_arrangement'] = $this->readBinData($fhBS, 6);
$info['dts']['raw']['sample_frequency'] = $this->readBinData($fhBS, 4);
$info['dts']['raw']['bitrate'] = $this->readBinData($fhBS, 5);
$info['dts']['flags']['embedded_downmix'] = (bool) $this->readBinData($fhBS, 1);
$info['dts']['flags']['dynamicrange'] = (bool) $this->readBinData($fhBS, 1);
$info['dts']['flags']['timestamp'] = (bool) $this->readBinData($fhBS, 1);
$info['dts']['flags']['auxdata'] = (bool) $this->readBinData($fhBS, 1);
$info['dts']['flags']['hdcd'] = (bool) $this->readBinData($fhBS, 1);
$info['dts']['raw']['extension_audio'] = $this->readBinData($fhBS, 3);
$info['dts']['flags']['extended_coding'] = (bool) $this->readBinData($fhBS, 1);
$info['dts']['flags']['audio_sync_insertion'] = (bool) $this->readBinData($fhBS, 1);
$info['dts']['raw']['lfe_effects'] = $this->readBinData($fhBS, 2);
$info['dts']['flags']['predictor_history'] = (bool) $this->readBinData($fhBS, 1);
if ($info['dts']['flags']['crc_present']) {
$info['dts']['raw']['crc16'] = $this->readBinData($fhBS, 16);
}
$info['dts']['flags']['mri_perfect_reconst'] = (bool) $this->readBinData($fhBS, 1);
$info['dts']['raw']['encoder_soft_version'] = $this->readBinData($fhBS, 4);
$info['dts']['raw']['copy_history'] = $this->readBinData($fhBS, 2);
$info['dts']['raw']['bits_per_sample'] = $this->readBinData($fhBS, 2);
$info['dts']['flags']['surround_es'] = (bool) $this->readBinData($fhBS, 1);
$info['dts']['flags']['front_sum_diff'] = (bool) $this->readBinData($fhBS, 1);
$info['dts']['flags']['surround_sum_diff'] = (bool) $this->readBinData($fhBS, 1);
$info['dts']['raw']['dialog_normalization'] = $this->readBinData($fhBS, 4);
$info['dts']['bitrate'] = self::bitrateLookup($info['dts']['raw']['bitrate']);
$info['dts']['bits_per_sample'] = self::bitPerSampleLookup($info['dts']['raw']['bits_per_sample']);
$info['dts']['sample_rate'] = self::sampleRateLookup($info['dts']['raw']['sample_frequency']);
$info['dts']['dialog_normalization'] = self::dialogNormalization($info['dts']['raw']['dialog_normalization'], $info['dts']['raw']['encoder_soft_version']);
$info['dts']['flags']['lossless'] = (($info['dts']['raw']['bitrate'] == 31) ? true : false);
$info['dts']['bitrate_mode'] = (($info['dts']['raw']['bitrate'] == 30) ? 'vbr' : 'cbr');
$info['dts']['channels'] = self::numChannelsLookup($info['dts']['raw']['channel_arrangement']);
$info['dts']['channel_arrangement'] = self::channelArrangementLookup($info['dts']['raw']['channel_arrangement']);
$info['audio']['dataformat'] = 'dts';
$info['audio']['lossless'] = $info['dts']['flags']['lossless'];
$info['audio']['bitrate_mode'] = $info['dts']['bitrate_mode'];
$info['audio']['bits_per_sample'] = $info['dts']['bits_per_sample'];
$info['audio']['sample_rate'] = $info['dts']['sample_rate'];
$info['audio']['channels'] = $info['dts']['channels'];
$info['audio']['bitrate'] = $info['dts']['bitrate'];
if (isset($info['avdataend']) && !empty($info['dts']['bitrate']) && is_numeric($info['dts']['bitrate'])) {
$info['playtime_seconds'] = ($info['avdataend'] - $info['avdataoffset']) / ($info['dts']['bitrate'] / 8);
if (($encoding == 2) || ($encoding == 3)) {
// 14-bit data packed into 16-bit words, so the playtime is wrong because only (14/16) of the bytes in the data portion of the file are used at the specified bitrate
$info['playtime_seconds'] *= (14 / 16);
}
}
return true;
}
private function readBinData($bin, $length) {
$data = substr($bin, $this->readBinDataOffset, $length);
$this->readBinDataOffset += $length;
return bindec($data);
}
public static function bitrateLookup($index) {
static $lookup = array(
0 => 32000,
1 => 56000,
2 => 64000,
3 => 96000,
4 => 112000,
5 => 128000,
6 => 192000,
7 => 224000,
8 => 256000,
9 => 320000,
10 => 384000,
11 => 448000,
12 => 512000,
13 => 576000,
14 => 640000,
15 => 768000,
16 => 960000,
17 => 1024000,
18 => 1152000,
19 => 1280000,
20 => 1344000,
21 => 1408000,
22 => 1411200,
23 => 1472000,
24 => 1536000,
25 => 1920000,
26 => 2048000,
27 => 3072000,
28 => 3840000,
29 => 'open',
30 => 'variable',
31 => 'lossless',
);
return (isset($lookup[$index]) ? $lookup[$index] : false);
}
public static function sampleRateLookup($index) {
static $lookup = array(
0 => 'invalid',
1 => 8000,
2 => 16000,
3 => 32000,
4 => 'invalid',
5 => 'invalid',
6 => 11025,
7 => 22050,
8 => 44100,
9 => 'invalid',
10 => 'invalid',
11 => 12000,
12 => 24000,
13 => 48000,
14 => 'invalid',
15 => 'invalid',
);
return (isset($lookup[$index]) ? $lookup[$index] : false);
}
public static function bitPerSampleLookup($index) {
static $lookup = array(
0 => 16,
1 => 20,
2 => 24,
3 => 24,
);
return (isset($lookup[$index]) ? $lookup[$index] : false);
}
public static function numChannelsLookup($index) {
switch ($index) {
case 0:
return 1;
break;
case 1:
case 2:
case 3:
case 4:
return 2;
break;
case 5:
case 6:
return 3;
break;
case 7:
case 8:
return 4;
break;
case 9:
return 5;
break;
case 10:
case 11:
case 12:
return 6;
break;
case 13:
return 7;
break;
case 14:
case 15:
return 8;
break;
}
return false;
}
public static function channelArrangementLookup($index) {
static $lookup = array(
0 => 'A',
1 => 'A + B (dual mono)',
2 => 'L + R (stereo)',
3 => '(L+R) + (L-R) (sum-difference)',
4 => 'LT + RT (left and right total)',
5 => 'C + L + R',
6 => 'L + R + S',
7 => 'C + L + R + S',
8 => 'L + R + SL + SR',
9 => 'C + L + R + SL + SR',
10 => 'CL + CR + L + R + SL + SR',
11 => 'C + L + R+ LR + RR + OV',
12 => 'CF + CR + LF + RF + LR + RR',
13 => 'CL + C + CR + L + R + SL + SR',
14 => 'CL + CR + L + R + SL1 + SL2 + SR1 + SR2',
15 => 'CL + C+ CR + L + R + SL + S + SR',
);
return (isset($lookup[$index]) ? $lookup[$index] : 'user-defined');
}
public static function dialogNormalization($index, $version) {
switch ($version) {
case 7:
return 0 - $index;
break;
case 6:
return 0 - 16 - $index;
break;
}
return false;
}
}
| PHP |
<?php
/////////////////////////////////////////////////////////////////
/// getID3() by James Heinrich <info@getid3.org> //
// available at http://getid3.sourceforge.net //
// or http://www.getid3.org //
/////////////////////////////////////////////////////////////////
// See readme.txt for more details //
/////////////////////////////////////////////////////////////////
// //
// module.audio.mp3.php //
// module for analyzing MP3 files //
// dependencies: NONE //
// ///
/////////////////////////////////////////////////////////////////
// number of frames to scan to determine if MPEG-audio sequence is valid
// Lower this number to 5-20 for faster scanning
// Increase this number to 50+ for most accurate detection of valid VBR/CBR
// mpeg-audio streams
define('GETID3_MP3_VALID_CHECK_FRAMES', 35);
class getid3_mp3 extends getid3_handler
{
public $allow_bruteforce = false; // forces getID3() to scan the file byte-by-byte and log all the valid audio frame headers - extremely slow, unrecommended, but may provide data from otherwise-unusuable files
public function Analyze() {
$info = &$this->getid3->info;
$initialOffset = $info['avdataoffset'];
if (!$this->getOnlyMPEGaudioInfo($info['avdataoffset'])) {
if ($this->allow_bruteforce) {
$info['error'][] = 'Rescanning file in BruteForce mode';
$this->getOnlyMPEGaudioInfoBruteForce($this->getid3->fp, $info);
}
}
if (isset($info['mpeg']['audio']['bitrate_mode'])) {
$info['audio']['bitrate_mode'] = strtolower($info['mpeg']['audio']['bitrate_mode']);
}
if (((isset($info['id3v2']['headerlength']) && ($info['avdataoffset'] > $info['id3v2']['headerlength'])) || (!isset($info['id3v2']) && ($info['avdataoffset'] > 0) && ($info['avdataoffset'] != $initialOffset)))) {
$synchoffsetwarning = 'Unknown data before synch ';
if (isset($info['id3v2']['headerlength'])) {
$synchoffsetwarning .= '(ID3v2 header ends at '.$info['id3v2']['headerlength'].', then '.($info['avdataoffset'] - $info['id3v2']['headerlength']).' bytes garbage, ';
} elseif ($initialOffset > 0) {
$synchoffsetwarning .= '(should be at '.$initialOffset.', ';
} else {
$synchoffsetwarning .= '(should be at beginning of file, ';
}
$synchoffsetwarning .= 'synch detected at '.$info['avdataoffset'].')';
if (isset($info['audio']['bitrate_mode']) && ($info['audio']['bitrate_mode'] == 'cbr')) {
if (!empty($info['id3v2']['headerlength']) && (($info['avdataoffset'] - $info['id3v2']['headerlength']) == $info['mpeg']['audio']['framelength'])) {
$synchoffsetwarning .= '. This is a known problem with some versions of LAME (3.90-3.92) DLL in CBR mode.';
$info['audio']['codec'] = 'LAME';
$CurrentDataLAMEversionString = 'LAME3.';
} elseif (empty($info['id3v2']['headerlength']) && ($info['avdataoffset'] == $info['mpeg']['audio']['framelength'])) {
$synchoffsetwarning .= '. This is a known problem with some versions of LAME (3.90 - 3.92) DLL in CBR mode.';
$info['audio']['codec'] = 'LAME';
$CurrentDataLAMEversionString = 'LAME3.';
}
}
$info['warning'][] = $synchoffsetwarning;
}
if (isset($info['mpeg']['audio']['LAME'])) {
$info['audio']['codec'] = 'LAME';
if (!empty($info['mpeg']['audio']['LAME']['long_version'])) {
$info['audio']['encoder'] = rtrim($info['mpeg']['audio']['LAME']['long_version'], "\x00");
} elseif (!empty($info['mpeg']['audio']['LAME']['short_version'])) {
$info['audio']['encoder'] = rtrim($info['mpeg']['audio']['LAME']['short_version'], "\x00");
}
}
$CurrentDataLAMEversionString = (!empty($CurrentDataLAMEversionString) ? $CurrentDataLAMEversionString : (isset($info['audio']['encoder']) ? $info['audio']['encoder'] : ''));
if (!empty($CurrentDataLAMEversionString) && (substr($CurrentDataLAMEversionString, 0, 6) == 'LAME3.') && !preg_match('[0-9\)]', substr($CurrentDataLAMEversionString, -1))) {
// a version number of LAME that does not end with a number like "LAME3.92"
// or with a closing parenthesis like "LAME3.88 (alpha)"
// or a version of LAME with the LAMEtag-not-filled-in-DLL-mode bug (3.90-3.92)
// not sure what the actual last frame length will be, but will be less than or equal to 1441
$PossiblyLongerLAMEversion_FrameLength = 1441;
// Not sure what version of LAME this is - look in padding of last frame for longer version string
$PossibleLAMEversionStringOffset = $info['avdataend'] - $PossiblyLongerLAMEversion_FrameLength;
fseek($this->getid3->fp, $PossibleLAMEversionStringOffset);
$PossiblyLongerLAMEversion_Data = fread($this->getid3->fp, $PossiblyLongerLAMEversion_FrameLength);
switch (substr($CurrentDataLAMEversionString, -1)) {
case 'a':
case 'b':
// "LAME3.94a" will have a longer version string of "LAME3.94 (alpha)" for example
// need to trim off "a" to match longer string
$CurrentDataLAMEversionString = substr($CurrentDataLAMEversionString, 0, -1);
break;
}
if (($PossiblyLongerLAMEversion_String = strstr($PossiblyLongerLAMEversion_Data, $CurrentDataLAMEversionString)) !== false) {
if (substr($PossiblyLongerLAMEversion_String, 0, strlen($CurrentDataLAMEversionString)) == $CurrentDataLAMEversionString) {
$PossiblyLongerLAMEversion_NewString = substr($PossiblyLongerLAMEversion_String, 0, strspn($PossiblyLongerLAMEversion_String, 'LAME0123456789., (abcdefghijklmnopqrstuvwxyzJFSOND)')); //"LAME3.90.3" "LAME3.87 (beta 1, Sep 27 2000)" "LAME3.88 (beta)"
if (empty($info['audio']['encoder']) || (strlen($PossiblyLongerLAMEversion_NewString) > strlen($info['audio']['encoder']))) {
$info['audio']['encoder'] = $PossiblyLongerLAMEversion_NewString;
}
}
}
}
if (!empty($info['audio']['encoder'])) {
$info['audio']['encoder'] = rtrim($info['audio']['encoder'], "\x00 ");
}
switch (isset($info['mpeg']['audio']['layer']) ? $info['mpeg']['audio']['layer'] : '') {
case 1:
case 2:
$info['audio']['dataformat'] = 'mp'.$info['mpeg']['audio']['layer'];
break;
}
if (isset($info['fileformat']) && ($info['fileformat'] == 'mp3')) {
switch ($info['audio']['dataformat']) {
case 'mp1':
case 'mp2':
case 'mp3':
$info['fileformat'] = $info['audio']['dataformat'];
break;
default:
$info['warning'][] = 'Expecting [audio][dataformat] to be mp1/mp2/mp3 when fileformat == mp3, [audio][dataformat] actually "'.$info['audio']['dataformat'].'"';
break;
}
}
if (empty($info['fileformat'])) {
unset($info['fileformat']);
unset($info['audio']['bitrate_mode']);
unset($info['avdataoffset']);
unset($info['avdataend']);
return false;
}
$info['mime_type'] = 'audio/mpeg';
$info['audio']['lossless'] = false;
// Calculate playtime
if (!isset($info['playtime_seconds']) && isset($info['audio']['bitrate']) && ($info['audio']['bitrate'] > 0)) {
$info['playtime_seconds'] = ($info['avdataend'] - $info['avdataoffset']) * 8 / $info['audio']['bitrate'];
}
$info['audio']['encoder_options'] = $this->GuessEncoderOptions();
return true;
}
public function GuessEncoderOptions() {
// shortcuts
$info = &$this->getid3->info;
if (!empty($info['mpeg']['audio'])) {
$thisfile_mpeg_audio = &$info['mpeg']['audio'];
if (!empty($thisfile_mpeg_audio['LAME'])) {
$thisfile_mpeg_audio_lame = &$thisfile_mpeg_audio['LAME'];
}
}
$encoder_options = '';
static $NamedPresetBitrates = array(16, 24, 40, 56, 112, 128, 160, 192, 256);
if (isset($thisfile_mpeg_audio['VBR_method']) && ($thisfile_mpeg_audio['VBR_method'] == 'Fraunhofer') && !empty($thisfile_mpeg_audio['VBR_quality'])) {
$encoder_options = 'VBR q'.$thisfile_mpeg_audio['VBR_quality'];
} elseif (!empty($thisfile_mpeg_audio_lame['preset_used']) && (!in_array($thisfile_mpeg_audio_lame['preset_used_id'], $NamedPresetBitrates))) {
$encoder_options = $thisfile_mpeg_audio_lame['preset_used'];
} elseif (!empty($thisfile_mpeg_audio_lame['vbr_quality'])) {
static $KnownEncoderValues = array();
if (empty($KnownEncoderValues)) {
//$KnownEncoderValues[abrbitrate_minbitrate][vbr_quality][raw_vbr_method][raw_noise_shaping][raw_stereo_mode][ath_type][lowpass_frequency] = 'preset name';
$KnownEncoderValues[0xFF][58][1][1][3][2][20500] = '--alt-preset insane'; // 3.90, 3.90.1, 3.92
$KnownEncoderValues[0xFF][58][1][1][3][2][20600] = '--alt-preset insane'; // 3.90.2, 3.90.3, 3.91
$KnownEncoderValues[0xFF][57][1][1][3][4][20500] = '--alt-preset insane'; // 3.94, 3.95
$KnownEncoderValues['**'][78][3][2][3][2][19500] = '--alt-preset extreme'; // 3.90, 3.90.1, 3.92
$KnownEncoderValues['**'][78][3][2][3][2][19600] = '--alt-preset extreme'; // 3.90.2, 3.91
$KnownEncoderValues['**'][78][3][1][3][2][19600] = '--alt-preset extreme'; // 3.90.3
$KnownEncoderValues['**'][78][4][2][3][2][19500] = '--alt-preset fast extreme'; // 3.90, 3.90.1, 3.92
$KnownEncoderValues['**'][78][4][2][3][2][19600] = '--alt-preset fast extreme'; // 3.90.2, 3.90.3, 3.91
$KnownEncoderValues['**'][78][3][2][3][4][19000] = '--alt-preset standard'; // 3.90, 3.90.1, 3.90.2, 3.91, 3.92
$KnownEncoderValues['**'][78][3][1][3][4][19000] = '--alt-preset standard'; // 3.90.3
$KnownEncoderValues['**'][78][4][2][3][4][19000] = '--alt-preset fast standard'; // 3.90, 3.90.1, 3.90.2, 3.91, 3.92
$KnownEncoderValues['**'][78][4][1][3][4][19000] = '--alt-preset fast standard'; // 3.90.3
$KnownEncoderValues['**'][88][4][1][3][3][19500] = '--r3mix'; // 3.90, 3.90.1, 3.92
$KnownEncoderValues['**'][88][4][1][3][3][19600] = '--r3mix'; // 3.90.2, 3.90.3, 3.91
$KnownEncoderValues['**'][67][4][1][3][4][18000] = '--r3mix'; // 3.94, 3.95
$KnownEncoderValues['**'][68][3][2][3][4][18000] = '--alt-preset medium'; // 3.90.3
$KnownEncoderValues['**'][68][4][2][3][4][18000] = '--alt-preset fast medium'; // 3.90.3
$KnownEncoderValues[0xFF][99][1][1][1][2][0] = '--preset studio'; // 3.90, 3.90.1, 3.90.2, 3.91, 3.92
$KnownEncoderValues[0xFF][58][2][1][3][2][20600] = '--preset studio'; // 3.90.3, 3.93.1
$KnownEncoderValues[0xFF][58][2][1][3][2][20500] = '--preset studio'; // 3.93
$KnownEncoderValues[0xFF][57][2][1][3][4][20500] = '--preset studio'; // 3.94, 3.95
$KnownEncoderValues[0xC0][88][1][1][1][2][0] = '--preset cd'; // 3.90, 3.90.1, 3.90.2, 3.91, 3.92
$KnownEncoderValues[0xC0][58][2][2][3][2][19600] = '--preset cd'; // 3.90.3, 3.93.1
$KnownEncoderValues[0xC0][58][2][2][3][2][19500] = '--preset cd'; // 3.93
$KnownEncoderValues[0xC0][57][2][1][3][4][19500] = '--preset cd'; // 3.94, 3.95
$KnownEncoderValues[0xA0][78][1][1][3][2][18000] = '--preset hifi'; // 3.90, 3.90.1, 3.90.2, 3.91, 3.92
$KnownEncoderValues[0xA0][58][2][2][3][2][18000] = '--preset hifi'; // 3.90.3, 3.93, 3.93.1
$KnownEncoderValues[0xA0][57][2][1][3][4][18000] = '--preset hifi'; // 3.94, 3.95
$KnownEncoderValues[0x80][67][1][1][3][2][18000] = '--preset tape'; // 3.90, 3.90.1, 3.90.2, 3.91, 3.92
$KnownEncoderValues[0x80][67][1][1][3][2][15000] = '--preset radio'; // 3.90, 3.90.1, 3.90.2, 3.91, 3.92
$KnownEncoderValues[0x70][67][1][1][3][2][15000] = '--preset fm'; // 3.90, 3.90.1, 3.90.2, 3.91, 3.92
$KnownEncoderValues[0x70][58][2][2][3][2][16000] = '--preset tape/radio/fm'; // 3.90.3, 3.93, 3.93.1
$KnownEncoderValues[0x70][57][2][1][3][4][16000] = '--preset tape/radio/fm'; // 3.94, 3.95
$KnownEncoderValues[0x38][58][2][2][0][2][10000] = '--preset voice'; // 3.90.3, 3.93, 3.93.1
$KnownEncoderValues[0x38][57][2][1][0][4][15000] = '--preset voice'; // 3.94, 3.95
$KnownEncoderValues[0x38][57][2][1][0][4][16000] = '--preset voice'; // 3.94a14
$KnownEncoderValues[0x28][65][1][1][0][2][7500] = '--preset mw-us'; // 3.90, 3.90.1, 3.92
$KnownEncoderValues[0x28][65][1][1][0][2][7600] = '--preset mw-us'; // 3.90.2, 3.91
$KnownEncoderValues[0x28][58][2][2][0][2][7000] = '--preset mw-us'; // 3.90.3, 3.93, 3.93.1
$KnownEncoderValues[0x28][57][2][1][0][4][10500] = '--preset mw-us'; // 3.94, 3.95
$KnownEncoderValues[0x28][57][2][1][0][4][11200] = '--preset mw-us'; // 3.94a14
$KnownEncoderValues[0x28][57][2][1][0][4][8800] = '--preset mw-us'; // 3.94a15
$KnownEncoderValues[0x18][58][2][2][0][2][4000] = '--preset phon+/lw/mw-eu/sw'; // 3.90.3, 3.93.1
$KnownEncoderValues[0x18][58][2][2][0][2][3900] = '--preset phon+/lw/mw-eu/sw'; // 3.93
$KnownEncoderValues[0x18][57][2][1][0][4][5900] = '--preset phon+/lw/mw-eu/sw'; // 3.94, 3.95
$KnownEncoderValues[0x18][57][2][1][0][4][6200] = '--preset phon+/lw/mw-eu/sw'; // 3.94a14
$KnownEncoderValues[0x18][57][2][1][0][4][3200] = '--preset phon+/lw/mw-eu/sw'; // 3.94a15
$KnownEncoderValues[0x10][58][2][2][0][2][3800] = '--preset phone'; // 3.90.3, 3.93.1
$KnownEncoderValues[0x10][58][2][2][0][2][3700] = '--preset phone'; // 3.93
$KnownEncoderValues[0x10][57][2][1][0][4][5600] = '--preset phone'; // 3.94, 3.95
}
if (isset($KnownEncoderValues[$thisfile_mpeg_audio_lame['raw']['abrbitrate_minbitrate']][$thisfile_mpeg_audio_lame['vbr_quality']][$thisfile_mpeg_audio_lame['raw']['vbr_method']][$thisfile_mpeg_audio_lame['raw']['noise_shaping']][$thisfile_mpeg_audio_lame['raw']['stereo_mode']][$thisfile_mpeg_audio_lame['ath_type']][$thisfile_mpeg_audio_lame['lowpass_frequency']])) {
$encoder_options = $KnownEncoderValues[$thisfile_mpeg_audio_lame['raw']['abrbitrate_minbitrate']][$thisfile_mpeg_audio_lame['vbr_quality']][$thisfile_mpeg_audio_lame['raw']['vbr_method']][$thisfile_mpeg_audio_lame['raw']['noise_shaping']][$thisfile_mpeg_audio_lame['raw']['stereo_mode']][$thisfile_mpeg_audio_lame['ath_type']][$thisfile_mpeg_audio_lame['lowpass_frequency']];
} elseif (isset($KnownEncoderValues['**'][$thisfile_mpeg_audio_lame['vbr_quality']][$thisfile_mpeg_audio_lame['raw']['vbr_method']][$thisfile_mpeg_audio_lame['raw']['noise_shaping']][$thisfile_mpeg_audio_lame['raw']['stereo_mode']][$thisfile_mpeg_audio_lame['ath_type']][$thisfile_mpeg_audio_lame['lowpass_frequency']])) {
$encoder_options = $KnownEncoderValues['**'][$thisfile_mpeg_audio_lame['vbr_quality']][$thisfile_mpeg_audio_lame['raw']['vbr_method']][$thisfile_mpeg_audio_lame['raw']['noise_shaping']][$thisfile_mpeg_audio_lame['raw']['stereo_mode']][$thisfile_mpeg_audio_lame['ath_type']][$thisfile_mpeg_audio_lame['lowpass_frequency']];
} elseif ($info['audio']['bitrate_mode'] == 'vbr') {
// http://gabriel.mp3-tech.org/mp3infotag.html
// int Quality = (100 - 10 * gfp->VBR_q - gfp->quality)h
$LAME_V_value = 10 - ceil($thisfile_mpeg_audio_lame['vbr_quality'] / 10);
$LAME_q_value = 100 - $thisfile_mpeg_audio_lame['vbr_quality'] - ($LAME_V_value * 10);
$encoder_options = '-V'.$LAME_V_value.' -q'.$LAME_q_value;
} elseif ($info['audio']['bitrate_mode'] == 'cbr') {
$encoder_options = strtoupper($info['audio']['bitrate_mode']).ceil($info['audio']['bitrate'] / 1000);
} else {
$encoder_options = strtoupper($info['audio']['bitrate_mode']);
}
} elseif (!empty($thisfile_mpeg_audio_lame['bitrate_abr'])) {
$encoder_options = 'ABR'.$thisfile_mpeg_audio_lame['bitrate_abr'];
} elseif (!empty($info['audio']['bitrate'])) {
if ($info['audio']['bitrate_mode'] == 'cbr') {
$encoder_options = strtoupper($info['audio']['bitrate_mode']).ceil($info['audio']['bitrate'] / 1000);
} else {
$encoder_options = strtoupper($info['audio']['bitrate_mode']);
}
}
if (!empty($thisfile_mpeg_audio_lame['bitrate_min'])) {
$encoder_options .= ' -b'.$thisfile_mpeg_audio_lame['bitrate_min'];
}
if (!empty($thisfile_mpeg_audio_lame['encoding_flags']['nogap_prev']) || !empty($thisfile_mpeg_audio_lame['encoding_flags']['nogap_next'])) {
$encoder_options .= ' --nogap';
}
if (!empty($thisfile_mpeg_audio_lame['lowpass_frequency'])) {
$ExplodedOptions = explode(' ', $encoder_options, 4);
if ($ExplodedOptions[0] == '--r3mix') {
$ExplodedOptions[1] = 'r3mix';
}
switch ($ExplodedOptions[0]) {
case '--preset':
case '--alt-preset':
case '--r3mix':
if ($ExplodedOptions[1] == 'fast') {
$ExplodedOptions[1] .= ' '.$ExplodedOptions[2];
}
switch ($ExplodedOptions[1]) {
case 'portable':
case 'medium':
case 'standard':
case 'extreme':
case 'insane':
case 'fast portable':
case 'fast medium':
case 'fast standard':
case 'fast extreme':
case 'fast insane':
case 'r3mix':
static $ExpectedLowpass = array(
'insane|20500' => 20500,
'insane|20600' => 20600, // 3.90.2, 3.90.3, 3.91
'medium|18000' => 18000,
'fast medium|18000' => 18000,
'extreme|19500' => 19500, // 3.90, 3.90.1, 3.92, 3.95
'extreme|19600' => 19600, // 3.90.2, 3.90.3, 3.91, 3.93.1
'fast extreme|19500' => 19500, // 3.90, 3.90.1, 3.92, 3.95
'fast extreme|19600' => 19600, // 3.90.2, 3.90.3, 3.91, 3.93.1
'standard|19000' => 19000,
'fast standard|19000' => 19000,
'r3mix|19500' => 19500, // 3.90, 3.90.1, 3.92
'r3mix|19600' => 19600, // 3.90.2, 3.90.3, 3.91
'r3mix|18000' => 18000, // 3.94, 3.95
);
if (!isset($ExpectedLowpass[$ExplodedOptions[1].'|'.$thisfile_mpeg_audio_lame['lowpass_frequency']]) && ($thisfile_mpeg_audio_lame['lowpass_frequency'] < 22050) && (round($thisfile_mpeg_audio_lame['lowpass_frequency'] / 1000) < round($thisfile_mpeg_audio['sample_rate'] / 2000))) {
$encoder_options .= ' --lowpass '.$thisfile_mpeg_audio_lame['lowpass_frequency'];
}
break;
default:
break;
}
break;
}
}
if (isset($thisfile_mpeg_audio_lame['raw']['source_sample_freq'])) {
if (($thisfile_mpeg_audio['sample_rate'] == 44100) && ($thisfile_mpeg_audio_lame['raw']['source_sample_freq'] != 1)) {
$encoder_options .= ' --resample 44100';
} elseif (($thisfile_mpeg_audio['sample_rate'] == 48000) && ($thisfile_mpeg_audio_lame['raw']['source_sample_freq'] != 2)) {
$encoder_options .= ' --resample 48000';
} elseif ($thisfile_mpeg_audio['sample_rate'] < 44100) {
switch ($thisfile_mpeg_audio_lame['raw']['source_sample_freq']) {
case 0: // <= 32000
// may or may not be same as source frequency - ignore
break;
case 1: // 44100
case 2: // 48000
case 3: // 48000+
$ExplodedOptions = explode(' ', $encoder_options, 4);
switch ($ExplodedOptions[0]) {
case '--preset':
case '--alt-preset':
switch ($ExplodedOptions[1]) {
case 'fast':
case 'portable':
case 'medium':
case 'standard':
case 'extreme':
case 'insane':
$encoder_options .= ' --resample '.$thisfile_mpeg_audio['sample_rate'];
break;
default:
static $ExpectedResampledRate = array(
'phon+/lw/mw-eu/sw|16000' => 16000,
'mw-us|24000' => 24000, // 3.95
'mw-us|32000' => 32000, // 3.93
'mw-us|16000' => 16000, // 3.92
'phone|16000' => 16000,
'phone|11025' => 11025, // 3.94a15
'radio|32000' => 32000, // 3.94a15
'fm/radio|32000' => 32000, // 3.92
'fm|32000' => 32000, // 3.90
'voice|32000' => 32000);
if (!isset($ExpectedResampledRate[$ExplodedOptions[1].'|'.$thisfile_mpeg_audio['sample_rate']])) {
$encoder_options .= ' --resample '.$thisfile_mpeg_audio['sample_rate'];
}
break;
}
break;
case '--r3mix':
default:
$encoder_options .= ' --resample '.$thisfile_mpeg_audio['sample_rate'];
break;
}
break;
}
}
}
if (empty($encoder_options) && !empty($info['audio']['bitrate']) && !empty($info['audio']['bitrate_mode'])) {
//$encoder_options = strtoupper($info['audio']['bitrate_mode']).ceil($info['audio']['bitrate'] / 1000);
$encoder_options = strtoupper($info['audio']['bitrate_mode']);
}
return $encoder_options;
}
public function decodeMPEGaudioHeader($offset, &$info, $recursivesearch=true, $ScanAsCBR=false, $FastMPEGheaderScan=false) {
static $MPEGaudioVersionLookup;
static $MPEGaudioLayerLookup;
static $MPEGaudioBitrateLookup;
static $MPEGaudioFrequencyLookup;
static $MPEGaudioChannelModeLookup;
static $MPEGaudioModeExtensionLookup;
static $MPEGaudioEmphasisLookup;
if (empty($MPEGaudioVersionLookup)) {
$MPEGaudioVersionLookup = self::MPEGaudioVersionArray();
$MPEGaudioLayerLookup = self::MPEGaudioLayerArray();
$MPEGaudioBitrateLookup = self::MPEGaudioBitrateArray();
$MPEGaudioFrequencyLookup = self::MPEGaudioFrequencyArray();
$MPEGaudioChannelModeLookup = self::MPEGaudioChannelModeArray();
$MPEGaudioModeExtensionLookup = self::MPEGaudioModeExtensionArray();
$MPEGaudioEmphasisLookup = self::MPEGaudioEmphasisArray();
}
if (fseek($this->getid3->fp, $offset, SEEK_SET) != 0) {
$info['error'][] = 'decodeMPEGaudioHeader() failed to seek to next offset at '.$offset;
return false;
}
//$headerstring = fread($this->getid3->fp, 1441); // worst-case max length = 32kHz @ 320kbps layer 3 = 1441 bytes/frame
$headerstring = fread($this->getid3->fp, 226); // LAME header at offset 36 + 190 bytes of Xing/LAME data
// MP3 audio frame structure:
// $aa $aa $aa $aa [$bb $bb] $cc...
// where $aa..$aa is the four-byte mpeg-audio header (below)
// $bb $bb is the optional 2-byte CRC
// and $cc... is the audio data
$head4 = substr($headerstring, 0, 4);
static $MPEGaudioHeaderDecodeCache = array();
if (isset($MPEGaudioHeaderDecodeCache[$head4])) {
$MPEGheaderRawArray = $MPEGaudioHeaderDecodeCache[$head4];
} else {
$MPEGheaderRawArray = self::MPEGaudioHeaderDecode($head4);
$MPEGaudioHeaderDecodeCache[$head4] = $MPEGheaderRawArray;
}
static $MPEGaudioHeaderValidCache = array();
if (!isset($MPEGaudioHeaderValidCache[$head4])) { // Not in cache
//$MPEGaudioHeaderValidCache[$head4] = self::MPEGaudioHeaderValid($MPEGheaderRawArray, false, true); // allow badly-formatted freeformat (from LAME 3.90 - 3.93.1)
$MPEGaudioHeaderValidCache[$head4] = self::MPEGaudioHeaderValid($MPEGheaderRawArray, false, false);
}
// shortcut
if (!isset($info['mpeg']['audio'])) {
$info['mpeg']['audio'] = array();
}
$thisfile_mpeg_audio = &$info['mpeg']['audio'];
if ($MPEGaudioHeaderValidCache[$head4]) {
$thisfile_mpeg_audio['raw'] = $MPEGheaderRawArray;
} else {
$info['error'][] = 'Invalid MPEG audio header ('.getid3_lib::PrintHexBytes($head4).') at offset '.$offset;
return false;
}
if (!$FastMPEGheaderScan) {
$thisfile_mpeg_audio['version'] = $MPEGaudioVersionLookup[$thisfile_mpeg_audio['raw']['version']];
$thisfile_mpeg_audio['layer'] = $MPEGaudioLayerLookup[$thisfile_mpeg_audio['raw']['layer']];
$thisfile_mpeg_audio['channelmode'] = $MPEGaudioChannelModeLookup[$thisfile_mpeg_audio['raw']['channelmode']];
$thisfile_mpeg_audio['channels'] = (($thisfile_mpeg_audio['channelmode'] == 'mono') ? 1 : 2);
$thisfile_mpeg_audio['sample_rate'] = $MPEGaudioFrequencyLookup[$thisfile_mpeg_audio['version']][$thisfile_mpeg_audio['raw']['sample_rate']];
$thisfile_mpeg_audio['protection'] = !$thisfile_mpeg_audio['raw']['protection'];
$thisfile_mpeg_audio['private'] = (bool) $thisfile_mpeg_audio['raw']['private'];
$thisfile_mpeg_audio['modeextension'] = $MPEGaudioModeExtensionLookup[$thisfile_mpeg_audio['layer']][$thisfile_mpeg_audio['raw']['modeextension']];
$thisfile_mpeg_audio['copyright'] = (bool) $thisfile_mpeg_audio['raw']['copyright'];
$thisfile_mpeg_audio['original'] = (bool) $thisfile_mpeg_audio['raw']['original'];
$thisfile_mpeg_audio['emphasis'] = $MPEGaudioEmphasisLookup[$thisfile_mpeg_audio['raw']['emphasis']];
$info['audio']['channels'] = $thisfile_mpeg_audio['channels'];
$info['audio']['sample_rate'] = $thisfile_mpeg_audio['sample_rate'];
if ($thisfile_mpeg_audio['protection']) {
$thisfile_mpeg_audio['crc'] = getid3_lib::BigEndian2Int(substr($headerstring, 4, 2));
}
}
if ($thisfile_mpeg_audio['raw']['bitrate'] == 15) {
// http://www.hydrogenaudio.org/?act=ST&f=16&t=9682&st=0
$info['warning'][] = 'Invalid bitrate index (15), this is a known bug in free-format MP3s encoded by LAME v3.90 - 3.93.1';
$thisfile_mpeg_audio['raw']['bitrate'] = 0;
}
$thisfile_mpeg_audio['padding'] = (bool) $thisfile_mpeg_audio['raw']['padding'];
$thisfile_mpeg_audio['bitrate'] = $MPEGaudioBitrateLookup[$thisfile_mpeg_audio['version']][$thisfile_mpeg_audio['layer']][$thisfile_mpeg_audio['raw']['bitrate']];
if (($thisfile_mpeg_audio['bitrate'] == 'free') && ($offset == $info['avdataoffset'])) {
// only skip multiple frame check if free-format bitstream found at beginning of file
// otherwise is quite possibly simply corrupted data
$recursivesearch = false;
}
// For Layer 2 there are some combinations of bitrate and mode which are not allowed.
if (!$FastMPEGheaderScan && ($thisfile_mpeg_audio['layer'] == '2')) {
$info['audio']['dataformat'] = 'mp2';
switch ($thisfile_mpeg_audio['channelmode']) {
case 'mono':
if (($thisfile_mpeg_audio['bitrate'] == 'free') || ($thisfile_mpeg_audio['bitrate'] <= 192000)) {
// these are ok
} else {
$info['error'][] = $thisfile_mpeg_audio['bitrate'].'kbps not allowed in Layer 2, '.$thisfile_mpeg_audio['channelmode'].'.';
return false;
}
break;
case 'stereo':
case 'joint stereo':
case 'dual channel':
if (($thisfile_mpeg_audio['bitrate'] == 'free') || ($thisfile_mpeg_audio['bitrate'] == 64000) || ($thisfile_mpeg_audio['bitrate'] >= 96000)) {
// these are ok
} else {
$info['error'][] = intval(round($thisfile_mpeg_audio['bitrate'] / 1000)).'kbps not allowed in Layer 2, '.$thisfile_mpeg_audio['channelmode'].'.';
return false;
}
break;
}
}
if ($info['audio']['sample_rate'] > 0) {
$thisfile_mpeg_audio['framelength'] = self::MPEGaudioFrameLength($thisfile_mpeg_audio['bitrate'], $thisfile_mpeg_audio['version'], $thisfile_mpeg_audio['layer'], (int) $thisfile_mpeg_audio['padding'], $info['audio']['sample_rate']);
}
$nextframetestoffset = $offset + 1;
if ($thisfile_mpeg_audio['bitrate'] != 'free') {
$info['audio']['bitrate'] = $thisfile_mpeg_audio['bitrate'];
if (isset($thisfile_mpeg_audio['framelength'])) {
$nextframetestoffset = $offset + $thisfile_mpeg_audio['framelength'];
} else {
$info['error'][] = 'Frame at offset('.$offset.') is has an invalid frame length.';
return false;
}
}
$ExpectedNumberOfAudioBytes = 0;
////////////////////////////////////////////////////////////////////////////////////
// Variable-bitrate headers
if (substr($headerstring, 4 + 32, 4) == 'VBRI') {
// Fraunhofer VBR header is hardcoded 'VBRI' at offset 0x24 (36)
// specs taken from http://minnie.tuhs.org/pipermail/mp3encoder/2001-January/001800.html
$thisfile_mpeg_audio['bitrate_mode'] = 'vbr';
$thisfile_mpeg_audio['VBR_method'] = 'Fraunhofer';
$info['audio']['codec'] = 'Fraunhofer';
$SideInfoData = substr($headerstring, 4 + 2, 32);
$FraunhoferVBROffset = 36;
$thisfile_mpeg_audio['VBR_encoder_version'] = getid3_lib::BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 4, 2)); // VbriVersion
$thisfile_mpeg_audio['VBR_encoder_delay'] = getid3_lib::BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 6, 2)); // VbriDelay
$thisfile_mpeg_audio['VBR_quality'] = getid3_lib::BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 8, 2)); // VbriQuality
$thisfile_mpeg_audio['VBR_bytes'] = getid3_lib::BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 10, 4)); // VbriStreamBytes
$thisfile_mpeg_audio['VBR_frames'] = getid3_lib::BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 14, 4)); // VbriStreamFrames
$thisfile_mpeg_audio['VBR_seek_offsets'] = getid3_lib::BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 18, 2)); // VbriTableSize
$thisfile_mpeg_audio['VBR_seek_scale'] = getid3_lib::BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 20, 2)); // VbriTableScale
$thisfile_mpeg_audio['VBR_entry_bytes'] = getid3_lib::BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 22, 2)); // VbriEntryBytes
$thisfile_mpeg_audio['VBR_entry_frames'] = getid3_lib::BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 24, 2)); // VbriEntryFrames
$ExpectedNumberOfAudioBytes = $thisfile_mpeg_audio['VBR_bytes'];
$previousbyteoffset = $offset;
for ($i = 0; $i < $thisfile_mpeg_audio['VBR_seek_offsets']; $i++) {
$Fraunhofer_OffsetN = getid3_lib::BigEndian2Int(substr($headerstring, $FraunhoferVBROffset, $thisfile_mpeg_audio['VBR_entry_bytes']));
$FraunhoferVBROffset += $thisfile_mpeg_audio['VBR_entry_bytes'];
$thisfile_mpeg_audio['VBR_offsets_relative'][$i] = ($Fraunhofer_OffsetN * $thisfile_mpeg_audio['VBR_seek_scale']);
$thisfile_mpeg_audio['VBR_offsets_absolute'][$i] = ($Fraunhofer_OffsetN * $thisfile_mpeg_audio['VBR_seek_scale']) + $previousbyteoffset;
$previousbyteoffset += $Fraunhofer_OffsetN;
}
} else {
// Xing VBR header is hardcoded 'Xing' at a offset 0x0D (13), 0x15 (21) or 0x24 (36)
// depending on MPEG layer and number of channels
$VBRidOffset = self::XingVBRidOffset($thisfile_mpeg_audio['version'], $thisfile_mpeg_audio['channelmode']);
$SideInfoData = substr($headerstring, 4 + 2, $VBRidOffset - 4);
if ((substr($headerstring, $VBRidOffset, strlen('Xing')) == 'Xing') || (substr($headerstring, $VBRidOffset, strlen('Info')) == 'Info')) {
// 'Xing' is traditional Xing VBR frame
// 'Info' is LAME-encoded CBR (This was done to avoid CBR files to be recognized as traditional Xing VBR files by some decoders.)
// 'Info' *can* legally be used to specify a VBR file as well, however.
// http://www.multiweb.cz/twoinches/MP3inside.htm
//00..03 = "Xing" or "Info"
//04..07 = Flags:
// 0x01 Frames Flag set if value for number of frames in file is stored
// 0x02 Bytes Flag set if value for filesize in bytes is stored
// 0x04 TOC Flag set if values for TOC are stored
// 0x08 VBR Scale Flag set if values for VBR scale is stored
//08..11 Frames: Number of frames in file (including the first Xing/Info one)
//12..15 Bytes: File length in Bytes
//16..115 TOC (Table of Contents):
// Contains of 100 indexes (one Byte length) for easier lookup in file. Approximately solves problem with moving inside file.
// Each Byte has a value according this formula:
// (TOC[i] / 256) * fileLenInBytes
// So if song lasts eg. 240 sec. and you want to jump to 60. sec. (and file is 5 000 000 Bytes length) you can use:
// TOC[(60/240)*100] = TOC[25]
// and corresponding Byte in file is then approximately at:
// (TOC[25]/256) * 5000000
//116..119 VBR Scale
// should be safe to leave this at 'vbr' and let it be overriden to 'cbr' if a CBR preset/mode is used by LAME
// if (substr($headerstring, $VBRidOffset, strlen('Info')) == 'Xing') {
$thisfile_mpeg_audio['bitrate_mode'] = 'vbr';
$thisfile_mpeg_audio['VBR_method'] = 'Xing';
// } else {
// $ScanAsCBR = true;
// $thisfile_mpeg_audio['bitrate_mode'] = 'cbr';
// }
$thisfile_mpeg_audio['xing_flags_raw'] = getid3_lib::BigEndian2Int(substr($headerstring, $VBRidOffset + 4, 4));
$thisfile_mpeg_audio['xing_flags']['frames'] = (bool) ($thisfile_mpeg_audio['xing_flags_raw'] & 0x00000001);
$thisfile_mpeg_audio['xing_flags']['bytes'] = (bool) ($thisfile_mpeg_audio['xing_flags_raw'] & 0x00000002);
$thisfile_mpeg_audio['xing_flags']['toc'] = (bool) ($thisfile_mpeg_audio['xing_flags_raw'] & 0x00000004);
$thisfile_mpeg_audio['xing_flags']['vbr_scale'] = (bool) ($thisfile_mpeg_audio['xing_flags_raw'] & 0x00000008);
if ($thisfile_mpeg_audio['xing_flags']['frames']) {
$thisfile_mpeg_audio['VBR_frames'] = getid3_lib::BigEndian2Int(substr($headerstring, $VBRidOffset + 8, 4));
//$thisfile_mpeg_audio['VBR_frames']--; // don't count header Xing/Info frame
}
if ($thisfile_mpeg_audio['xing_flags']['bytes']) {
$thisfile_mpeg_audio['VBR_bytes'] = getid3_lib::BigEndian2Int(substr($headerstring, $VBRidOffset + 12, 4));
}
//if (($thisfile_mpeg_audio['bitrate'] == 'free') && !empty($thisfile_mpeg_audio['VBR_frames']) && !empty($thisfile_mpeg_audio['VBR_bytes'])) {
if (!empty($thisfile_mpeg_audio['VBR_frames']) && !empty($thisfile_mpeg_audio['VBR_bytes'])) {
$framelengthfloat = $thisfile_mpeg_audio['VBR_bytes'] / $thisfile_mpeg_audio['VBR_frames'];
if ($thisfile_mpeg_audio['layer'] == '1') {
// BitRate = (((FrameLengthInBytes / 4) - Padding) * SampleRate) / 12
//$info['audio']['bitrate'] = ((($framelengthfloat / 4) - intval($thisfile_mpeg_audio['padding'])) * $thisfile_mpeg_audio['sample_rate']) / 12;
$info['audio']['bitrate'] = ($framelengthfloat / 4) * $thisfile_mpeg_audio['sample_rate'] * (2 / $info['audio']['channels']) / 12;
} else {
// Bitrate = ((FrameLengthInBytes - Padding) * SampleRate) / 144
//$info['audio']['bitrate'] = (($framelengthfloat - intval($thisfile_mpeg_audio['padding'])) * $thisfile_mpeg_audio['sample_rate']) / 144;
$info['audio']['bitrate'] = $framelengthfloat * $thisfile_mpeg_audio['sample_rate'] * (2 / $info['audio']['channels']) / 144;
}
$thisfile_mpeg_audio['framelength'] = floor($framelengthfloat);
}
if ($thisfile_mpeg_audio['xing_flags']['toc']) {
$LAMEtocData = substr($headerstring, $VBRidOffset + 16, 100);
for ($i = 0; $i < 100; $i++) {
$thisfile_mpeg_audio['toc'][$i] = ord($LAMEtocData{$i});
}
}
if ($thisfile_mpeg_audio['xing_flags']['vbr_scale']) {
$thisfile_mpeg_audio['VBR_scale'] = getid3_lib::BigEndian2Int(substr($headerstring, $VBRidOffset + 116, 4));
}
// http://gabriel.mp3-tech.org/mp3infotag.html
if (substr($headerstring, $VBRidOffset + 120, 4) == 'LAME') {
// shortcut
$thisfile_mpeg_audio['LAME'] = array();
$thisfile_mpeg_audio_lame = &$thisfile_mpeg_audio['LAME'];
$thisfile_mpeg_audio_lame['long_version'] = substr($headerstring, $VBRidOffset + 120, 20);
$thisfile_mpeg_audio_lame['short_version'] = substr($thisfile_mpeg_audio_lame['long_version'], 0, 9);
if ($thisfile_mpeg_audio_lame['short_version'] >= 'LAME3.90') {
// extra 11 chars are not part of version string when LAMEtag present
unset($thisfile_mpeg_audio_lame['long_version']);
// It the LAME tag was only introduced in LAME v3.90
// http://www.hydrogenaudio.org/?act=ST&f=15&t=9933
// Offsets of various bytes in http://gabriel.mp3-tech.org/mp3infotag.html
// are assuming a 'Xing' identifier offset of 0x24, which is the case for
// MPEG-1 non-mono, but not for other combinations
$LAMEtagOffsetContant = $VBRidOffset - 0x24;
// shortcuts
$thisfile_mpeg_audio_lame['RGAD'] = array('track'=>array(), 'album'=>array());
$thisfile_mpeg_audio_lame_RGAD = &$thisfile_mpeg_audio_lame['RGAD'];
$thisfile_mpeg_audio_lame_RGAD_track = &$thisfile_mpeg_audio_lame_RGAD['track'];
$thisfile_mpeg_audio_lame_RGAD_album = &$thisfile_mpeg_audio_lame_RGAD['album'];
$thisfile_mpeg_audio_lame['raw'] = array();
$thisfile_mpeg_audio_lame_raw = &$thisfile_mpeg_audio_lame['raw'];
// byte $9B VBR Quality
// This field is there to indicate a quality level, although the scale was not precised in the original Xing specifications.
// Actually overwrites original Xing bytes
unset($thisfile_mpeg_audio['VBR_scale']);
$thisfile_mpeg_audio_lame['vbr_quality'] = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0x9B, 1));
// bytes $9C-$A4 Encoder short VersionString
$thisfile_mpeg_audio_lame['short_version'] = substr($headerstring, $LAMEtagOffsetContant + 0x9C, 9);
// byte $A5 Info Tag revision + VBR method
$LAMEtagRevisionVBRmethod = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xA5, 1));
$thisfile_mpeg_audio_lame['tag_revision'] = ($LAMEtagRevisionVBRmethod & 0xF0) >> 4;
$thisfile_mpeg_audio_lame_raw['vbr_method'] = $LAMEtagRevisionVBRmethod & 0x0F;
$thisfile_mpeg_audio_lame['vbr_method'] = self::LAMEvbrMethodLookup($thisfile_mpeg_audio_lame_raw['vbr_method']);
$thisfile_mpeg_audio['bitrate_mode'] = substr($thisfile_mpeg_audio_lame['vbr_method'], 0, 3); // usually either 'cbr' or 'vbr', but truncates 'vbr-old / vbr-rh' to 'vbr'
// byte $A6 Lowpass filter value
$thisfile_mpeg_audio_lame['lowpass_frequency'] = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xA6, 1)) * 100;
// bytes $A7-$AE Replay Gain
// http://privatewww.essex.ac.uk/~djmrob/replaygain/rg_data_format.html
// bytes $A7-$AA : 32 bit floating point "Peak signal amplitude"
if ($thisfile_mpeg_audio_lame['short_version'] >= 'LAME3.94b') {
// LAME 3.94a16 and later - 9.23 fixed point
// ie 0x0059E2EE / (2^23) = 5890798 / 8388608 = 0.7022378444671630859375
$thisfile_mpeg_audio_lame_RGAD['peak_amplitude'] = (float) ((getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xA7, 4))) / 8388608);
} else {
// LAME 3.94a15 and earlier - 32-bit floating point
// Actually 3.94a16 will fall in here too and be WRONG, but is hard to detect 3.94a16 vs 3.94a15
$thisfile_mpeg_audio_lame_RGAD['peak_amplitude'] = getid3_lib::LittleEndian2Float(substr($headerstring, $LAMEtagOffsetContant + 0xA7, 4));
}
if ($thisfile_mpeg_audio_lame_RGAD['peak_amplitude'] == 0) {
unset($thisfile_mpeg_audio_lame_RGAD['peak_amplitude']);
} else {
$thisfile_mpeg_audio_lame_RGAD['peak_db'] = getid3_lib::RGADamplitude2dB($thisfile_mpeg_audio_lame_RGAD['peak_amplitude']);
}
$thisfile_mpeg_audio_lame_raw['RGAD_track'] = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xAB, 2));
$thisfile_mpeg_audio_lame_raw['RGAD_album'] = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xAD, 2));
if ($thisfile_mpeg_audio_lame_raw['RGAD_track'] != 0) {
$thisfile_mpeg_audio_lame_RGAD_track['raw']['name'] = ($thisfile_mpeg_audio_lame_raw['RGAD_track'] & 0xE000) >> 13;
$thisfile_mpeg_audio_lame_RGAD_track['raw']['originator'] = ($thisfile_mpeg_audio_lame_raw['RGAD_track'] & 0x1C00) >> 10;
$thisfile_mpeg_audio_lame_RGAD_track['raw']['sign_bit'] = ($thisfile_mpeg_audio_lame_raw['RGAD_track'] & 0x0200) >> 9;
$thisfile_mpeg_audio_lame_RGAD_track['raw']['gain_adjust'] = $thisfile_mpeg_audio_lame_raw['RGAD_track'] & 0x01FF;
$thisfile_mpeg_audio_lame_RGAD_track['name'] = getid3_lib::RGADnameLookup($thisfile_mpeg_audio_lame_RGAD_track['raw']['name']);
$thisfile_mpeg_audio_lame_RGAD_track['originator'] = getid3_lib::RGADoriginatorLookup($thisfile_mpeg_audio_lame_RGAD_track['raw']['originator']);
$thisfile_mpeg_audio_lame_RGAD_track['gain_db'] = getid3_lib::RGADadjustmentLookup($thisfile_mpeg_audio_lame_RGAD_track['raw']['gain_adjust'], $thisfile_mpeg_audio_lame_RGAD_track['raw']['sign_bit']);
if (!empty($thisfile_mpeg_audio_lame_RGAD['peak_amplitude'])) {
$info['replay_gain']['track']['peak'] = $thisfile_mpeg_audio_lame_RGAD['peak_amplitude'];
}
$info['replay_gain']['track']['originator'] = $thisfile_mpeg_audio_lame_RGAD_track['originator'];
$info['replay_gain']['track']['adjustment'] = $thisfile_mpeg_audio_lame_RGAD_track['gain_db'];
} else {
unset($thisfile_mpeg_audio_lame_RGAD['track']);
}
if ($thisfile_mpeg_audio_lame_raw['RGAD_album'] != 0) {
$thisfile_mpeg_audio_lame_RGAD_album['raw']['name'] = ($thisfile_mpeg_audio_lame_raw['RGAD_album'] & 0xE000) >> 13;
$thisfile_mpeg_audio_lame_RGAD_album['raw']['originator'] = ($thisfile_mpeg_audio_lame_raw['RGAD_album'] & 0x1C00) >> 10;
$thisfile_mpeg_audio_lame_RGAD_album['raw']['sign_bit'] = ($thisfile_mpeg_audio_lame_raw['RGAD_album'] & 0x0200) >> 9;
$thisfile_mpeg_audio_lame_RGAD_album['raw']['gain_adjust'] = $thisfile_mpeg_audio_lame_raw['RGAD_album'] & 0x01FF;
$thisfile_mpeg_audio_lame_RGAD_album['name'] = getid3_lib::RGADnameLookup($thisfile_mpeg_audio_lame_RGAD_album['raw']['name']);
$thisfile_mpeg_audio_lame_RGAD_album['originator'] = getid3_lib::RGADoriginatorLookup($thisfile_mpeg_audio_lame_RGAD_album['raw']['originator']);
$thisfile_mpeg_audio_lame_RGAD_album['gain_db'] = getid3_lib::RGADadjustmentLookup($thisfile_mpeg_audio_lame_RGAD_album['raw']['gain_adjust'], $thisfile_mpeg_audio_lame_RGAD_album['raw']['sign_bit']);
if (!empty($thisfile_mpeg_audio_lame_RGAD['peak_amplitude'])) {
$info['replay_gain']['album']['peak'] = $thisfile_mpeg_audio_lame_RGAD['peak_amplitude'];
}
$info['replay_gain']['album']['originator'] = $thisfile_mpeg_audio_lame_RGAD_album['originator'];
$info['replay_gain']['album']['adjustment'] = $thisfile_mpeg_audio_lame_RGAD_album['gain_db'];
} else {
unset($thisfile_mpeg_audio_lame_RGAD['album']);
}
if (empty($thisfile_mpeg_audio_lame_RGAD)) {
unset($thisfile_mpeg_audio_lame['RGAD']);
}
// byte $AF Encoding flags + ATH Type
$EncodingFlagsATHtype = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xAF, 1));
$thisfile_mpeg_audio_lame['encoding_flags']['nspsytune'] = (bool) ($EncodingFlagsATHtype & 0x10);
$thisfile_mpeg_audio_lame['encoding_flags']['nssafejoint'] = (bool) ($EncodingFlagsATHtype & 0x20);
$thisfile_mpeg_audio_lame['encoding_flags']['nogap_next'] = (bool) ($EncodingFlagsATHtype & 0x40);
$thisfile_mpeg_audio_lame['encoding_flags']['nogap_prev'] = (bool) ($EncodingFlagsATHtype & 0x80);
$thisfile_mpeg_audio_lame['ath_type'] = $EncodingFlagsATHtype & 0x0F;
// byte $B0 if ABR {specified bitrate} else {minimal bitrate}
$thisfile_mpeg_audio_lame['raw']['abrbitrate_minbitrate'] = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB0, 1));
if ($thisfile_mpeg_audio_lame_raw['vbr_method'] == 2) { // Average BitRate (ABR)
$thisfile_mpeg_audio_lame['bitrate_abr'] = $thisfile_mpeg_audio_lame['raw']['abrbitrate_minbitrate'];
} elseif ($thisfile_mpeg_audio_lame_raw['vbr_method'] == 1) { // Constant BitRate (CBR)
// ignore
} elseif ($thisfile_mpeg_audio_lame['raw']['abrbitrate_minbitrate'] > 0) { // Variable BitRate (VBR) - minimum bitrate
$thisfile_mpeg_audio_lame['bitrate_min'] = $thisfile_mpeg_audio_lame['raw']['abrbitrate_minbitrate'];
}
// bytes $B1-$B3 Encoder delays
$EncoderDelays = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB1, 3));
$thisfile_mpeg_audio_lame['encoder_delay'] = ($EncoderDelays & 0xFFF000) >> 12;
$thisfile_mpeg_audio_lame['end_padding'] = $EncoderDelays & 0x000FFF;
// byte $B4 Misc
$MiscByte = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB4, 1));
$thisfile_mpeg_audio_lame_raw['noise_shaping'] = ($MiscByte & 0x03);
$thisfile_mpeg_audio_lame_raw['stereo_mode'] = ($MiscByte & 0x1C) >> 2;
$thisfile_mpeg_audio_lame_raw['not_optimal_quality'] = ($MiscByte & 0x20) >> 5;
$thisfile_mpeg_audio_lame_raw['source_sample_freq'] = ($MiscByte & 0xC0) >> 6;
$thisfile_mpeg_audio_lame['noise_shaping'] = $thisfile_mpeg_audio_lame_raw['noise_shaping'];
$thisfile_mpeg_audio_lame['stereo_mode'] = self::LAMEmiscStereoModeLookup($thisfile_mpeg_audio_lame_raw['stereo_mode']);
$thisfile_mpeg_audio_lame['not_optimal_quality'] = (bool) $thisfile_mpeg_audio_lame_raw['not_optimal_quality'];
$thisfile_mpeg_audio_lame['source_sample_freq'] = self::LAMEmiscSourceSampleFrequencyLookup($thisfile_mpeg_audio_lame_raw['source_sample_freq']);
// byte $B5 MP3 Gain
$thisfile_mpeg_audio_lame_raw['mp3_gain'] = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB5, 1), false, true);
$thisfile_mpeg_audio_lame['mp3_gain_db'] = (getid3_lib::RGADamplitude2dB(2) / 4) * $thisfile_mpeg_audio_lame_raw['mp3_gain'];
$thisfile_mpeg_audio_lame['mp3_gain_factor'] = pow(2, ($thisfile_mpeg_audio_lame['mp3_gain_db'] / 6));
// bytes $B6-$B7 Preset and surround info
$PresetSurroundBytes = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB6, 2));
// Reserved = ($PresetSurroundBytes & 0xC000);
$thisfile_mpeg_audio_lame_raw['surround_info'] = ($PresetSurroundBytes & 0x3800);
$thisfile_mpeg_audio_lame['surround_info'] = self::LAMEsurroundInfoLookup($thisfile_mpeg_audio_lame_raw['surround_info']);
$thisfile_mpeg_audio_lame['preset_used_id'] = ($PresetSurroundBytes & 0x07FF);
$thisfile_mpeg_audio_lame['preset_used'] = self::LAMEpresetUsedLookup($thisfile_mpeg_audio_lame);
if (!empty($thisfile_mpeg_audio_lame['preset_used_id']) && empty($thisfile_mpeg_audio_lame['preset_used'])) {
$info['warning'][] = 'Unknown LAME preset used ('.$thisfile_mpeg_audio_lame['preset_used_id'].') - please report to info@getid3.org';
}
if (($thisfile_mpeg_audio_lame['short_version'] == 'LAME3.90.') && !empty($thisfile_mpeg_audio_lame['preset_used_id'])) {
// this may change if 3.90.4 ever comes out
$thisfile_mpeg_audio_lame['short_version'] = 'LAME3.90.3';
}
// bytes $B8-$BB MusicLength
$thisfile_mpeg_audio_lame['audio_bytes'] = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB8, 4));
$ExpectedNumberOfAudioBytes = (($thisfile_mpeg_audio_lame['audio_bytes'] > 0) ? $thisfile_mpeg_audio_lame['audio_bytes'] : $thisfile_mpeg_audio['VBR_bytes']);
// bytes $BC-$BD MusicCRC
$thisfile_mpeg_audio_lame['music_crc'] = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xBC, 2));
// bytes $BE-$BF CRC-16 of Info Tag
$thisfile_mpeg_audio_lame['lame_tag_crc'] = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xBE, 2));
// LAME CBR
if ($thisfile_mpeg_audio_lame_raw['vbr_method'] == 1) {
$thisfile_mpeg_audio['bitrate_mode'] = 'cbr';
$thisfile_mpeg_audio['bitrate'] = self::ClosestStandardMP3Bitrate($thisfile_mpeg_audio['bitrate']);
$info['audio']['bitrate'] = $thisfile_mpeg_audio['bitrate'];
//if (empty($thisfile_mpeg_audio['bitrate']) || (!empty($thisfile_mpeg_audio_lame['bitrate_min']) && ($thisfile_mpeg_audio_lame['bitrate_min'] != 255))) {
// $thisfile_mpeg_audio['bitrate'] = $thisfile_mpeg_audio_lame['bitrate_min'];
//}
}
}
}
} else {
// not Fraunhofer or Xing VBR methods, most likely CBR (but could be VBR with no header)
$thisfile_mpeg_audio['bitrate_mode'] = 'cbr';
if ($recursivesearch) {
$thisfile_mpeg_audio['bitrate_mode'] = 'vbr';
if ($this->RecursiveFrameScanning($offset, $nextframetestoffset, true)) {
$recursivesearch = false;
$thisfile_mpeg_audio['bitrate_mode'] = 'cbr';
}
if ($thisfile_mpeg_audio['bitrate_mode'] == 'vbr') {
$info['warning'][] = 'VBR file with no VBR header. Bitrate values calculated from actual frame bitrates.';
}
}
}
}
if (($ExpectedNumberOfAudioBytes > 0) && ($ExpectedNumberOfAudioBytes != ($info['avdataend'] - $info['avdataoffset']))) {
if ($ExpectedNumberOfAudioBytes > ($info['avdataend'] - $info['avdataoffset'])) {
if (isset($info['fileformat']) && ($info['fileformat'] == 'riff')) {
// ignore, audio data is broken into chunks so will always be data "missing"
} elseif (($ExpectedNumberOfAudioBytes - ($info['avdataend'] - $info['avdataoffset'])) == 1) {
$info['warning'][] = 'Last byte of data truncated (this is a known bug in Meracl ID3 Tag Writer before v1.3.5)';
} else {
$info['warning'][] = 'Probable truncated file: expecting '.$ExpectedNumberOfAudioBytes.' bytes of audio data, only found '.($info['avdataend'] - $info['avdataoffset']).' (short by '.($ExpectedNumberOfAudioBytes - ($info['avdataend'] - $info['avdataoffset'])).' bytes)';
}
} else {
if ((($info['avdataend'] - $info['avdataoffset']) - $ExpectedNumberOfAudioBytes) == 1) {
// $prenullbytefileoffset = ftell($this->getid3->fp);
// fseek($this->getid3->fp, $info['avdataend'], SEEK_SET);
// $PossibleNullByte = fread($this->getid3->fp, 1);
// fseek($this->getid3->fp, $prenullbytefileoffset, SEEK_SET);
// if ($PossibleNullByte === "\x00") {
$info['avdataend']--;
// $info['warning'][] = 'Extra null byte at end of MP3 data assumed to be RIFF padding and therefore ignored';
// } else {
// $info['warning'][] = 'Too much data in file: expecting '.$ExpectedNumberOfAudioBytes.' bytes of audio data, found '.($info['avdataend'] - $info['avdataoffset']).' ('.(($info['avdataend'] - $info['avdataoffset']) - $ExpectedNumberOfAudioBytes).' bytes too many)';
// }
} else {
$info['warning'][] = 'Too much data in file: expecting '.$ExpectedNumberOfAudioBytes.' bytes of audio data, found '.($info['avdataend'] - $info['avdataoffset']).' ('.(($info['avdataend'] - $info['avdataoffset']) - $ExpectedNumberOfAudioBytes).' bytes too many)';
}
}
}
if (($thisfile_mpeg_audio['bitrate'] == 'free') && empty($info['audio']['bitrate'])) {
if (($offset == $info['avdataoffset']) && empty($thisfile_mpeg_audio['VBR_frames'])) {
$framebytelength = $this->FreeFormatFrameLength($offset, true);
if ($framebytelength > 0) {
$thisfile_mpeg_audio['framelength'] = $framebytelength;
if ($thisfile_mpeg_audio['layer'] == '1') {
// BitRate = (((FrameLengthInBytes / 4) - Padding) * SampleRate) / 12
$info['audio']['bitrate'] = ((($framebytelength / 4) - intval($thisfile_mpeg_audio['padding'])) * $thisfile_mpeg_audio['sample_rate']) / 12;
} else {
// Bitrate = ((FrameLengthInBytes - Padding) * SampleRate) / 144
$info['audio']['bitrate'] = (($framebytelength - intval($thisfile_mpeg_audio['padding'])) * $thisfile_mpeg_audio['sample_rate']) / 144;
}
} else {
$info['error'][] = 'Error calculating frame length of free-format MP3 without Xing/LAME header';
}
}
}
if (isset($thisfile_mpeg_audio['VBR_frames']) ? $thisfile_mpeg_audio['VBR_frames'] : '') {
switch ($thisfile_mpeg_audio['bitrate_mode']) {
case 'vbr':
case 'abr':
$bytes_per_frame = 1152;
if (($thisfile_mpeg_audio['version'] == '1') && ($thisfile_mpeg_audio['layer'] == 1)) {
$bytes_per_frame = 384;
} elseif ((($thisfile_mpeg_audio['version'] == '2') || ($thisfile_mpeg_audio['version'] == '2.5')) && ($thisfile_mpeg_audio['layer'] == 3)) {
$bytes_per_frame = 576;
}
$thisfile_mpeg_audio['VBR_bitrate'] = (isset($thisfile_mpeg_audio['VBR_bytes']) ? (($thisfile_mpeg_audio['VBR_bytes'] / $thisfile_mpeg_audio['VBR_frames']) * 8) * ($info['audio']['sample_rate'] / $bytes_per_frame) : 0);
if ($thisfile_mpeg_audio['VBR_bitrate'] > 0) {
$info['audio']['bitrate'] = $thisfile_mpeg_audio['VBR_bitrate'];
$thisfile_mpeg_audio['bitrate'] = $thisfile_mpeg_audio['VBR_bitrate']; // to avoid confusion
}
break;
}
}
// End variable-bitrate headers
////////////////////////////////////////////////////////////////////////////////////
if ($recursivesearch) {
if (!$this->RecursiveFrameScanning($offset, $nextframetestoffset, $ScanAsCBR)) {
return false;
}
}
//if (false) {
// // experimental side info parsing section - not returning anything useful yet
//
// $SideInfoBitstream = getid3_lib::BigEndian2Bin($SideInfoData);
// $SideInfoOffset = 0;
//
// if ($thisfile_mpeg_audio['version'] == '1') {
// if ($thisfile_mpeg_audio['channelmode'] == 'mono') {
// // MPEG-1 (mono)
// $thisfile_mpeg_audio['side_info']['main_data_begin'] = substr($SideInfoBitstream, $SideInfoOffset, 9);
// $SideInfoOffset += 9;
// $SideInfoOffset += 5;
// } else {
// // MPEG-1 (stereo, joint-stereo, dual-channel)
// $thisfile_mpeg_audio['side_info']['main_data_begin'] = substr($SideInfoBitstream, $SideInfoOffset, 9);
// $SideInfoOffset += 9;
// $SideInfoOffset += 3;
// }
// } else { // 2 or 2.5
// if ($thisfile_mpeg_audio['channelmode'] == 'mono') {
// // MPEG-2, MPEG-2.5 (mono)
// $thisfile_mpeg_audio['side_info']['main_data_begin'] = substr($SideInfoBitstream, $SideInfoOffset, 8);
// $SideInfoOffset += 8;
// $SideInfoOffset += 1;
// } else {
// // MPEG-2, MPEG-2.5 (stereo, joint-stereo, dual-channel)
// $thisfile_mpeg_audio['side_info']['main_data_begin'] = substr($SideInfoBitstream, $SideInfoOffset, 8);
// $SideInfoOffset += 8;
// $SideInfoOffset += 2;
// }
// }
//
// if ($thisfile_mpeg_audio['version'] == '1') {
// for ($channel = 0; $channel < $info['audio']['channels']; $channel++) {
// for ($scfsi_band = 0; $scfsi_band < 4; $scfsi_band++) {
// $thisfile_mpeg_audio['scfsi'][$channel][$scfsi_band] = substr($SideInfoBitstream, $SideInfoOffset, 1);
// $SideInfoOffset += 2;
// }
// }
// }
// for ($granule = 0; $granule < (($thisfile_mpeg_audio['version'] == '1') ? 2 : 1); $granule++) {
// for ($channel = 0; $channel < $info['audio']['channels']; $channel++) {
// $thisfile_mpeg_audio['part2_3_length'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 12);
// $SideInfoOffset += 12;
// $thisfile_mpeg_audio['big_values'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 9);
// $SideInfoOffset += 9;
// $thisfile_mpeg_audio['global_gain'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 8);
// $SideInfoOffset += 8;
// if ($thisfile_mpeg_audio['version'] == '1') {
// $thisfile_mpeg_audio['scalefac_compress'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 4);
// $SideInfoOffset += 4;
// } else {
// $thisfile_mpeg_audio['scalefac_compress'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 9);
// $SideInfoOffset += 9;
// }
// $thisfile_mpeg_audio['window_switching_flag'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 1);
// $SideInfoOffset += 1;
//
// if ($thisfile_mpeg_audio['window_switching_flag'][$granule][$channel] == '1') {
//
// $thisfile_mpeg_audio['block_type'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 2);
// $SideInfoOffset += 2;
// $thisfile_mpeg_audio['mixed_block_flag'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 1);
// $SideInfoOffset += 1;
//
// for ($region = 0; $region < 2; $region++) {
// $thisfile_mpeg_audio['table_select'][$granule][$channel][$region] = substr($SideInfoBitstream, $SideInfoOffset, 5);
// $SideInfoOffset += 5;
// }
// $thisfile_mpeg_audio['table_select'][$granule][$channel][2] = 0;
//
// for ($window = 0; $window < 3; $window++) {
// $thisfile_mpeg_audio['subblock_gain'][$granule][$channel][$window] = substr($SideInfoBitstream, $SideInfoOffset, 3);
// $SideInfoOffset += 3;
// }
//
// } else {
//
// for ($region = 0; $region < 3; $region++) {
// $thisfile_mpeg_audio['table_select'][$granule][$channel][$region] = substr($SideInfoBitstream, $SideInfoOffset, 5);
// $SideInfoOffset += 5;
// }
//
// $thisfile_mpeg_audio['region0_count'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 4);
// $SideInfoOffset += 4;
// $thisfile_mpeg_audio['region1_count'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 3);
// $SideInfoOffset += 3;
// $thisfile_mpeg_audio['block_type'][$granule][$channel] = 0;
// }
//
// if ($thisfile_mpeg_audio['version'] == '1') {
// $thisfile_mpeg_audio['preflag'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 1);
// $SideInfoOffset += 1;
// }
// $thisfile_mpeg_audio['scalefac_scale'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 1);
// $SideInfoOffset += 1;
// $thisfile_mpeg_audio['count1table_select'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 1);
// $SideInfoOffset += 1;
// }
// }
//}
return true;
}
public function RecursiveFrameScanning(&$offset, &$nextframetestoffset, $ScanAsCBR) {
$info = &$this->getid3->info;
$firstframetestarray = array('error'=>'', 'warning'=>'', 'avdataend'=>$info['avdataend'], 'avdataoffset'=>$info['avdataoffset']);
$this->decodeMPEGaudioHeader($offset, $firstframetestarray, false);
for ($i = 0; $i < GETID3_MP3_VALID_CHECK_FRAMES; $i++) {
// check next GETID3_MP3_VALID_CHECK_FRAMES frames for validity, to make sure we haven't run across a false synch
if (($nextframetestoffset + 4) >= $info['avdataend']) {
// end of file
return true;
}
$nextframetestarray = array('error'=>'', 'warning'=>'', 'avdataend'=>$info['avdataend'], 'avdataoffset'=>$info['avdataoffset']);
if ($this->decodeMPEGaudioHeader($nextframetestoffset, $nextframetestarray, false)) {
if ($ScanAsCBR) {
// force CBR mode, used for trying to pick out invalid audio streams with valid(?) VBR headers, or VBR streams with no VBR header
if (!isset($nextframetestarray['mpeg']['audio']['bitrate']) || !isset($firstframetestarray['mpeg']['audio']['bitrate']) || ($nextframetestarray['mpeg']['audio']['bitrate'] != $firstframetestarray['mpeg']['audio']['bitrate'])) {
return false;
}
}
// next frame is OK, get ready to check the one after that
if (isset($nextframetestarray['mpeg']['audio']['framelength']) && ($nextframetestarray['mpeg']['audio']['framelength'] > 0)) {
$nextframetestoffset += $nextframetestarray['mpeg']['audio']['framelength'];
} else {
$info['error'][] = 'Frame at offset ('.$offset.') is has an invalid frame length.';
return false;
}
} elseif (!empty($firstframetestarray['mpeg']['audio']['framelength']) && (($nextframetestoffset + $firstframetestarray['mpeg']['audio']['framelength']) > $info['avdataend'])) {
// it's not the end of the file, but there's not enough data left for another frame, so assume it's garbage/padding and return OK
return true;
} else {
// next frame is not valid, note the error and fail, so scanning can contiue for a valid frame sequence
$info['warning'][] = 'Frame at offset ('.$offset.') is valid, but the next one at ('.$nextframetestoffset.') is not.';
return false;
}
}
return true;
}
public function FreeFormatFrameLength($offset, $deepscan=false) {
$info = &$this->getid3->info;
fseek($this->getid3->fp, $offset, SEEK_SET);
$MPEGaudioData = fread($this->getid3->fp, 32768);
$SyncPattern1 = substr($MPEGaudioData, 0, 4);
// may be different pattern due to padding
$SyncPattern2 = $SyncPattern1{0}.$SyncPattern1{1}.chr(ord($SyncPattern1{2}) | 0x02).$SyncPattern1{3};
if ($SyncPattern2 === $SyncPattern1) {
$SyncPattern2 = $SyncPattern1{0}.$SyncPattern1{1}.chr(ord($SyncPattern1{2}) & 0xFD).$SyncPattern1{3};
}
$framelength = false;
$framelength1 = strpos($MPEGaudioData, $SyncPattern1, 4);
$framelength2 = strpos($MPEGaudioData, $SyncPattern2, 4);
if ($framelength1 > 4) {
$framelength = $framelength1;
}
if (($framelength2 > 4) && ($framelength2 < $framelength1)) {
$framelength = $framelength2;
}
if (!$framelength) {
// LAME 3.88 has a different value for modeextension on the first frame vs the rest
$framelength1 = strpos($MPEGaudioData, substr($SyncPattern1, 0, 3), 4);
$framelength2 = strpos($MPEGaudioData, substr($SyncPattern2, 0, 3), 4);
if ($framelength1 > 4) {
$framelength = $framelength1;
}
if (($framelength2 > 4) && ($framelength2 < $framelength1)) {
$framelength = $framelength2;
}
if (!$framelength) {
$info['error'][] = 'Cannot find next free-format synch pattern ('.getid3_lib::PrintHexBytes($SyncPattern1).' or '.getid3_lib::PrintHexBytes($SyncPattern2).') after offset '.$offset;
return false;
} else {
$info['warning'][] = 'ModeExtension varies between first frame and other frames (known free-format issue in LAME 3.88)';
$info['audio']['codec'] = 'LAME';
$info['audio']['encoder'] = 'LAME3.88';
$SyncPattern1 = substr($SyncPattern1, 0, 3);
$SyncPattern2 = substr($SyncPattern2, 0, 3);
}
}
if ($deepscan) {
$ActualFrameLengthValues = array();
$nextoffset = $offset + $framelength;
while ($nextoffset < ($info['avdataend'] - 6)) {
fseek($this->getid3->fp, $nextoffset - 1, SEEK_SET);
$NextSyncPattern = fread($this->getid3->fp, 6);
if ((substr($NextSyncPattern, 1, strlen($SyncPattern1)) == $SyncPattern1) || (substr($NextSyncPattern, 1, strlen($SyncPattern2)) == $SyncPattern2)) {
// good - found where expected
$ActualFrameLengthValues[] = $framelength;
} elseif ((substr($NextSyncPattern, 0, strlen($SyncPattern1)) == $SyncPattern1) || (substr($NextSyncPattern, 0, strlen($SyncPattern2)) == $SyncPattern2)) {
// ok - found one byte earlier than expected (last frame wasn't padded, first frame was)
$ActualFrameLengthValues[] = ($framelength - 1);
$nextoffset--;
} elseif ((substr($NextSyncPattern, 2, strlen($SyncPattern1)) == $SyncPattern1) || (substr($NextSyncPattern, 2, strlen($SyncPattern2)) == $SyncPattern2)) {
// ok - found one byte later than expected (last frame was padded, first frame wasn't)
$ActualFrameLengthValues[] = ($framelength + 1);
$nextoffset++;
} else {
$info['error'][] = 'Did not find expected free-format sync pattern at offset '.$nextoffset;
return false;
}
$nextoffset += $framelength;
}
if (count($ActualFrameLengthValues) > 0) {
$framelength = intval(round(array_sum($ActualFrameLengthValues) / count($ActualFrameLengthValues)));
}
}
return $framelength;
}
public function getOnlyMPEGaudioInfoBruteForce() {
$MPEGaudioHeaderDecodeCache = array();
$MPEGaudioHeaderValidCache = array();
$MPEGaudioHeaderLengthCache = array();
$MPEGaudioVersionLookup = self::MPEGaudioVersionArray();
$MPEGaudioLayerLookup = self::MPEGaudioLayerArray();
$MPEGaudioBitrateLookup = self::MPEGaudioBitrateArray();
$MPEGaudioFrequencyLookup = self::MPEGaudioFrequencyArray();
$MPEGaudioChannelModeLookup = self::MPEGaudioChannelModeArray();
$MPEGaudioModeExtensionLookup = self::MPEGaudioModeExtensionArray();
$MPEGaudioEmphasisLookup = self::MPEGaudioEmphasisArray();
$LongMPEGversionLookup = array();
$LongMPEGlayerLookup = array();
$LongMPEGbitrateLookup = array();
$LongMPEGpaddingLookup = array();
$LongMPEGfrequencyLookup = array();
$Distribution['bitrate'] = array();
$Distribution['frequency'] = array();
$Distribution['layer'] = array();
$Distribution['version'] = array();
$Distribution['padding'] = array();
$info = &$this->getid3->info;
fseek($this->getid3->fp, $info['avdataoffset'], SEEK_SET);
$max_frames_scan = 5000;
$frames_scanned = 0;
$previousvalidframe = $info['avdataoffset'];
while (ftell($this->getid3->fp) < $info['avdataend']) {
set_time_limit(30);
$head4 = fread($this->getid3->fp, 4);
if (strlen($head4) < 4) {
break;
}
if ($head4{0} != "\xFF") {
for ($i = 1; $i < 4; $i++) {
if ($head4{$i} == "\xFF") {
fseek($this->getid3->fp, $i - 4, SEEK_CUR);
continue 2;
}
}
continue;
}
if (!isset($MPEGaudioHeaderDecodeCache[$head4])) {
$MPEGaudioHeaderDecodeCache[$head4] = self::MPEGaudioHeaderDecode($head4);
}
if (!isset($MPEGaudioHeaderValidCache[$head4])) {
$MPEGaudioHeaderValidCache[$head4] = self::MPEGaudioHeaderValid($MPEGaudioHeaderDecodeCache[$head4], false, false);
}
if ($MPEGaudioHeaderValidCache[$head4]) {
if (!isset($MPEGaudioHeaderLengthCache[$head4])) {
$LongMPEGversionLookup[$head4] = $MPEGaudioVersionLookup[$MPEGaudioHeaderDecodeCache[$head4]['version']];
$LongMPEGlayerLookup[$head4] = $MPEGaudioLayerLookup[$MPEGaudioHeaderDecodeCache[$head4]['layer']];
$LongMPEGbitrateLookup[$head4] = $MPEGaudioBitrateLookup[$LongMPEGversionLookup[$head4]][$LongMPEGlayerLookup[$head4]][$MPEGaudioHeaderDecodeCache[$head4]['bitrate']];
$LongMPEGpaddingLookup[$head4] = (bool) $MPEGaudioHeaderDecodeCache[$head4]['padding'];
$LongMPEGfrequencyLookup[$head4] = $MPEGaudioFrequencyLookup[$LongMPEGversionLookup[$head4]][$MPEGaudioHeaderDecodeCache[$head4]['sample_rate']];
$MPEGaudioHeaderLengthCache[$head4] = self::MPEGaudioFrameLength(
$LongMPEGbitrateLookup[$head4],
$LongMPEGversionLookup[$head4],
$LongMPEGlayerLookup[$head4],
$LongMPEGpaddingLookup[$head4],
$LongMPEGfrequencyLookup[$head4]);
}
if ($MPEGaudioHeaderLengthCache[$head4] > 4) {
$WhereWeWere = ftell($this->getid3->fp);
fseek($this->getid3->fp, $MPEGaudioHeaderLengthCache[$head4] - 4, SEEK_CUR);
$next4 = fread($this->getid3->fp, 4);
if ($next4{0} == "\xFF") {
if (!isset($MPEGaudioHeaderDecodeCache[$next4])) {
$MPEGaudioHeaderDecodeCache[$next4] = self::MPEGaudioHeaderDecode($next4);
}
if (!isset($MPEGaudioHeaderValidCache[$next4])) {
$MPEGaudioHeaderValidCache[$next4] = self::MPEGaudioHeaderValid($MPEGaudioHeaderDecodeCache[$next4], false, false);
}
if ($MPEGaudioHeaderValidCache[$next4]) {
fseek($this->getid3->fp, -4, SEEK_CUR);
getid3_lib::safe_inc($Distribution['bitrate'][$LongMPEGbitrateLookup[$head4]]);
getid3_lib::safe_inc($Distribution['layer'][$LongMPEGlayerLookup[$head4]]);
getid3_lib::safe_inc($Distribution['version'][$LongMPEGversionLookup[$head4]]);
getid3_lib::safe_inc($Distribution['padding'][intval($LongMPEGpaddingLookup[$head4])]);
getid3_lib::safe_inc($Distribution['frequency'][$LongMPEGfrequencyLookup[$head4]]);
if ($max_frames_scan && (++$frames_scanned >= $max_frames_scan)) {
$pct_data_scanned = (ftell($this->getid3->fp) - $info['avdataoffset']) / ($info['avdataend'] - $info['avdataoffset']);
$info['warning'][] = 'too many MPEG audio frames to scan, only scanned first '.$max_frames_scan.' frames ('.number_format($pct_data_scanned * 100, 1).'% of file) and extrapolated distribution, playtime and bitrate may be incorrect.';
foreach ($Distribution as $key1 => $value1) {
foreach ($value1 as $key2 => $value2) {
$Distribution[$key1][$key2] = round($value2 / $pct_data_scanned);
}
}
break;
}
continue;
}
}
unset($next4);
fseek($this->getid3->fp, $WhereWeWere - 3, SEEK_SET);
}
}
}
foreach ($Distribution as $key => $value) {
ksort($Distribution[$key], SORT_NUMERIC);
}
ksort($Distribution['version'], SORT_STRING);
$info['mpeg']['audio']['bitrate_distribution'] = $Distribution['bitrate'];
$info['mpeg']['audio']['frequency_distribution'] = $Distribution['frequency'];
$info['mpeg']['audio']['layer_distribution'] = $Distribution['layer'];
$info['mpeg']['audio']['version_distribution'] = $Distribution['version'];
$info['mpeg']['audio']['padding_distribution'] = $Distribution['padding'];
if (count($Distribution['version']) > 1) {
$info['error'][] = 'Corrupt file - more than one MPEG version detected';
}
if (count($Distribution['layer']) > 1) {
$info['error'][] = 'Corrupt file - more than one MPEG layer detected';
}
if (count($Distribution['frequency']) > 1) {
$info['error'][] = 'Corrupt file - more than one MPEG sample rate detected';
}
$bittotal = 0;
foreach ($Distribution['bitrate'] as $bitratevalue => $bitratecount) {
if ($bitratevalue != 'free') {
$bittotal += ($bitratevalue * $bitratecount);
}
}
$info['mpeg']['audio']['frame_count'] = array_sum($Distribution['bitrate']);
if ($info['mpeg']['audio']['frame_count'] == 0) {
$info['error'][] = 'no MPEG audio frames found';
return false;
}
$info['mpeg']['audio']['bitrate'] = ($bittotal / $info['mpeg']['audio']['frame_count']);
$info['mpeg']['audio']['bitrate_mode'] = ((count($Distribution['bitrate']) > 0) ? 'vbr' : 'cbr');
$info['mpeg']['audio']['sample_rate'] = getid3_lib::array_max($Distribution['frequency'], true);
$info['audio']['bitrate'] = $info['mpeg']['audio']['bitrate'];
$info['audio']['bitrate_mode'] = $info['mpeg']['audio']['bitrate_mode'];
$info['audio']['sample_rate'] = $info['mpeg']['audio']['sample_rate'];
$info['audio']['dataformat'] = 'mp'.getid3_lib::array_max($Distribution['layer'], true);
$info['fileformat'] = $info['audio']['dataformat'];
return true;
}
public function getOnlyMPEGaudioInfo($avdataoffset, $BitrateHistogram=false) {
// looks for synch, decodes MPEG audio header
$info = &$this->getid3->info;
static $MPEGaudioVersionLookup;
static $MPEGaudioLayerLookup;
static $MPEGaudioBitrateLookup;
if (empty($MPEGaudioVersionLookup)) {
$MPEGaudioVersionLookup = self::MPEGaudioVersionArray();
$MPEGaudioLayerLookup = self::MPEGaudioLayerArray();
$MPEGaudioBitrateLookup = self::MPEGaudioBitrateArray();
}
fseek($this->getid3->fp, $avdataoffset, SEEK_SET);
$sync_seek_buffer_size = min(128 * 1024, $info['avdataend'] - $avdataoffset);
if ($sync_seek_buffer_size <= 0) {
$info['error'][] = 'Invalid $sync_seek_buffer_size at offset '.$avdataoffset;
return false;
}
$header = fread($this->getid3->fp, $sync_seek_buffer_size);
$sync_seek_buffer_size = strlen($header);
$SynchSeekOffset = 0;
while ($SynchSeekOffset < $sync_seek_buffer_size) {
if ((($avdataoffset + $SynchSeekOffset) < $info['avdataend']) && !feof($this->getid3->fp)) {
if ($SynchSeekOffset > $sync_seek_buffer_size) {
// if a synch's not found within the first 128k bytes, then give up
$info['error'][] = 'Could not find valid MPEG audio synch within the first '.round($sync_seek_buffer_size / 1024).'kB';
if (isset($info['audio']['bitrate'])) {
unset($info['audio']['bitrate']);
}
if (isset($info['mpeg']['audio'])) {
unset($info['mpeg']['audio']);
}
if (empty($info['mpeg'])) {
unset($info['mpeg']);
}
return false;
} elseif (feof($this->getid3->fp)) {
$info['error'][] = 'Could not find valid MPEG audio synch before end of file';
if (isset($info['audio']['bitrate'])) {
unset($info['audio']['bitrate']);
}
if (isset($info['mpeg']['audio'])) {
unset($info['mpeg']['audio']);
}
if (isset($info['mpeg']) && (!is_array($info['mpeg']) || (count($info['mpeg']) == 0))) {
unset($info['mpeg']);
}
return false;
}
}
if (($SynchSeekOffset + 1) >= strlen($header)) {
$info['error'][] = 'Could not find valid MPEG synch before end of file';
return false;
}
if (($header{$SynchSeekOffset} == "\xFF") && ($header{($SynchSeekOffset + 1)} > "\xE0")) { // synch detected
if (!isset($FirstFrameThisfileInfo) && !isset($info['mpeg']['audio'])) {
$FirstFrameThisfileInfo = $info;
$FirstFrameAVDataOffset = $avdataoffset + $SynchSeekOffset;
if (!$this->decodeMPEGaudioHeader($FirstFrameAVDataOffset, $FirstFrameThisfileInfo, false)) {
// if this is the first valid MPEG-audio frame, save it in case it's a VBR header frame and there's
// garbage between this frame and a valid sequence of MPEG-audio frames, to be restored below
unset($FirstFrameThisfileInfo);
}
}
$dummy = $info; // only overwrite real data if valid header found
if ($this->decodeMPEGaudioHeader($avdataoffset + $SynchSeekOffset, $dummy, true)) {
$info = $dummy;
$info['avdataoffset'] = $avdataoffset + $SynchSeekOffset;
switch (isset($info['fileformat']) ? $info['fileformat'] : '') {
case '':
case 'id3':
case 'ape':
case 'mp3':
$info['fileformat'] = 'mp3';
$info['audio']['dataformat'] = 'mp3';
break;
}
if (isset($FirstFrameThisfileInfo['mpeg']['audio']['bitrate_mode']) && ($FirstFrameThisfileInfo['mpeg']['audio']['bitrate_mode'] == 'vbr')) {
if (!(abs($info['audio']['bitrate'] - $FirstFrameThisfileInfo['audio']['bitrate']) <= 1)) {
// If there is garbage data between a valid VBR header frame and a sequence
// of valid MPEG-audio frames the VBR data is no longer discarded.
$info = $FirstFrameThisfileInfo;
$info['avdataoffset'] = $FirstFrameAVDataOffset;
$info['fileformat'] = 'mp3';
$info['audio']['dataformat'] = 'mp3';
$dummy = $info;
unset($dummy['mpeg']['audio']);
$GarbageOffsetStart = $FirstFrameAVDataOffset + $FirstFrameThisfileInfo['mpeg']['audio']['framelength'];
$GarbageOffsetEnd = $avdataoffset + $SynchSeekOffset;
if ($this->decodeMPEGaudioHeader($GarbageOffsetEnd, $dummy, true, true)) {
$info = $dummy;
$info['avdataoffset'] = $GarbageOffsetEnd;
$info['warning'][] = 'apparently-valid VBR header not used because could not find '.GETID3_MP3_VALID_CHECK_FRAMES.' consecutive MPEG-audio frames immediately after VBR header (garbage data for '.($GarbageOffsetEnd - $GarbageOffsetStart).' bytes between '.$GarbageOffsetStart.' and '.$GarbageOffsetEnd.'), but did find valid CBR stream starting at '.$GarbageOffsetEnd;
} else {
$info['warning'][] = 'using data from VBR header even though could not find '.GETID3_MP3_VALID_CHECK_FRAMES.' consecutive MPEG-audio frames immediately after VBR header (garbage data for '.($GarbageOffsetEnd - $GarbageOffsetStart).' bytes between '.$GarbageOffsetStart.' and '.$GarbageOffsetEnd.')';
}
}
}
if (isset($info['mpeg']['audio']['bitrate_mode']) && ($info['mpeg']['audio']['bitrate_mode'] == 'vbr') && !isset($info['mpeg']['audio']['VBR_method'])) {
// VBR file with no VBR header
$BitrateHistogram = true;
}
if ($BitrateHistogram) {
$info['mpeg']['audio']['stereo_distribution'] = array('stereo'=>0, 'joint stereo'=>0, 'dual channel'=>0, 'mono'=>0);
$info['mpeg']['audio']['version_distribution'] = array('1'=>0, '2'=>0, '2.5'=>0);
if ($info['mpeg']['audio']['version'] == '1') {
if ($info['mpeg']['audio']['layer'] == 3) {
$info['mpeg']['audio']['bitrate_distribution'] = array('free'=>0, 32000=>0, 40000=>0, 48000=>0, 56000=>0, 64000=>0, 80000=>0, 96000=>0, 112000=>0, 128000=>0, 160000=>0, 192000=>0, 224000=>0, 256000=>0, 320000=>0);
} elseif ($info['mpeg']['audio']['layer'] == 2) {
$info['mpeg']['audio']['bitrate_distribution'] = array('free'=>0, 32000=>0, 48000=>0, 56000=>0, 64000=>0, 80000=>0, 96000=>0, 112000=>0, 128000=>0, 160000=>0, 192000=>0, 224000=>0, 256000=>0, 320000=>0, 384000=>0);
} elseif ($info['mpeg']['audio']['layer'] == 1) {
$info['mpeg']['audio']['bitrate_distribution'] = array('free'=>0, 32000=>0, 64000=>0, 96000=>0, 128000=>0, 160000=>0, 192000=>0, 224000=>0, 256000=>0, 288000=>0, 320000=>0, 352000=>0, 384000=>0, 416000=>0, 448000=>0);
}
} elseif ($info['mpeg']['audio']['layer'] == 1) {
$info['mpeg']['audio']['bitrate_distribution'] = array('free'=>0, 32000=>0, 48000=>0, 56000=>0, 64000=>0, 80000=>0, 96000=>0, 112000=>0, 128000=>0, 144000=>0, 160000=>0, 176000=>0, 192000=>0, 224000=>0, 256000=>0);
} else {
$info['mpeg']['audio']['bitrate_distribution'] = array('free'=>0, 8000=>0, 16000=>0, 24000=>0, 32000=>0, 40000=>0, 48000=>0, 56000=>0, 64000=>0, 80000=>0, 96000=>0, 112000=>0, 128000=>0, 144000=>0, 160000=>0);
}
$dummy = array('error'=>$info['error'], 'warning'=>$info['warning'], 'avdataend'=>$info['avdataend'], 'avdataoffset'=>$info['avdataoffset']);
$synchstartoffset = $info['avdataoffset'];
fseek($this->getid3->fp, $info['avdataoffset'], SEEK_SET);
// you can play with these numbers:
$max_frames_scan = 50000;
$max_scan_segments = 10;
// don't play with these numbers:
$FastMode = false;
$SynchErrorsFound = 0;
$frames_scanned = 0;
$this_scan_segment = 0;
$frames_scan_per_segment = ceil($max_frames_scan / $max_scan_segments);
$pct_data_scanned = 0;
for ($current_segment = 0; $current_segment < $max_scan_segments; $current_segment++) {
$frames_scanned_this_segment = 0;
if (ftell($this->getid3->fp) >= $info['avdataend']) {
break;
}
$scan_start_offset[$current_segment] = max(ftell($this->getid3->fp), $info['avdataoffset'] + round($current_segment * (($info['avdataend'] - $info['avdataoffset']) / $max_scan_segments)));
if ($current_segment > 0) {
fseek($this->getid3->fp, $scan_start_offset[$current_segment], SEEK_SET);
$buffer_4k = fread($this->getid3->fp, 4096);
for ($j = 0; $j < (strlen($buffer_4k) - 4); $j++) {
if (($buffer_4k{$j} == "\xFF") && ($buffer_4k{($j + 1)} > "\xE0")) { // synch detected
if ($this->decodeMPEGaudioHeader($scan_start_offset[$current_segment] + $j, $dummy, false, false, $FastMode)) {
$calculated_next_offset = $scan_start_offset[$current_segment] + $j + $dummy['mpeg']['audio']['framelength'];
if ($this->decodeMPEGaudioHeader($calculated_next_offset, $dummy, false, false, $FastMode)) {
$scan_start_offset[$current_segment] += $j;
break;
}
}
}
}
}
$synchstartoffset = $scan_start_offset[$current_segment];
while ($this->decodeMPEGaudioHeader($synchstartoffset, $dummy, false, false, $FastMode)) {
$FastMode = true;
$thisframebitrate = $MPEGaudioBitrateLookup[$MPEGaudioVersionLookup[$dummy['mpeg']['audio']['raw']['version']]][$MPEGaudioLayerLookup[$dummy['mpeg']['audio']['raw']['layer']]][$dummy['mpeg']['audio']['raw']['bitrate']];
if (empty($dummy['mpeg']['audio']['framelength'])) {
$SynchErrorsFound++;
$synchstartoffset++;
} else {
getid3_lib::safe_inc($info['mpeg']['audio']['bitrate_distribution'][$thisframebitrate]);
getid3_lib::safe_inc($info['mpeg']['audio']['stereo_distribution'][$dummy['mpeg']['audio']['channelmode']]);
getid3_lib::safe_inc($info['mpeg']['audio']['version_distribution'][$dummy['mpeg']['audio']['version']]);
$synchstartoffset += $dummy['mpeg']['audio']['framelength'];
}
$frames_scanned++;
if ($frames_scan_per_segment && (++$frames_scanned_this_segment >= $frames_scan_per_segment)) {
$this_pct_scanned = (ftell($this->getid3->fp) - $scan_start_offset[$current_segment]) / ($info['avdataend'] - $info['avdataoffset']);
if (($current_segment == 0) && (($this_pct_scanned * $max_scan_segments) >= 1)) {
// file likely contains < $max_frames_scan, just scan as one segment
$max_scan_segments = 1;
$frames_scan_per_segment = $max_frames_scan;
} else {
$pct_data_scanned += $this_pct_scanned;
break;
}
}
}
}
if ($pct_data_scanned > 0) {
$info['warning'][] = 'too many MPEG audio frames to scan, only scanned '.$frames_scanned.' frames in '.$max_scan_segments.' segments ('.number_format($pct_data_scanned * 100, 1).'% of file) and extrapolated distribution, playtime and bitrate may be incorrect.';
foreach ($info['mpeg']['audio'] as $key1 => $value1) {
if (!preg_match('#_distribution$#i', $key1)) {
continue;
}
foreach ($value1 as $key2 => $value2) {
$info['mpeg']['audio'][$key1][$key2] = round($value2 / $pct_data_scanned);
}
}
}
if ($SynchErrorsFound > 0) {
$info['warning'][] = 'Found '.$SynchErrorsFound.' synch errors in histogram analysis';
//return false;
}
$bittotal = 0;
$framecounter = 0;
foreach ($info['mpeg']['audio']['bitrate_distribution'] as $bitratevalue => $bitratecount) {
$framecounter += $bitratecount;
if ($bitratevalue != 'free') {
$bittotal += ($bitratevalue * $bitratecount);
}
}
if ($framecounter == 0) {
$info['error'][] = 'Corrupt MP3 file: framecounter == zero';
return false;
}
$info['mpeg']['audio']['frame_count'] = getid3_lib::CastAsInt($framecounter);
$info['mpeg']['audio']['bitrate'] = ($bittotal / $framecounter);
$info['audio']['bitrate'] = $info['mpeg']['audio']['bitrate'];
// Definitively set VBR vs CBR, even if the Xing/LAME/VBRI header says differently
$distinct_bitrates = 0;
foreach ($info['mpeg']['audio']['bitrate_distribution'] as $bitrate_value => $bitrate_count) {
if ($bitrate_count > 0) {
$distinct_bitrates++;
}
}
if ($distinct_bitrates > 1) {
$info['mpeg']['audio']['bitrate_mode'] = 'vbr';
} else {
$info['mpeg']['audio']['bitrate_mode'] = 'cbr';
}
$info['audio']['bitrate_mode'] = $info['mpeg']['audio']['bitrate_mode'];
}
break; // exit while()
}
}
$SynchSeekOffset++;
if (($avdataoffset + $SynchSeekOffset) >= $info['avdataend']) {
// end of file/data
if (empty($info['mpeg']['audio'])) {
$info['error'][] = 'could not find valid MPEG synch before end of file';
if (isset($info['audio']['bitrate'])) {
unset($info['audio']['bitrate']);
}
if (isset($info['mpeg']['audio'])) {
unset($info['mpeg']['audio']);
}
if (isset($info['mpeg']) && (!is_array($info['mpeg']) || empty($info['mpeg']))) {
unset($info['mpeg']);
}
return false;
}
break;
}
}
$info['audio']['channels'] = $info['mpeg']['audio']['channels'];
$info['audio']['channelmode'] = $info['mpeg']['audio']['channelmode'];
$info['audio']['sample_rate'] = $info['mpeg']['audio']['sample_rate'];
return true;
}
public static function MPEGaudioVersionArray() {
static $MPEGaudioVersion = array('2.5', false, '2', '1');
return $MPEGaudioVersion;
}
public static function MPEGaudioLayerArray() {
static $MPEGaudioLayer = array(false, 3, 2, 1);
return $MPEGaudioLayer;
}
public static function MPEGaudioBitrateArray() {
static $MPEGaudioBitrate;
if (empty($MPEGaudioBitrate)) {
$MPEGaudioBitrate = array (
'1' => array (1 => array('free', 32000, 64000, 96000, 128000, 160000, 192000, 224000, 256000, 288000, 320000, 352000, 384000, 416000, 448000),
2 => array('free', 32000, 48000, 56000, 64000, 80000, 96000, 112000, 128000, 160000, 192000, 224000, 256000, 320000, 384000),
3 => array('free', 32000, 40000, 48000, 56000, 64000, 80000, 96000, 112000, 128000, 160000, 192000, 224000, 256000, 320000)
),
'2' => array (1 => array('free', 32000, 48000, 56000, 64000, 80000, 96000, 112000, 128000, 144000, 160000, 176000, 192000, 224000, 256000),
2 => array('free', 8000, 16000, 24000, 32000, 40000, 48000, 56000, 64000, 80000, 96000, 112000, 128000, 144000, 160000),
)
);
$MPEGaudioBitrate['2'][3] = $MPEGaudioBitrate['2'][2];
$MPEGaudioBitrate['2.5'] = $MPEGaudioBitrate['2'];
}
return $MPEGaudioBitrate;
}
public static function MPEGaudioFrequencyArray() {
static $MPEGaudioFrequency;
if (empty($MPEGaudioFrequency)) {
$MPEGaudioFrequency = array (
'1' => array(44100, 48000, 32000),
'2' => array(22050, 24000, 16000),
'2.5' => array(11025, 12000, 8000)
);
}
return $MPEGaudioFrequency;
}
public static function MPEGaudioChannelModeArray() {
static $MPEGaudioChannelMode = array('stereo', 'joint stereo', 'dual channel', 'mono');
return $MPEGaudioChannelMode;
}
public static function MPEGaudioModeExtensionArray() {
static $MPEGaudioModeExtension;
if (empty($MPEGaudioModeExtension)) {
$MPEGaudioModeExtension = array (
1 => array('4-31', '8-31', '12-31', '16-31'),
2 => array('4-31', '8-31', '12-31', '16-31'),
3 => array('', 'IS', 'MS', 'IS+MS')
);
}
return $MPEGaudioModeExtension;
}
public static function MPEGaudioEmphasisArray() {
static $MPEGaudioEmphasis = array('none', '50/15ms', false, 'CCIT J.17');
return $MPEGaudioEmphasis;
}
public static function MPEGaudioHeaderBytesValid($head4, $allowBitrate15=false) {
return self::MPEGaudioHeaderValid(self::MPEGaudioHeaderDecode($head4), false, $allowBitrate15);
}
public static function MPEGaudioHeaderValid($rawarray, $echoerrors=false, $allowBitrate15=false) {
if (($rawarray['synch'] & 0x0FFE) != 0x0FFE) {
return false;
}
static $MPEGaudioVersionLookup;
static $MPEGaudioLayerLookup;
static $MPEGaudioBitrateLookup;
static $MPEGaudioFrequencyLookup;
static $MPEGaudioChannelModeLookup;
static $MPEGaudioModeExtensionLookup;
static $MPEGaudioEmphasisLookup;
if (empty($MPEGaudioVersionLookup)) {
$MPEGaudioVersionLookup = self::MPEGaudioVersionArray();
$MPEGaudioLayerLookup = self::MPEGaudioLayerArray();
$MPEGaudioBitrateLookup = self::MPEGaudioBitrateArray();
$MPEGaudioFrequencyLookup = self::MPEGaudioFrequencyArray();
$MPEGaudioChannelModeLookup = self::MPEGaudioChannelModeArray();
$MPEGaudioModeExtensionLookup = self::MPEGaudioModeExtensionArray();
$MPEGaudioEmphasisLookup = self::MPEGaudioEmphasisArray();
}
if (isset($MPEGaudioVersionLookup[$rawarray['version']])) {
$decodedVersion = $MPEGaudioVersionLookup[$rawarray['version']];
} else {
echo ($echoerrors ? "\n".'invalid Version ('.$rawarray['version'].')' : '');
return false;
}
if (isset($MPEGaudioLayerLookup[$rawarray['layer']])) {
$decodedLayer = $MPEGaudioLayerLookup[$rawarray['layer']];
} else {
echo ($echoerrors ? "\n".'invalid Layer ('.$rawarray['layer'].')' : '');
return false;
}
if (!isset($MPEGaudioBitrateLookup[$decodedVersion][$decodedLayer][$rawarray['bitrate']])) {
echo ($echoerrors ? "\n".'invalid Bitrate ('.$rawarray['bitrate'].')' : '');
if ($rawarray['bitrate'] == 15) {
// known issue in LAME 3.90 - 3.93.1 where free-format has bitrate ID of 15 instead of 0
// let it go through here otherwise file will not be identified
if (!$allowBitrate15) {
return false;
}
} else {
return false;
}
}
if (!isset($MPEGaudioFrequencyLookup[$decodedVersion][$rawarray['sample_rate']])) {
echo ($echoerrors ? "\n".'invalid Frequency ('.$rawarray['sample_rate'].')' : '');
return false;
}
if (!isset($MPEGaudioChannelModeLookup[$rawarray['channelmode']])) {
echo ($echoerrors ? "\n".'invalid ChannelMode ('.$rawarray['channelmode'].')' : '');
return false;
}
if (!isset($MPEGaudioModeExtensionLookup[$decodedLayer][$rawarray['modeextension']])) {
echo ($echoerrors ? "\n".'invalid Mode Extension ('.$rawarray['modeextension'].')' : '');
return false;
}
if (!isset($MPEGaudioEmphasisLookup[$rawarray['emphasis']])) {
echo ($echoerrors ? "\n".'invalid Emphasis ('.$rawarray['emphasis'].')' : '');
return false;
}
// These are just either set or not set, you can't mess that up :)
// $rawarray['protection'];
// $rawarray['padding'];
// $rawarray['private'];
// $rawarray['copyright'];
// $rawarray['original'];
return true;
}
public static function MPEGaudioHeaderDecode($Header4Bytes) {
// AAAA AAAA AAAB BCCD EEEE FFGH IIJJ KLMM
// A - Frame sync (all bits set)
// B - MPEG Audio version ID
// C - Layer description
// D - Protection bit
// E - Bitrate index
// F - Sampling rate frequency index
// G - Padding bit
// H - Private bit
// I - Channel Mode
// J - Mode extension (Only if Joint stereo)
// K - Copyright
// L - Original
// M - Emphasis
if (strlen($Header4Bytes) != 4) {
return false;
}
$MPEGrawHeader['synch'] = (getid3_lib::BigEndian2Int(substr($Header4Bytes, 0, 2)) & 0xFFE0) >> 4;
$MPEGrawHeader['version'] = (ord($Header4Bytes{1}) & 0x18) >> 3; // BB
$MPEGrawHeader['layer'] = (ord($Header4Bytes{1}) & 0x06) >> 1; // CC
$MPEGrawHeader['protection'] = (ord($Header4Bytes{1}) & 0x01); // D
$MPEGrawHeader['bitrate'] = (ord($Header4Bytes{2}) & 0xF0) >> 4; // EEEE
$MPEGrawHeader['sample_rate'] = (ord($Header4Bytes{2}) & 0x0C) >> 2; // FF
$MPEGrawHeader['padding'] = (ord($Header4Bytes{2}) & 0x02) >> 1; // G
$MPEGrawHeader['private'] = (ord($Header4Bytes{2}) & 0x01); // H
$MPEGrawHeader['channelmode'] = (ord($Header4Bytes{3}) & 0xC0) >> 6; // II
$MPEGrawHeader['modeextension'] = (ord($Header4Bytes{3}) & 0x30) >> 4; // JJ
$MPEGrawHeader['copyright'] = (ord($Header4Bytes{3}) & 0x08) >> 3; // K
$MPEGrawHeader['original'] = (ord($Header4Bytes{3}) & 0x04) >> 2; // L
$MPEGrawHeader['emphasis'] = (ord($Header4Bytes{3}) & 0x03); // MM
return $MPEGrawHeader;
}
public static function MPEGaudioFrameLength(&$bitrate, &$version, &$layer, $padding, &$samplerate) {
static $AudioFrameLengthCache = array();
if (!isset($AudioFrameLengthCache[$bitrate][$version][$layer][$padding][$samplerate])) {
$AudioFrameLengthCache[$bitrate][$version][$layer][$padding][$samplerate] = false;
if ($bitrate != 'free') {
if ($version == '1') {
if ($layer == '1') {
// For Layer I slot is 32 bits long
$FrameLengthCoefficient = 48;
$SlotLength = 4;
} else { // Layer 2 / 3
// for Layer 2 and Layer 3 slot is 8 bits long.
$FrameLengthCoefficient = 144;
$SlotLength = 1;
}
} else { // MPEG-2 / MPEG-2.5
if ($layer == '1') {
// For Layer I slot is 32 bits long
$FrameLengthCoefficient = 24;
$SlotLength = 4;
} elseif ($layer == '2') {
// for Layer 2 and Layer 3 slot is 8 bits long.
$FrameLengthCoefficient = 144;
$SlotLength = 1;
} else { // layer 3
// for Layer 2 and Layer 3 slot is 8 bits long.
$FrameLengthCoefficient = 72;
$SlotLength = 1;
}
}
// FrameLengthInBytes = ((Coefficient * BitRate) / SampleRate) + Padding
if ($samplerate > 0) {
$NewFramelength = ($FrameLengthCoefficient * $bitrate) / $samplerate;
$NewFramelength = floor($NewFramelength / $SlotLength) * $SlotLength; // round to next-lower multiple of SlotLength (1 byte for Layer 2/3, 4 bytes for Layer I)
if ($padding) {
$NewFramelength += $SlotLength;
}
$AudioFrameLengthCache[$bitrate][$version][$layer][$padding][$samplerate] = (int) $NewFramelength;
}
}
}
return $AudioFrameLengthCache[$bitrate][$version][$layer][$padding][$samplerate];
}
public static function ClosestStandardMP3Bitrate($bit_rate) {
static $standard_bit_rates = array (320000, 256000, 224000, 192000, 160000, 128000, 112000, 96000, 80000, 64000, 56000, 48000, 40000, 32000, 24000, 16000, 8000);
static $bit_rate_table = array (0=>'-');
$round_bit_rate = intval(round($bit_rate, -3));
if (!isset($bit_rate_table[$round_bit_rate])) {
if ($round_bit_rate > max($standard_bit_rates)) {
$bit_rate_table[$round_bit_rate] = round($bit_rate, 2 - strlen($bit_rate));
} else {
$bit_rate_table[$round_bit_rate] = max($standard_bit_rates);
foreach ($standard_bit_rates as $standard_bit_rate) {
if ($round_bit_rate >= $standard_bit_rate + (($bit_rate_table[$round_bit_rate] - $standard_bit_rate) / 2)) {
break;
}
$bit_rate_table[$round_bit_rate] = $standard_bit_rate;
}
}
}
return $bit_rate_table[$round_bit_rate];
}
public static function XingVBRidOffset($version, $channelmode) {
static $XingVBRidOffsetCache = array();
if (empty($XingVBRidOffset)) {
$XingVBRidOffset = array (
'1' => array ('mono' => 0x15, // 4 + 17 = 21
'stereo' => 0x24, // 4 + 32 = 36
'joint stereo' => 0x24,
'dual channel' => 0x24
),
'2' => array ('mono' => 0x0D, // 4 + 9 = 13
'stereo' => 0x15, // 4 + 17 = 21
'joint stereo' => 0x15,
'dual channel' => 0x15
),
'2.5' => array ('mono' => 0x15,
'stereo' => 0x15,
'joint stereo' => 0x15,
'dual channel' => 0x15
)
);
}
return $XingVBRidOffset[$version][$channelmode];
}
public static function LAMEvbrMethodLookup($VBRmethodID) {
static $LAMEvbrMethodLookup = array(
0x00 => 'unknown',
0x01 => 'cbr',
0x02 => 'abr',
0x03 => 'vbr-old / vbr-rh',
0x04 => 'vbr-new / vbr-mtrh',
0x05 => 'vbr-mt',
0x06 => 'vbr (full vbr method 4)',
0x08 => 'cbr (constant bitrate 2 pass)',
0x09 => 'abr (2 pass)',
0x0F => 'reserved'
);
return (isset($LAMEvbrMethodLookup[$VBRmethodID]) ? $LAMEvbrMethodLookup[$VBRmethodID] : '');
}
public static function LAMEmiscStereoModeLookup($StereoModeID) {
static $LAMEmiscStereoModeLookup = array(
0 => 'mono',
1 => 'stereo',
2 => 'dual mono',
3 => 'joint stereo',
4 => 'forced stereo',
5 => 'auto',
6 => 'intensity stereo',
7 => 'other'
);
return (isset($LAMEmiscStereoModeLookup[$StereoModeID]) ? $LAMEmiscStereoModeLookup[$StereoModeID] : '');
}
public static function LAMEmiscSourceSampleFrequencyLookup($SourceSampleFrequencyID) {
static $LAMEmiscSourceSampleFrequencyLookup = array(
0 => '<= 32 kHz',
1 => '44.1 kHz',
2 => '48 kHz',
3 => '> 48kHz'
);
return (isset($LAMEmiscSourceSampleFrequencyLookup[$SourceSampleFrequencyID]) ? $LAMEmiscSourceSampleFrequencyLookup[$SourceSampleFrequencyID] : '');
}
public static function LAMEsurroundInfoLookup($SurroundInfoID) {
static $LAMEsurroundInfoLookup = array(
0 => 'no surround info',
1 => 'DPL encoding',
2 => 'DPL2 encoding',
3 => 'Ambisonic encoding'
);
return (isset($LAMEsurroundInfoLookup[$SurroundInfoID]) ? $LAMEsurroundInfoLookup[$SurroundInfoID] : 'reserved');
}
public static function LAMEpresetUsedLookup($LAMEtag) {
if ($LAMEtag['preset_used_id'] == 0) {
// no preset used (LAME >=3.93)
// no preset recorded (LAME <3.93)
return '';
}
$LAMEpresetUsedLookup = array();
///// THIS PART CANNOT BE STATIC .
for ($i = 8; $i <= 320; $i++) {
switch ($LAMEtag['vbr_method']) {
case 'cbr':
$LAMEpresetUsedLookup[$i] = '--alt-preset '.$LAMEtag['vbr_method'].' '.$i;
break;
case 'abr':
default: // other VBR modes shouldn't be here(?)
$LAMEpresetUsedLookup[$i] = '--alt-preset '.$i;
break;
}
}
// named old-style presets (studio, phone, voice, etc) are handled in GuessEncoderOptions()
// named alt-presets
$LAMEpresetUsedLookup[1000] = '--r3mix';
$LAMEpresetUsedLookup[1001] = '--alt-preset standard';
$LAMEpresetUsedLookup[1002] = '--alt-preset extreme';
$LAMEpresetUsedLookup[1003] = '--alt-preset insane';
$LAMEpresetUsedLookup[1004] = '--alt-preset fast standard';
$LAMEpresetUsedLookup[1005] = '--alt-preset fast extreme';
$LAMEpresetUsedLookup[1006] = '--alt-preset medium';
$LAMEpresetUsedLookup[1007] = '--alt-preset fast medium';
// LAME 3.94 additions/changes
$LAMEpresetUsedLookup[1010] = '--preset portable'; // 3.94a15 Oct 21 2003
$LAMEpresetUsedLookup[1015] = '--preset radio'; // 3.94a15 Oct 21 2003
$LAMEpresetUsedLookup[320] = '--preset insane'; // 3.94a15 Nov 12 2003
$LAMEpresetUsedLookup[410] = '-V9';
$LAMEpresetUsedLookup[420] = '-V8';
$LAMEpresetUsedLookup[440] = '-V6';
$LAMEpresetUsedLookup[430] = '--preset radio'; // 3.94a15 Nov 12 2003
$LAMEpresetUsedLookup[450] = '--preset '.(($LAMEtag['raw']['vbr_method'] == 4) ? 'fast ' : '').'portable'; // 3.94a15 Nov 12 2003
$LAMEpresetUsedLookup[460] = '--preset '.(($LAMEtag['raw']['vbr_method'] == 4) ? 'fast ' : '').'medium'; // 3.94a15 Nov 12 2003
$LAMEpresetUsedLookup[470] = '--r3mix'; // 3.94b1 Dec 18 2003
$LAMEpresetUsedLookup[480] = '--preset '.(($LAMEtag['raw']['vbr_method'] == 4) ? 'fast ' : '').'standard'; // 3.94a15 Nov 12 2003
$LAMEpresetUsedLookup[490] = '-V1';
$LAMEpresetUsedLookup[500] = '--preset '.(($LAMEtag['raw']['vbr_method'] == 4) ? 'fast ' : '').'extreme'; // 3.94a15 Nov 12 2003
return (isset($LAMEpresetUsedLookup[$LAMEtag['preset_used_id']]) ? $LAMEpresetUsedLookup[$LAMEtag['preset_used_id']] : 'new/unknown preset: '.$LAMEtag['preset_used_id'].' - report to info@getid3.org');
}
}
| PHP |
<?php
/////////////////////////////////////////////////////////////////
/// getID3() by James Heinrich <info@getid3.org> //
// available at http://getid3.sourceforge.net //
// or http://www.getid3.org //
/////////////////////////////////////////////////////////////////
// //
// getid3.lib.php - part of getID3() //
// See readme.txt for more details //
// ///
/////////////////////////////////////////////////////////////////
class getid3_lib
{
public static function PrintHexBytes($string, $hex=true, $spaces=true, $htmlencoding='UTF-8') {
$returnstring = '';
for ($i = 0; $i < strlen($string); $i++) {
if ($hex) {
$returnstring .= str_pad(dechex(ord($string{$i})), 2, '0', STR_PAD_LEFT);
} else {
$returnstring .= ' '.(preg_match("#[\x20-\x7E]#", $string{$i}) ? $string{$i} : '¤');
}
if ($spaces) {
$returnstring .= ' ';
}
}
if (!empty($htmlencoding)) {
if ($htmlencoding === true) {
$htmlencoding = 'UTF-8'; // prior to getID3 v1.9.0 the function's 4th parameter was boolean
}
$returnstring = htmlentities($returnstring, ENT_QUOTES, $htmlencoding);
}
return $returnstring;
}
public static function trunc($floatnumber) {
// truncates a floating-point number at the decimal point
// returns int (if possible, otherwise float)
if ($floatnumber >= 1) {
$truncatednumber = floor($floatnumber);
} elseif ($floatnumber <= -1) {
$truncatednumber = ceil($floatnumber);
} else {
$truncatednumber = 0;
}
if (self::intValueSupported($truncatednumber)) {
$truncatednumber = (int) $truncatednumber;
}
return $truncatednumber;
}
public static function safe_inc(&$variable, $increment=1) {
if (isset($variable)) {
$variable += $increment;
} else {
$variable = $increment;
}
return true;
}
public static function CastAsInt($floatnum) {
// convert to float if not already
$floatnum = (float) $floatnum;
// convert a float to type int, only if possible
if (self::trunc($floatnum) == $floatnum) {
// it's not floating point
if (self::intValueSupported($floatnum)) {
// it's within int range
$floatnum = (int) $floatnum;
}
}
return $floatnum;
}
public static function intValueSupported($num) {
// check if integers are 64-bit
static $hasINT64 = null;
if ($hasINT64 === null) { // 10x faster than is_null()
$hasINT64 = is_int(pow(2, 31)); // 32-bit int are limited to (2^31)-1
if (!$hasINT64 && !defined('PHP_INT_MIN')) {
define('PHP_INT_MIN', ~PHP_INT_MAX);
}
}
// if integers are 64-bit - no other check required
if ($hasINT64 || (($num <= PHP_INT_MAX) && ($num >= PHP_INT_MIN))) {
return true;
}
return false;
}
public static function DecimalizeFraction($fraction) {
list($numerator, $denominator) = explode('/', $fraction);
return $numerator / ($denominator ? $denominator : 1);
}
public static function DecimalBinary2Float($binarynumerator) {
$numerator = self::Bin2Dec($binarynumerator);
$denominator = self::Bin2Dec('1'.str_repeat('0', strlen($binarynumerator)));
return ($numerator / $denominator);
}
public static function NormalizeBinaryPoint($binarypointnumber, $maxbits=52) {
// http://www.scri.fsu.edu/~jac/MAD3401/Backgrnd/binary.html
if (strpos($binarypointnumber, '.') === false) {
$binarypointnumber = '0.'.$binarypointnumber;
} elseif ($binarypointnumber{0} == '.') {
$binarypointnumber = '0'.$binarypointnumber;
}
$exponent = 0;
while (($binarypointnumber{0} != '1') || (substr($binarypointnumber, 1, 1) != '.')) {
if (substr($binarypointnumber, 1, 1) == '.') {
$exponent--;
$binarypointnumber = substr($binarypointnumber, 2, 1).'.'.substr($binarypointnumber, 3);
} else {
$pointpos = strpos($binarypointnumber, '.');
$exponent += ($pointpos - 1);
$binarypointnumber = str_replace('.', '', $binarypointnumber);
$binarypointnumber = $binarypointnumber{0}.'.'.substr($binarypointnumber, 1);
}
}
$binarypointnumber = str_pad(substr($binarypointnumber, 0, $maxbits + 2), $maxbits + 2, '0', STR_PAD_RIGHT);
return array('normalized'=>$binarypointnumber, 'exponent'=>(int) $exponent);
}
public static function Float2BinaryDecimal($floatvalue) {
// http://www.scri.fsu.edu/~jac/MAD3401/Backgrnd/binary.html
$maxbits = 128; // to how many bits of precision should the calculations be taken?
$intpart = self::trunc($floatvalue);
$floatpart = abs($floatvalue - $intpart);
$pointbitstring = '';
while (($floatpart != 0) && (strlen($pointbitstring) < $maxbits)) {
$floatpart *= 2;
$pointbitstring .= (string) self::trunc($floatpart);
$floatpart -= self::trunc($floatpart);
}
$binarypointnumber = decbin($intpart).'.'.$pointbitstring;
return $binarypointnumber;
}
public static function Float2String($floatvalue, $bits) {
// http://www.scri.fsu.edu/~jac/MAD3401/Backgrnd/ieee-expl.html
switch ($bits) {
case 32:
$exponentbits = 8;
$fractionbits = 23;
break;
case 64:
$exponentbits = 11;
$fractionbits = 52;
break;
default:
return false;
break;
}
if ($floatvalue >= 0) {
$signbit = '0';
} else {
$signbit = '1';
}
$normalizedbinary = self::NormalizeBinaryPoint(self::Float2BinaryDecimal($floatvalue), $fractionbits);
$biasedexponent = pow(2, $exponentbits - 1) - 1 + $normalizedbinary['exponent']; // (127 or 1023) +/- exponent
$exponentbitstring = str_pad(decbin($biasedexponent), $exponentbits, '0', STR_PAD_LEFT);
$fractionbitstring = str_pad(substr($normalizedbinary['normalized'], 2), $fractionbits, '0', STR_PAD_RIGHT);
return self::BigEndian2String(self::Bin2Dec($signbit.$exponentbitstring.$fractionbitstring), $bits % 8, false);
}
public static function LittleEndian2Float($byteword) {
return self::BigEndian2Float(strrev($byteword));
}
public static function BigEndian2Float($byteword) {
// ANSI/IEEE Standard 754-1985, Standard for Binary Floating Point Arithmetic
// http://www.psc.edu/general/software/packages/ieee/ieee.html
// http://www.scri.fsu.edu/~jac/MAD3401/Backgrnd/ieee.html
$bitword = self::BigEndian2Bin($byteword);
if (!$bitword) {
return 0;
}
$signbit = $bitword{0};
switch (strlen($byteword) * 8) {
case 32:
$exponentbits = 8;
$fractionbits = 23;
break;
case 64:
$exponentbits = 11;
$fractionbits = 52;
break;
case 80:
// 80-bit Apple SANE format
// http://www.mactech.com/articles/mactech/Vol.06/06.01/SANENormalized/
$exponentstring = substr($bitword, 1, 15);
$isnormalized = intval($bitword{16});
$fractionstring = substr($bitword, 17, 63);
$exponent = pow(2, self::Bin2Dec($exponentstring) - 16383);
$fraction = $isnormalized + self::DecimalBinary2Float($fractionstring);
$floatvalue = $exponent * $fraction;
if ($signbit == '1') {
$floatvalue *= -1;
}
return $floatvalue;
break;
default:
return false;
break;
}
$exponentstring = substr($bitword, 1, $exponentbits);
$fractionstring = substr($bitword, $exponentbits + 1, $fractionbits);
$exponent = self::Bin2Dec($exponentstring);
$fraction = self::Bin2Dec($fractionstring);
if (($exponent == (pow(2, $exponentbits) - 1)) && ($fraction != 0)) {
// Not a Number
$floatvalue = false;
} elseif (($exponent == (pow(2, $exponentbits) - 1)) && ($fraction == 0)) {
if ($signbit == '1') {
$floatvalue = '-infinity';
} else {
$floatvalue = '+infinity';
}
} elseif (($exponent == 0) && ($fraction == 0)) {
if ($signbit == '1') {
$floatvalue = -0;
} else {
$floatvalue = 0;
}
$floatvalue = ($signbit ? 0 : -0);
} elseif (($exponent == 0) && ($fraction != 0)) {
// These are 'unnormalized' values
$floatvalue = pow(2, (-1 * (pow(2, $exponentbits - 1) - 2))) * self::DecimalBinary2Float($fractionstring);
if ($signbit == '1') {
$floatvalue *= -1;
}
} elseif ($exponent != 0) {
$floatvalue = pow(2, ($exponent - (pow(2, $exponentbits - 1) - 1))) * (1 + self::DecimalBinary2Float($fractionstring));
if ($signbit == '1') {
$floatvalue *= -1;
}
}
return (float) $floatvalue;
}
public static function BigEndian2Int($byteword, $synchsafe=false, $signed=false) {
$intvalue = 0;
$bytewordlen = strlen($byteword);
if ($bytewordlen == 0) {
return false;
}
for ($i = 0; $i < $bytewordlen; $i++) {
if ($synchsafe) { // disregard MSB, effectively 7-bit bytes
//$intvalue = $intvalue | (ord($byteword{$i}) & 0x7F) << (($bytewordlen - 1 - $i) * 7); // faster, but runs into problems past 2^31 on 32-bit systems
$intvalue += (ord($byteword{$i}) & 0x7F) * pow(2, ($bytewordlen - 1 - $i) * 7);
} else {
$intvalue += ord($byteword{$i}) * pow(256, ($bytewordlen - 1 - $i));
}
}
if ($signed && !$synchsafe) {
// synchsafe ints are not allowed to be signed
if ($bytewordlen <= PHP_INT_SIZE) {
$signMaskBit = 0x80 << (8 * ($bytewordlen - 1));
if ($intvalue & $signMaskBit) {
$intvalue = 0 - ($intvalue & ($signMaskBit - 1));
}
} else {
throw new Exception('ERROR: Cannot have signed integers larger than '.(8 * PHP_INT_SIZE).'-bits ('.strlen($byteword).') in self::BigEndian2Int()');
break;
}
}
return self::CastAsInt($intvalue);
}
public static function LittleEndian2Int($byteword, $signed=false) {
return self::BigEndian2Int(strrev($byteword), false, $signed);
}
public static function BigEndian2Bin($byteword) {
$binvalue = '';
$bytewordlen = strlen($byteword);
for ($i = 0; $i < $bytewordlen; $i++) {
$binvalue .= str_pad(decbin(ord($byteword{$i})), 8, '0', STR_PAD_LEFT);
}
return $binvalue;
}
public static function BigEndian2String($number, $minbytes=1, $synchsafe=false, $signed=false) {
if ($number < 0) {
throw new Exception('ERROR: self::BigEndian2String() does not support negative numbers');
}
$maskbyte = (($synchsafe || $signed) ? 0x7F : 0xFF);
$intstring = '';
if ($signed) {
if ($minbytes > PHP_INT_SIZE) {
throw new Exception('ERROR: Cannot have signed integers larger than '.(8 * PHP_INT_SIZE).'-bits in self::BigEndian2String()');
}
$number = $number & (0x80 << (8 * ($minbytes - 1)));
}
while ($number != 0) {
$quotient = ($number / ($maskbyte + 1));
$intstring = chr(ceil(($quotient - floor($quotient)) * $maskbyte)).$intstring;
$number = floor($quotient);
}
return str_pad($intstring, $minbytes, "\x00", STR_PAD_LEFT);
}
public static function Dec2Bin($number) {
while ($number >= 256) {
$bytes[] = (($number / 256) - (floor($number / 256))) * 256;
$number = floor($number / 256);
}
$bytes[] = $number;
$binstring = '';
for ($i = 0; $i < count($bytes); $i++) {
$binstring = (($i == count($bytes) - 1) ? decbin($bytes[$i]) : str_pad(decbin($bytes[$i]), 8, '0', STR_PAD_LEFT)).$binstring;
}
return $binstring;
}
public static function Bin2Dec($binstring, $signed=false) {
$signmult = 1;
if ($signed) {
if ($binstring{0} == '1') {
$signmult = -1;
}
$binstring = substr($binstring, 1);
}
$decvalue = 0;
for ($i = 0; $i < strlen($binstring); $i++) {
$decvalue += ((int) substr($binstring, strlen($binstring) - $i - 1, 1)) * pow(2, $i);
}
return self::CastAsInt($decvalue * $signmult);
}
public static function Bin2String($binstring) {
// return 'hi' for input of '0110100001101001'
$string = '';
$binstringreversed = strrev($binstring);
for ($i = 0; $i < strlen($binstringreversed); $i += 8) {
$string = chr(self::Bin2Dec(strrev(substr($binstringreversed, $i, 8)))).$string;
}
return $string;
}
public static function LittleEndian2String($number, $minbytes=1, $synchsafe=false) {
$intstring = '';
while ($number > 0) {
if ($synchsafe) {
$intstring = $intstring.chr($number & 127);
$number >>= 7;
} else {
$intstring = $intstring.chr($number & 255);
$number >>= 8;
}
}
return str_pad($intstring, $minbytes, "\x00", STR_PAD_RIGHT);
}
public static function array_merge_clobber($array1, $array2) {
// written by kcØhireability*com
// taken from http://www.php.net/manual/en/function.array-merge-recursive.php
if (!is_array($array1) || !is_array($array2)) {
return false;
}
$newarray = $array1;
foreach ($array2 as $key => $val) {
if (is_array($val) && isset($newarray[$key]) && is_array($newarray[$key])) {
$newarray[$key] = self::array_merge_clobber($newarray[$key], $val);
} else {
$newarray[$key] = $val;
}
}
return $newarray;
}
public static function array_merge_noclobber($array1, $array2) {
if (!is_array($array1) || !is_array($array2)) {
return false;
}
$newarray = $array1;
foreach ($array2 as $key => $val) {
if (is_array($val) && isset($newarray[$key]) && is_array($newarray[$key])) {
$newarray[$key] = self::array_merge_noclobber($newarray[$key], $val);
} elseif (!isset($newarray[$key])) {
$newarray[$key] = $val;
}
}
return $newarray;
}
public static function ksort_recursive(&$theArray) {
ksort($theArray);
foreach ($theArray as $key => $value) {
if (is_array($value)) {
self::ksort_recursive($theArray[$key]);
}
}
return true;
}
public static function fileextension($filename, $numextensions=1) {
if (strstr($filename, '.')) {
$reversedfilename = strrev($filename);
$offset = 0;
for ($i = 0; $i < $numextensions; $i++) {
$offset = strpos($reversedfilename, '.', $offset + 1);
if ($offset === false) {
return '';
}
}
return strrev(substr($reversedfilename, 0, $offset));
}
return '';
}
public static function PlaytimeString($seconds) {
$sign = (($seconds < 0) ? '-' : '');
$seconds = round(abs($seconds));
$H = (int) floor( $seconds / 3600);
$M = (int) floor(($seconds - (3600 * $H) ) / 60);
$S = (int) round( $seconds - (3600 * $H) - (60 * $M) );
return $sign.($H ? $H.':' : '').($H ? str_pad($M, 2, '0', STR_PAD_LEFT) : intval($M)).':'.str_pad($S, 2, 0, STR_PAD_LEFT);
}
public static function DateMac2Unix($macdate) {
// Macintosh timestamp: seconds since 00:00h January 1, 1904
// UNIX timestamp: seconds since 00:00h January 1, 1970
return self::CastAsInt($macdate - 2082844800);
}
public static function FixedPoint8_8($rawdata) {
return self::BigEndian2Int(substr($rawdata, 0, 1)) + (float) (self::BigEndian2Int(substr($rawdata, 1, 1)) / pow(2, 8));
}
public static function FixedPoint16_16($rawdata) {
return self::BigEndian2Int(substr($rawdata, 0, 2)) + (float) (self::BigEndian2Int(substr($rawdata, 2, 2)) / pow(2, 16));
}
public static function FixedPoint2_30($rawdata) {
$binarystring = self::BigEndian2Bin($rawdata);
return self::Bin2Dec(substr($binarystring, 0, 2)) + (float) (self::Bin2Dec(substr($binarystring, 2, 30)) / pow(2, 30));
}
public static function CreateDeepArray($ArrayPath, $Separator, $Value) {
// assigns $Value to a nested array path:
// $foo = self::CreateDeepArray('/path/to/my', '/', 'file.txt')
// is the same as:
// $foo = array('path'=>array('to'=>'array('my'=>array('file.txt'))));
// or
// $foo['path']['to']['my'] = 'file.txt';
$ArrayPath = ltrim($ArrayPath, $Separator);
if (($pos = strpos($ArrayPath, $Separator)) !== false) {
$ReturnedArray[substr($ArrayPath, 0, $pos)] = self::CreateDeepArray(substr($ArrayPath, $pos + 1), $Separator, $Value);
} else {
$ReturnedArray[$ArrayPath] = $Value;
}
return $ReturnedArray;
}
public static function array_max($arraydata, $returnkey=false) {
$maxvalue = false;
$maxkey = false;
foreach ($arraydata as $key => $value) {
if (!is_array($value)) {
if ($value > $maxvalue) {
$maxvalue = $value;
$maxkey = $key;
}
}
}
return ($returnkey ? $maxkey : $maxvalue);
}
public static function array_min($arraydata, $returnkey=false) {
$minvalue = false;
$minkey = false;
foreach ($arraydata as $key => $value) {
if (!is_array($value)) {
if ($value > $minvalue) {
$minvalue = $value;
$minkey = $key;
}
}
}
return ($returnkey ? $minkey : $minvalue);
}
public static function XML2array($XMLstring) {
if ( function_exists( 'simplexml_load_string' ) && function_exists( 'libxml_disable_entity_loader' ) ) {
$loader = libxml_disable_entity_loader( true );
$XMLobject = simplexml_load_string( $XMLstring, 'SimpleXMLElement', LIBXML_NOENT );
$return = self::SimpleXMLelement2array( $XMLobject );
libxml_disable_entity_loader( $loader );
return $return;
}
return false;
}
public static function SimpleXMLelement2array($XMLobject) {
if (!is_object($XMLobject) && !is_array($XMLobject)) {
return $XMLobject;
}
$XMLarray = (is_object($XMLobject) ? get_object_vars($XMLobject) : $XMLobject);
foreach ($XMLarray as $key => $value) {
$XMLarray[$key] = self::SimpleXMLelement2array($value);
}
return $XMLarray;
}
// Allan Hansen <ahØartemis*dk>
// self::md5_data() - returns md5sum for a file from startuing position to absolute end position
public static function hash_data($file, $offset, $end, $algorithm) {
static $tempdir = '';
if (!self::intValueSupported($end)) {
return false;
}
switch ($algorithm) {
case 'md5':
$hash_function = 'md5_file';
$unix_call = 'md5sum';
$windows_call = 'md5sum.exe';
$hash_length = 32;
break;
case 'sha1':
$hash_function = 'sha1_file';
$unix_call = 'sha1sum';
$windows_call = 'sha1sum.exe';
$hash_length = 40;
break;
default:
throw new Exception('Invalid algorithm ('.$algorithm.') in self::hash_data()');
break;
}
$size = $end - $offset;
while (true) {
if (GETID3_OS_ISWINDOWS) {
// It seems that sha1sum.exe for Windows only works on physical files, does not accept piped data
// Fall back to create-temp-file method:
if ($algorithm == 'sha1') {
break;
}
$RequiredFiles = array('cygwin1.dll', 'head.exe', 'tail.exe', $windows_call);
foreach ($RequiredFiles as $required_file) {
if (!is_readable(GETID3_HELPERAPPSDIR.$required_file)) {
// helper apps not available - fall back to old method
break 2;
}
}
$commandline = GETID3_HELPERAPPSDIR.'head.exe -c '.$end.' '.escapeshellarg(str_replace('/', DIRECTORY_SEPARATOR, $file)).' | ';
$commandline .= GETID3_HELPERAPPSDIR.'tail.exe -c '.$size.' | ';
$commandline .= GETID3_HELPERAPPSDIR.$windows_call;
} else {
$commandline = 'head -c'.$end.' '.escapeshellarg($file).' | ';
$commandline .= 'tail -c'.$size.' | ';
$commandline .= $unix_call;
}
if (preg_match('#(1|ON)#i', ini_get('safe_mode'))) {
//throw new Exception('PHP running in Safe Mode - backtick operator not available, using slower non-system-call '.$algorithm.' algorithm');
break;
}
return substr(`$commandline`, 0, $hash_length);
}
if (empty($tempdir)) {
// yes this is ugly, feel free to suggest a better way
require_once(dirname(__FILE__).'/getid3.php');
$getid3_temp = new getID3();
$tempdir = $getid3_temp->tempdir;
unset($getid3_temp);
}
// try to create a temporary file in the system temp directory - invalid dirname should force to system temp dir
if (($data_filename = tempnam($tempdir, 'gI3')) === false) {
// can't find anywhere to create a temp file, just fail
return false;
}
// Init
$result = false;
// copy parts of file
try {
self::CopyFileParts($file, $data_filename, $offset, $end - $offset);
$result = $hash_function($data_filename);
} catch (Exception $e) {
throw new Exception('self::CopyFileParts() failed in getid_lib::hash_data(): '.$e->getMessage());
}
unlink($data_filename);
return $result;
}
public static function CopyFileParts($filename_source, $filename_dest, $offset, $length) {
if (!self::intValueSupported($offset + $length)) {
throw new Exception('cannot copy file portion, it extends beyond the '.round(PHP_INT_MAX / 1073741824).'GB limit');
}
if (is_readable($filename_source) && is_file($filename_source) && ($fp_src = fopen($filename_source, 'rb'))) {
if (($fp_dest = fopen($filename_dest, 'wb'))) {
if (fseek($fp_src, $offset, SEEK_SET) == 0) {
$byteslefttowrite = $length;
while (($byteslefttowrite > 0) && ($buffer = fread($fp_src, min($byteslefttowrite, getID3::FREAD_BUFFER_SIZE)))) {
$byteswritten = fwrite($fp_dest, $buffer, $byteslefttowrite);
$byteslefttowrite -= $byteswritten;
}
return true;
} else {
throw new Exception('failed to seek to offset '.$offset.' in '.$filename_source);
}
fclose($fp_dest);
} else {
throw new Exception('failed to create file for writing '.$filename_dest);
}
fclose($fp_src);
} else {
throw new Exception('failed to open file for reading '.$filename_source);
}
return false;
}
public static function iconv_fallback_int_utf8($charval) {
if ($charval < 128) {
// 0bbbbbbb
$newcharstring = chr($charval);
} elseif ($charval < 2048) {
// 110bbbbb 10bbbbbb
$newcharstring = chr(($charval >> 6) | 0xC0);
$newcharstring .= chr(($charval & 0x3F) | 0x80);
} elseif ($charval < 65536) {
// 1110bbbb 10bbbbbb 10bbbbbb
$newcharstring = chr(($charval >> 12) | 0xE0);
$newcharstring .= chr(($charval >> 6) | 0xC0);
$newcharstring .= chr(($charval & 0x3F) | 0x80);
} else {
// 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
$newcharstring = chr(($charval >> 18) | 0xF0);
$newcharstring .= chr(($charval >> 12) | 0xC0);
$newcharstring .= chr(($charval >> 6) | 0xC0);
$newcharstring .= chr(($charval & 0x3F) | 0x80);
}
return $newcharstring;
}
// ISO-8859-1 => UTF-8
public static function iconv_fallback_iso88591_utf8($string, $bom=false) {
if (function_exists('utf8_encode')) {
return utf8_encode($string);
}
// utf8_encode() unavailable, use getID3()'s iconv_fallback() conversions (possibly PHP is compiled without XML support)
$newcharstring = '';
if ($bom) {
$newcharstring .= "\xEF\xBB\xBF";
}
for ($i = 0; $i < strlen($string); $i++) {
$charval = ord($string{$i});
$newcharstring .= self::iconv_fallback_int_utf8($charval);
}
return $newcharstring;
}
// ISO-8859-1 => UTF-16BE
public static function iconv_fallback_iso88591_utf16be($string, $bom=false) {
$newcharstring = '';
if ($bom) {
$newcharstring .= "\xFE\xFF";
}
for ($i = 0; $i < strlen($string); $i++) {
$newcharstring .= "\x00".$string{$i};
}
return $newcharstring;
}
// ISO-8859-1 => UTF-16LE
public static function iconv_fallback_iso88591_utf16le($string, $bom=false) {
$newcharstring = '';
if ($bom) {
$newcharstring .= "\xFF\xFE";
}
for ($i = 0; $i < strlen($string); $i++) {
$newcharstring .= $string{$i}."\x00";
}
return $newcharstring;
}
// ISO-8859-1 => UTF-16LE (BOM)
public static function iconv_fallback_iso88591_utf16($string) {
return self::iconv_fallback_iso88591_utf16le($string, true);
}
// UTF-8 => ISO-8859-1
public static function iconv_fallback_utf8_iso88591($string) {
if (function_exists('utf8_decode')) {
return utf8_decode($string);
}
// utf8_decode() unavailable, use getID3()'s iconv_fallback() conversions (possibly PHP is compiled without XML support)
$newcharstring = '';
$offset = 0;
$stringlength = strlen($string);
while ($offset < $stringlength) {
if ((ord($string{$offset}) | 0x07) == 0xF7) {
// 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
$charval = ((ord($string{($offset + 0)}) & 0x07) << 18) &
((ord($string{($offset + 1)}) & 0x3F) << 12) &
((ord($string{($offset + 2)}) & 0x3F) << 6) &
(ord($string{($offset + 3)}) & 0x3F);
$offset += 4;
} elseif ((ord($string{$offset}) | 0x0F) == 0xEF) {
// 1110bbbb 10bbbbbb 10bbbbbb
$charval = ((ord($string{($offset + 0)}) & 0x0F) << 12) &
((ord($string{($offset + 1)}) & 0x3F) << 6) &
(ord($string{($offset + 2)}) & 0x3F);
$offset += 3;
} elseif ((ord($string{$offset}) | 0x1F) == 0xDF) {
// 110bbbbb 10bbbbbb
$charval = ((ord($string{($offset + 0)}) & 0x1F) << 6) &
(ord($string{($offset + 1)}) & 0x3F);
$offset += 2;
} elseif ((ord($string{$offset}) | 0x7F) == 0x7F) {
// 0bbbbbbb
$charval = ord($string{$offset});
$offset += 1;
} else {
// error? throw some kind of warning here?
$charval = false;
$offset += 1;
}
if ($charval !== false) {
$newcharstring .= (($charval < 256) ? chr($charval) : '?');
}
}
return $newcharstring;
}
// UTF-8 => UTF-16BE
public static function iconv_fallback_utf8_utf16be($string, $bom=false) {
$newcharstring = '';
if ($bom) {
$newcharstring .= "\xFE\xFF";
}
$offset = 0;
$stringlength = strlen($string);
while ($offset < $stringlength) {
if ((ord($string{$offset}) | 0x07) == 0xF7) {
// 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
$charval = ((ord($string{($offset + 0)}) & 0x07) << 18) &
((ord($string{($offset + 1)}) & 0x3F) << 12) &
((ord($string{($offset + 2)}) & 0x3F) << 6) &
(ord($string{($offset + 3)}) & 0x3F);
$offset += 4;
} elseif ((ord($string{$offset}) | 0x0F) == 0xEF) {
// 1110bbbb 10bbbbbb 10bbbbbb
$charval = ((ord($string{($offset + 0)}) & 0x0F) << 12) &
((ord($string{($offset + 1)}) & 0x3F) << 6) &
(ord($string{($offset + 2)}) & 0x3F);
$offset += 3;
} elseif ((ord($string{$offset}) | 0x1F) == 0xDF) {
// 110bbbbb 10bbbbbb
$charval = ((ord($string{($offset + 0)}) & 0x1F) << 6) &
(ord($string{($offset + 1)}) & 0x3F);
$offset += 2;
} elseif ((ord($string{$offset}) | 0x7F) == 0x7F) {
// 0bbbbbbb
$charval = ord($string{$offset});
$offset += 1;
} else {
// error? throw some kind of warning here?
$charval = false;
$offset += 1;
}
if ($charval !== false) {
$newcharstring .= (($charval < 65536) ? self::BigEndian2String($charval, 2) : "\x00".'?');
}
}
return $newcharstring;
}
// UTF-8 => UTF-16LE
public static function iconv_fallback_utf8_utf16le($string, $bom=false) {
$newcharstring = '';
if ($bom) {
$newcharstring .= "\xFF\xFE";
}
$offset = 0;
$stringlength = strlen($string);
while ($offset < $stringlength) {
if ((ord($string{$offset}) | 0x07) == 0xF7) {
// 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
$charval = ((ord($string{($offset + 0)}) & 0x07) << 18) &
((ord($string{($offset + 1)}) & 0x3F) << 12) &
((ord($string{($offset + 2)}) & 0x3F) << 6) &
(ord($string{($offset + 3)}) & 0x3F);
$offset += 4;
} elseif ((ord($string{$offset}) | 0x0F) == 0xEF) {
// 1110bbbb 10bbbbbb 10bbbbbb
$charval = ((ord($string{($offset + 0)}) & 0x0F) << 12) &
((ord($string{($offset + 1)}) & 0x3F) << 6) &
(ord($string{($offset + 2)}) & 0x3F);
$offset += 3;
} elseif ((ord($string{$offset}) | 0x1F) == 0xDF) {
// 110bbbbb 10bbbbbb
$charval = ((ord($string{($offset + 0)}) & 0x1F) << 6) &
(ord($string{($offset + 1)}) & 0x3F);
$offset += 2;
} elseif ((ord($string{$offset}) | 0x7F) == 0x7F) {
// 0bbbbbbb
$charval = ord($string{$offset});
$offset += 1;
} else {
// error? maybe throw some warning here?
$charval = false;
$offset += 1;
}
if ($charval !== false) {
$newcharstring .= (($charval < 65536) ? self::LittleEndian2String($charval, 2) : '?'."\x00");
}
}
return $newcharstring;
}
// UTF-8 => UTF-16LE (BOM)
public static function iconv_fallback_utf8_utf16($string) {
return self::iconv_fallback_utf8_utf16le($string, true);
}
// UTF-16BE => UTF-8
public static function iconv_fallback_utf16be_utf8($string) {
if (substr($string, 0, 2) == "\xFE\xFF") {
// strip BOM
$string = substr($string, 2);
}
$newcharstring = '';
for ($i = 0; $i < strlen($string); $i += 2) {
$charval = self::BigEndian2Int(substr($string, $i, 2));
$newcharstring .= self::iconv_fallback_int_utf8($charval);
}
return $newcharstring;
}
// UTF-16LE => UTF-8
public static function iconv_fallback_utf16le_utf8($string) {
if (substr($string, 0, 2) == "\xFF\xFE") {
// strip BOM
$string = substr($string, 2);
}
$newcharstring = '';
for ($i = 0; $i < strlen($string); $i += 2) {
$charval = self::LittleEndian2Int(substr($string, $i, 2));
$newcharstring .= self::iconv_fallback_int_utf8($charval);
}
return $newcharstring;
}
// UTF-16BE => ISO-8859-1
public static function iconv_fallback_utf16be_iso88591($string) {
if (substr($string, 0, 2) == "\xFE\xFF") {
// strip BOM
$string = substr($string, 2);
}
$newcharstring = '';
for ($i = 0; $i < strlen($string); $i += 2) {
$charval = self::BigEndian2Int(substr($string, $i, 2));
$newcharstring .= (($charval < 256) ? chr($charval) : '?');
}
return $newcharstring;
}
// UTF-16LE => ISO-8859-1
public static function iconv_fallback_utf16le_iso88591($string) {
if (substr($string, 0, 2) == "\xFF\xFE") {
// strip BOM
$string = substr($string, 2);
}
$newcharstring = '';
for ($i = 0; $i < strlen($string); $i += 2) {
$charval = self::LittleEndian2Int(substr($string, $i, 2));
$newcharstring .= (($charval < 256) ? chr($charval) : '?');
}
return $newcharstring;
}
// UTF-16 (BOM) => ISO-8859-1
public static function iconv_fallback_utf16_iso88591($string) {
$bom = substr($string, 0, 2);
if ($bom == "\xFE\xFF") {
return self::iconv_fallback_utf16be_iso88591(substr($string, 2));
} elseif ($bom == "\xFF\xFE") {
return self::iconv_fallback_utf16le_iso88591(substr($string, 2));
}
return $string;
}
// UTF-16 (BOM) => UTF-8
public static function iconv_fallback_utf16_utf8($string) {
$bom = substr($string, 0, 2);
if ($bom == "\xFE\xFF") {
return self::iconv_fallback_utf16be_utf8(substr($string, 2));
} elseif ($bom == "\xFF\xFE") {
return self::iconv_fallback_utf16le_utf8(substr($string, 2));
}
return $string;
}
public static function iconv_fallback($in_charset, $out_charset, $string) {
if ($in_charset == $out_charset) {
return $string;
}
// iconv() availble
if (function_exists('iconv')) {
if ($converted_string = @iconv($in_charset, $out_charset.'//TRANSLIT', $string)) {
switch ($out_charset) {
case 'ISO-8859-1':
$converted_string = rtrim($converted_string, "\x00");
break;
}
return $converted_string;
}
// iconv() may sometimes fail with "illegal character in input string" error message
// and return an empty string, but returning the unconverted string is more useful
return $string;
}
// iconv() not available
static $ConversionFunctionList = array();
if (empty($ConversionFunctionList)) {
$ConversionFunctionList['ISO-8859-1']['UTF-8'] = 'iconv_fallback_iso88591_utf8';
$ConversionFunctionList['ISO-8859-1']['UTF-16'] = 'iconv_fallback_iso88591_utf16';
$ConversionFunctionList['ISO-8859-1']['UTF-16BE'] = 'iconv_fallback_iso88591_utf16be';
$ConversionFunctionList['ISO-8859-1']['UTF-16LE'] = 'iconv_fallback_iso88591_utf16le';
$ConversionFunctionList['UTF-8']['ISO-8859-1'] = 'iconv_fallback_utf8_iso88591';
$ConversionFunctionList['UTF-8']['UTF-16'] = 'iconv_fallback_utf8_utf16';
$ConversionFunctionList['UTF-8']['UTF-16BE'] = 'iconv_fallback_utf8_utf16be';
$ConversionFunctionList['UTF-8']['UTF-16LE'] = 'iconv_fallback_utf8_utf16le';
$ConversionFunctionList['UTF-16']['ISO-8859-1'] = 'iconv_fallback_utf16_iso88591';
$ConversionFunctionList['UTF-16']['UTF-8'] = 'iconv_fallback_utf16_utf8';
$ConversionFunctionList['UTF-16LE']['ISO-8859-1'] = 'iconv_fallback_utf16le_iso88591';
$ConversionFunctionList['UTF-16LE']['UTF-8'] = 'iconv_fallback_utf16le_utf8';
$ConversionFunctionList['UTF-16BE']['ISO-8859-1'] = 'iconv_fallback_utf16be_iso88591';
$ConversionFunctionList['UTF-16BE']['UTF-8'] = 'iconv_fallback_utf16be_utf8';
}
if (isset($ConversionFunctionList[strtoupper($in_charset)][strtoupper($out_charset)])) {
$ConversionFunction = $ConversionFunctionList[strtoupper($in_charset)][strtoupper($out_charset)];
return self::$ConversionFunction($string);
}
throw new Exception('PHP does not have iconv() support - cannot convert from '.$in_charset.' to '.$out_charset);
}
public static function MultiByteCharString2HTML($string, $charset='ISO-8859-1') {
$string = (string) $string; // in case trying to pass a numeric (float, int) string, would otherwise return an empty string
$HTMLstring = '';
switch ($charset) {
case '1251':
case '1252':
case '866':
case '932':
case '936':
case '950':
case 'BIG5':
case 'BIG5-HKSCS':
case 'cp1251':
case 'cp1252':
case 'cp866':
case 'EUC-JP':
case 'EUCJP':
case 'GB2312':
case 'ibm866':
case 'ISO-8859-1':
case 'ISO-8859-15':
case 'ISO8859-1':
case 'ISO8859-15':
case 'KOI8-R':
case 'koi8-ru':
case 'koi8r':
case 'Shift_JIS':
case 'SJIS':
case 'win-1251':
case 'Windows-1251':
case 'Windows-1252':
$HTMLstring = htmlentities($string, ENT_COMPAT, $charset);
break;
case 'UTF-8':
$strlen = strlen($string);
for ($i = 0; $i < $strlen; $i++) {
$char_ord_val = ord($string{$i});
$charval = 0;
if ($char_ord_val < 0x80) {
$charval = $char_ord_val;
} elseif ((($char_ord_val & 0xF0) >> 4) == 0x0F && $i+3 < $strlen) {
$charval = (($char_ord_val & 0x07) << 18);
$charval += ((ord($string{++$i}) & 0x3F) << 12);
$charval += ((ord($string{++$i}) & 0x3F) << 6);
$charval += (ord($string{++$i}) & 0x3F);
} elseif ((($char_ord_val & 0xE0) >> 5) == 0x07 && $i+2 < $strlen) {
$charval = (($char_ord_val & 0x0F) << 12);
$charval += ((ord($string{++$i}) & 0x3F) << 6);
$charval += (ord($string{++$i}) & 0x3F);
} elseif ((($char_ord_val & 0xC0) >> 6) == 0x03 && $i+1 < $strlen) {
$charval = (($char_ord_val & 0x1F) << 6);
$charval += (ord($string{++$i}) & 0x3F);
}
if (($charval >= 32) && ($charval <= 127)) {
$HTMLstring .= htmlentities(chr($charval));
} else {
$HTMLstring .= '&#'.$charval.';';
}
}
break;
case 'UTF-16LE':
for ($i = 0; $i < strlen($string); $i += 2) {
$charval = self::LittleEndian2Int(substr($string, $i, 2));
if (($charval >= 32) && ($charval <= 127)) {
$HTMLstring .= chr($charval);
} else {
$HTMLstring .= '&#'.$charval.';';
}
}
break;
case 'UTF-16BE':
for ($i = 0; $i < strlen($string); $i += 2) {
$charval = self::BigEndian2Int(substr($string, $i, 2));
if (($charval >= 32) && ($charval <= 127)) {
$HTMLstring .= chr($charval);
} else {
$HTMLstring .= '&#'.$charval.';';
}
}
break;
default:
$HTMLstring = 'ERROR: Character set "'.$charset.'" not supported in MultiByteCharString2HTML()';
break;
}
return $HTMLstring;
}
public static function RGADnameLookup($namecode) {
static $RGADname = array();
if (empty($RGADname)) {
$RGADname[0] = 'not set';
$RGADname[1] = 'Track Gain Adjustment';
$RGADname[2] = 'Album Gain Adjustment';
}
return (isset($RGADname[$namecode]) ? $RGADname[$namecode] : '');
}
public static function RGADoriginatorLookup($originatorcode) {
static $RGADoriginator = array();
if (empty($RGADoriginator)) {
$RGADoriginator[0] = 'unspecified';
$RGADoriginator[1] = 'pre-set by artist/producer/mastering engineer';
$RGADoriginator[2] = 'set by user';
$RGADoriginator[3] = 'determined automatically';
}
return (isset($RGADoriginator[$originatorcode]) ? $RGADoriginator[$originatorcode] : '');
}
public static function RGADadjustmentLookup($rawadjustment, $signbit) {
$adjustment = $rawadjustment / 10;
if ($signbit == 1) {
$adjustment *= -1;
}
return (float) $adjustment;
}
public static function RGADgainString($namecode, $originatorcode, $replaygain) {
if ($replaygain < 0) {
$signbit = '1';
} else {
$signbit = '0';
}
$storedreplaygain = intval(round($replaygain * 10));
$gainstring = str_pad(decbin($namecode), 3, '0', STR_PAD_LEFT);
$gainstring .= str_pad(decbin($originatorcode), 3, '0', STR_PAD_LEFT);
$gainstring .= $signbit;
$gainstring .= str_pad(decbin($storedreplaygain), 9, '0', STR_PAD_LEFT);
return $gainstring;
}
public static function RGADamplitude2dB($amplitude) {
return 20 * log10($amplitude);
}
public static function GetDataImageSize($imgData, &$imageinfo=array()) {
static $tempdir = '';
if (empty($tempdir)) {
// yes this is ugly, feel free to suggest a better way
require_once(dirname(__FILE__).'/getid3.php');
$getid3_temp = new getID3();
$tempdir = $getid3_temp->tempdir;
unset($getid3_temp);
}
$GetDataImageSize = false;
if ($tempfilename = tempnam($tempdir, 'gI3')) {
if (is_writable($tempfilename) && is_file($tempfilename) && ($tmp = fopen($tempfilename, 'wb'))) {
fwrite($tmp, $imgData);
fclose($tmp);
$GetDataImageSize = @getimagesize($tempfilename, $imageinfo);
}
unlink($tempfilename);
}
return $GetDataImageSize;
}
public static function ImageExtFromMime($mime_type) {
// temporary way, works OK for now, but should be reworked in the future
return str_replace(array('image/', 'x-', 'jpeg'), array('', '', 'jpg'), $mime_type);
}
public static function ImageTypesLookup($imagetypeid) {
static $ImageTypesLookup = array();
if (empty($ImageTypesLookup)) {
$ImageTypesLookup[1] = 'gif';
$ImageTypesLookup[2] = 'jpeg';
$ImageTypesLookup[3] = 'png';
$ImageTypesLookup[4] = 'swf';
$ImageTypesLookup[5] = 'psd';
$ImageTypesLookup[6] = 'bmp';
$ImageTypesLookup[7] = 'tiff (little-endian)';
$ImageTypesLookup[8] = 'tiff (big-endian)';
$ImageTypesLookup[9] = 'jpc';
$ImageTypesLookup[10] = 'jp2';
$ImageTypesLookup[11] = 'jpx';
$ImageTypesLookup[12] = 'jb2';
$ImageTypesLookup[13] = 'swc';
$ImageTypesLookup[14] = 'iff';
}
return (isset($ImageTypesLookup[$imagetypeid]) ? $ImageTypesLookup[$imagetypeid] : '');
}
public static function CopyTagsToComments(&$ThisFileInfo) {
// Copy all entries from ['tags'] into common ['comments']
if (!empty($ThisFileInfo['tags'])) {
foreach ($ThisFileInfo['tags'] as $tagtype => $tagarray) {
foreach ($tagarray as $tagname => $tagdata) {
foreach ($tagdata as $key => $value) {
if (!empty($value)) {
if (empty($ThisFileInfo['comments'][$tagname])) {
// fall through and append value
} elseif ($tagtype == 'id3v1') {
$newvaluelength = strlen(trim($value));
foreach ($ThisFileInfo['comments'][$tagname] as $existingkey => $existingvalue) {
$oldvaluelength = strlen(trim($existingvalue));
if (($newvaluelength <= $oldvaluelength) && (substr($existingvalue, 0, $newvaluelength) == trim($value))) {
// new value is identical but shorter-than (or equal-length to) one already in comments - skip
break 2;
}
}
} elseif (!is_array($value)) {
$newvaluelength = strlen(trim($value));
foreach ($ThisFileInfo['comments'][$tagname] as $existingkey => $existingvalue) {
$oldvaluelength = strlen(trim($existingvalue));
if (($newvaluelength > $oldvaluelength) && (substr(trim($value), 0, strlen($existingvalue)) == $existingvalue)) {
$ThisFileInfo['comments'][$tagname][$existingkey] = trim($value);
break 2;
}
}
}
if (is_array($value) || empty($ThisFileInfo['comments'][$tagname]) || !in_array(trim($value), $ThisFileInfo['comments'][$tagname])) {
$value = (is_string($value) ? trim($value) : $value);
$ThisFileInfo['comments'][$tagname][] = $value;
}
}
}
}
}
// Copy to ['comments_html']
foreach ($ThisFileInfo['comments'] as $field => $values) {
if ($field == 'picture') {
// pictures can take up a lot of space, and we don't need multiple copies of them
// let there be a single copy in [comments][picture], and not elsewhere
continue;
}
foreach ($values as $index => $value) {
if (is_array($value)) {
$ThisFileInfo['comments_html'][$field][$index] = $value;
} else {
$ThisFileInfo['comments_html'][$field][$index] = str_replace('�', '', self::MultiByteCharString2HTML($value, $ThisFileInfo['encoding']));
}
}
}
}
return true;
}
public static function EmbeddedLookup($key, $begin, $end, $file, $name) {
// Cached
static $cache;
if (isset($cache[$file][$name])) {
return (isset($cache[$file][$name][$key]) ? $cache[$file][$name][$key] : '');
}
// Init
$keylength = strlen($key);
$line_count = $end - $begin - 7;
// Open php file
$fp = fopen($file, 'r');
// Discard $begin lines
for ($i = 0; $i < ($begin + 3); $i++) {
fgets($fp, 1024);
}
// Loop thru line
while (0 < $line_count--) {
// Read line
$line = ltrim(fgets($fp, 1024), "\t ");
// METHOD A: only cache the matching key - less memory but slower on next lookup of not-previously-looked-up key
//$keycheck = substr($line, 0, $keylength);
//if ($key == $keycheck) {
// $cache[$file][$name][$keycheck] = substr($line, $keylength + 1);
// break;
//}
// METHOD B: cache all keys in this lookup - more memory but faster on next lookup of not-previously-looked-up key
//$cache[$file][$name][substr($line, 0, $keylength)] = trim(substr($line, $keylength + 1));
$explodedLine = explode("\t", $line, 2);
$ThisKey = (isset($explodedLine[0]) ? $explodedLine[0] : '');
$ThisValue = (isset($explodedLine[1]) ? $explodedLine[1] : '');
$cache[$file][$name][$ThisKey] = trim($ThisValue);
}
// Close and return
fclose($fp);
return (isset($cache[$file][$name][$key]) ? $cache[$file][$name][$key] : '');
}
public static function IncludeDependency($filename, $sourcefile, $DieOnFailure=false) {
global $GETID3_ERRORARRAY;
if (file_exists($filename)) {
if (include_once($filename)) {
return true;
} else {
$diemessage = basename($sourcefile).' depends on '.$filename.', which has errors';
}
} else {
$diemessage = basename($sourcefile).' depends on '.$filename.', which is missing';
}
if ($DieOnFailure) {
throw new Exception($diemessage);
} else {
$GETID3_ERRORARRAY[] = $diemessage;
}
return false;
}
public static function trimNullByte($string) {
return trim($string, "\x00");
}
public static function getFileSizeSyscall($path) {
$filesize = false;
if (GETID3_OS_ISWINDOWS) {
if (class_exists('COM')) { // From PHP 5.3.15 and 5.4.5, COM and DOTNET is no longer built into the php core.you have to add COM support in php.ini:
$filesystem = new COM('Scripting.FileSystemObject');
$file = $filesystem->GetFile($path);
$filesize = $file->Size();
unset($filesystem, $file);
} else {
$commandline = 'for %I in ('.escapeshellarg($path).') do @echo %~zI';
}
} else {
$commandline = 'ls -l '.escapeshellarg($path).' | awk \'{print $5}\'';
}
if (isset($commandline)) {
$output = trim(`$commandline`);
if (ctype_digit($output)) {
$filesize = (float) $output;
}
}
return $filesize;
}
} | PHP |
<?php
/////////////////////////////////////////////////////////////////
/// getID3() by James Heinrich <info@getid3.org> //
// available at http://getid3.sourceforge.net //
// or http://www.getid3.org //
/////////////////////////////////////////////////////////////////
// See readme.txt for more details //
/////////////////////////////////////////////////////////////////
// //
// module.audio-video.matriska.php //
// module for analyzing Matroska containers //
// dependencies: NONE //
// ///
/////////////////////////////////////////////////////////////////
define('EBML_ID_CHAPTERS', 0x0043A770); // [10][43][A7][70] -- A system to define basic menus and partition data. For more detailed information, look at the Chapters Explanation.
define('EBML_ID_SEEKHEAD', 0x014D9B74); // [11][4D][9B][74] -- Contains the position of other level 1 elements.
define('EBML_ID_TAGS', 0x0254C367); // [12][54][C3][67] -- Element containing elements specific to Tracks/Chapters. A list of valid tags can be found <http://www.matroska.org/technical/specs/tagging/index.html>.
define('EBML_ID_INFO', 0x0549A966); // [15][49][A9][66] -- Contains miscellaneous general information and statistics on the file.
define('EBML_ID_TRACKS', 0x0654AE6B); // [16][54][AE][6B] -- A top-level block of information with many tracks described.
define('EBML_ID_SEGMENT', 0x08538067); // [18][53][80][67] -- This element contains all other top-level (level 1) elements. Typically a Matroska file is composed of 1 segment.
define('EBML_ID_ATTACHMENTS', 0x0941A469); // [19][41][A4][69] -- Contain attached files.
define('EBML_ID_EBML', 0x0A45DFA3); // [1A][45][DF][A3] -- Set the EBML characteristics of the data to follow. Each EBML document has to start with this.
define('EBML_ID_CUES', 0x0C53BB6B); // [1C][53][BB][6B] -- A top-level element to speed seeking access. All entries are local to the segment.
define('EBML_ID_CLUSTER', 0x0F43B675); // [1F][43][B6][75] -- The lower level element containing the (monolithic) Block structure.
define('EBML_ID_LANGUAGE', 0x02B59C); // [22][B5][9C] -- Specifies the language of the track in the Matroska languages form.
define('EBML_ID_TRACKTIMECODESCALE', 0x03314F); // [23][31][4F] -- The scale to apply on this track to work at normal speed in relation with other tracks (mostly used to adjust video speed when the audio length differs).
define('EBML_ID_DEFAULTDURATION', 0x03E383); // [23][E3][83] -- Number of nanoseconds (i.e. not scaled) per frame.
define('EBML_ID_CODECNAME', 0x058688); // [25][86][88] -- A human-readable string specifying the codec.
define('EBML_ID_CODECDOWNLOADURL', 0x06B240); // [26][B2][40] -- A URL to download about the codec used.
define('EBML_ID_TIMECODESCALE', 0x0AD7B1); // [2A][D7][B1] -- Timecode scale in nanoseconds (1.000.000 means all timecodes in the segment are expressed in milliseconds).
define('EBML_ID_COLOURSPACE', 0x0EB524); // [2E][B5][24] -- Same value as in AVI (32 bits).
define('EBML_ID_GAMMAVALUE', 0x0FB523); // [2F][B5][23] -- Gamma Value.
define('EBML_ID_CODECSETTINGS', 0x1A9697); // [3A][96][97] -- A string describing the encoding setting used.
define('EBML_ID_CODECINFOURL', 0x1B4040); // [3B][40][40] -- A URL to find information about the codec used.
define('EBML_ID_PREVFILENAME', 0x1C83AB); // [3C][83][AB] -- An escaped filename corresponding to the previous segment.
define('EBML_ID_PREVUID', 0x1CB923); // [3C][B9][23] -- A unique ID to identify the previous chained segment (128 bits).
define('EBML_ID_NEXTFILENAME', 0x1E83BB); // [3E][83][BB] -- An escaped filename corresponding to the next segment.
define('EBML_ID_NEXTUID', 0x1EB923); // [3E][B9][23] -- A unique ID to identify the next chained segment (128 bits).
define('EBML_ID_CONTENTCOMPALGO', 0x0254); // [42][54] -- The compression algorithm used. Algorithms that have been specified so far are:
define('EBML_ID_CONTENTCOMPSETTINGS', 0x0255); // [42][55] -- Settings that might be needed by the decompressor. For Header Stripping (ContentCompAlgo=3), the bytes that were removed from the beggining of each frames of the track.
define('EBML_ID_DOCTYPE', 0x0282); // [42][82] -- A string that describes the type of document that follows this EBML header ('matroska' in our case).
define('EBML_ID_DOCTYPEREADVERSION', 0x0285); // [42][85] -- The minimum DocType version an interpreter has to support to read this file.
define('EBML_ID_EBMLVERSION', 0x0286); // [42][86] -- The version of EBML parser used to create the file.
define('EBML_ID_DOCTYPEVERSION', 0x0287); // [42][87] -- The version of DocType interpreter used to create the file.
define('EBML_ID_EBMLMAXIDLENGTH', 0x02F2); // [42][F2] -- The maximum length of the IDs you'll find in this file (4 or less in Matroska).
define('EBML_ID_EBMLMAXSIZELENGTH', 0x02F3); // [42][F3] -- The maximum length of the sizes you'll find in this file (8 or less in Matroska). This does not override the element size indicated at the beginning of an element. Elements that have an indicated size which is larger than what is allowed by EBMLMaxSizeLength shall be considered invalid.
define('EBML_ID_EBMLREADVERSION', 0x02F7); // [42][F7] -- The minimum EBML version a parser has to support to read this file.
define('EBML_ID_CHAPLANGUAGE', 0x037C); // [43][7C] -- The languages corresponding to the string, in the bibliographic ISO-639-2 form.
define('EBML_ID_CHAPCOUNTRY', 0x037E); // [43][7E] -- The countries corresponding to the string, same 2 octets as in Internet domains.
define('EBML_ID_SEGMENTFAMILY', 0x0444); // [44][44] -- A randomly generated unique ID that all segments related to each other must use (128 bits).
define('EBML_ID_DATEUTC', 0x0461); // [44][61] -- Date of the origin of timecode (value 0), i.e. production date.
define('EBML_ID_TAGLANGUAGE', 0x047A); // [44][7A] -- Specifies the language of the tag specified, in the Matroska languages form.
define('EBML_ID_TAGDEFAULT', 0x0484); // [44][84] -- Indication to know if this is the default/original language to use for the given tag.
define('EBML_ID_TAGBINARY', 0x0485); // [44][85] -- The values of the Tag if it is binary. Note that this cannot be used in the same SimpleTag as TagString.
define('EBML_ID_TAGSTRING', 0x0487); // [44][87] -- The value of the Tag.
define('EBML_ID_DURATION', 0x0489); // [44][89] -- Duration of the segment (based on TimecodeScale).
define('EBML_ID_CHAPPROCESSPRIVATE', 0x050D); // [45][0D] -- Some optional data attached to the ChapProcessCodecID information. For ChapProcessCodecID = 1, it is the "DVD level" equivalent.
define('EBML_ID_CHAPTERFLAGENABLED', 0x0598); // [45][98] -- Specify wether the chapter is enabled. It can be enabled/disabled by a Control Track. When disabled, the movie should skip all the content between the TimeStart and TimeEnd of this chapter.
define('EBML_ID_TAGNAME', 0x05A3); // [45][A3] -- The name of the Tag that is going to be stored.
define('EBML_ID_EDITIONENTRY', 0x05B9); // [45][B9] -- Contains all information about a segment edition.
define('EBML_ID_EDITIONUID', 0x05BC); // [45][BC] -- A unique ID to identify the edition. It's useful for tagging an edition.
define('EBML_ID_EDITIONFLAGHIDDEN', 0x05BD); // [45][BD] -- If an edition is hidden (1), it should not be available to the user interface (but still to Control Tracks).
define('EBML_ID_EDITIONFLAGDEFAULT', 0x05DB); // [45][DB] -- If a flag is set (1) the edition should be used as the default one.
define('EBML_ID_EDITIONFLAGORDERED', 0x05DD); // [45][DD] -- Specify if the chapters can be defined multiple times and the order to play them is enforced.
define('EBML_ID_FILEDATA', 0x065C); // [46][5C] -- The data of the file.
define('EBML_ID_FILEMIMETYPE', 0x0660); // [46][60] -- MIME type of the file.
define('EBML_ID_FILENAME', 0x066E); // [46][6E] -- Filename of the attached file.
define('EBML_ID_FILEREFERRAL', 0x0675); // [46][75] -- A binary value that a track/codec can refer to when the attachment is needed.
define('EBML_ID_FILEDESCRIPTION', 0x067E); // [46][7E] -- A human-friendly name for the attached file.
define('EBML_ID_FILEUID', 0x06AE); // [46][AE] -- Unique ID representing the file, as random as possible.
define('EBML_ID_CONTENTENCALGO', 0x07E1); // [47][E1] -- The encryption algorithm used. The value '0' means that the contents have not been encrypted but only signed. Predefined values:
define('EBML_ID_CONTENTENCKEYID', 0x07E2); // [47][E2] -- For public key algorithms this is the ID of the public key the the data was encrypted with.
define('EBML_ID_CONTENTSIGNATURE', 0x07E3); // [47][E3] -- A cryptographic signature of the contents.
define('EBML_ID_CONTENTSIGKEYID', 0x07E4); // [47][E4] -- This is the ID of the private key the data was signed with.
define('EBML_ID_CONTENTSIGALGO', 0x07E5); // [47][E5] -- The algorithm used for the signature. A value of '0' means that the contents have not been signed but only encrypted. Predefined values:
define('EBML_ID_CONTENTSIGHASHALGO', 0x07E6); // [47][E6] -- The hash algorithm used for the signature. A value of '0' means that the contents have not been signed but only encrypted. Predefined values:
define('EBML_ID_MUXINGAPP', 0x0D80); // [4D][80] -- Muxing application or library ("libmatroska-0.4.3").
define('EBML_ID_SEEK', 0x0DBB); // [4D][BB] -- Contains a single seek entry to an EBML element.
define('EBML_ID_CONTENTENCODINGORDER', 0x1031); // [50][31] -- Tells when this modification was used during encoding/muxing starting with 0 and counting upwards. The decoder/demuxer has to start with the highest order number it finds and work its way down. This value has to be unique over all ContentEncodingOrder elements in the segment.
define('EBML_ID_CONTENTENCODINGSCOPE', 0x1032); // [50][32] -- A bit field that describes which elements have been modified in this way. Values (big endian) can be OR'ed. Possible values:
define('EBML_ID_CONTENTENCODINGTYPE', 0x1033); // [50][33] -- A value describing what kind of transformation has been done. Possible values:
define('EBML_ID_CONTENTCOMPRESSION', 0x1034); // [50][34] -- Settings describing the compression used. Must be present if the value of ContentEncodingType is 0 and absent otherwise. Each block must be decompressable even if no previous block is available in order not to prevent seeking.
define('EBML_ID_CONTENTENCRYPTION', 0x1035); // [50][35] -- Settings describing the encryption used. Must be present if the value of ContentEncodingType is 1 and absent otherwise.
define('EBML_ID_CUEREFNUMBER', 0x135F); // [53][5F] -- Number of the referenced Block of Track X in the specified Cluster.
define('EBML_ID_NAME', 0x136E); // [53][6E] -- A human-readable track name.
define('EBML_ID_CUEBLOCKNUMBER', 0x1378); // [53][78] -- Number of the Block in the specified Cluster.
define('EBML_ID_TRACKOFFSET', 0x137F); // [53][7F] -- A value to add to the Block's Timecode. This can be used to adjust the playback offset of a track.
define('EBML_ID_SEEKID', 0x13AB); // [53][AB] -- The binary ID corresponding to the element name.
define('EBML_ID_SEEKPOSITION', 0x13AC); // [53][AC] -- The position of the element in the segment in octets (0 = first level 1 element).
define('EBML_ID_STEREOMODE', 0x13B8); // [53][B8] -- Stereo-3D video mode.
define('EBML_ID_OLDSTEREOMODE', 0x13B9); // [53][B9] -- Bogus StereoMode value used in old versions of libmatroska. DO NOT USE. (0: mono, 1: right eye, 2: left eye, 3: both eyes).
define('EBML_ID_PIXELCROPBOTTOM', 0x14AA); // [54][AA] -- The number of video pixels to remove at the bottom of the image (for HDTV content).
define('EBML_ID_DISPLAYWIDTH', 0x14B0); // [54][B0] -- Width of the video frames to display.
define('EBML_ID_DISPLAYUNIT', 0x14B2); // [54][B2] -- Type of the unit for DisplayWidth/Height (0: pixels, 1: centimeters, 2: inches).
define('EBML_ID_ASPECTRATIOTYPE', 0x14B3); // [54][B3] -- Specify the possible modifications to the aspect ratio (0: free resizing, 1: keep aspect ratio, 2: fixed).
define('EBML_ID_DISPLAYHEIGHT', 0x14BA); // [54][BA] -- Height of the video frames to display.
define('EBML_ID_PIXELCROPTOP', 0x14BB); // [54][BB] -- The number of video pixels to remove at the top of the image.
define('EBML_ID_PIXELCROPLEFT', 0x14CC); // [54][CC] -- The number of video pixels to remove on the left of the image.
define('EBML_ID_PIXELCROPRIGHT', 0x14DD); // [54][DD] -- The number of video pixels to remove on the right of the image.
define('EBML_ID_FLAGFORCED', 0x15AA); // [55][AA] -- Set if that track MUST be used during playback. There can be many forced track for a kind (audio, video or subs), the player should select the one which language matches the user preference or the default + forced track. Overlay MAY happen between a forced and non-forced track of the same kind.
define('EBML_ID_MAXBLOCKADDITIONID', 0x15EE); // [55][EE] -- The maximum value of BlockAddID. A value 0 means there is no BlockAdditions for this track.
define('EBML_ID_WRITINGAPP', 0x1741); // [57][41] -- Writing application ("mkvmerge-0.3.3").
define('EBML_ID_CLUSTERSILENTTRACKS', 0x1854); // [58][54] -- The list of tracks that are not used in that part of the stream. It is useful when using overlay tracks on seeking. Then you should decide what track to use.
define('EBML_ID_CLUSTERSILENTTRACKNUMBER', 0x18D7); // [58][D7] -- One of the track number that are not used from now on in the stream. It could change later if not specified as silent in a further Cluster.
define('EBML_ID_ATTACHEDFILE', 0x21A7); // [61][A7] -- An attached file.
define('EBML_ID_CONTENTENCODING', 0x2240); // [62][40] -- Settings for one content encoding like compression or encryption.
define('EBML_ID_BITDEPTH', 0x2264); // [62][64] -- Bits per sample, mostly used for PCM.
define('EBML_ID_CODECPRIVATE', 0x23A2); // [63][A2] -- Private data only known to the codec.
define('EBML_ID_TARGETS', 0x23C0); // [63][C0] -- Contain all UIDs where the specified meta data apply. It is void to describe everything in the segment.
define('EBML_ID_CHAPTERPHYSICALEQUIV', 0x23C3); // [63][C3] -- Specify the physical equivalent of this ChapterAtom like "DVD" (60) or "SIDE" (50), see complete list of values.
define('EBML_ID_TAGCHAPTERUID', 0x23C4); // [63][C4] -- A unique ID to identify the Chapter(s) the tags belong to. If the value is 0 at this level, the tags apply to all chapters in the Segment.
define('EBML_ID_TAGTRACKUID', 0x23C5); // [63][C5] -- A unique ID to identify the Track(s) the tags belong to. If the value is 0 at this level, the tags apply to all tracks in the Segment.
define('EBML_ID_TAGATTACHMENTUID', 0x23C6); // [63][C6] -- A unique ID to identify the Attachment(s) the tags belong to. If the value is 0 at this level, the tags apply to all the attachments in the Segment.
define('EBML_ID_TAGEDITIONUID', 0x23C9); // [63][C9] -- A unique ID to identify the EditionEntry(s) the tags belong to. If the value is 0 at this level, the tags apply to all editions in the Segment.
define('EBML_ID_TARGETTYPE', 0x23CA); // [63][CA] -- An informational string that can be used to display the logical level of the target like "ALBUM", "TRACK", "MOVIE", "CHAPTER", etc (see TargetType).
define('EBML_ID_TRACKTRANSLATE', 0x2624); // [66][24] -- The track identification for the given Chapter Codec.
define('EBML_ID_TRACKTRANSLATETRACKID', 0x26A5); // [66][A5] -- The binary value used to represent this track in the chapter codec data. The format depends on the ChapProcessCodecID used.
define('EBML_ID_TRACKTRANSLATECODEC', 0x26BF); // [66][BF] -- The chapter codec using this ID (0: Matroska Script, 1: DVD-menu).
define('EBML_ID_TRACKTRANSLATEEDITIONUID', 0x26FC); // [66][FC] -- Specify an edition UID on which this translation applies. When not specified, it means for all editions found in the segment.
define('EBML_ID_SIMPLETAG', 0x27C8); // [67][C8] -- Contains general information about the target.
define('EBML_ID_TARGETTYPEVALUE', 0x28CA); // [68][CA] -- A number to indicate the logical level of the target (see TargetType).
define('EBML_ID_CHAPPROCESSCOMMAND', 0x2911); // [69][11] -- Contains all the commands associated to the Atom.
define('EBML_ID_CHAPPROCESSTIME', 0x2922); // [69][22] -- Defines when the process command should be handled (0: during the whole chapter, 1: before starting playback, 2: after playback of the chapter).
define('EBML_ID_CHAPTERTRANSLATE', 0x2924); // [69][24] -- A tuple of corresponding ID used by chapter codecs to represent this segment.
define('EBML_ID_CHAPPROCESSDATA', 0x2933); // [69][33] -- Contains the command information. The data should be interpreted depending on the ChapProcessCodecID value. For ChapProcessCodecID = 1, the data correspond to the binary DVD cell pre/post commands.
define('EBML_ID_CHAPPROCESS', 0x2944); // [69][44] -- Contains all the commands associated to the Atom.
define('EBML_ID_CHAPPROCESSCODECID', 0x2955); // [69][55] -- Contains the type of the codec used for the processing. A value of 0 means native Matroska processing (to be defined), a value of 1 means the DVD command set is used. More codec IDs can be added later.
define('EBML_ID_CHAPTERTRANSLATEID', 0x29A5); // [69][A5] -- The binary value used to represent this segment in the chapter codec data. The format depends on the ChapProcessCodecID used.
define('EBML_ID_CHAPTERTRANSLATECODEC', 0x29BF); // [69][BF] -- The chapter codec using this ID (0: Matroska Script, 1: DVD-menu).
define('EBML_ID_CHAPTERTRANSLATEEDITIONUID', 0x29FC); // [69][FC] -- Specify an edition UID on which this correspondance applies. When not specified, it means for all editions found in the segment.
define('EBML_ID_CONTENTENCODINGS', 0x2D80); // [6D][80] -- Settings for several content encoding mechanisms like compression or encryption.
define('EBML_ID_MINCACHE', 0x2DE7); // [6D][E7] -- The minimum number of frames a player should be able to cache during playback. If set to 0, the reference pseudo-cache system is not used.
define('EBML_ID_MAXCACHE', 0x2DF8); // [6D][F8] -- The maximum cache size required to store referenced frames in and the current frame. 0 means no cache is needed.
define('EBML_ID_CHAPTERSEGMENTUID', 0x2E67); // [6E][67] -- A segment to play in place of this chapter. Edition ChapterSegmentEditionUID should be used for this segment, otherwise no edition is used.
define('EBML_ID_CHAPTERSEGMENTEDITIONUID', 0x2EBC); // [6E][BC] -- The edition to play from the segment linked in ChapterSegmentUID.
define('EBML_ID_TRACKOVERLAY', 0x2FAB); // [6F][AB] -- Specify that this track is an overlay track for the Track specified (in the u-integer). That means when this track has a gap (see SilentTracks) the overlay track should be used instead. The order of multiple TrackOverlay matters, the first one is the one that should be used. If not found it should be the second, etc.
define('EBML_ID_TAG', 0x3373); // [73][73] -- Element containing elements specific to Tracks/Chapters.
define('EBML_ID_SEGMENTFILENAME', 0x3384); // [73][84] -- A filename corresponding to this segment.
define('EBML_ID_SEGMENTUID', 0x33A4); // [73][A4] -- A randomly generated unique ID to identify the current segment between many others (128 bits).
define('EBML_ID_CHAPTERUID', 0x33C4); // [73][C4] -- A unique ID to identify the Chapter.
define('EBML_ID_TRACKUID', 0x33C5); // [73][C5] -- A unique ID to identify the Track. This should be kept the same when making a direct stream copy of the Track to another file.
define('EBML_ID_ATTACHMENTLINK', 0x3446); // [74][46] -- The UID of an attachment that is used by this codec.
define('EBML_ID_CLUSTERBLOCKADDITIONS', 0x35A1); // [75][A1] -- Contain additional blocks to complete the main one. An EBML parser that has no knowledge of the Block structure could still see and use/skip these data.
define('EBML_ID_CHANNELPOSITIONS', 0x347B); // [7D][7B] -- Table of horizontal angles for each successive channel, see appendix.
define('EBML_ID_OUTPUTSAMPLINGFREQUENCY', 0x38B5); // [78][B5] -- Real output sampling frequency in Hz (used for SBR techniques).
define('EBML_ID_TITLE', 0x3BA9); // [7B][A9] -- General name of the segment.
define('EBML_ID_CHAPTERDISPLAY', 0x00); // [80] -- Contains all possible strings to use for the chapter display.
define('EBML_ID_TRACKTYPE', 0x03); // [83] -- A set of track types coded on 8 bits (1: video, 2: audio, 3: complex, 0x10: logo, 0x11: subtitle, 0x12: buttons, 0x20: control).
define('EBML_ID_CHAPSTRING', 0x05); // [85] -- Contains the string to use as the chapter atom.
define('EBML_ID_CODECID', 0x06); // [86] -- An ID corresponding to the codec, see the codec page for more info.
define('EBML_ID_FLAGDEFAULT', 0x08); // [88] -- Set if that track (audio, video or subs) SHOULD be used if no language found matches the user preference.
define('EBML_ID_CHAPTERTRACKNUMBER', 0x09); // [89] -- UID of the Track to apply this chapter too. In the absense of a control track, choosing this chapter will select the listed Tracks and deselect unlisted tracks. Absense of this element indicates that the Chapter should be applied to any currently used Tracks.
define('EBML_ID_CLUSTERSLICES', 0x0E); // [8E] -- Contains slices description.
define('EBML_ID_CHAPTERTRACK', 0x0F); // [8F] -- List of tracks on which the chapter applies. If this element is not present, all tracks apply
define('EBML_ID_CHAPTERTIMESTART', 0x11); // [91] -- Timecode of the start of Chapter (not scaled).
define('EBML_ID_CHAPTERTIMEEND', 0x12); // [92] -- Timecode of the end of Chapter (timecode excluded, not scaled).
define('EBML_ID_CUEREFTIME', 0x16); // [96] -- Timecode of the referenced Block.
define('EBML_ID_CUEREFCLUSTER', 0x17); // [97] -- Position of the Cluster containing the referenced Block.
define('EBML_ID_CHAPTERFLAGHIDDEN', 0x18); // [98] -- If a chapter is hidden (1), it should not be available to the user interface (but still to Control Tracks).
define('EBML_ID_FLAGINTERLACED', 0x1A); // [9A] -- Set if the video is interlaced.
define('EBML_ID_CLUSTERBLOCKDURATION', 0x1B); // [9B] -- The duration of the Block (based on TimecodeScale). This element is mandatory when DefaultDuration is set for the track. When not written and with no DefaultDuration, the value is assumed to be the difference between the timecode of this Block and the timecode of the next Block in "display" order (not coding order). This element can be useful at the end of a Track (as there is not other Block available), or when there is a break in a track like for subtitle tracks.
define('EBML_ID_FLAGLACING', 0x1C); // [9C] -- Set if the track may contain blocks using lacing.
define('EBML_ID_CHANNELS', 0x1F); // [9F] -- Numbers of channels in the track.
define('EBML_ID_CLUSTERBLOCKGROUP', 0x20); // [A0] -- Basic container of information containing a single Block or BlockVirtual, and information specific to that Block/VirtualBlock.
define('EBML_ID_CLUSTERBLOCK', 0x21); // [A1] -- Block containing the actual data to be rendered and a timecode relative to the Cluster Timecode.
define('EBML_ID_CLUSTERBLOCKVIRTUAL', 0x22); // [A2] -- A Block with no data. It must be stored in the stream at the place the real Block should be in display order.
define('EBML_ID_CLUSTERSIMPLEBLOCK', 0x23); // [A3] -- Similar to Block but without all the extra information, mostly used to reduced overhead when no extra feature is needed.
define('EBML_ID_CLUSTERCODECSTATE', 0x24); // [A4] -- The new codec state to use. Data interpretation is private to the codec. This information should always be referenced by a seek entry.
define('EBML_ID_CLUSTERBLOCKADDITIONAL', 0x25); // [A5] -- Interpreted by the codec as it wishes (using the BlockAddID).
define('EBML_ID_CLUSTERBLOCKMORE', 0x26); // [A6] -- Contain the BlockAdditional and some parameters.
define('EBML_ID_CLUSTERPOSITION', 0x27); // [A7] -- Position of the Cluster in the segment (0 in live broadcast streams). It might help to resynchronise offset on damaged streams.
define('EBML_ID_CODECDECODEALL', 0x2A); // [AA] -- The codec can decode potentially damaged data.
define('EBML_ID_CLUSTERPREVSIZE', 0x2B); // [AB] -- Size of the previous Cluster, in octets. Can be useful for backward playing.
define('EBML_ID_TRACKENTRY', 0x2E); // [AE] -- Describes a track with all elements.
define('EBML_ID_CLUSTERENCRYPTEDBLOCK', 0x2F); // [AF] -- Similar to SimpleBlock but the data inside the Block are Transformed (encrypt and/or signed).
define('EBML_ID_PIXELWIDTH', 0x30); // [B0] -- Width of the encoded video frames in pixels.
define('EBML_ID_CUETIME', 0x33); // [B3] -- Absolute timecode according to the segment time base.
define('EBML_ID_SAMPLINGFREQUENCY', 0x35); // [B5] -- Sampling frequency in Hz.
define('EBML_ID_CHAPTERATOM', 0x36); // [B6] -- Contains the atom information to use as the chapter atom (apply to all tracks).
define('EBML_ID_CUETRACKPOSITIONS', 0x37); // [B7] -- Contain positions for different tracks corresponding to the timecode.
define('EBML_ID_FLAGENABLED', 0x39); // [B9] -- Set if the track is used.
define('EBML_ID_PIXELHEIGHT', 0x3A); // [BA] -- Height of the encoded video frames in pixels.
define('EBML_ID_CUEPOINT', 0x3B); // [BB] -- Contains all information relative to a seek point in the segment.
define('EBML_ID_CRC32', 0x3F); // [BF] -- The CRC is computed on all the data of the Master element it's in, regardless of its position. It's recommended to put the CRC value at the beggining of the Master element for easier reading. All level 1 elements should include a CRC-32.
define('EBML_ID_CLUSTERBLOCKADDITIONID', 0x4B); // [CB] -- The ID of the BlockAdditional element (0 is the main Block).
define('EBML_ID_CLUSTERLACENUMBER', 0x4C); // [CC] -- The reverse number of the frame in the lace (0 is the last frame, 1 is the next to last, etc). While there are a few files in the wild with this element, it is no longer in use and has been deprecated. Being able to interpret this element is not required for playback.
define('EBML_ID_CLUSTERFRAMENUMBER', 0x4D); // [CD] -- The number of the frame to generate from this lace with this delay (allow you to generate many frames from the same Block/Frame).
define('EBML_ID_CLUSTERDELAY', 0x4E); // [CE] -- The (scaled) delay to apply to the element.
define('EBML_ID_CLUSTERDURATION', 0x4F); // [CF] -- The (scaled) duration to apply to the element.
define('EBML_ID_TRACKNUMBER', 0x57); // [D7] -- The track number as used in the Block Header (using more than 127 tracks is not encouraged, though the design allows an unlimited number).
define('EBML_ID_CUEREFERENCE', 0x5B); // [DB] -- The Clusters containing the required referenced Blocks.
define('EBML_ID_VIDEO', 0x60); // [E0] -- Video settings.
define('EBML_ID_AUDIO', 0x61); // [E1] -- Audio settings.
define('EBML_ID_CLUSTERTIMESLICE', 0x68); // [E8] -- Contains extra time information about the data contained in the Block. While there are a few files in the wild with this element, it is no longer in use and has been deprecated. Being able to interpret this element is not required for playback.
define('EBML_ID_CUECODECSTATE', 0x6A); // [EA] -- The position of the Codec State corresponding to this Cue element. 0 means that the data is taken from the initial Track Entry.
define('EBML_ID_CUEREFCODECSTATE', 0x6B); // [EB] -- The position of the Codec State corresponding to this referenced element. 0 means that the data is taken from the initial Track Entry.
define('EBML_ID_VOID', 0x6C); // [EC] -- Used to void damaged data, to avoid unexpected behaviors when using damaged data. The content is discarded. Also used to reserve space in a sub-element for later use.
define('EBML_ID_CLUSTERTIMECODE', 0x67); // [E7] -- Absolute timecode of the cluster (based on TimecodeScale).
define('EBML_ID_CLUSTERBLOCKADDID', 0x6E); // [EE] -- An ID to identify the BlockAdditional level.
define('EBML_ID_CUECLUSTERPOSITION', 0x71); // [F1] -- The position of the Cluster containing the required Block.
define('EBML_ID_CUETRACK', 0x77); // [F7] -- The track for which a position is given.
define('EBML_ID_CLUSTERREFERENCEPRIORITY', 0x7A); // [FA] -- This frame is referenced and has the specified cache priority. In cache only a frame of the same or higher priority can replace this frame. A value of 0 means the frame is not referenced.
define('EBML_ID_CLUSTERREFERENCEBLOCK', 0x7B); // [FB] -- Timecode of another frame used as a reference (ie: B or P frame). The timecode is relative to the block it's attached to.
define('EBML_ID_CLUSTERREFERENCEVIRTUAL', 0x7D); // [FD] -- Relative position of the data that should be in position of the virtual block.
/**
* @tutorial http://www.matroska.org/technical/specs/index.html
*
* @todo Rewrite EBML parser to reduce it's size and honor default element values
* @todo After rewrite implement stream size calculation, that will provide additional useful info and enable AAC/FLAC audio bitrate detection
*/
class getid3_matroska extends getid3_handler
{
// public options
public static $hide_clusters = true; // if true, do not return information about CLUSTER chunks, since there's a lot of them and they're not usually useful [default: TRUE]
public static $parse_whole_file = false; // true to parse the whole file, not only header [default: FALSE]
// private parser settings/placeholders
private $EBMLbuffer = '';
private $EBMLbuffer_offset = 0;
private $EBMLbuffer_length = 0;
private $current_offset = 0;
private $unuseful_elements = array(EBML_ID_CRC32, EBML_ID_VOID);
public function Analyze()
{
$info = &$this->getid3->info;
// parse container
try {
$this->parseEBML($info);
} catch (Exception $e) {
$info['error'][] = 'EBML parser: '.$e->getMessage();
}
// calculate playtime
if (isset($info['matroska']['info']) && is_array($info['matroska']['info'])) {
foreach ($info['matroska']['info'] as $key => $infoarray) {
if (isset($infoarray['Duration'])) {
// TimecodeScale is how many nanoseconds each Duration unit is
$info['playtime_seconds'] = $infoarray['Duration'] * ((isset($infoarray['TimecodeScale']) ? $infoarray['TimecodeScale'] : 1000000) / 1000000000);
break;
}
}
}
// extract tags
if (isset($info['matroska']['tags']) && is_array($info['matroska']['tags'])) {
foreach ($info['matroska']['tags'] as $key => $infoarray) {
$this->ExtractCommentsSimpleTag($infoarray);
}
}
// process tracks
if (isset($info['matroska']['tracks']['tracks']) && is_array($info['matroska']['tracks']['tracks'])) {
foreach ($info['matroska']['tracks']['tracks'] as $key => $trackarray) {
$track_info = array();
$track_info['dataformat'] = self::CodecIDtoCommonName($trackarray['CodecID']);
$track_info['default'] = (isset($trackarray['FlagDefault']) ? $trackarray['FlagDefault'] : true);
if (isset($trackarray['Name'])) { $track_info['name'] = $trackarray['Name']; }
switch ($trackarray['TrackType']) {
case 1: // Video
$track_info['resolution_x'] = $trackarray['PixelWidth'];
$track_info['resolution_y'] = $trackarray['PixelHeight'];
$track_info['display_unit'] = self::displayUnit(isset($trackarray['DisplayUnit']) ? $trackarray['DisplayUnit'] : 0);
$track_info['display_x'] = (isset($trackarray['DisplayWidth']) ? $trackarray['DisplayWidth'] : $trackarray['PixelWidth']);
$track_info['display_y'] = (isset($trackarray['DisplayHeight']) ? $trackarray['DisplayHeight'] : $trackarray['PixelHeight']);
if (isset($trackarray['PixelCropBottom'])) { $track_info['crop_bottom'] = $trackarray['PixelCropBottom']; }
if (isset($trackarray['PixelCropTop'])) { $track_info['crop_top'] = $trackarray['PixelCropTop']; }
if (isset($trackarray['PixelCropLeft'])) { $track_info['crop_left'] = $trackarray['PixelCropLeft']; }
if (isset($trackarray['PixelCropRight'])) { $track_info['crop_right'] = $trackarray['PixelCropRight']; }
if (isset($trackarray['DefaultDuration'])) { $track_info['frame_rate'] = round(1000000000 / $trackarray['DefaultDuration'], 3); }
if (isset($trackarray['CodecName'])) { $track_info['codec'] = $trackarray['CodecName']; }
switch ($trackarray['CodecID']) {
case 'V_MS/VFW/FOURCC':
if (!getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.audio-video.riff.php', __FILE__, false)) {
$this->warning('Unable to parse codec private data ['.basename(__FILE__).':'.__LINE__.'] because cannot include "module.audio-video.riff.php"');
break;
}
$parsed = getid3_riff::ParseBITMAPINFOHEADER($trackarray['CodecPrivate']);
$track_info['codec'] = getid3_riff::fourccLookup($parsed['fourcc']);
$info['matroska']['track_codec_parsed'][$trackarray['TrackNumber']] = $parsed;
break;
/*case 'V_MPEG4/ISO/AVC':
$h264['profile'] = getid3_lib::BigEndian2Int(substr($trackarray['CodecPrivate'], 1, 1));
$h264['level'] = getid3_lib::BigEndian2Int(substr($trackarray['CodecPrivate'], 3, 1));
$rn = getid3_lib::BigEndian2Int(substr($trackarray['CodecPrivate'], 4, 1));
$h264['NALUlength'] = ($rn & 3) + 1;
$rn = getid3_lib::BigEndian2Int(substr($trackarray['CodecPrivate'], 5, 1));
$nsps = ($rn & 31);
$offset = 6;
for ($i = 0; $i < $nsps; $i ++) {
$length = getid3_lib::BigEndian2Int(substr($trackarray['CodecPrivate'], $offset, 2));
$h264['SPS'][] = substr($trackarray['CodecPrivate'], $offset + 2, $length);
$offset += 2 + $length;
}
$npps = getid3_lib::BigEndian2Int(substr($trackarray['CodecPrivate'], $offset, 1));
$offset += 1;
for ($i = 0; $i < $npps; $i ++) {
$length = getid3_lib::BigEndian2Int(substr($trackarray['CodecPrivate'], $offset, 2));
$h264['PPS'][] = substr($trackarray['CodecPrivate'], $offset + 2, $length);
$offset += 2 + $length;
}
$info['matroska']['track_codec_parsed'][$trackarray['TrackNumber']] = $h264;
break;*/
}
$info['video']['streams'][] = $track_info;
break;
case 2: // Audio
$track_info['sample_rate'] = (isset($trackarray['SamplingFrequency']) ? $trackarray['SamplingFrequency'] : 8000.0);
$track_info['channels'] = (isset($trackarray['Channels']) ? $trackarray['Channels'] : 1);
$track_info['language'] = (isset($trackarray['Language']) ? $trackarray['Language'] : 'eng');
if (isset($trackarray['BitDepth'])) { $track_info['bits_per_sample'] = $trackarray['BitDepth']; }
if (isset($trackarray['CodecName'])) { $track_info['codec'] = $trackarray['CodecName']; }
switch ($trackarray['CodecID']) {
case 'A_PCM/INT/LIT':
case 'A_PCM/INT/BIG':
$track_info['bitrate'] = $trackarray['SamplingFrequency'] * $trackarray['Channels'] * $trackarray['BitDepth'];
break;
case 'A_AC3':
case 'A_DTS':
case 'A_MPEG/L3':
case 'A_MPEG/L2':
case 'A_FLAC':
if (!getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.audio.'.($track_info['dataformat'] == 'mp2' ? 'mp3' : $track_info['dataformat']).'.php', __FILE__, false)) {
$this->warning('Unable to parse audio data ['.basename(__FILE__).':'.__LINE__.'] because cannot include "module.audio.'.$track_info['dataformat'].'.php"');
break;
}
if (!isset($info['matroska']['track_data_offsets'][$trackarray['TrackNumber']])) {
$this->warning('Unable to parse audio data ['.basename(__FILE__).':'.__LINE__.'] because $info[matroska][track_data_offsets]['.$trackarray['TrackNumber'].'] not set');
break;
}
// create temp instance
$getid3_temp = new getID3();
if ($track_info['dataformat'] != 'flac') {
$getid3_temp->openfile($this->getid3->filename);
}
$getid3_temp->info['avdataoffset'] = $info['matroska']['track_data_offsets'][$trackarray['TrackNumber']]['offset'];
if ($track_info['dataformat'][0] == 'm' || $track_info['dataformat'] == 'flac') {
$getid3_temp->info['avdataend'] = $info['matroska']['track_data_offsets'][$trackarray['TrackNumber']]['offset'] + $info['matroska']['track_data_offsets'][$trackarray['TrackNumber']]['length'];
}
// analyze
$class = 'getid3_'.($track_info['dataformat'] == 'mp2' ? 'mp3' : $track_info['dataformat']);
$header_data_key = $track_info['dataformat'][0] == 'm' ? 'mpeg' : $track_info['dataformat'];
$getid3_audio = new $class($getid3_temp, __CLASS__);
if ($track_info['dataformat'] == 'flac') {
$getid3_audio->AnalyzeString($trackarray['CodecPrivate']);
}
else {
$getid3_audio->Analyze();
}
if (!empty($getid3_temp->info[$header_data_key])) {
$info['matroska']['track_codec_parsed'][$trackarray['TrackNumber']] = $getid3_temp->info[$header_data_key];
if (isset($getid3_temp->info['audio']) && is_array($getid3_temp->info['audio'])) {
foreach ($getid3_temp->info['audio'] as $key => $value) {
$track_info[$key] = $value;
}
}
}
else {
$this->warning('Unable to parse audio data ['.basename(__FILE__).':'.__LINE__.'] because '.$class.'::Analyze() failed at offset '.$getid3_temp->info['avdataoffset']);
}
// copy errors and warnings
if (!empty($getid3_temp->info['error'])) {
foreach ($getid3_temp->info['error'] as $newerror) {
$this->warning($class.'() says: ['.$newerror.']');
}
}
if (!empty($getid3_temp->info['warning'])) {
foreach ($getid3_temp->info['warning'] as $newerror) {
if ($track_info['dataformat'] == 'mp3' && preg_match('/^Probable truncated file: expecting \d+ bytes of audio data, only found \d+ \(short by \d+ bytes\)$/', $newerror)) {
// LAME/Xing header is probably set, but audio data is chunked into Matroska file and near-impossible to verify if audio stream is complete, so ignore useless warning
continue;
}
$this->warning($class.'() says: ['.$newerror.']');
}
}
unset($getid3_temp, $getid3_audio);
break;
case 'A_AAC':
case 'A_AAC/MPEG2/LC':
case 'A_AAC/MPEG2/LC/SBR':
case 'A_AAC/MPEG4/LC':
case 'A_AAC/MPEG4/LC/SBR':
$this->warning($trackarray['CodecID'].' audio data contains no header, audio/video bitrates can\'t be calculated');
break;
case 'A_VORBIS':
if (!isset($trackarray['CodecPrivate'])) {
$this->warning('Unable to parse audio data ['.basename(__FILE__).':'.__LINE__.'] because CodecPrivate data not set');
break;
}
$vorbis_offset = strpos($trackarray['CodecPrivate'], 'vorbis', 1);
if ($vorbis_offset === false) {
$this->warning('Unable to parse audio data ['.basename(__FILE__).':'.__LINE__.'] because CodecPrivate data does not contain "vorbis" keyword');
break;
}
$vorbis_offset -= 1;
if (!getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.audio.ogg.php', __FILE__, false)) {
$this->warning('Unable to parse audio data ['.basename(__FILE__).':'.__LINE__.'] because cannot include "module.audio.ogg.php"');
break;
}
// create temp instance
$getid3_temp = new getID3();
// analyze
$getid3_ogg = new getid3_ogg($getid3_temp);
$oggpageinfo['page_seqno'] = 0;
$getid3_ogg->ParseVorbisPageHeader($trackarray['CodecPrivate'], $vorbis_offset, $oggpageinfo);
if (!empty($getid3_temp->info['ogg'])) {
$info['matroska']['track_codec_parsed'][$trackarray['TrackNumber']] = $getid3_temp->info['ogg'];
if (isset($getid3_temp->info['audio']) && is_array($getid3_temp->info['audio'])) {
foreach ($getid3_temp->info['audio'] as $key => $value) {
$track_info[$key] = $value;
}
}
}
// copy errors and warnings
if (!empty($getid3_temp->info['error'])) {
foreach ($getid3_temp->info['error'] as $newerror) {
$this->warning('getid3_ogg() says: ['.$newerror.']');
}
}
if (!empty($getid3_temp->info['warning'])) {
foreach ($getid3_temp->info['warning'] as $newerror) {
$this->warning('getid3_ogg() says: ['.$newerror.']');
}
}
if (!empty($getid3_temp->info['ogg']['bitrate_nominal'])) {
$track_info['bitrate'] = $getid3_temp->info['ogg']['bitrate_nominal'];
}
unset($getid3_temp, $getid3_ogg, $oggpageinfo, $vorbis_offset);
break;
case 'A_MS/ACM':
if (!getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.audio-video.riff.php', __FILE__, false)) {
$this->warning('Unable to parse audio data ['.basename(__FILE__).':'.__LINE__.'] because cannot include "module.audio-video.riff.php"');
break;
}
$parsed = getid3_riff::parseWAVEFORMATex($trackarray['CodecPrivate']);
foreach ($parsed as $key => $value) {
if ($key != 'raw') {
$track_info[$key] = $value;
}
}
$info['matroska']['track_codec_parsed'][$trackarray['TrackNumber']] = $parsed;
break;
default:
$this->warning('Unhandled audio type "'.(isset($trackarray['CodecID']) ? $trackarray['CodecID'] : '').'"');
}
$info['audio']['streams'][] = $track_info;
break;
}
}
if (!empty($info['video']['streams'])) {
$info['video'] = self::getDefaultStreamInfo($info['video']['streams']);
}
if (!empty($info['audio']['streams'])) {
$info['audio'] = self::getDefaultStreamInfo($info['audio']['streams']);
}
}
// process attachments
if (isset($info['matroska']['attachments']) && $this->getid3->option_save_attachments !== getID3::ATTACHMENTS_NONE) {
foreach ($info['matroska']['attachments'] as $i => $entry) {
if (strpos($entry['FileMimeType'], 'image/') === 0 && !empty($entry['FileData'])) {
$info['matroska']['comments']['picture'][] = array('data' => $entry['FileData'], 'image_mime' => $entry['FileMimeType'], 'filename' => $entry['FileName']);
}
}
}
// determine mime type
if (!empty($info['video']['streams'])) {
$info['mime_type'] = ($info['matroska']['doctype'] == 'webm' ? 'video/webm' : 'video/x-matroska');
} elseif (!empty($info['audio']['streams'])) {
$info['mime_type'] = ($info['matroska']['doctype'] == 'webm' ? 'audio/webm' : 'audio/x-matroska');
} elseif (isset($info['mime_type'])) {
unset($info['mime_type']);
}
return true;
}
private function parseEBML(&$info) {
// http://www.matroska.org/technical/specs/index.html#EBMLBasics
$this->current_offset = $info['avdataoffset'];
while ($this->getEBMLelement($top_element, $info['avdataend'])) {
switch ($top_element['id']) {
case EBML_ID_EBML:
$info['fileformat'] = 'matroska';
$info['matroska']['header']['offset'] = $top_element['offset'];
$info['matroska']['header']['length'] = $top_element['length'];
while ($this->getEBMLelement($element_data, $top_element['end'], true)) {
switch ($element_data['id']) {
case EBML_ID_EBMLVERSION:
case EBML_ID_EBMLREADVERSION:
case EBML_ID_EBMLMAXIDLENGTH:
case EBML_ID_EBMLMAXSIZELENGTH:
case EBML_ID_DOCTYPEVERSION:
case EBML_ID_DOCTYPEREADVERSION:
$element_data['data'] = getid3_lib::BigEndian2Int($element_data['data']);
break;
case EBML_ID_DOCTYPE:
$element_data['data'] = getid3_lib::trimNullByte($element_data['data']);
$info['matroska']['doctype'] = $element_data['data'];
break;
default:
$this->unhandledElement('header', __LINE__, $element_data);
}
unset($element_data['offset'], $element_data['end']);
$info['matroska']['header']['elements'][] = $element_data;
}
break;
case EBML_ID_SEGMENT:
$info['matroska']['segment'][0]['offset'] = $top_element['offset'];
$info['matroska']['segment'][0]['length'] = $top_element['length'];
while ($this->getEBMLelement($element_data, $top_element['end'])) {
if ($element_data['id'] != EBML_ID_CLUSTER || !self::$hide_clusters) { // collect clusters only if required
$info['matroska']['segments'][] = $element_data;
}
switch ($element_data['id']) {
case EBML_ID_SEEKHEAD: // Contains the position of other level 1 elements.
while ($this->getEBMLelement($seek_entry, $element_data['end'])) {
switch ($seek_entry['id']) {
case EBML_ID_SEEK: // Contains a single seek entry to an EBML element
while ($this->getEBMLelement($sub_seek_entry, $seek_entry['end'], true)) {
switch ($sub_seek_entry['id']) {
case EBML_ID_SEEKID:
$seek_entry['target_id'] = self::EBML2Int($sub_seek_entry['data']);
$seek_entry['target_name'] = self::EBMLidName($seek_entry['target_id']);
break;
case EBML_ID_SEEKPOSITION:
$seek_entry['target_offset'] = $element_data['offset'] + getid3_lib::BigEndian2Int($sub_seek_entry['data']);
break;
default:
$this->unhandledElement('seekhead.seek', __LINE__, $sub_seek_entry); }
}
if ($seek_entry['target_id'] != EBML_ID_CLUSTER || !self::$hide_clusters) { // collect clusters only if required
$info['matroska']['seek'][] = $seek_entry;
}
break;
default:
$this->unhandledElement('seekhead', __LINE__, $seek_entry);
}
}
break;
case EBML_ID_TRACKS: // A top-level block of information with many tracks described.
$info['matroska']['tracks'] = $element_data;
while ($this->getEBMLelement($track_entry, $element_data['end'])) {
switch ($track_entry['id']) {
case EBML_ID_TRACKENTRY: //subelements: Describes a track with all elements.
while ($this->getEBMLelement($subelement, $track_entry['end'], array(EBML_ID_VIDEO, EBML_ID_AUDIO, EBML_ID_CONTENTENCODINGS, EBML_ID_CODECPRIVATE))) {
switch ($subelement['id']) {
case EBML_ID_TRACKNUMBER:
case EBML_ID_TRACKUID:
case EBML_ID_TRACKTYPE:
case EBML_ID_MINCACHE:
case EBML_ID_MAXCACHE:
case EBML_ID_MAXBLOCKADDITIONID:
case EBML_ID_DEFAULTDURATION: // nanoseconds per frame
$track_entry[$subelement['id_name']] = getid3_lib::BigEndian2Int($subelement['data']);
break;
case EBML_ID_TRACKTIMECODESCALE:
$track_entry[$subelement['id_name']] = getid3_lib::BigEndian2Float($subelement['data']);
break;
case EBML_ID_CODECID:
case EBML_ID_LANGUAGE:
case EBML_ID_NAME:
case EBML_ID_CODECNAME:
$track_entry[$subelement['id_name']] = getid3_lib::trimNullByte($subelement['data']);
break;
case EBML_ID_CODECPRIVATE:
$track_entry[$subelement['id_name']] = $this->readEBMLelementData($subelement['length'], true);
break;
case EBML_ID_FLAGENABLED:
case EBML_ID_FLAGDEFAULT:
case EBML_ID_FLAGFORCED:
case EBML_ID_FLAGLACING:
case EBML_ID_CODECDECODEALL:
$track_entry[$subelement['id_name']] = (bool) getid3_lib::BigEndian2Int($subelement['data']);
break;
case EBML_ID_VIDEO:
while ($this->getEBMLelement($sub_subelement, $subelement['end'], true)) {
switch ($sub_subelement['id']) {
case EBML_ID_PIXELWIDTH:
case EBML_ID_PIXELHEIGHT:
case EBML_ID_PIXELCROPBOTTOM:
case EBML_ID_PIXELCROPTOP:
case EBML_ID_PIXELCROPLEFT:
case EBML_ID_PIXELCROPRIGHT:
case EBML_ID_DISPLAYWIDTH:
case EBML_ID_DISPLAYHEIGHT:
case EBML_ID_DISPLAYUNIT:
case EBML_ID_ASPECTRATIOTYPE:
case EBML_ID_STEREOMODE:
case EBML_ID_OLDSTEREOMODE:
$track_entry[$sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_subelement['data']);
break;
case EBML_ID_FLAGINTERLACED:
$track_entry[$sub_subelement['id_name']] = (bool)getid3_lib::BigEndian2Int($sub_subelement['data']);
break;
case EBML_ID_GAMMAVALUE:
$track_entry[$sub_subelement['id_name']] = getid3_lib::BigEndian2Float($sub_subelement['data']);
break;
case EBML_ID_COLOURSPACE:
$track_entry[$sub_subelement['id_name']] = getid3_lib::trimNullByte($sub_subelement['data']);
break;
default:
$this->unhandledElement('track.video', __LINE__, $sub_subelement);
}
}
break;
case EBML_ID_AUDIO:
while ($this->getEBMLelement($sub_subelement, $subelement['end'], true)) {
switch ($sub_subelement['id']) {
case EBML_ID_CHANNELS:
case EBML_ID_BITDEPTH:
$track_entry[$sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_subelement['data']);
break;
case EBML_ID_SAMPLINGFREQUENCY:
case EBML_ID_OUTPUTSAMPLINGFREQUENCY:
$track_entry[$sub_subelement['id_name']] = getid3_lib::BigEndian2Float($sub_subelement['data']);
break;
case EBML_ID_CHANNELPOSITIONS:
$track_entry[$sub_subelement['id_name']] = getid3_lib::trimNullByte($sub_subelement['data']);
break;
default:
$this->unhandledElement('track.audio', __LINE__, $sub_subelement);
}
}
break;
case EBML_ID_CONTENTENCODINGS:
while ($this->getEBMLelement($sub_subelement, $subelement['end'])) {
switch ($sub_subelement['id']) {
case EBML_ID_CONTENTENCODING:
while ($this->getEBMLelement($sub_sub_subelement, $sub_subelement['end'], array(EBML_ID_CONTENTCOMPRESSION, EBML_ID_CONTENTENCRYPTION))) {
switch ($sub_sub_subelement['id']) {
case EBML_ID_CONTENTENCODINGORDER:
case EBML_ID_CONTENTENCODINGSCOPE:
case EBML_ID_CONTENTENCODINGTYPE:
$track_entry[$sub_subelement['id_name']][$sub_sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_sub_subelement['data']);
break;
case EBML_ID_CONTENTCOMPRESSION:
while ($this->getEBMLelement($sub_sub_sub_subelement, $sub_sub_subelement['end'], true)) {
switch ($sub_sub_sub_subelement['id']) {
case EBML_ID_CONTENTCOMPALGO:
$track_entry[$sub_subelement['id_name']][$sub_sub_subelement['id_name']][$sub_sub_sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_sub_sub_subelement['data']);
break;
case EBML_ID_CONTENTCOMPSETTINGS:
$track_entry[$sub_subelement['id_name']][$sub_sub_subelement['id_name']][$sub_sub_sub_subelement['id_name']] = $sub_sub_sub_subelement['data'];
break;
default:
$this->unhandledElement('track.contentencodings.contentencoding.contentcompression', __LINE__, $sub_sub_sub_subelement);
}
}
break;
case EBML_ID_CONTENTENCRYPTION:
while ($this->getEBMLelement($sub_sub_sub_subelement, $sub_sub_subelement['end'], true)) {
switch ($sub_sub_sub_subelement['id']) {
case EBML_ID_CONTENTENCALGO:
case EBML_ID_CONTENTSIGALGO:
case EBML_ID_CONTENTSIGHASHALGO:
$track_entry[$sub_subelement['id_name']][$sub_sub_subelement['id_name']][$sub_sub_sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_sub_sub_subelement['data']);
break;
case EBML_ID_CONTENTENCKEYID:
case EBML_ID_CONTENTSIGNATURE:
case EBML_ID_CONTENTSIGKEYID:
$track_entry[$sub_subelement['id_name']][$sub_sub_subelement['id_name']][$sub_sub_sub_subelement['id_name']] = $sub_sub_sub_subelement['data'];
break;
default:
$this->unhandledElement('track.contentencodings.contentencoding.contentcompression', __LINE__, $sub_sub_sub_subelement);
}
}
break;
default:
$this->unhandledElement('track.contentencodings.contentencoding', __LINE__, $sub_sub_subelement);
}
}
break;
default:
$this->unhandledElement('track.contentencodings', __LINE__, $sub_subelement);
}
}
break;
default:
$this->unhandledElement('track', __LINE__, $subelement);
}
}
$info['matroska']['tracks']['tracks'][] = $track_entry;
break;
default:
$this->unhandledElement('tracks', __LINE__, $track_entry);
}
}
break;
case EBML_ID_INFO: // Contains miscellaneous general information and statistics on the file.
$info_entry = array();
while ($this->getEBMLelement($subelement, $element_data['end'], true)) {
switch ($subelement['id']) {
case EBML_ID_TIMECODESCALE:
$info_entry[$subelement['id_name']] = getid3_lib::BigEndian2Int($subelement['data']);
break;
case EBML_ID_DURATION:
$info_entry[$subelement['id_name']] = getid3_lib::BigEndian2Float($subelement['data']);
break;
case EBML_ID_DATEUTC:
$info_entry[$subelement['id_name']] = getid3_lib::BigEndian2Int($subelement['data']);
$info_entry[$subelement['id_name'].'_unix'] = self::EBMLdate2unix($info_entry[$subelement['id_name']]);
break;
case EBML_ID_SEGMENTUID:
case EBML_ID_PREVUID:
case EBML_ID_NEXTUID:
$info_entry[$subelement['id_name']] = getid3_lib::trimNullByte($subelement['data']);
break;
case EBML_ID_SEGMENTFAMILY:
$info_entry[$subelement['id_name']][] = getid3_lib::trimNullByte($subelement['data']);
break;
case EBML_ID_SEGMENTFILENAME:
case EBML_ID_PREVFILENAME:
case EBML_ID_NEXTFILENAME:
case EBML_ID_TITLE:
case EBML_ID_MUXINGAPP:
case EBML_ID_WRITINGAPP:
$info_entry[$subelement['id_name']] = getid3_lib::trimNullByte($subelement['data']);
$info['matroska']['comments'][strtolower($subelement['id_name'])][] = $info_entry[$subelement['id_name']];
break;
case EBML_ID_CHAPTERTRANSLATE:
$chaptertranslate_entry = array();
while ($this->getEBMLelement($sub_subelement, $subelement['end'], true)) {
switch ($sub_subelement['id']) {
case EBML_ID_CHAPTERTRANSLATEEDITIONUID:
$chaptertranslate_entry[$sub_subelement['id_name']][] = getid3_lib::BigEndian2Int($sub_subelement['data']);
break;
case EBML_ID_CHAPTERTRANSLATECODEC:
$chaptertranslate_entry[$sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_subelement['data']);
break;
case EBML_ID_CHAPTERTRANSLATEID:
$chaptertranslate_entry[$sub_subelement['id_name']] = getid3_lib::trimNullByte($sub_subelement['data']);
break;
default:
$this->unhandledElement('info.chaptertranslate', __LINE__, $sub_subelement);
}
}
$info_entry[$subelement['id_name']] = $chaptertranslate_entry;
break;
default:
$this->unhandledElement('info', __LINE__, $subelement);
}
}
$info['matroska']['info'][] = $info_entry;
break;
case EBML_ID_CUES: // A top-level element to speed seeking access. All entries are local to the segment. Should be mandatory for non "live" streams.
if (self::$hide_clusters) { // do not parse cues if hide clusters is "ON" till they point to clusters anyway
$this->current_offset = $element_data['end'];
break;
}
$cues_entry = array();
while ($this->getEBMLelement($subelement, $element_data['end'])) {
switch ($subelement['id']) {
case EBML_ID_CUEPOINT:
$cuepoint_entry = array();
while ($this->getEBMLelement($sub_subelement, $subelement['end'], array(EBML_ID_CUETRACKPOSITIONS))) {
switch ($sub_subelement['id']) {
case EBML_ID_CUETRACKPOSITIONS:
$cuetrackpositions_entry = array();
while ($this->getEBMLelement($sub_sub_subelement, $sub_subelement['end'], true)) {
switch ($sub_sub_subelement['id']) {
case EBML_ID_CUETRACK:
case EBML_ID_CUECLUSTERPOSITION:
case EBML_ID_CUEBLOCKNUMBER:
case EBML_ID_CUECODECSTATE:
$cuetrackpositions_entry[$sub_sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_sub_subelement['data']);
break;
default:
$this->unhandledElement('cues.cuepoint.cuetrackpositions', __LINE__, $sub_sub_subelement);
}
}
$cuepoint_entry[$sub_subelement['id_name']][] = $cuetrackpositions_entry;
break;
case EBML_ID_CUETIME:
$cuepoint_entry[$sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_subelement['data']);
break;
default:
$this->unhandledElement('cues.cuepoint', __LINE__, $sub_subelement);
}
}
$cues_entry[] = $cuepoint_entry;
break;
default:
$this->unhandledElement('cues', __LINE__, $subelement);
}
}
$info['matroska']['cues'] = $cues_entry;
break;
case EBML_ID_TAGS: // Element containing elements specific to Tracks/Chapters.
$tags_entry = array();
while ($this->getEBMLelement($subelement, $element_data['end'], false)) {
switch ($subelement['id']) {
case EBML_ID_TAG:
$tag_entry = array();
while ($this->getEBMLelement($sub_subelement, $subelement['end'], false)) {
switch ($sub_subelement['id']) {
case EBML_ID_TARGETS:
$targets_entry = array();
while ($this->getEBMLelement($sub_sub_subelement, $sub_subelement['end'], true)) {
switch ($sub_sub_subelement['id']) {
case EBML_ID_TARGETTYPEVALUE:
$targets_entry[$sub_sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_sub_subelement['data']);
$targets_entry[strtolower($sub_sub_subelement['id_name']).'_long'] = self::TargetTypeValue($targets_entry[$sub_sub_subelement['id_name']]);
break;
case EBML_ID_TARGETTYPE:
$targets_entry[$sub_sub_subelement['id_name']] = $sub_sub_subelement['data'];
break;
case EBML_ID_TAGTRACKUID:
case EBML_ID_TAGEDITIONUID:
case EBML_ID_TAGCHAPTERUID:
case EBML_ID_TAGATTACHMENTUID:
$targets_entry[$sub_sub_subelement['id_name']][] = getid3_lib::BigEndian2Int($sub_sub_subelement['data']);
break;
default:
$this->unhandledElement('tags.tag.targets', __LINE__, $sub_sub_subelement);
}
}
$tag_entry[$sub_subelement['id_name']] = $targets_entry;
break;
case EBML_ID_SIMPLETAG:
$tag_entry[$sub_subelement['id_name']][] = $this->HandleEMBLSimpleTag($sub_subelement['end']);
break;
default:
$this->unhandledElement('tags.tag', __LINE__, $sub_subelement);
}
}
$tags_entry[] = $tag_entry;
break;
default:
$this->unhandledElement('tags', __LINE__, $subelement);
}
}
$info['matroska']['tags'] = $tags_entry;
break;
case EBML_ID_ATTACHMENTS: // Contain attached files.
while ($this->getEBMLelement($subelement, $element_data['end'])) {
switch ($subelement['id']) {
case EBML_ID_ATTACHEDFILE:
$attachedfile_entry = array();
while ($this->getEBMLelement($sub_subelement, $subelement['end'], array(EBML_ID_FILEDATA))) {
switch ($sub_subelement['id']) {
case EBML_ID_FILEDESCRIPTION:
case EBML_ID_FILENAME:
case EBML_ID_FILEMIMETYPE:
$attachedfile_entry[$sub_subelement['id_name']] = $sub_subelement['data'];
break;
case EBML_ID_FILEDATA:
$attachedfile_entry['data_offset'] = $this->current_offset;
$attachedfile_entry['data_length'] = $sub_subelement['length'];
$attachedfile_entry[$sub_subelement['id_name']] = $this->saveAttachment(
$attachedfile_entry['FileName'],
$attachedfile_entry['data_offset'],
$attachedfile_entry['data_length']);
$this->current_offset = $sub_subelement['end'];
break;
case EBML_ID_FILEUID:
$attachedfile_entry[$sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_subelement['data']);
break;
default:
$this->unhandledElement('attachments.attachedfile', __LINE__, $sub_subelement);
}
}
$info['matroska']['attachments'][] = $attachedfile_entry;
break;
default:
$this->unhandledElement('attachments', __LINE__, $subelement);
}
}
break;
case EBML_ID_CHAPTERS:
while ($this->getEBMLelement($subelement, $element_data['end'])) {
switch ($subelement['id']) {
case EBML_ID_EDITIONENTRY:
$editionentry_entry = array();
while ($this->getEBMLelement($sub_subelement, $subelement['end'], array(EBML_ID_CHAPTERATOM))) {
switch ($sub_subelement['id']) {
case EBML_ID_EDITIONUID:
$editionentry_entry[$sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_subelement['data']);
break;
case EBML_ID_EDITIONFLAGHIDDEN:
case EBML_ID_EDITIONFLAGDEFAULT:
case EBML_ID_EDITIONFLAGORDERED:
$editionentry_entry[$sub_subelement['id_name']] = (bool)getid3_lib::BigEndian2Int($sub_subelement['data']);
break;
case EBML_ID_CHAPTERATOM:
$chapteratom_entry = array();
while ($this->getEBMLelement($sub_sub_subelement, $sub_subelement['end'], array(EBML_ID_CHAPTERTRACK, EBML_ID_CHAPTERDISPLAY))) {
switch ($sub_sub_subelement['id']) {
case EBML_ID_CHAPTERSEGMENTUID:
case EBML_ID_CHAPTERSEGMENTEDITIONUID:
$chapteratom_entry[$sub_sub_subelement['id_name']] = $sub_sub_subelement['data'];
break;
case EBML_ID_CHAPTERFLAGENABLED:
case EBML_ID_CHAPTERFLAGHIDDEN:
$chapteratom_entry[$sub_sub_subelement['id_name']] = (bool)getid3_lib::BigEndian2Int($sub_sub_subelement['data']);
break;
case EBML_ID_CHAPTERUID:
case EBML_ID_CHAPTERTIMESTART:
case EBML_ID_CHAPTERTIMEEND:
$chapteratom_entry[$sub_sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_sub_subelement['data']);
break;
case EBML_ID_CHAPTERTRACK:
$chaptertrack_entry = array();
while ($this->getEBMLelement($sub_sub_sub_subelement, $sub_sub_subelement['end'], true)) {
switch ($sub_sub_sub_subelement['id']) {
case EBML_ID_CHAPTERTRACKNUMBER:
$chaptertrack_entry[$sub_sub_sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_sub_sub_subelement['data']);
break;
default:
$this->unhandledElement('chapters.editionentry.chapteratom.chaptertrack', __LINE__, $sub_sub_sub_subelement);
}
}
$chapteratom_entry[$sub_sub_subelement['id_name']][] = $chaptertrack_entry;
break;
case EBML_ID_CHAPTERDISPLAY:
$chapterdisplay_entry = array();
while ($this->getEBMLelement($sub_sub_sub_subelement, $sub_sub_subelement['end'], true)) {
switch ($sub_sub_sub_subelement['id']) {
case EBML_ID_CHAPSTRING:
case EBML_ID_CHAPLANGUAGE:
case EBML_ID_CHAPCOUNTRY:
$chapterdisplay_entry[$sub_sub_sub_subelement['id_name']] = $sub_sub_sub_subelement['data'];
break;
default:
$this->unhandledElement('chapters.editionentry.chapteratom.chapterdisplay', __LINE__, $sub_sub_sub_subelement);
}
}
$chapteratom_entry[$sub_sub_subelement['id_name']][] = $chapterdisplay_entry;
break;
default:
$this->unhandledElement('chapters.editionentry.chapteratom', __LINE__, $sub_sub_subelement);
}
}
$editionentry_entry[$sub_subelement['id_name']][] = $chapteratom_entry;
break;
default:
$this->unhandledElement('chapters.editionentry', __LINE__, $sub_subelement);
}
}
$info['matroska']['chapters'][] = $editionentry_entry;
break;
default:
$this->unhandledElement('chapters', __LINE__, $subelement);
}
}
break;
case EBML_ID_CLUSTER: // The lower level element containing the (monolithic) Block structure.
$cluster_entry = array();
while ($this->getEBMLelement($subelement, $element_data['end'], array(EBML_ID_CLUSTERSILENTTRACKS, EBML_ID_CLUSTERBLOCKGROUP, EBML_ID_CLUSTERSIMPLEBLOCK))) {
switch ($subelement['id']) {
case EBML_ID_CLUSTERTIMECODE:
case EBML_ID_CLUSTERPOSITION:
case EBML_ID_CLUSTERPREVSIZE:
$cluster_entry[$subelement['id_name']] = getid3_lib::BigEndian2Int($subelement['data']);
break;
case EBML_ID_CLUSTERSILENTTRACKS:
$cluster_silent_tracks = array();
while ($this->getEBMLelement($sub_subelement, $subelement['end'], true)) {
switch ($sub_subelement['id']) {
case EBML_ID_CLUSTERSILENTTRACKNUMBER:
$cluster_silent_tracks[] = getid3_lib::BigEndian2Int($sub_subelement['data']);
break;
default:
$this->unhandledElement('cluster.silenttracks', __LINE__, $sub_subelement);
}
}
$cluster_entry[$subelement['id_name']][] = $cluster_silent_tracks;
break;
case EBML_ID_CLUSTERBLOCKGROUP:
$cluster_block_group = array('offset' => $this->current_offset);
while ($this->getEBMLelement($sub_subelement, $subelement['end'], array(EBML_ID_CLUSTERBLOCK))) {
switch ($sub_subelement['id']) {
case EBML_ID_CLUSTERBLOCK:
$cluster_block_group[$sub_subelement['id_name']] = $this->HandleEMBLClusterBlock($sub_subelement, EBML_ID_CLUSTERBLOCK, $info);
break;
case EBML_ID_CLUSTERREFERENCEPRIORITY: // unsigned-int
case EBML_ID_CLUSTERBLOCKDURATION: // unsigned-int
$cluster_block_group[$sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_subelement['data']);
break;
case EBML_ID_CLUSTERREFERENCEBLOCK: // signed-int
$cluster_block_group[$sub_subelement['id_name']][] = getid3_lib::BigEndian2Int($sub_subelement['data'], false, true);
break;
case EBML_ID_CLUSTERCODECSTATE:
$cluster_block_group[$sub_subelement['id_name']] = getid3_lib::trimNullByte($sub_subelement['data']);
break;
default:
$this->unhandledElement('clusters.blockgroup', __LINE__, $sub_subelement);
}
}
$cluster_entry[$subelement['id_name']][] = $cluster_block_group;
break;
case EBML_ID_CLUSTERSIMPLEBLOCK:
$cluster_entry[$subelement['id_name']][] = $this->HandleEMBLClusterBlock($subelement, EBML_ID_CLUSTERSIMPLEBLOCK, $info);
break;
default:
$this->unhandledElement('cluster', __LINE__, $subelement);
}
$this->current_offset = $subelement['end'];
}
if (!self::$hide_clusters) {
$info['matroska']['cluster'][] = $cluster_entry;
}
// check to see if all the data we need exists already, if so, break out of the loop
if (!self::$parse_whole_file) {
if (isset($info['matroska']['info']) && is_array($info['matroska']['info'])) {
if (isset($info['matroska']['tracks']['tracks']) && is_array($info['matroska']['tracks']['tracks'])) {
if (count($info['matroska']['track_data_offsets']) == count($info['matroska']['tracks']['tracks'])) {
return;
}
}
}
}
break;
default:
$this->unhandledElement('segment', __LINE__, $element_data);
}
}
break;
default:
$this->unhandledElement('root', __LINE__, $top_element);
}
}
}
private function EnsureBufferHasEnoughData($min_data=1024) {
if (($this->current_offset - $this->EBMLbuffer_offset) >= ($this->EBMLbuffer_length - $min_data)) {
$read_bytes = max($min_data, $this->getid3->fread_buffer_size());
try {
$this->fseek($this->current_offset);
$this->EBMLbuffer_offset = $this->current_offset;
$this->EBMLbuffer = $this->fread($read_bytes);
$this->EBMLbuffer_length = strlen($this->EBMLbuffer);
} catch (getid3_exception $e) {
$this->warning('EBML parser: '.$e->getMessage());
return false;
}
if ($this->EBMLbuffer_length == 0 && $this->feof()) {
return $this->error('EBML parser: ran out of file at offset '.$this->current_offset);
}
}
return true;
}
private function readEBMLint() {
$actual_offset = $this->current_offset - $this->EBMLbuffer_offset;
// get length of integer
$first_byte_int = ord($this->EBMLbuffer[$actual_offset]);
if (0x80 & $first_byte_int) {
$length = 1;
} elseif (0x40 & $first_byte_int) {
$length = 2;
} elseif (0x20 & $first_byte_int) {
$length = 3;
} elseif (0x10 & $first_byte_int) {
$length = 4;
} elseif (0x08 & $first_byte_int) {
$length = 5;
} elseif (0x04 & $first_byte_int) {
$length = 6;
} elseif (0x02 & $first_byte_int) {
$length = 7;
} elseif (0x01 & $first_byte_int) {
$length = 8;
} else {
throw new Exception('invalid EBML integer (leading 0x00) at '.$this->current_offset);
}
// read
$int_value = self::EBML2Int(substr($this->EBMLbuffer, $actual_offset, $length));
$this->current_offset += $length;
return $int_value;
}
private function readEBMLelementData($length, $check_buffer=false) {
if ($check_buffer && !$this->EnsureBufferHasEnoughData($length)) {
return false;
}
$data = substr($this->EBMLbuffer, $this->current_offset - $this->EBMLbuffer_offset, $length);
$this->current_offset += $length;
return $data;
}
private function getEBMLelement(&$element, $parent_end, $get_data=false) {
if ($this->current_offset >= $parent_end) {
return false;
}
if (!$this->EnsureBufferHasEnoughData()) {
$this->current_offset = PHP_INT_MAX; // do not exit parser right now, allow to finish current loop to gather maximum information
return false;
}
$element = array();
// set offset
$element['offset'] = $this->current_offset;
// get ID
$element['id'] = $this->readEBMLint();
// get name
$element['id_name'] = self::EBMLidName($element['id']);
// get length
$element['length'] = $this->readEBMLint();
// get end offset
$element['end'] = $this->current_offset + $element['length'];
// get raw data
$dont_parse = (in_array($element['id'], $this->unuseful_elements) || $element['id_name'] == dechex($element['id']));
if (($get_data === true || (is_array($get_data) && !in_array($element['id'], $get_data))) && !$dont_parse) {
$element['data'] = $this->readEBMLelementData($element['length'], $element);
}
return true;
}
private function unhandledElement($type, $line, $element) {
// warn only about unknown and missed elements, not about unuseful
if (!in_array($element['id'], $this->unuseful_elements)) {
$this->warning('Unhandled '.$type.' element ['.basename(__FILE__).':'.$line.'] ('.$element['id'].'::'.$element['id_name'].' ['.$element['length'].' bytes]) at '.$element['offset']);
}
// increase offset for unparsed elements
if (!isset($element['data'])) {
$this->current_offset = $element['end'];
}
}
private function ExtractCommentsSimpleTag($SimpleTagArray) {
if (!empty($SimpleTagArray['SimpleTag'])) {
foreach ($SimpleTagArray['SimpleTag'] as $SimpleTagKey => $SimpleTagData) {
if (!empty($SimpleTagData['TagName']) && !empty($SimpleTagData['TagString'])) {
$this->getid3->info['matroska']['comments'][strtolower($SimpleTagData['TagName'])][] = $SimpleTagData['TagString'];
}
if (!empty($SimpleTagData['SimpleTag'])) {
$this->ExtractCommentsSimpleTag($SimpleTagData);
}
}
}
return true;
}
private function HandleEMBLSimpleTag($parent_end) {
$simpletag_entry = array();
while ($this->getEBMLelement($element, $parent_end, array(EBML_ID_SIMPLETAG))) {
switch ($element['id']) {
case EBML_ID_TAGNAME:
case EBML_ID_TAGLANGUAGE:
case EBML_ID_TAGSTRING:
case EBML_ID_TAGBINARY:
$simpletag_entry[$element['id_name']] = $element['data'];
break;
case EBML_ID_SIMPLETAG:
$simpletag_entry[$element['id_name']][] = $this->HandleEMBLSimpleTag($element['end']);
break;
case EBML_ID_TAGDEFAULT:
$simpletag_entry[$element['id_name']] = (bool)getid3_lib::BigEndian2Int($element['data']);
break;
default:
$this->unhandledElement('tag.simpletag', __LINE__, $element);
}
}
return $simpletag_entry;
}
private function HandleEMBLClusterBlock($element, $block_type, &$info) {
// http://www.matroska.org/technical/specs/index.html#block_structure
// http://www.matroska.org/technical/specs/index.html#simpleblock_structure
$block_data = array();
$block_data['tracknumber'] = $this->readEBMLint();
$block_data['timecode'] = getid3_lib::BigEndian2Int($this->readEBMLelementData(2), false, true);
$block_data['flags_raw'] = getid3_lib::BigEndian2Int($this->readEBMLelementData(1));
if ($block_type == EBML_ID_CLUSTERSIMPLEBLOCK) {
$block_data['flags']['keyframe'] = (($block_data['flags_raw'] & 0x80) >> 7);
//$block_data['flags']['reserved1'] = (($block_data['flags_raw'] & 0x70) >> 4);
}
else {
//$block_data['flags']['reserved1'] = (($block_data['flags_raw'] & 0xF0) >> 4);
}
$block_data['flags']['invisible'] = (bool)(($block_data['flags_raw'] & 0x08) >> 3);
$block_data['flags']['lacing'] = (($block_data['flags_raw'] & 0x06) >> 1); // 00=no lacing; 01=Xiph lacing; 11=EBML lacing; 10=fixed-size lacing
if ($block_type == EBML_ID_CLUSTERSIMPLEBLOCK) {
$block_data['flags']['discardable'] = (($block_data['flags_raw'] & 0x01));
}
else {
//$block_data['flags']['reserved2'] = (($block_data['flags_raw'] & 0x01) >> 0);
}
$block_data['flags']['lacing_type'] = self::BlockLacingType($block_data['flags']['lacing']);
// Lace (when lacing bit is set)
if ($block_data['flags']['lacing'] > 0) {
$block_data['lace_frames'] = getid3_lib::BigEndian2Int($this->readEBMLelementData(1)) + 1; // Number of frames in the lace-1 (uint8)
if ($block_data['flags']['lacing'] != 0x02) {
for ($i = 1; $i < $block_data['lace_frames']; $i ++) { // Lace-coded size of each frame of the lace, except for the last one (multiple uint8). *This is not used with Fixed-size lacing as it is calculated automatically from (total size of lace) / (number of frames in lace).
if ($block_data['flags']['lacing'] == 0x03) { // EBML lacing
$block_data['lace_frames_size'][$i] = $this->readEBMLint(); // TODO: read size correctly, calc size for the last frame. For now offsets are deteminded OK with readEBMLint() and that's the most important thing.
}
else { // Xiph lacing
$block_data['lace_frames_size'][$i] = 0;
do {
$size = getid3_lib::BigEndian2Int($this->readEBMLelementData(1));
$block_data['lace_frames_size'][$i] += $size;
}
while ($size == 255);
}
}
if ($block_data['flags']['lacing'] == 0x01) { // calc size of the last frame only for Xiph lacing, till EBML sizes are now anyway determined incorrectly
$block_data['lace_frames_size'][] = $element['end'] - $this->current_offset - array_sum($block_data['lace_frames_size']);
}
}
}
if (!isset($info['matroska']['track_data_offsets'][$block_data['tracknumber']])) {
$info['matroska']['track_data_offsets'][$block_data['tracknumber']]['offset'] = $this->current_offset;
$info['matroska']['track_data_offsets'][$block_data['tracknumber']]['length'] = $element['end'] - $this->current_offset;
//$info['matroska']['track_data_offsets'][$block_data['tracknumber']]['total_length'] = 0;
}
//$info['matroska']['track_data_offsets'][$block_data['tracknumber']]['total_length'] += $info['matroska']['track_data_offsets'][$block_data['tracknumber']]['length'];
//$info['matroska']['track_data_offsets'][$block_data['tracknumber']]['duration'] = $block_data['timecode'] * ((isset($info['matroska']['info'][0]['TimecodeScale']) ? $info['matroska']['info'][0]['TimecodeScale'] : 1000000) / 1000000000);
// set offset manually
$this->current_offset = $element['end'];
return $block_data;
}
private static function EBML2Int($EBMLstring) {
// http://matroska.org/specs/
// Element ID coded with an UTF-8 like system:
// 1xxx xxxx - Class A IDs (2^7 -2 possible values) (base 0x8X)
// 01xx xxxx xxxx xxxx - Class B IDs (2^14-2 possible values) (base 0x4X 0xXX)
// 001x xxxx xxxx xxxx xxxx xxxx - Class C IDs (2^21-2 possible values) (base 0x2X 0xXX 0xXX)
// 0001 xxxx xxxx xxxx xxxx xxxx xxxx xxxx - Class D IDs (2^28-2 possible values) (base 0x1X 0xXX 0xXX 0xXX)
// Values with all x at 0 and 1 are reserved (hence the -2).
// Data size, in octets, is also coded with an UTF-8 like system :
// 1xxx xxxx - value 0 to 2^7-2
// 01xx xxxx xxxx xxxx - value 0 to 2^14-2
// 001x xxxx xxxx xxxx xxxx xxxx - value 0 to 2^21-2
// 0001 xxxx xxxx xxxx xxxx xxxx xxxx xxxx - value 0 to 2^28-2
// 0000 1xxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx - value 0 to 2^35-2
// 0000 01xx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx - value 0 to 2^42-2
// 0000 001x xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx - value 0 to 2^49-2
// 0000 0001 xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx - value 0 to 2^56-2
$first_byte_int = ord($EBMLstring[0]);
if (0x80 & $first_byte_int) {
$EBMLstring[0] = chr($first_byte_int & 0x7F);
} elseif (0x40 & $first_byte_int) {
$EBMLstring[0] = chr($first_byte_int & 0x3F);
} elseif (0x20 & $first_byte_int) {
$EBMLstring[0] = chr($first_byte_int & 0x1F);
} elseif (0x10 & $first_byte_int) {
$EBMLstring[0] = chr($first_byte_int & 0x0F);
} elseif (0x08 & $first_byte_int) {
$EBMLstring[0] = chr($first_byte_int & 0x07);
} elseif (0x04 & $first_byte_int) {
$EBMLstring[0] = chr($first_byte_int & 0x03);
} elseif (0x02 & $first_byte_int) {
$EBMLstring[0] = chr($first_byte_int & 0x01);
} elseif (0x01 & $first_byte_int) {
$EBMLstring[0] = chr($first_byte_int & 0x00);
}
return getid3_lib::BigEndian2Int($EBMLstring);
}
private static function EBMLdate2unix($EBMLdatestamp) {
// Date - signed 8 octets integer in nanoseconds with 0 indicating the precise beginning of the millennium (at 2001-01-01T00:00:00,000000000 UTC)
// 978307200 == mktime(0, 0, 0, 1, 1, 2001) == January 1, 2001 12:00:00am UTC
return round(($EBMLdatestamp / 1000000000) + 978307200);
}
public static function TargetTypeValue($target_type) {
// http://www.matroska.org/technical/specs/tagging/index.html
static $TargetTypeValue = array();
if (empty($TargetTypeValue)) {
$TargetTypeValue[10] = 'A: ~ V:shot'; // the lowest hierarchy found in music or movies
$TargetTypeValue[20] = 'A:subtrack/part/movement ~ V:scene'; // corresponds to parts of a track for audio (like a movement)
$TargetTypeValue[30] = 'A:track/song ~ V:chapter'; // the common parts of an album or a movie
$TargetTypeValue[40] = 'A:part/session ~ V:part/session'; // when an album or episode has different logical parts
$TargetTypeValue[50] = 'A:album/opera/concert ~ V:movie/episode/concert'; // the most common grouping level of music and video (equals to an episode for TV series)
$TargetTypeValue[60] = 'A:edition/issue/volume/opus ~ V:season/sequel/volume'; // a list of lower levels grouped together
$TargetTypeValue[70] = 'A:collection ~ V:collection'; // the high hierarchy consisting of many different lower items
}
return (isset($TargetTypeValue[$target_type]) ? $TargetTypeValue[$target_type] : $target_type);
}
public static function BlockLacingType($lacingtype) {
// http://matroska.org/technical/specs/index.html#block_structure
static $BlockLacingType = array();
if (empty($BlockLacingType)) {
$BlockLacingType[0x00] = 'no lacing';
$BlockLacingType[0x01] = 'Xiph lacing';
$BlockLacingType[0x02] = 'fixed-size lacing';
$BlockLacingType[0x03] = 'EBML lacing';
}
return (isset($BlockLacingType[$lacingtype]) ? $BlockLacingType[$lacingtype] : $lacingtype);
}
public static function CodecIDtoCommonName($codecid) {
// http://www.matroska.org/technical/specs/codecid/index.html
static $CodecIDlist = array();
if (empty($CodecIDlist)) {
$CodecIDlist['A_AAC'] = 'aac';
$CodecIDlist['A_AAC/MPEG2/LC'] = 'aac';
$CodecIDlist['A_AC3'] = 'ac3';
$CodecIDlist['A_DTS'] = 'dts';
$CodecIDlist['A_FLAC'] = 'flac';
$CodecIDlist['A_MPEG/L1'] = 'mp1';
$CodecIDlist['A_MPEG/L2'] = 'mp2';
$CodecIDlist['A_MPEG/L3'] = 'mp3';
$CodecIDlist['A_PCM/INT/LIT'] = 'pcm'; // PCM Integer Little Endian
$CodecIDlist['A_PCM/INT/BIG'] = 'pcm'; // PCM Integer Big Endian
$CodecIDlist['A_QUICKTIME/QDMC'] = 'quicktime'; // Quicktime: QDesign Music
$CodecIDlist['A_QUICKTIME/QDM2'] = 'quicktime'; // Quicktime: QDesign Music v2
$CodecIDlist['A_VORBIS'] = 'vorbis';
$CodecIDlist['V_MPEG1'] = 'mpeg';
$CodecIDlist['V_THEORA'] = 'theora';
$CodecIDlist['V_REAL/RV40'] = 'real';
$CodecIDlist['V_REAL/RV10'] = 'real';
$CodecIDlist['V_REAL/RV20'] = 'real';
$CodecIDlist['V_REAL/RV30'] = 'real';
$CodecIDlist['V_QUICKTIME'] = 'quicktime'; // Quicktime
$CodecIDlist['V_MPEG4/ISO/AP'] = 'mpeg4';
$CodecIDlist['V_MPEG4/ISO/ASP'] = 'mpeg4';
$CodecIDlist['V_MPEG4/ISO/AVC'] = 'h264';
$CodecIDlist['V_MPEG4/ISO/SP'] = 'mpeg4';
$CodecIDlist['V_VP8'] = 'vp8';
$CodecIDlist['V_MS/VFW/FOURCC'] = 'riff';
$CodecIDlist['A_MS/ACM'] = 'riff';
}
return (isset($CodecIDlist[$codecid]) ? $CodecIDlist[$codecid] : $codecid);
}
private static function EBMLidName($value) {
static $EBMLidList = array();
if (empty($EBMLidList)) {
$EBMLidList[EBML_ID_ASPECTRATIOTYPE] = 'AspectRatioType';
$EBMLidList[EBML_ID_ATTACHEDFILE] = 'AttachedFile';
$EBMLidList[EBML_ID_ATTACHMENTLINK] = 'AttachmentLink';
$EBMLidList[EBML_ID_ATTACHMENTS] = 'Attachments';
$EBMLidList[EBML_ID_AUDIO] = 'Audio';
$EBMLidList[EBML_ID_BITDEPTH] = 'BitDepth';
$EBMLidList[EBML_ID_CHANNELPOSITIONS] = 'ChannelPositions';
$EBMLidList[EBML_ID_CHANNELS] = 'Channels';
$EBMLidList[EBML_ID_CHAPCOUNTRY] = 'ChapCountry';
$EBMLidList[EBML_ID_CHAPLANGUAGE] = 'ChapLanguage';
$EBMLidList[EBML_ID_CHAPPROCESS] = 'ChapProcess';
$EBMLidList[EBML_ID_CHAPPROCESSCODECID] = 'ChapProcessCodecID';
$EBMLidList[EBML_ID_CHAPPROCESSCOMMAND] = 'ChapProcessCommand';
$EBMLidList[EBML_ID_CHAPPROCESSDATA] = 'ChapProcessData';
$EBMLidList[EBML_ID_CHAPPROCESSPRIVATE] = 'ChapProcessPrivate';
$EBMLidList[EBML_ID_CHAPPROCESSTIME] = 'ChapProcessTime';
$EBMLidList[EBML_ID_CHAPSTRING] = 'ChapString';
$EBMLidList[EBML_ID_CHAPTERATOM] = 'ChapterAtom';
$EBMLidList[EBML_ID_CHAPTERDISPLAY] = 'ChapterDisplay';
$EBMLidList[EBML_ID_CHAPTERFLAGENABLED] = 'ChapterFlagEnabled';
$EBMLidList[EBML_ID_CHAPTERFLAGHIDDEN] = 'ChapterFlagHidden';
$EBMLidList[EBML_ID_CHAPTERPHYSICALEQUIV] = 'ChapterPhysicalEquiv';
$EBMLidList[EBML_ID_CHAPTERS] = 'Chapters';
$EBMLidList[EBML_ID_CHAPTERSEGMENTEDITIONUID] = 'ChapterSegmentEditionUID';
$EBMLidList[EBML_ID_CHAPTERSEGMENTUID] = 'ChapterSegmentUID';
$EBMLidList[EBML_ID_CHAPTERTIMEEND] = 'ChapterTimeEnd';
$EBMLidList[EBML_ID_CHAPTERTIMESTART] = 'ChapterTimeStart';
$EBMLidList[EBML_ID_CHAPTERTRACK] = 'ChapterTrack';
$EBMLidList[EBML_ID_CHAPTERTRACKNUMBER] = 'ChapterTrackNumber';
$EBMLidList[EBML_ID_CHAPTERTRANSLATE] = 'ChapterTranslate';
$EBMLidList[EBML_ID_CHAPTERTRANSLATECODEC] = 'ChapterTranslateCodec';
$EBMLidList[EBML_ID_CHAPTERTRANSLATEEDITIONUID] = 'ChapterTranslateEditionUID';
$EBMLidList[EBML_ID_CHAPTERTRANSLATEID] = 'ChapterTranslateID';
$EBMLidList[EBML_ID_CHAPTERUID] = 'ChapterUID';
$EBMLidList[EBML_ID_CLUSTER] = 'Cluster';
$EBMLidList[EBML_ID_CLUSTERBLOCK] = 'ClusterBlock';
$EBMLidList[EBML_ID_CLUSTERBLOCKADDID] = 'ClusterBlockAddID';
$EBMLidList[EBML_ID_CLUSTERBLOCKADDITIONAL] = 'ClusterBlockAdditional';
$EBMLidList[EBML_ID_CLUSTERBLOCKADDITIONID] = 'ClusterBlockAdditionID';
$EBMLidList[EBML_ID_CLUSTERBLOCKADDITIONS] = 'ClusterBlockAdditions';
$EBMLidList[EBML_ID_CLUSTERBLOCKDURATION] = 'ClusterBlockDuration';
$EBMLidList[EBML_ID_CLUSTERBLOCKGROUP] = 'ClusterBlockGroup';
$EBMLidList[EBML_ID_CLUSTERBLOCKMORE] = 'ClusterBlockMore';
$EBMLidList[EBML_ID_CLUSTERBLOCKVIRTUAL] = 'ClusterBlockVirtual';
$EBMLidList[EBML_ID_CLUSTERCODECSTATE] = 'ClusterCodecState';
$EBMLidList[EBML_ID_CLUSTERDELAY] = 'ClusterDelay';
$EBMLidList[EBML_ID_CLUSTERDURATION] = 'ClusterDuration';
$EBMLidList[EBML_ID_CLUSTERENCRYPTEDBLOCK] = 'ClusterEncryptedBlock';
$EBMLidList[EBML_ID_CLUSTERFRAMENUMBER] = 'ClusterFrameNumber';
$EBMLidList[EBML_ID_CLUSTERLACENUMBER] = 'ClusterLaceNumber';
$EBMLidList[EBML_ID_CLUSTERPOSITION] = 'ClusterPosition';
$EBMLidList[EBML_ID_CLUSTERPREVSIZE] = 'ClusterPrevSize';
$EBMLidList[EBML_ID_CLUSTERREFERENCEBLOCK] = 'ClusterReferenceBlock';
$EBMLidList[EBML_ID_CLUSTERREFERENCEPRIORITY] = 'ClusterReferencePriority';
$EBMLidList[EBML_ID_CLUSTERREFERENCEVIRTUAL] = 'ClusterReferenceVirtual';
$EBMLidList[EBML_ID_CLUSTERSILENTTRACKNUMBER] = 'ClusterSilentTrackNumber';
$EBMLidList[EBML_ID_CLUSTERSILENTTRACKS] = 'ClusterSilentTracks';
$EBMLidList[EBML_ID_CLUSTERSIMPLEBLOCK] = 'ClusterSimpleBlock';
$EBMLidList[EBML_ID_CLUSTERTIMECODE] = 'ClusterTimecode';
$EBMLidList[EBML_ID_CLUSTERTIMESLICE] = 'ClusterTimeSlice';
$EBMLidList[EBML_ID_CODECDECODEALL] = 'CodecDecodeAll';
$EBMLidList[EBML_ID_CODECDOWNLOADURL] = 'CodecDownloadURL';
$EBMLidList[EBML_ID_CODECID] = 'CodecID';
$EBMLidList[EBML_ID_CODECINFOURL] = 'CodecInfoURL';
$EBMLidList[EBML_ID_CODECNAME] = 'CodecName';
$EBMLidList[EBML_ID_CODECPRIVATE] = 'CodecPrivate';
$EBMLidList[EBML_ID_CODECSETTINGS] = 'CodecSettings';
$EBMLidList[EBML_ID_COLOURSPACE] = 'ColourSpace';
$EBMLidList[EBML_ID_CONTENTCOMPALGO] = 'ContentCompAlgo';
$EBMLidList[EBML_ID_CONTENTCOMPRESSION] = 'ContentCompression';
$EBMLidList[EBML_ID_CONTENTCOMPSETTINGS] = 'ContentCompSettings';
$EBMLidList[EBML_ID_CONTENTENCALGO] = 'ContentEncAlgo';
$EBMLidList[EBML_ID_CONTENTENCKEYID] = 'ContentEncKeyID';
$EBMLidList[EBML_ID_CONTENTENCODING] = 'ContentEncoding';
$EBMLidList[EBML_ID_CONTENTENCODINGORDER] = 'ContentEncodingOrder';
$EBMLidList[EBML_ID_CONTENTENCODINGS] = 'ContentEncodings';
$EBMLidList[EBML_ID_CONTENTENCODINGSCOPE] = 'ContentEncodingScope';
$EBMLidList[EBML_ID_CONTENTENCODINGTYPE] = 'ContentEncodingType';
$EBMLidList[EBML_ID_CONTENTENCRYPTION] = 'ContentEncryption';
$EBMLidList[EBML_ID_CONTENTSIGALGO] = 'ContentSigAlgo';
$EBMLidList[EBML_ID_CONTENTSIGHASHALGO] = 'ContentSigHashAlgo';
$EBMLidList[EBML_ID_CONTENTSIGKEYID] = 'ContentSigKeyID';
$EBMLidList[EBML_ID_CONTENTSIGNATURE] = 'ContentSignature';
$EBMLidList[EBML_ID_CRC32] = 'CRC32';
$EBMLidList[EBML_ID_CUEBLOCKNUMBER] = 'CueBlockNumber';
$EBMLidList[EBML_ID_CUECLUSTERPOSITION] = 'CueClusterPosition';
$EBMLidList[EBML_ID_CUECODECSTATE] = 'CueCodecState';
$EBMLidList[EBML_ID_CUEPOINT] = 'CuePoint';
$EBMLidList[EBML_ID_CUEREFCLUSTER] = 'CueRefCluster';
$EBMLidList[EBML_ID_CUEREFCODECSTATE] = 'CueRefCodecState';
$EBMLidList[EBML_ID_CUEREFERENCE] = 'CueReference';
$EBMLidList[EBML_ID_CUEREFNUMBER] = 'CueRefNumber';
$EBMLidList[EBML_ID_CUEREFTIME] = 'CueRefTime';
$EBMLidList[EBML_ID_CUES] = 'Cues';
$EBMLidList[EBML_ID_CUETIME] = 'CueTime';
$EBMLidList[EBML_ID_CUETRACK] = 'CueTrack';
$EBMLidList[EBML_ID_CUETRACKPOSITIONS] = 'CueTrackPositions';
$EBMLidList[EBML_ID_DATEUTC] = 'DateUTC';
$EBMLidList[EBML_ID_DEFAULTDURATION] = 'DefaultDuration';
$EBMLidList[EBML_ID_DISPLAYHEIGHT] = 'DisplayHeight';
$EBMLidList[EBML_ID_DISPLAYUNIT] = 'DisplayUnit';
$EBMLidList[EBML_ID_DISPLAYWIDTH] = 'DisplayWidth';
$EBMLidList[EBML_ID_DOCTYPE] = 'DocType';
$EBMLidList[EBML_ID_DOCTYPEREADVERSION] = 'DocTypeReadVersion';
$EBMLidList[EBML_ID_DOCTYPEVERSION] = 'DocTypeVersion';
$EBMLidList[EBML_ID_DURATION] = 'Duration';
$EBMLidList[EBML_ID_EBML] = 'EBML';
$EBMLidList[EBML_ID_EBMLMAXIDLENGTH] = 'EBMLMaxIDLength';
$EBMLidList[EBML_ID_EBMLMAXSIZELENGTH] = 'EBMLMaxSizeLength';
$EBMLidList[EBML_ID_EBMLREADVERSION] = 'EBMLReadVersion';
$EBMLidList[EBML_ID_EBMLVERSION] = 'EBMLVersion';
$EBMLidList[EBML_ID_EDITIONENTRY] = 'EditionEntry';
$EBMLidList[EBML_ID_EDITIONFLAGDEFAULT] = 'EditionFlagDefault';
$EBMLidList[EBML_ID_EDITIONFLAGHIDDEN] = 'EditionFlagHidden';
$EBMLidList[EBML_ID_EDITIONFLAGORDERED] = 'EditionFlagOrdered';
$EBMLidList[EBML_ID_EDITIONUID] = 'EditionUID';
$EBMLidList[EBML_ID_FILEDATA] = 'FileData';
$EBMLidList[EBML_ID_FILEDESCRIPTION] = 'FileDescription';
$EBMLidList[EBML_ID_FILEMIMETYPE] = 'FileMimeType';
$EBMLidList[EBML_ID_FILENAME] = 'FileName';
$EBMLidList[EBML_ID_FILEREFERRAL] = 'FileReferral';
$EBMLidList[EBML_ID_FILEUID] = 'FileUID';
$EBMLidList[EBML_ID_FLAGDEFAULT] = 'FlagDefault';
$EBMLidList[EBML_ID_FLAGENABLED] = 'FlagEnabled';
$EBMLidList[EBML_ID_FLAGFORCED] = 'FlagForced';
$EBMLidList[EBML_ID_FLAGINTERLACED] = 'FlagInterlaced';
$EBMLidList[EBML_ID_FLAGLACING] = 'FlagLacing';
$EBMLidList[EBML_ID_GAMMAVALUE] = 'GammaValue';
$EBMLidList[EBML_ID_INFO] = 'Info';
$EBMLidList[EBML_ID_LANGUAGE] = 'Language';
$EBMLidList[EBML_ID_MAXBLOCKADDITIONID] = 'MaxBlockAdditionID';
$EBMLidList[EBML_ID_MAXCACHE] = 'MaxCache';
$EBMLidList[EBML_ID_MINCACHE] = 'MinCache';
$EBMLidList[EBML_ID_MUXINGAPP] = 'MuxingApp';
$EBMLidList[EBML_ID_NAME] = 'Name';
$EBMLidList[EBML_ID_NEXTFILENAME] = 'NextFilename';
$EBMLidList[EBML_ID_NEXTUID] = 'NextUID';
$EBMLidList[EBML_ID_OUTPUTSAMPLINGFREQUENCY] = 'OutputSamplingFrequency';
$EBMLidList[EBML_ID_PIXELCROPBOTTOM] = 'PixelCropBottom';
$EBMLidList[EBML_ID_PIXELCROPLEFT] = 'PixelCropLeft';
$EBMLidList[EBML_ID_PIXELCROPRIGHT] = 'PixelCropRight';
$EBMLidList[EBML_ID_PIXELCROPTOP] = 'PixelCropTop';
$EBMLidList[EBML_ID_PIXELHEIGHT] = 'PixelHeight';
$EBMLidList[EBML_ID_PIXELWIDTH] = 'PixelWidth';
$EBMLidList[EBML_ID_PREVFILENAME] = 'PrevFilename';
$EBMLidList[EBML_ID_PREVUID] = 'PrevUID';
$EBMLidList[EBML_ID_SAMPLINGFREQUENCY] = 'SamplingFrequency';
$EBMLidList[EBML_ID_SEEK] = 'Seek';
$EBMLidList[EBML_ID_SEEKHEAD] = 'SeekHead';
$EBMLidList[EBML_ID_SEEKID] = 'SeekID';
$EBMLidList[EBML_ID_SEEKPOSITION] = 'SeekPosition';
$EBMLidList[EBML_ID_SEGMENT] = 'Segment';
$EBMLidList[EBML_ID_SEGMENTFAMILY] = 'SegmentFamily';
$EBMLidList[EBML_ID_SEGMENTFILENAME] = 'SegmentFilename';
$EBMLidList[EBML_ID_SEGMENTUID] = 'SegmentUID';
$EBMLidList[EBML_ID_SIMPLETAG] = 'SimpleTag';
$EBMLidList[EBML_ID_CLUSTERSLICES] = 'ClusterSlices';
$EBMLidList[EBML_ID_STEREOMODE] = 'StereoMode';
$EBMLidList[EBML_ID_OLDSTEREOMODE] = 'OldStereoMode';
$EBMLidList[EBML_ID_TAG] = 'Tag';
$EBMLidList[EBML_ID_TAGATTACHMENTUID] = 'TagAttachmentUID';
$EBMLidList[EBML_ID_TAGBINARY] = 'TagBinary';
$EBMLidList[EBML_ID_TAGCHAPTERUID] = 'TagChapterUID';
$EBMLidList[EBML_ID_TAGDEFAULT] = 'TagDefault';
$EBMLidList[EBML_ID_TAGEDITIONUID] = 'TagEditionUID';
$EBMLidList[EBML_ID_TAGLANGUAGE] = 'TagLanguage';
$EBMLidList[EBML_ID_TAGNAME] = 'TagName';
$EBMLidList[EBML_ID_TAGTRACKUID] = 'TagTrackUID';
$EBMLidList[EBML_ID_TAGS] = 'Tags';
$EBMLidList[EBML_ID_TAGSTRING] = 'TagString';
$EBMLidList[EBML_ID_TARGETS] = 'Targets';
$EBMLidList[EBML_ID_TARGETTYPE] = 'TargetType';
$EBMLidList[EBML_ID_TARGETTYPEVALUE] = 'TargetTypeValue';
$EBMLidList[EBML_ID_TIMECODESCALE] = 'TimecodeScale';
$EBMLidList[EBML_ID_TITLE] = 'Title';
$EBMLidList[EBML_ID_TRACKENTRY] = 'TrackEntry';
$EBMLidList[EBML_ID_TRACKNUMBER] = 'TrackNumber';
$EBMLidList[EBML_ID_TRACKOFFSET] = 'TrackOffset';
$EBMLidList[EBML_ID_TRACKOVERLAY] = 'TrackOverlay';
$EBMLidList[EBML_ID_TRACKS] = 'Tracks';
$EBMLidList[EBML_ID_TRACKTIMECODESCALE] = 'TrackTimecodeScale';
$EBMLidList[EBML_ID_TRACKTRANSLATE] = 'TrackTranslate';
$EBMLidList[EBML_ID_TRACKTRANSLATECODEC] = 'TrackTranslateCodec';
$EBMLidList[EBML_ID_TRACKTRANSLATEEDITIONUID] = 'TrackTranslateEditionUID';
$EBMLidList[EBML_ID_TRACKTRANSLATETRACKID] = 'TrackTranslateTrackID';
$EBMLidList[EBML_ID_TRACKTYPE] = 'TrackType';
$EBMLidList[EBML_ID_TRACKUID] = 'TrackUID';
$EBMLidList[EBML_ID_VIDEO] = 'Video';
$EBMLidList[EBML_ID_VOID] = 'Void';
$EBMLidList[EBML_ID_WRITINGAPP] = 'WritingApp';
}
return (isset($EBMLidList[$value]) ? $EBMLidList[$value] : dechex($value));
}
public static function displayUnit($value) {
// http://www.matroska.org/technical/specs/index.html#DisplayUnit
static $units = array(
0 => 'pixels',
1 => 'centimeters',
2 => 'inches',
3 => 'Display Aspect Ratio');
return (isset($units[$value]) ? $units[$value] : 'unknown');
}
private static function getDefaultStreamInfo($streams)
{
foreach (array_reverse($streams) as $stream) {
if ($stream['default']) {
break;
}
}
$unset = array('default', 'name');
foreach ($unset as $u) {
if (isset($stream[$u])) {
unset($stream[$u]);
}
}
$info = $stream;
$info['streams'] = $streams;
return $info;
}
}
| PHP |
<?php
/////////////////////////////////////////////////////////////////
/// getID3() by James Heinrich <info@getid3.org> //
// available at http://getid3.sourceforge.net //
// or http://www.getid3.org //
/////////////////////////////////////////////////////////////////
// See readme.txt for more details //
/////////////////////////////////////////////////////////////////
// //
// module.audio.flac.php //
// module for analyzing FLAC and OggFLAC audio files //
// dependencies: module.audio.ogg.php //
// ///
/////////////////////////////////////////////////////////////////
getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.audio.ogg.php', __FILE__, true);
/**
* @tutorial http://flac.sourceforge.net/format.html
*/
class getid3_flac extends getid3_handler
{
const syncword = 'fLaC';
public function Analyze() {
$info = &$this->getid3->info;
$this->fseek($info['avdataoffset']);
$StreamMarker = $this->fread(4);
if ($StreamMarker != self::syncword) {
return $this->error('Expecting "'.getid3_lib::PrintHexBytes(self::syncword).'" at offset '.$info['avdataoffset'].', found "'.getid3_lib::PrintHexBytes($StreamMarker).'"');
}
$info['fileformat'] = 'flac';
$info['audio']['dataformat'] = 'flac';
$info['audio']['bitrate_mode'] = 'vbr';
$info['audio']['lossless'] = true;
// parse flac container
return $this->parseMETAdata();
}
public function parseMETAdata() {
$info = &$this->getid3->info;
do {
$BlockOffset = $this->ftell();
$BlockHeader = $this->fread(4);
$LBFBT = getid3_lib::BigEndian2Int(substr($BlockHeader, 0, 1));
$LastBlockFlag = (bool) ($LBFBT & 0x80);
$BlockType = ($LBFBT & 0x7F);
$BlockLength = getid3_lib::BigEndian2Int(substr($BlockHeader, 1, 3));
$BlockTypeText = self::metaBlockTypeLookup($BlockType);
if (($BlockOffset + 4 + $BlockLength) > $info['avdataend']) {
$this->error('METADATA_BLOCK_HEADER.BLOCK_TYPE ('.$BlockTypeText.') at offset '.$BlockOffset.' extends beyond end of file');
break;
}
if ($BlockLength < 1) {
$this->error('METADATA_BLOCK_HEADER.BLOCK_LENGTH ('.$BlockLength.') at offset '.$BlockOffset.' is invalid');
break;
}
$info['flac'][$BlockTypeText]['raw'] = array();
$BlockTypeText_raw = &$info['flac'][$BlockTypeText]['raw'];
$BlockTypeText_raw['offset'] = $BlockOffset;
$BlockTypeText_raw['last_meta_block'] = $LastBlockFlag;
$BlockTypeText_raw['block_type'] = $BlockType;
$BlockTypeText_raw['block_type_text'] = $BlockTypeText;
$BlockTypeText_raw['block_length'] = $BlockLength;
if ($BlockTypeText_raw['block_type'] != 0x06) { // do not read attachment data automatically
$BlockTypeText_raw['block_data'] = $this->fread($BlockLength);
}
switch ($BlockTypeText) {
case 'STREAMINFO': // 0x00
if (!$this->parseSTREAMINFO($BlockTypeText_raw['block_data'])) {
return false;
}
break;
case 'PADDING': // 0x01
unset($info['flac']['PADDING']); // ignore
break;
case 'APPLICATION': // 0x02
if (!$this->parseAPPLICATION($BlockTypeText_raw['block_data'])) {
return false;
}
break;
case 'SEEKTABLE': // 0x03
if (!$this->parseSEEKTABLE($BlockTypeText_raw['block_data'])) {
return false;
}
break;
case 'VORBIS_COMMENT': // 0x04
if (!$this->parseVORBIS_COMMENT($BlockTypeText_raw['block_data'])) {
return false;
}
break;
case 'CUESHEET': // 0x05
if (!$this->parseCUESHEET($BlockTypeText_raw['block_data'])) {
return false;
}
break;
case 'PICTURE': // 0x06
if (!$this->parsePICTURE()) {
return false;
}
break;
default:
$this->warning('Unhandled METADATA_BLOCK_HEADER.BLOCK_TYPE ('.$BlockType.') at offset '.$BlockOffset);
}
unset($info['flac'][$BlockTypeText]['raw']);
$info['avdataoffset'] = $this->ftell();
}
while ($LastBlockFlag === false);
// handle tags
if (!empty($info['flac']['VORBIS_COMMENT']['comments'])) {
$info['flac']['comments'] = $info['flac']['VORBIS_COMMENT']['comments'];
}
if (!empty($info['flac']['VORBIS_COMMENT']['vendor'])) {
$info['audio']['encoder'] = str_replace('reference ', '', $info['flac']['VORBIS_COMMENT']['vendor']);
}
// copy attachments to 'comments' array if nesesary
if (isset($info['flac']['PICTURE']) && ($this->getid3->option_save_attachments !== getID3::ATTACHMENTS_NONE)) {
foreach ($info['flac']['PICTURE'] as $entry) {
if (!empty($entry['data'])) {
$info['flac']['comments']['picture'][] = array('image_mime'=>$entry['image_mime'], 'data'=>$entry['data']);
}
}
}
if (isset($info['flac']['STREAMINFO'])) {
if (!$this->isDependencyFor('matroska')) {
$info['flac']['compressed_audio_bytes'] = $info['avdataend'] - $info['avdataoffset'];
}
$info['flac']['uncompressed_audio_bytes'] = $info['flac']['STREAMINFO']['samples_stream'] * $info['flac']['STREAMINFO']['channels'] * ($info['flac']['STREAMINFO']['bits_per_sample'] / 8);
if ($info['flac']['uncompressed_audio_bytes'] == 0) {
return $this->error('Corrupt FLAC file: uncompressed_audio_bytes == zero');
}
if (!empty($info['flac']['compressed_audio_bytes'])) {
$info['flac']['compression_ratio'] = $info['flac']['compressed_audio_bytes'] / $info['flac']['uncompressed_audio_bytes'];
}
}
// set md5_data_source - built into flac 0.5+
if (isset($info['flac']['STREAMINFO']['audio_signature'])) {
if ($info['flac']['STREAMINFO']['audio_signature'] === str_repeat("\x00", 16)) {
$this->warning('FLAC STREAMINFO.audio_signature is null (known issue with libOggFLAC)');
}
else {
$info['md5_data_source'] = '';
$md5 = $info['flac']['STREAMINFO']['audio_signature'];
for ($i = 0; $i < strlen($md5); $i++) {
$info['md5_data_source'] .= str_pad(dechex(ord($md5[$i])), 2, '00', STR_PAD_LEFT);
}
if (!preg_match('/^[0-9a-f]{32}$/', $info['md5_data_source'])) {
unset($info['md5_data_source']);
}
}
}
if (isset($info['flac']['STREAMINFO']['bits_per_sample'])) {
$info['audio']['bits_per_sample'] = $info['flac']['STREAMINFO']['bits_per_sample'];
if ($info['audio']['bits_per_sample'] == 8) {
// special case
// must invert sign bit on all data bytes before MD5'ing to match FLAC's calculated value
// MD5sum calculates on unsigned bytes, but FLAC calculated MD5 on 8-bit audio data as signed
$this->warning('FLAC calculates MD5 data strangely on 8-bit audio, so the stored md5_data_source value will not match the decoded WAV file');
}
}
return true;
}
private function parseSTREAMINFO($BlockData) {
$info = &$this->getid3->info;
$info['flac']['STREAMINFO'] = array();
$streaminfo = &$info['flac']['STREAMINFO'];
$streaminfo['min_block_size'] = getid3_lib::BigEndian2Int(substr($BlockData, 0, 2));
$streaminfo['max_block_size'] = getid3_lib::BigEndian2Int(substr($BlockData, 2, 2));
$streaminfo['min_frame_size'] = getid3_lib::BigEndian2Int(substr($BlockData, 4, 3));
$streaminfo['max_frame_size'] = getid3_lib::BigEndian2Int(substr($BlockData, 7, 3));
$SRCSBSS = getid3_lib::BigEndian2Bin(substr($BlockData, 10, 8));
$streaminfo['sample_rate'] = getid3_lib::Bin2Dec(substr($SRCSBSS, 0, 20));
$streaminfo['channels'] = getid3_lib::Bin2Dec(substr($SRCSBSS, 20, 3)) + 1;
$streaminfo['bits_per_sample'] = getid3_lib::Bin2Dec(substr($SRCSBSS, 23, 5)) + 1;
$streaminfo['samples_stream'] = getid3_lib::Bin2Dec(substr($SRCSBSS, 28, 36));
$streaminfo['audio_signature'] = substr($BlockData, 18, 16);
if (!empty($streaminfo['sample_rate'])) {
$info['audio']['bitrate_mode'] = 'vbr';
$info['audio']['sample_rate'] = $streaminfo['sample_rate'];
$info['audio']['channels'] = $streaminfo['channels'];
$info['audio']['bits_per_sample'] = $streaminfo['bits_per_sample'];
$info['playtime_seconds'] = $streaminfo['samples_stream'] / $streaminfo['sample_rate'];
if ($info['playtime_seconds'] > 0) {
if (!$this->isDependencyFor('matroska')) {
$info['audio']['bitrate'] = (($info['avdataend'] - $info['avdataoffset']) * 8) / $info['playtime_seconds'];
}
else {
$this->warning('Cannot determine audio bitrate because total stream size is unknown');
}
}
} else {
return $this->error('Corrupt METAdata block: STREAMINFO');
}
return true;
}
private function parseAPPLICATION($BlockData) {
$info = &$this->getid3->info;
$ApplicationID = getid3_lib::BigEndian2Int(substr($BlockData, 0, 4));
$info['flac']['APPLICATION'][$ApplicationID]['name'] = self::applicationIDLookup($ApplicationID);
$info['flac']['APPLICATION'][$ApplicationID]['data'] = substr($BlockData, 4);
return true;
}
private function parseSEEKTABLE($BlockData) {
$info = &$this->getid3->info;
$offset = 0;
$BlockLength = strlen($BlockData);
$placeholderpattern = str_repeat("\xFF", 8);
while ($offset < $BlockLength) {
$SampleNumberString = substr($BlockData, $offset, 8);
$offset += 8;
if ($SampleNumberString == $placeholderpattern) {
// placeholder point
getid3_lib::safe_inc($info['flac']['SEEKTABLE']['placeholders'], 1);
$offset += 10;
} else {
$SampleNumber = getid3_lib::BigEndian2Int($SampleNumberString);
$info['flac']['SEEKTABLE'][$SampleNumber]['offset'] = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 8));
$offset += 8;
$info['flac']['SEEKTABLE'][$SampleNumber]['samples'] = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 2));
$offset += 2;
}
}
return true;
}
private function parseVORBIS_COMMENT($BlockData) {
$info = &$this->getid3->info;
$getid3_ogg = new getid3_ogg($this->getid3);
if ($this->isDependencyFor('matroska')) {
$getid3_ogg->setStringMode($this->data_string);
}
$getid3_ogg->ParseVorbisComments();
if (isset($info['ogg'])) {
unset($info['ogg']['comments_raw']);
$info['flac']['VORBIS_COMMENT'] = $info['ogg'];
unset($info['ogg']);
}
unset($getid3_ogg);
return true;
}
private function parseCUESHEET($BlockData) {
$info = &$this->getid3->info;
$offset = 0;
$info['flac']['CUESHEET']['media_catalog_number'] = trim(substr($BlockData, $offset, 128), "\0");
$offset += 128;
$info['flac']['CUESHEET']['lead_in_samples'] = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 8));
$offset += 8;
$info['flac']['CUESHEET']['flags']['is_cd'] = (bool) (getid3_lib::BigEndian2Int(substr($BlockData, $offset, 1)) & 0x80);
$offset += 1;
$offset += 258; // reserved
$info['flac']['CUESHEET']['number_tracks'] = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 1));
$offset += 1;
for ($track = 0; $track < $info['flac']['CUESHEET']['number_tracks']; $track++) {
$TrackSampleOffset = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 8));
$offset += 8;
$TrackNumber = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 1));
$offset += 1;
$info['flac']['CUESHEET']['tracks'][$TrackNumber]['sample_offset'] = $TrackSampleOffset;
$info['flac']['CUESHEET']['tracks'][$TrackNumber]['isrc'] = substr($BlockData, $offset, 12);
$offset += 12;
$TrackFlagsRaw = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 1));
$offset += 1;
$info['flac']['CUESHEET']['tracks'][$TrackNumber]['flags']['is_audio'] = (bool) ($TrackFlagsRaw & 0x80);
$info['flac']['CUESHEET']['tracks'][$TrackNumber]['flags']['pre_emphasis'] = (bool) ($TrackFlagsRaw & 0x40);
$offset += 13; // reserved
$info['flac']['CUESHEET']['tracks'][$TrackNumber]['index_points'] = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 1));
$offset += 1;
for ($index = 0; $index < $info['flac']['CUESHEET']['tracks'][$TrackNumber]['index_points']; $index++) {
$IndexSampleOffset = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 8));
$offset += 8;
$IndexNumber = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 1));
$offset += 1;
$offset += 3; // reserved
$info['flac']['CUESHEET']['tracks'][$TrackNumber]['indexes'][$IndexNumber] = $IndexSampleOffset;
}
}
return true;
}
/**
* Parse METADATA_BLOCK_PICTURE flac structure and extract attachment
* External usage: audio.ogg
*/
public function parsePICTURE() {
$info = &$this->getid3->info;
$picture['typeid'] = getid3_lib::BigEndian2Int($this->fread(4));
$picture['type'] = self::pictureTypeLookup($picture['typeid']);
$picture['image_mime'] = $this->fread(getid3_lib::BigEndian2Int($this->fread(4)));
$descr_length = getid3_lib::BigEndian2Int($this->fread(4));
if ($descr_length) {
$picture['description'] = $this->fread($descr_length);
}
$picture['width'] = getid3_lib::BigEndian2Int($this->fread(4));
$picture['height'] = getid3_lib::BigEndian2Int($this->fread(4));
$picture['color_depth'] = getid3_lib::BigEndian2Int($this->fread(4));
$picture['colors_indexed'] = getid3_lib::BigEndian2Int($this->fread(4));
$data_length = getid3_lib::BigEndian2Int($this->fread(4));
if ($picture['image_mime'] == '-->') {
$picture['data'] = $this->fread($data_length);
} else {
$picture['data'] = $this->saveAttachment(
str_replace('/', '_', $picture['type']).'_'.$this->ftell(),
$this->ftell(),
$data_length,
$picture['image_mime']);
}
$info['flac']['PICTURE'][] = $picture;
return true;
}
public static function metaBlockTypeLookup($blocktype) {
static $lookup = array(
0 => 'STREAMINFO',
1 => 'PADDING',
2 => 'APPLICATION',
3 => 'SEEKTABLE',
4 => 'VORBIS_COMMENT',
5 => 'CUESHEET',
6 => 'PICTURE',
);
return (isset($lookup[$blocktype]) ? $lookup[$blocktype] : 'reserved');
}
public static function applicationIDLookup($applicationid) {
// http://flac.sourceforge.net/id.html
static $lookup = array(
0x41544348 => 'FlacFile', // "ATCH"
0x42534F4C => 'beSolo', // "BSOL"
0x42554753 => 'Bugs Player', // "BUGS"
0x43756573 => 'GoldWave cue points (specification)', // "Cues"
0x46696361 => 'CUE Splitter', // "Fica"
0x46746F6C => 'flac-tools', // "Ftol"
0x4D4F5442 => 'MOTB MetaCzar', // "MOTB"
0x4D505345 => 'MP3 Stream Editor', // "MPSE"
0x4D754D4C => 'MusicML: Music Metadata Language', // "MuML"
0x52494646 => 'Sound Devices RIFF chunk storage', // "RIFF"
0x5346464C => 'Sound Font FLAC', // "SFFL"
0x534F4E59 => 'Sony Creative Software', // "SONY"
0x5351455A => 'flacsqueeze', // "SQEZ"
0x54745776 => 'TwistedWave', // "TtWv"
0x55495453 => 'UITS Embedding tools', // "UITS"
0x61696666 => 'FLAC AIFF chunk storage', // "aiff"
0x696D6167 => 'flac-image application for storing arbitrary files in APPLICATION metadata blocks', // "imag"
0x7065656D => 'Parseable Embedded Extensible Metadata (specification)', // "peem"
0x71667374 => 'QFLAC Studio', // "qfst"
0x72696666 => 'FLAC RIFF chunk storage', // "riff"
0x74756E65 => 'TagTuner', // "tune"
0x78626174 => 'XBAT', // "xbat"
0x786D6364 => 'xmcd', // "xmcd"
);
return (isset($lookup[$applicationid]) ? $lookup[$applicationid] : 'reserved');
}
public static function pictureTypeLookup($type_id) {
static $lookup = array (
0 => 'Other',
1 => '32x32 pixels \'file icon\' (PNG only)',
2 => 'Other file icon',
3 => 'Cover (front)',
4 => 'Cover (back)',
5 => 'Leaflet page',
6 => 'Media (e.g. label side of CD)',
7 => 'Lead artist/lead performer/soloist',
8 => 'Artist/performer',
9 => 'Conductor',
10 => 'Band/Orchestra',
11 => 'Composer',
12 => 'Lyricist/text writer',
13 => 'Recording Location',
14 => 'During recording',
15 => 'During performance',
16 => 'Movie/video screen capture',
17 => 'A bright coloured fish',
18 => 'Illustration',
19 => 'Band/artist logotype',
20 => 'Publisher/Studio logotype',
);
return (isset($lookup[$type_id]) ? $lookup[$type_id] : 'reserved');
}
}
| PHP |
<?php
/////////////////////////////////////////////////////////////////
/// getID3() by James Heinrich <info@getid3.org> //
// available at http://getid3.sourceforge.net //
// or http://www.getid3.org //
/////////////////////////////////////////////////////////////////
// See readme.txt for more details //
/////////////////////////////////////////////////////////////////
// //
// module.audio.ogg.php //
// module for analyzing Ogg Vorbis, OggFLAC and Speex files //
// dependencies: module.audio.flac.php //
// ///
/////////////////////////////////////////////////////////////////
getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.audio.flac.php', __FILE__, true);
class getid3_ogg extends getid3_handler
{
// http://xiph.org/vorbis/doc/Vorbis_I_spec.html
public function Analyze() {
$info = &$this->getid3->info;
$info['fileformat'] = 'ogg';
// Warn about illegal tags - only vorbiscomments are allowed
if (isset($info['id3v2'])) {
$info['warning'][] = 'Illegal ID3v2 tag present.';
}
if (isset($info['id3v1'])) {
$info['warning'][] = 'Illegal ID3v1 tag present.';
}
if (isset($info['ape'])) {
$info['warning'][] = 'Illegal APE tag present.';
}
// Page 1 - Stream Header
$this->fseek($info['avdataoffset']);
$oggpageinfo = $this->ParseOggPageHeader();
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']] = $oggpageinfo;
if ($this->ftell() >= $this->getid3->fread_buffer_size()) {
$info['error'][] = 'Could not find start of Ogg page in the first '.$this->getid3->fread_buffer_size().' bytes (this might not be an Ogg-Vorbis file?)';
unset($info['fileformat']);
unset($info['ogg']);
return false;
}
$filedata = $this->fread($oggpageinfo['page_length']);
$filedataoffset = 0;
if (substr($filedata, 0, 4) == 'fLaC') {
$info['audio']['dataformat'] = 'flac';
$info['audio']['bitrate_mode'] = 'vbr';
$info['audio']['lossless'] = true;
} elseif (substr($filedata, 1, 6) == 'vorbis') {
$this->ParseVorbisPageHeader($filedata, $filedataoffset, $oggpageinfo);
} elseif (substr($filedata, 0, 8) == 'Speex ') {
// http://www.speex.org/manual/node10.html
$info['audio']['dataformat'] = 'speex';
$info['mime_type'] = 'audio/speex';
$info['audio']['bitrate_mode'] = 'abr';
$info['audio']['lossless'] = false;
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['speex_string'] = substr($filedata, $filedataoffset, 8); // hard-coded to 'Speex '
$filedataoffset += 8;
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['speex_version'] = substr($filedata, $filedataoffset, 20);
$filedataoffset += 20;
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['speex_version_id'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['header_size'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['rate'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['mode'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['mode_bitstream_version'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['nb_channels'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['bitrate'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['framesize'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['vbr'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['frames_per_packet'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['extra_headers'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['reserved1'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['reserved2'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$info['speex']['speex_version'] = trim($info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['speex_version']);
$info['speex']['sample_rate'] = $info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['rate'];
$info['speex']['channels'] = $info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['nb_channels'];
$info['speex']['vbr'] = (bool) $info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['vbr'];
$info['speex']['band_type'] = $this->SpeexBandModeLookup($info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['mode']);
$info['audio']['sample_rate'] = $info['speex']['sample_rate'];
$info['audio']['channels'] = $info['speex']['channels'];
if ($info['speex']['vbr']) {
$info['audio']['bitrate_mode'] = 'vbr';
}
} elseif (substr($filedata, 0, 8) == "fishead\x00") {
// Ogg Skeleton version 3.0 Format Specification
// http://xiph.org/ogg/doc/skeleton.html
$filedataoffset += 8;
$info['ogg']['skeleton']['fishead']['raw']['version_major'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 2));
$filedataoffset += 2;
$info['ogg']['skeleton']['fishead']['raw']['version_minor'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 2));
$filedataoffset += 2;
$info['ogg']['skeleton']['fishead']['raw']['presentationtime_numerator'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 8));
$filedataoffset += 8;
$info['ogg']['skeleton']['fishead']['raw']['presentationtime_denominator'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 8));
$filedataoffset += 8;
$info['ogg']['skeleton']['fishead']['raw']['basetime_numerator'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 8));
$filedataoffset += 8;
$info['ogg']['skeleton']['fishead']['raw']['basetime_denominator'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 8));
$filedataoffset += 8;
$info['ogg']['skeleton']['fishead']['raw']['utc'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 20));
$filedataoffset += 20;
$info['ogg']['skeleton']['fishead']['version'] = $info['ogg']['skeleton']['fishead']['raw']['version_major'].'.'.$info['ogg']['skeleton']['fishead']['raw']['version_minor'];
$info['ogg']['skeleton']['fishead']['presentationtime'] = $info['ogg']['skeleton']['fishead']['raw']['presentationtime_numerator'] / $info['ogg']['skeleton']['fishead']['raw']['presentationtime_denominator'];
$info['ogg']['skeleton']['fishead']['basetime'] = $info['ogg']['skeleton']['fishead']['raw']['basetime_numerator'] / $info['ogg']['skeleton']['fishead']['raw']['basetime_denominator'];
$info['ogg']['skeleton']['fishead']['utc'] = $info['ogg']['skeleton']['fishead']['raw']['utc'];
$counter = 0;
do {
$oggpageinfo = $this->ParseOggPageHeader();
$info['ogg']['pageheader'][$oggpageinfo['page_seqno'].'.'.$counter++] = $oggpageinfo;
$filedata = $this->fread($oggpageinfo['page_length']);
$this->fseek($oggpageinfo['page_end_offset']);
if (substr($filedata, 0, 8) == "fisbone\x00") {
$filedataoffset = 8;
$info['ogg']['skeleton']['fisbone']['raw']['message_header_offset'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$info['ogg']['skeleton']['fisbone']['raw']['serial_number'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$info['ogg']['skeleton']['fisbone']['raw']['number_header_packets'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$info['ogg']['skeleton']['fisbone']['raw']['granulerate_numerator'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 8));
$filedataoffset += 8;
$info['ogg']['skeleton']['fisbone']['raw']['granulerate_denominator'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 8));
$filedataoffset += 8;
$info['ogg']['skeleton']['fisbone']['raw']['basegranule'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 8));
$filedataoffset += 8;
$info['ogg']['skeleton']['fisbone']['raw']['preroll'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$info['ogg']['skeleton']['fisbone']['raw']['granuleshift'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 1));
$filedataoffset += 1;
$info['ogg']['skeleton']['fisbone']['raw']['padding'] = substr($filedata, $filedataoffset, 3);
$filedataoffset += 3;
} elseif (substr($filedata, 1, 6) == 'theora') {
$info['video']['dataformat'] = 'theora';
$info['error'][] = 'Ogg Theora not correctly handled in this version of getID3 ['.$this->getid3->version().']';
//break;
} elseif (substr($filedata, 1, 6) == 'vorbis') {
$this->ParseVorbisPageHeader($filedata, $filedataoffset, $oggpageinfo);
} else {
$info['error'][] = 'unexpected';
//break;
}
//} while ($oggpageinfo['page_seqno'] == 0);
} while (($oggpageinfo['page_seqno'] == 0) && (substr($filedata, 0, 8) != "fisbone\x00"));
$this->fseek($oggpageinfo['page_start_offset']);
$info['error'][] = 'Ogg Skeleton not correctly handled in this version of getID3 ['.$this->getid3->version().']';
//return false;
} else {
$info['error'][] = 'Expecting either "Speex " or "vorbis" identifier strings, found "'.substr($filedata, 0, 8).'"';
unset($info['ogg']);
unset($info['mime_type']);
return false;
}
// Page 2 - Comment Header
$oggpageinfo = $this->ParseOggPageHeader();
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']] = $oggpageinfo;
switch ($info['audio']['dataformat']) {
case 'vorbis':
$filedata = $this->fread($info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['page_length']);
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['packet_type'] = getid3_lib::LittleEndian2Int(substr($filedata, 0, 1));
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['stream_type'] = substr($filedata, 1, 6); // hard-coded to 'vorbis'
$this->ParseVorbisComments();
break;
case 'flac':
$flac = new getid3_flac($this->getid3);
if (!$flac->parseMETAdata()) {
$info['error'][] = 'Failed to parse FLAC headers';
return false;
}
unset($flac);
break;
case 'speex':
$this->fseek($info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['page_length'], SEEK_CUR);
$this->ParseVorbisComments();
break;
}
// Last Page - Number of Samples
if (!getid3_lib::intValueSupported($info['avdataend'])) {
$info['warning'][] = 'Unable to parse Ogg end chunk file (PHP does not support file operations beyond '.round(PHP_INT_MAX / 1073741824).'GB)';
} else {
$this->fseek(max($info['avdataend'] - $this->getid3->fread_buffer_size(), 0));
$LastChunkOfOgg = strrev($this->fread($this->getid3->fread_buffer_size()));
if ($LastOggSpostion = strpos($LastChunkOfOgg, 'SggO')) {
$this->fseek($info['avdataend'] - ($LastOggSpostion + strlen('SggO')));
$info['avdataend'] = $this->ftell();
$info['ogg']['pageheader']['eos'] = $this->ParseOggPageHeader();
$info['ogg']['samples'] = $info['ogg']['pageheader']['eos']['pcm_abs_position'];
if ($info['ogg']['samples'] == 0) {
$info['error'][] = 'Corrupt Ogg file: eos.number of samples == zero';
return false;
}
if (!empty($info['audio']['sample_rate'])) {
$info['ogg']['bitrate_average'] = (($info['avdataend'] - $info['avdataoffset']) * 8) / ($info['ogg']['samples'] / $info['audio']['sample_rate']);
}
}
}
if (!empty($info['ogg']['bitrate_average'])) {
$info['audio']['bitrate'] = $info['ogg']['bitrate_average'];
} elseif (!empty($info['ogg']['bitrate_nominal'])) {
$info['audio']['bitrate'] = $info['ogg']['bitrate_nominal'];
} elseif (!empty($info['ogg']['bitrate_min']) && !empty($info['ogg']['bitrate_max'])) {
$info['audio']['bitrate'] = ($info['ogg']['bitrate_min'] + $info['ogg']['bitrate_max']) / 2;
}
if (isset($info['audio']['bitrate']) && !isset($info['playtime_seconds'])) {
if ($info['audio']['bitrate'] == 0) {
$info['error'][] = 'Corrupt Ogg file: bitrate_audio == zero';
return false;
}
$info['playtime_seconds'] = (float) ((($info['avdataend'] - $info['avdataoffset']) * 8) / $info['audio']['bitrate']);
}
if (isset($info['ogg']['vendor'])) {
$info['audio']['encoder'] = preg_replace('/^Encoded with /', '', $info['ogg']['vendor']);
// Vorbis only
if ($info['audio']['dataformat'] == 'vorbis') {
// Vorbis 1.0 starts with Xiph.Org
if (preg_match('/^Xiph.Org/', $info['audio']['encoder'])) {
if ($info['audio']['bitrate_mode'] == 'abr') {
// Set -b 128 on abr files
$info['audio']['encoder_options'] = '-b '.round($info['ogg']['bitrate_nominal'] / 1000);
} elseif (($info['audio']['bitrate_mode'] == 'vbr') && ($info['audio']['channels'] == 2) && ($info['audio']['sample_rate'] >= 44100) && ($info['audio']['sample_rate'] <= 48000)) {
// Set -q N on vbr files
$info['audio']['encoder_options'] = '-q '.$this->get_quality_from_nominal_bitrate($info['ogg']['bitrate_nominal']);
}
}
if (empty($info['audio']['encoder_options']) && !empty($info['ogg']['bitrate_nominal'])) {
$info['audio']['encoder_options'] = 'Nominal bitrate: '.intval(round($info['ogg']['bitrate_nominal'] / 1000)).'kbps';
}
}
}
return true;
}
public function ParseVorbisPageHeader(&$filedata, &$filedataoffset, &$oggpageinfo) {
$info = &$this->getid3->info;
$info['audio']['dataformat'] = 'vorbis';
$info['audio']['lossless'] = false;
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['packet_type'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 1));
$filedataoffset += 1;
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['stream_type'] = substr($filedata, $filedataoffset, 6); // hard-coded to 'vorbis'
$filedataoffset += 6;
$info['ogg']['bitstreamversion'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$info['ogg']['numberofchannels'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 1));
$filedataoffset += 1;
$info['audio']['channels'] = $info['ogg']['numberofchannels'];
$info['ogg']['samplerate'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
if ($info['ogg']['samplerate'] == 0) {
$info['error'][] = 'Corrupt Ogg file: sample rate == zero';
return false;
}
$info['audio']['sample_rate'] = $info['ogg']['samplerate'];
$info['ogg']['samples'] = 0; // filled in later
$info['ogg']['bitrate_average'] = 0; // filled in later
$info['ogg']['bitrate_max'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$info['ogg']['bitrate_nominal'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$info['ogg']['bitrate_min'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$info['ogg']['blocksize_small'] = pow(2, getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 1)) & 0x0F);
$info['ogg']['blocksize_large'] = pow(2, (getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 1)) & 0xF0) >> 4);
$info['ogg']['stop_bit'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 1)); // must be 1, marks end of packet
$info['audio']['bitrate_mode'] = 'vbr'; // overridden if actually abr
if ($info['ogg']['bitrate_max'] == 0xFFFFFFFF) {
unset($info['ogg']['bitrate_max']);
$info['audio']['bitrate_mode'] = 'abr';
}
if ($info['ogg']['bitrate_nominal'] == 0xFFFFFFFF) {
unset($info['ogg']['bitrate_nominal']);
}
if ($info['ogg']['bitrate_min'] == 0xFFFFFFFF) {
unset($info['ogg']['bitrate_min']);
$info['audio']['bitrate_mode'] = 'abr';
}
return true;
}
public function ParseOggPageHeader() {
// http://xiph.org/ogg/vorbis/doc/framing.html
$oggheader['page_start_offset'] = $this->ftell(); // where we started from in the file
$filedata = $this->fread($this->getid3->fread_buffer_size());
$filedataoffset = 0;
while ((substr($filedata, $filedataoffset++, 4) != 'OggS')) {
if (($this->ftell() - $oggheader['page_start_offset']) >= $this->getid3->fread_buffer_size()) {
// should be found before here
return false;
}
if ((($filedataoffset + 28) > strlen($filedata)) || (strlen($filedata) < 28)) {
if ($this->feof() || (($filedata .= $this->fread($this->getid3->fread_buffer_size())) === false)) {
// get some more data, unless eof, in which case fail
return false;
}
}
}
$filedataoffset += strlen('OggS') - 1; // page, delimited by 'OggS'
$oggheader['stream_structver'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 1));
$filedataoffset += 1;
$oggheader['flags_raw'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 1));
$filedataoffset += 1;
$oggheader['flags']['fresh'] = (bool) ($oggheader['flags_raw'] & 0x01); // fresh packet
$oggheader['flags']['bos'] = (bool) ($oggheader['flags_raw'] & 0x02); // first page of logical bitstream (bos)
$oggheader['flags']['eos'] = (bool) ($oggheader['flags_raw'] & 0x04); // last page of logical bitstream (eos)
$oggheader['pcm_abs_position'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 8));
$filedataoffset += 8;
$oggheader['stream_serialno'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$oggheader['page_seqno'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$oggheader['page_checksum'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 4));
$filedataoffset += 4;
$oggheader['page_segments'] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 1));
$filedataoffset += 1;
$oggheader['page_length'] = 0;
for ($i = 0; $i < $oggheader['page_segments']; $i++) {
$oggheader['segment_table'][$i] = getid3_lib::LittleEndian2Int(substr($filedata, $filedataoffset, 1));
$filedataoffset += 1;
$oggheader['page_length'] += $oggheader['segment_table'][$i];
}
$oggheader['header_end_offset'] = $oggheader['page_start_offset'] + $filedataoffset;
$oggheader['page_end_offset'] = $oggheader['header_end_offset'] + $oggheader['page_length'];
$this->fseek($oggheader['header_end_offset']);
return $oggheader;
}
// http://xiph.org/vorbis/doc/Vorbis_I_spec.html#x1-810005
public function ParseVorbisComments() {
$info = &$this->getid3->info;
$OriginalOffset = $this->ftell();
$commentdataoffset = 0;
$VorbisCommentPage = 1;
switch ($info['audio']['dataformat']) {
case 'vorbis':
case 'speex':
$CommentStartOffset = $info['ogg']['pageheader'][$VorbisCommentPage]['page_start_offset']; // Second Ogg page, after header block
$this->fseek($CommentStartOffset);
$commentdataoffset = 27 + $info['ogg']['pageheader'][$VorbisCommentPage]['page_segments'];
$commentdata = $this->fread(self::OggPageSegmentLength($info['ogg']['pageheader'][$VorbisCommentPage], 1) + $commentdataoffset);
if ($info['audio']['dataformat'] == 'vorbis') {
$commentdataoffset += (strlen('vorbis') + 1);
}
break;
case 'flac':
$CommentStartOffset = $info['flac']['VORBIS_COMMENT']['raw']['offset'] + 4;
$this->fseek($CommentStartOffset);
$commentdata = $this->fread($info['flac']['VORBIS_COMMENT']['raw']['block_length']);
break;
default:
return false;
}
$VendorSize = getid3_lib::LittleEndian2Int(substr($commentdata, $commentdataoffset, 4));
$commentdataoffset += 4;
$info['ogg']['vendor'] = substr($commentdata, $commentdataoffset, $VendorSize);
$commentdataoffset += $VendorSize;
$CommentsCount = getid3_lib::LittleEndian2Int(substr($commentdata, $commentdataoffset, 4));
$commentdataoffset += 4;
$info['avdataoffset'] = $CommentStartOffset + $commentdataoffset;
$basicfields = array('TITLE', 'ARTIST', 'ALBUM', 'TRACKNUMBER', 'GENRE', 'DATE', 'DESCRIPTION', 'COMMENT');
$ThisFileInfo_ogg_comments_raw = &$info['ogg']['comments_raw'];
for ($i = 0; $i < $CommentsCount; $i++) {
$ThisFileInfo_ogg_comments_raw[$i]['dataoffset'] = $CommentStartOffset + $commentdataoffset;
if ($this->ftell() < ($ThisFileInfo_ogg_comments_raw[$i]['dataoffset'] + 4)) {
if ($oggpageinfo = $this->ParseOggPageHeader()) {
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']] = $oggpageinfo;
$VorbisCommentPage++;
// First, save what we haven't read yet
$AsYetUnusedData = substr($commentdata, $commentdataoffset);
// Then take that data off the end
$commentdata = substr($commentdata, 0, $commentdataoffset);
// Add [headerlength] bytes of dummy data for the Ogg Page Header, just to keep absolute offsets correct
$commentdata .= str_repeat("\x00", 27 + $info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['page_segments']);
$commentdataoffset += (27 + $info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['page_segments']);
// Finally, stick the unused data back on the end
$commentdata .= $AsYetUnusedData;
//$commentdata .= $this->fread($info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['page_length']);
$commentdata .= $this->fread($this->OggPageSegmentLength($info['ogg']['pageheader'][$VorbisCommentPage], 1));
}
}
$ThisFileInfo_ogg_comments_raw[$i]['size'] = getid3_lib::LittleEndian2Int(substr($commentdata, $commentdataoffset, 4));
// replace avdataoffset with position just after the last vorbiscomment
$info['avdataoffset'] = $ThisFileInfo_ogg_comments_raw[$i]['dataoffset'] + $ThisFileInfo_ogg_comments_raw[$i]['size'] + 4;
$commentdataoffset += 4;
while ((strlen($commentdata) - $commentdataoffset) < $ThisFileInfo_ogg_comments_raw[$i]['size']) {
if (($ThisFileInfo_ogg_comments_raw[$i]['size'] > $info['avdataend']) || ($ThisFileInfo_ogg_comments_raw[$i]['size'] < 0)) {
$info['warning'][] = 'Invalid Ogg comment size (comment #'.$i.', claims to be '.number_format($ThisFileInfo_ogg_comments_raw[$i]['size']).' bytes) - aborting reading comments';
break 2;
}
$VorbisCommentPage++;
$oggpageinfo = $this->ParseOggPageHeader();
$info['ogg']['pageheader'][$oggpageinfo['page_seqno']] = $oggpageinfo;
// First, save what we haven't read yet
$AsYetUnusedData = substr($commentdata, $commentdataoffset);
// Then take that data off the end
$commentdata = substr($commentdata, 0, $commentdataoffset);
// Add [headerlength] bytes of dummy data for the Ogg Page Header, just to keep absolute offsets correct
$commentdata .= str_repeat("\x00", 27 + $info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['page_segments']);
$commentdataoffset += (27 + $info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['page_segments']);
// Finally, stick the unused data back on the end
$commentdata .= $AsYetUnusedData;
//$commentdata .= $this->fread($info['ogg']['pageheader'][$oggpageinfo['page_seqno']]['page_length']);
if (!isset($info['ogg']['pageheader'][$VorbisCommentPage])) {
$info['warning'][] = 'undefined Vorbis Comment page "'.$VorbisCommentPage.'" at offset '.$this->ftell();
break;
}
$readlength = self::OggPageSegmentLength($info['ogg']['pageheader'][$VorbisCommentPage], 1);
if ($readlength <= 0) {
$info['warning'][] = 'invalid length Vorbis Comment page "'.$VorbisCommentPage.'" at offset '.$this->ftell();
break;
}
$commentdata .= $this->fread($readlength);
//$filebaseoffset += $oggpageinfo['header_end_offset'] - $oggpageinfo['page_start_offset'];
}
$ThisFileInfo_ogg_comments_raw[$i]['offset'] = $commentdataoffset;
$commentstring = substr($commentdata, $commentdataoffset, $ThisFileInfo_ogg_comments_raw[$i]['size']);
$commentdataoffset += $ThisFileInfo_ogg_comments_raw[$i]['size'];
if (!$commentstring) {
// no comment?
$info['warning'][] = 'Blank Ogg comment ['.$i.']';
} elseif (strstr($commentstring, '=')) {
$commentexploded = explode('=', $commentstring, 2);
$ThisFileInfo_ogg_comments_raw[$i]['key'] = strtoupper($commentexploded[0]);
$ThisFileInfo_ogg_comments_raw[$i]['value'] = (isset($commentexploded[1]) ? $commentexploded[1] : '');
if ($ThisFileInfo_ogg_comments_raw[$i]['key'] == 'METADATA_BLOCK_PICTURE') {
// http://wiki.xiph.org/VorbisComment#METADATA_BLOCK_PICTURE
// The unencoded format is that of the FLAC picture block. The fields are stored in big endian order as in FLAC, picture data is stored according to the relevant standard.
// http://flac.sourceforge.net/format.html#metadata_block_picture
$flac = new getid3_flac($this->getid3);
$flac->setStringMode(base64_decode($ThisFileInfo_ogg_comments_raw[$i]['value']));
$flac->parsePICTURE();
$info['ogg']['comments']['picture'][] = $flac->getid3->info['flac']['PICTURE'][0];
unset($flac);
} elseif ($ThisFileInfo_ogg_comments_raw[$i]['key'] == 'COVERART') {
$data = base64_decode($ThisFileInfo_ogg_comments_raw[$i]['value']);
$this->notice('Found deprecated COVERART tag, it should be replaced in honor of METADATA_BLOCK_PICTURE structure');
/** @todo use 'coverartmime' where available */
$imageinfo = getid3_lib::GetDataImageSize($data);
if ($imageinfo === false || !isset($imageinfo['mime'])) {
$this->warning('COVERART vorbiscomment tag contains invalid image');
continue;
}
$ogg = new self($this->getid3);
$ogg->setStringMode($data);
$info['ogg']['comments']['picture'][] = array(
'image_mime' => $imageinfo['mime'],
'data' => $ogg->saveAttachment('coverart', 0, strlen($data), $imageinfo['mime']),
);
unset($ogg);
} else {
$info['ogg']['comments'][strtolower($ThisFileInfo_ogg_comments_raw[$i]['key'])][] = $ThisFileInfo_ogg_comments_raw[$i]['value'];
}
} else {
$info['warning'][] = '[known problem with CDex >= v1.40, < v1.50b7] Invalid Ogg comment name/value pair ['.$i.']: '.$commentstring;
}
unset($ThisFileInfo_ogg_comments_raw[$i]);
}
unset($ThisFileInfo_ogg_comments_raw);
// Replay Gain Adjustment
// http://privatewww.essex.ac.uk/~djmrob/replaygain/
if (isset($info['ogg']['comments']) && is_array($info['ogg']['comments'])) {
foreach ($info['ogg']['comments'] as $index => $commentvalue) {
switch ($index) {
case 'rg_audiophile':
case 'replaygain_album_gain':
$info['replay_gain']['album']['adjustment'] = (double) $commentvalue[0];
unset($info['ogg']['comments'][$index]);
break;
case 'rg_radio':
case 'replaygain_track_gain':
$info['replay_gain']['track']['adjustment'] = (double) $commentvalue[0];
unset($info['ogg']['comments'][$index]);
break;
case 'replaygain_album_peak':
$info['replay_gain']['album']['peak'] = (double) $commentvalue[0];
unset($info['ogg']['comments'][$index]);
break;
case 'rg_peak':
case 'replaygain_track_peak':
$info['replay_gain']['track']['peak'] = (double) $commentvalue[0];
unset($info['ogg']['comments'][$index]);
break;
case 'replaygain_reference_loudness':
$info['replay_gain']['reference_volume'] = (double) $commentvalue[0];
unset($info['ogg']['comments'][$index]);
break;
default:
// do nothing
break;
}
}
}
$this->fseek($OriginalOffset);
return true;
}
public static function SpeexBandModeLookup($mode) {
static $SpeexBandModeLookup = array();
if (empty($SpeexBandModeLookup)) {
$SpeexBandModeLookup[0] = 'narrow';
$SpeexBandModeLookup[1] = 'wide';
$SpeexBandModeLookup[2] = 'ultra-wide';
}
return (isset($SpeexBandModeLookup[$mode]) ? $SpeexBandModeLookup[$mode] : null);
}
public static function OggPageSegmentLength($OggInfoArray, $SegmentNumber=1) {
for ($i = 0; $i < $SegmentNumber; $i++) {
$segmentlength = 0;
foreach ($OggInfoArray['segment_table'] as $key => $value) {
$segmentlength += $value;
if ($value < 255) {
break;
}
}
}
return $segmentlength;
}
public static function get_quality_from_nominal_bitrate($nominal_bitrate) {
// decrease precision
$nominal_bitrate = $nominal_bitrate / 1000;
if ($nominal_bitrate < 128) {
// q-1 to q4
$qval = ($nominal_bitrate - 64) / 16;
} elseif ($nominal_bitrate < 256) {
// q4 to q8
$qval = $nominal_bitrate / 32;
} elseif ($nominal_bitrate < 320) {
// q8 to q9
$qval = ($nominal_bitrate + 256) / 64;
} else {
// q9 to q10
$qval = ($nominal_bitrate + 1300) / 180;
}
//return $qval; // 5.031324
//return intval($qval); // 5
return round($qval, 1); // 5 or 4.9
}
}
| PHP |
<?php
/////////////////////////////////////////////////////////////////
/// getID3() by James Heinrich <info@getid3.org> //
// available at http://getid3.sourceforge.net //
// or http://www.getid3.org //
/////////////////////////////////////////////////////////////////
// See readme.txt for more details //
/////////////////////////////////////////////////////////////////
// //
// module.audio-video.asf.php //
// module for analyzing ASF, WMA and WMV files //
// dependencies: module.audio-video.riff.php //
// ///
/////////////////////////////////////////////////////////////////
getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.audio-video.riff.php', __FILE__, true);
class getid3_asf extends getid3_handler
{
public function __construct(getID3 $getid3) {
parent::__construct($getid3); // extends getid3_handler::__construct()
// initialize all GUID constants
$GUIDarray = $this->KnownGUIDs();
foreach ($GUIDarray as $GUIDname => $hexstringvalue) {
if (!defined($GUIDname)) {
define($GUIDname, $this->GUIDtoBytestring($hexstringvalue));
}
}
}
public function Analyze() {
$info = &$this->getid3->info;
// Shortcuts
$thisfile_audio = &$info['audio'];
$thisfile_video = &$info['video'];
$info['asf'] = array();
$thisfile_asf = &$info['asf'];
$thisfile_asf['comments'] = array();
$thisfile_asf_comments = &$thisfile_asf['comments'];
$thisfile_asf['header_object'] = array();
$thisfile_asf_headerobject = &$thisfile_asf['header_object'];
// ASF structure:
// * Header Object [required]
// * File Properties Object [required] (global file attributes)
// * Stream Properties Object [required] (defines media stream & characteristics)
// * Header Extension Object [required] (additional functionality)
// * Content Description Object (bibliographic information)
// * Script Command Object (commands for during playback)
// * Marker Object (named jumped points within the file)
// * Data Object [required]
// * Data Packets
// * Index Object
// Header Object: (mandatory, one only)
// Field Name Field Type Size (bits)
// Object ID GUID 128 // GUID for header object - GETID3_ASF_Header_Object
// Object Size QWORD 64 // size of header object, including 30 bytes of Header Object header
// Number of Header Objects DWORD 32 // number of objects in header object
// Reserved1 BYTE 8 // hardcoded: 0x01
// Reserved2 BYTE 8 // hardcoded: 0x02
$info['fileformat'] = 'asf';
fseek($this->getid3->fp, $info['avdataoffset'], SEEK_SET);
$HeaderObjectData = fread($this->getid3->fp, 30);
$thisfile_asf_headerobject['objectid'] = substr($HeaderObjectData, 0, 16);
$thisfile_asf_headerobject['objectid_guid'] = $this->BytestringToGUID($thisfile_asf_headerobject['objectid']);
if ($thisfile_asf_headerobject['objectid'] != GETID3_ASF_Header_Object) {
$info['warning'][] = 'ASF header GUID {'.$this->BytestringToGUID($thisfile_asf_headerobject['objectid']).'} does not match expected "GETID3_ASF_Header_Object" GUID {'.$this->BytestringToGUID(GETID3_ASF_Header_Object).'}';
unset($info['fileformat']);
unset($info['asf']);
return false;
break;
}
$thisfile_asf_headerobject['objectsize'] = getid3_lib::LittleEndian2Int(substr($HeaderObjectData, 16, 8));
$thisfile_asf_headerobject['headerobjects'] = getid3_lib::LittleEndian2Int(substr($HeaderObjectData, 24, 4));
$thisfile_asf_headerobject['reserved1'] = getid3_lib::LittleEndian2Int(substr($HeaderObjectData, 28, 1));
$thisfile_asf_headerobject['reserved2'] = getid3_lib::LittleEndian2Int(substr($HeaderObjectData, 29, 1));
$NextObjectOffset = ftell($this->getid3->fp);
$ASFHeaderData = fread($this->getid3->fp, $thisfile_asf_headerobject['objectsize'] - 30);
$offset = 0;
for ($HeaderObjectsCounter = 0; $HeaderObjectsCounter < $thisfile_asf_headerobject['headerobjects']; $HeaderObjectsCounter++) {
$NextObjectGUID = substr($ASFHeaderData, $offset, 16);
$offset += 16;
$NextObjectGUIDtext = $this->BytestringToGUID($NextObjectGUID);
$NextObjectSize = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 8));
$offset += 8;
switch ($NextObjectGUID) {
case GETID3_ASF_File_Properties_Object:
// File Properties Object: (mandatory, one only)
// Field Name Field Type Size (bits)
// Object ID GUID 128 // GUID for file properties object - GETID3_ASF_File_Properties_Object
// Object Size QWORD 64 // size of file properties object, including 104 bytes of File Properties Object header
// File ID GUID 128 // unique ID - identical to File ID in Data Object
// File Size QWORD 64 // entire file in bytes. Invalid if Broadcast Flag == 1
// Creation Date QWORD 64 // date & time of file creation. Maybe invalid if Broadcast Flag == 1
// Data Packets Count QWORD 64 // number of data packets in Data Object. Invalid if Broadcast Flag == 1
// Play Duration QWORD 64 // playtime, in 100-nanosecond units. Invalid if Broadcast Flag == 1
// Send Duration QWORD 64 // time needed to send file, in 100-nanosecond units. Players can ignore this value. Invalid if Broadcast Flag == 1
// Preroll QWORD 64 // time to buffer data before starting to play file, in 1-millisecond units. If <> 0, PlayDuration and PresentationTime have been offset by this amount
// Flags DWORD 32 //
// * Broadcast Flag bits 1 (0x01) // file is currently being written, some header values are invalid
// * Seekable Flag bits 1 (0x02) // is file seekable
// * Reserved bits 30 (0xFFFFFFFC) // reserved - set to zero
// Minimum Data Packet Size DWORD 32 // in bytes. should be same as Maximum Data Packet Size. Invalid if Broadcast Flag == 1
// Maximum Data Packet Size DWORD 32 // in bytes. should be same as Minimum Data Packet Size. Invalid if Broadcast Flag == 1
// Maximum Bitrate DWORD 32 // maximum instantaneous bitrate in bits per second for entire file, including all data streams and ASF overhead
// shortcut
$thisfile_asf['file_properties_object'] = array();
$thisfile_asf_filepropertiesobject = &$thisfile_asf['file_properties_object'];
$thisfile_asf_filepropertiesobject['offset'] = $NextObjectOffset + $offset;
$thisfile_asf_filepropertiesobject['objectid'] = $NextObjectGUID;
$thisfile_asf_filepropertiesobject['objectid_guid'] = $NextObjectGUIDtext;
$thisfile_asf_filepropertiesobject['objectsize'] = $NextObjectSize;
$thisfile_asf_filepropertiesobject['fileid'] = substr($ASFHeaderData, $offset, 16);
$offset += 16;
$thisfile_asf_filepropertiesobject['fileid_guid'] = $this->BytestringToGUID($thisfile_asf_filepropertiesobject['fileid']);
$thisfile_asf_filepropertiesobject['filesize'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 8));
$offset += 8;
$thisfile_asf_filepropertiesobject['creation_date'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 8));
$thisfile_asf_filepropertiesobject['creation_date_unix'] = $this->FILETIMEtoUNIXtime($thisfile_asf_filepropertiesobject['creation_date']);
$offset += 8;
$thisfile_asf_filepropertiesobject['data_packets'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 8));
$offset += 8;
$thisfile_asf_filepropertiesobject['play_duration'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 8));
$offset += 8;
$thisfile_asf_filepropertiesobject['send_duration'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 8));
$offset += 8;
$thisfile_asf_filepropertiesobject['preroll'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 8));
$offset += 8;
$thisfile_asf_filepropertiesobject['flags_raw'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 4));
$offset += 4;
$thisfile_asf_filepropertiesobject['flags']['broadcast'] = (bool) ($thisfile_asf_filepropertiesobject['flags_raw'] & 0x0001);
$thisfile_asf_filepropertiesobject['flags']['seekable'] = (bool) ($thisfile_asf_filepropertiesobject['flags_raw'] & 0x0002);
$thisfile_asf_filepropertiesobject['min_packet_size'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 4));
$offset += 4;
$thisfile_asf_filepropertiesobject['max_packet_size'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 4));
$offset += 4;
$thisfile_asf_filepropertiesobject['max_bitrate'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 4));
$offset += 4;
if ($thisfile_asf_filepropertiesobject['flags']['broadcast']) {
// broadcast flag is set, some values invalid
unset($thisfile_asf_filepropertiesobject['filesize']);
unset($thisfile_asf_filepropertiesobject['data_packets']);
unset($thisfile_asf_filepropertiesobject['play_duration']);
unset($thisfile_asf_filepropertiesobject['send_duration']);
unset($thisfile_asf_filepropertiesobject['min_packet_size']);
unset($thisfile_asf_filepropertiesobject['max_packet_size']);
} else {
// broadcast flag NOT set, perform calculations
$info['playtime_seconds'] = ($thisfile_asf_filepropertiesobject['play_duration'] / 10000000) - ($thisfile_asf_filepropertiesobject['preroll'] / 1000);
//$info['bitrate'] = $thisfile_asf_filepropertiesobject['max_bitrate'];
$info['bitrate'] = ((isset($thisfile_asf_filepropertiesobject['filesize']) ? $thisfile_asf_filepropertiesobject['filesize'] : $info['filesize']) * 8) / $info['playtime_seconds'];
}
break;
case GETID3_ASF_Stream_Properties_Object:
// Stream Properties Object: (mandatory, one per media stream)
// Field Name Field Type Size (bits)
// Object ID GUID 128 // GUID for stream properties object - GETID3_ASF_Stream_Properties_Object
// Object Size QWORD 64 // size of stream properties object, including 78 bytes of Stream Properties Object header
// Stream Type GUID 128 // GETID3_ASF_Audio_Media, GETID3_ASF_Video_Media or GETID3_ASF_Command_Media
// Error Correction Type GUID 128 // GETID3_ASF_Audio_Spread for audio-only streams, GETID3_ASF_No_Error_Correction for other stream types
// Time Offset QWORD 64 // 100-nanosecond units. typically zero. added to all timestamps of samples in the stream
// Type-Specific Data Length DWORD 32 // number of bytes for Type-Specific Data field
// Error Correction Data Length DWORD 32 // number of bytes for Error Correction Data field
// Flags WORD 16 //
// * Stream Number bits 7 (0x007F) // number of this stream. 1 <= valid <= 127
// * Reserved bits 8 (0x7F80) // reserved - set to zero
// * Encrypted Content Flag bits 1 (0x8000) // stream contents encrypted if set
// Reserved DWORD 32 // reserved - set to zero
// Type-Specific Data BYTESTREAM variable // type-specific format data, depending on value of Stream Type
// Error Correction Data BYTESTREAM variable // error-correction-specific format data, depending on value of Error Correct Type
// There is one GETID3_ASF_Stream_Properties_Object for each stream (audio, video) but the
// stream number isn't known until halfway through decoding the structure, hence it
// it is decoded to a temporary variable and then stuck in the appropriate index later
$StreamPropertiesObjectData['offset'] = $NextObjectOffset + $offset;
$StreamPropertiesObjectData['objectid'] = $NextObjectGUID;
$StreamPropertiesObjectData['objectid_guid'] = $NextObjectGUIDtext;
$StreamPropertiesObjectData['objectsize'] = $NextObjectSize;
$StreamPropertiesObjectData['stream_type'] = substr($ASFHeaderData, $offset, 16);
$offset += 16;
$StreamPropertiesObjectData['stream_type_guid'] = $this->BytestringToGUID($StreamPropertiesObjectData['stream_type']);
$StreamPropertiesObjectData['error_correct_type'] = substr($ASFHeaderData, $offset, 16);
$offset += 16;
$StreamPropertiesObjectData['error_correct_guid'] = $this->BytestringToGUID($StreamPropertiesObjectData['error_correct_type']);
$StreamPropertiesObjectData['time_offset'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 8));
$offset += 8;
$StreamPropertiesObjectData['type_data_length'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 4));
$offset += 4;
$StreamPropertiesObjectData['error_data_length'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 4));
$offset += 4;
$StreamPropertiesObjectData['flags_raw'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
$offset += 2;
$StreamPropertiesObjectStreamNumber = $StreamPropertiesObjectData['flags_raw'] & 0x007F;
$StreamPropertiesObjectData['flags']['encrypted'] = (bool) ($StreamPropertiesObjectData['flags_raw'] & 0x8000);
$offset += 4; // reserved - DWORD
$StreamPropertiesObjectData['type_specific_data'] = substr($ASFHeaderData, $offset, $StreamPropertiesObjectData['type_data_length']);
$offset += $StreamPropertiesObjectData['type_data_length'];
$StreamPropertiesObjectData['error_correct_data'] = substr($ASFHeaderData, $offset, $StreamPropertiesObjectData['error_data_length']);
$offset += $StreamPropertiesObjectData['error_data_length'];
switch ($StreamPropertiesObjectData['stream_type']) {
case GETID3_ASF_Audio_Media:
$thisfile_audio['dataformat'] = (!empty($thisfile_audio['dataformat']) ? $thisfile_audio['dataformat'] : 'asf');
$thisfile_audio['bitrate_mode'] = (!empty($thisfile_audio['bitrate_mode']) ? $thisfile_audio['bitrate_mode'] : 'cbr');
$audiodata = getid3_riff::parseWAVEFORMATex(substr($StreamPropertiesObjectData['type_specific_data'], 0, 16));
unset($audiodata['raw']);
$thisfile_audio = getid3_lib::array_merge_noclobber($audiodata, $thisfile_audio);
break;
case GETID3_ASF_Video_Media:
$thisfile_video['dataformat'] = (!empty($thisfile_video['dataformat']) ? $thisfile_video['dataformat'] : 'asf');
$thisfile_video['bitrate_mode'] = (!empty($thisfile_video['bitrate_mode']) ? $thisfile_video['bitrate_mode'] : 'cbr');
break;
case GETID3_ASF_Command_Media:
default:
// do nothing
break;
}
$thisfile_asf['stream_properties_object'][$StreamPropertiesObjectStreamNumber] = $StreamPropertiesObjectData;
unset($StreamPropertiesObjectData); // clear for next stream, if any
break;
case GETID3_ASF_Header_Extension_Object:
// Header Extension Object: (mandatory, one only)
// Field Name Field Type Size (bits)
// Object ID GUID 128 // GUID for Header Extension object - GETID3_ASF_Header_Extension_Object
// Object Size QWORD 64 // size of Header Extension object, including 46 bytes of Header Extension Object header
// Reserved Field 1 GUID 128 // hardcoded: GETID3_ASF_Reserved_1
// Reserved Field 2 WORD 16 // hardcoded: 0x00000006
// Header Extension Data Size DWORD 32 // in bytes. valid: 0, or > 24. equals object size minus 46
// Header Extension Data BYTESTREAM variable // array of zero or more extended header objects
// shortcut
$thisfile_asf['header_extension_object'] = array();
$thisfile_asf_headerextensionobject = &$thisfile_asf['header_extension_object'];
$thisfile_asf_headerextensionobject['offset'] = $NextObjectOffset + $offset;
$thisfile_asf_headerextensionobject['objectid'] = $NextObjectGUID;
$thisfile_asf_headerextensionobject['objectid_guid'] = $NextObjectGUIDtext;
$thisfile_asf_headerextensionobject['objectsize'] = $NextObjectSize;
$thisfile_asf_headerextensionobject['reserved_1'] = substr($ASFHeaderData, $offset, 16);
$offset += 16;
$thisfile_asf_headerextensionobject['reserved_1_guid'] = $this->BytestringToGUID($thisfile_asf_headerextensionobject['reserved_1']);
if ($thisfile_asf_headerextensionobject['reserved_1'] != GETID3_ASF_Reserved_1) {
$info['warning'][] = 'header_extension_object.reserved_1 GUID ('.$this->BytestringToGUID($thisfile_asf_headerextensionobject['reserved_1']).') does not match expected "GETID3_ASF_Reserved_1" GUID ('.$this->BytestringToGUID(GETID3_ASF_Reserved_1).')';
//return false;
break;
}
$thisfile_asf_headerextensionobject['reserved_2'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
$offset += 2;
if ($thisfile_asf_headerextensionobject['reserved_2'] != 6) {
$info['warning'][] = 'header_extension_object.reserved_2 ('.getid3_lib::PrintHexBytes($thisfile_asf_headerextensionobject['reserved_2']).') does not match expected value of "6"';
//return false;
break;
}
$thisfile_asf_headerextensionobject['extension_data_size'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 4));
$offset += 4;
$thisfile_asf_headerextensionobject['extension_data'] = substr($ASFHeaderData, $offset, $thisfile_asf_headerextensionobject['extension_data_size']);
$unhandled_sections = 0;
$thisfile_asf_headerextensionobject['extension_data_parsed'] = $this->ASF_HeaderExtensionObjectDataParse($thisfile_asf_headerextensionobject['extension_data'], $unhandled_sections);
if ($unhandled_sections === 0) {
unset($thisfile_asf_headerextensionobject['extension_data']);
}
$offset += $thisfile_asf_headerextensionobject['extension_data_size'];
break;
case GETID3_ASF_Codec_List_Object:
// Codec List Object: (optional, one only)
// Field Name Field Type Size (bits)
// Object ID GUID 128 // GUID for Codec List object - GETID3_ASF_Codec_List_Object
// Object Size QWORD 64 // size of Codec List object, including 44 bytes of Codec List Object header
// Reserved GUID 128 // hardcoded: 86D15241-311D-11D0-A3A4-00A0C90348F6
// Codec Entries Count DWORD 32 // number of entries in Codec Entries array
// Codec Entries array of: variable //
// * Type WORD 16 // 0x0001 = Video Codec, 0x0002 = Audio Codec, 0xFFFF = Unknown Codec
// * Codec Name Length WORD 16 // number of Unicode characters stored in the Codec Name field
// * Codec Name WCHAR variable // array of Unicode characters - name of codec used to create the content
// * Codec Description Length WORD 16 // number of Unicode characters stored in the Codec Description field
// * Codec Description WCHAR variable // array of Unicode characters - description of format used to create the content
// * Codec Information Length WORD 16 // number of Unicode characters stored in the Codec Information field
// * Codec Information BYTESTREAM variable // opaque array of information bytes about the codec used to create the content
// shortcut
$thisfile_asf['codec_list_object'] = array();
$thisfile_asf_codeclistobject = &$thisfile_asf['codec_list_object'];
$thisfile_asf_codeclistobject['offset'] = $NextObjectOffset + $offset;
$thisfile_asf_codeclistobject['objectid'] = $NextObjectGUID;
$thisfile_asf_codeclistobject['objectid_guid'] = $NextObjectGUIDtext;
$thisfile_asf_codeclistobject['objectsize'] = $NextObjectSize;
$thisfile_asf_codeclistobject['reserved'] = substr($ASFHeaderData, $offset, 16);
$offset += 16;
$thisfile_asf_codeclistobject['reserved_guid'] = $this->BytestringToGUID($thisfile_asf_codeclistobject['reserved']);
if ($thisfile_asf_codeclistobject['reserved'] != $this->GUIDtoBytestring('86D15241-311D-11D0-A3A4-00A0C90348F6')) {
$info['warning'][] = 'codec_list_object.reserved GUID {'.$this->BytestringToGUID($thisfile_asf_codeclistobject['reserved']).'} does not match expected "GETID3_ASF_Reserved_1" GUID {86D15241-311D-11D0-A3A4-00A0C90348F6}';
//return false;
break;
}
$thisfile_asf_codeclistobject['codec_entries_count'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 4));
$offset += 4;
for ($CodecEntryCounter = 0; $CodecEntryCounter < $thisfile_asf_codeclistobject['codec_entries_count']; $CodecEntryCounter++) {
// shortcut
$thisfile_asf_codeclistobject['codec_entries'][$CodecEntryCounter] = array();
$thisfile_asf_codeclistobject_codecentries_current = &$thisfile_asf_codeclistobject['codec_entries'][$CodecEntryCounter];
$thisfile_asf_codeclistobject_codecentries_current['type_raw'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
$offset += 2;
$thisfile_asf_codeclistobject_codecentries_current['type'] = $this->ASFCodecListObjectTypeLookup($thisfile_asf_codeclistobject_codecentries_current['type_raw']);
$CodecNameLength = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2)) * 2; // 2 bytes per character
$offset += 2;
$thisfile_asf_codeclistobject_codecentries_current['name'] = substr($ASFHeaderData, $offset, $CodecNameLength);
$offset += $CodecNameLength;
$CodecDescriptionLength = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2)) * 2; // 2 bytes per character
$offset += 2;
$thisfile_asf_codeclistobject_codecentries_current['description'] = substr($ASFHeaderData, $offset, $CodecDescriptionLength);
$offset += $CodecDescriptionLength;
$CodecInformationLength = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
$offset += 2;
$thisfile_asf_codeclistobject_codecentries_current['information'] = substr($ASFHeaderData, $offset, $CodecInformationLength);
$offset += $CodecInformationLength;
if ($thisfile_asf_codeclistobject_codecentries_current['type_raw'] == 2) { // audio codec
if (strpos($thisfile_asf_codeclistobject_codecentries_current['description'], ',') === false) {
$info['warning'][] = '[asf][codec_list_object][codec_entries]['.$CodecEntryCounter.'][description] expected to contain comma-seperated list of parameters: "'.$thisfile_asf_codeclistobject_codecentries_current['description'].'"';
} else {
list($AudioCodecBitrate, $AudioCodecFrequency, $AudioCodecChannels) = explode(',', $this->TrimConvert($thisfile_asf_codeclistobject_codecentries_current['description']));
$thisfile_audio['codec'] = $this->TrimConvert($thisfile_asf_codeclistobject_codecentries_current['name']);
if (!isset($thisfile_audio['bitrate']) && strstr($AudioCodecBitrate, 'kbps')) {
$thisfile_audio['bitrate'] = (int) (trim(str_replace('kbps', '', $AudioCodecBitrate)) * 1000);
}
//if (!isset($thisfile_video['bitrate']) && isset($thisfile_audio['bitrate']) && isset($thisfile_asf['file_properties_object']['max_bitrate']) && ($thisfile_asf_codeclistobject['codec_entries_count'] > 1)) {
if (empty($thisfile_video['bitrate']) && !empty($thisfile_audio['bitrate']) && !empty($info['bitrate'])) {
//$thisfile_video['bitrate'] = $thisfile_asf['file_properties_object']['max_bitrate'] - $thisfile_audio['bitrate'];
$thisfile_video['bitrate'] = $info['bitrate'] - $thisfile_audio['bitrate'];
}
$AudioCodecFrequency = (int) trim(str_replace('kHz', '', $AudioCodecFrequency));
switch ($AudioCodecFrequency) {
case 8:
case 8000:
$thisfile_audio['sample_rate'] = 8000;
break;
case 11:
case 11025:
$thisfile_audio['sample_rate'] = 11025;
break;
case 12:
case 12000:
$thisfile_audio['sample_rate'] = 12000;
break;
case 16:
case 16000:
$thisfile_audio['sample_rate'] = 16000;
break;
case 22:
case 22050:
$thisfile_audio['sample_rate'] = 22050;
break;
case 24:
case 24000:
$thisfile_audio['sample_rate'] = 24000;
break;
case 32:
case 32000:
$thisfile_audio['sample_rate'] = 32000;
break;
case 44:
case 441000:
$thisfile_audio['sample_rate'] = 44100;
break;
case 48:
case 48000:
$thisfile_audio['sample_rate'] = 48000;
break;
default:
$info['warning'][] = 'unknown frequency: "'.$AudioCodecFrequency.'" ('.$this->TrimConvert($thisfile_asf_codeclistobject_codecentries_current['description']).')';
break;
}
if (!isset($thisfile_audio['channels'])) {
if (strstr($AudioCodecChannels, 'stereo')) {
$thisfile_audio['channels'] = 2;
} elseif (strstr($AudioCodecChannels, 'mono')) {
$thisfile_audio['channels'] = 1;
}
}
}
}
}
break;
case GETID3_ASF_Script_Command_Object:
// Script Command Object: (optional, one only)
// Field Name Field Type Size (bits)
// Object ID GUID 128 // GUID for Script Command object - GETID3_ASF_Script_Command_Object
// Object Size QWORD 64 // size of Script Command object, including 44 bytes of Script Command Object header
// Reserved GUID 128 // hardcoded: 4B1ACBE3-100B-11D0-A39B-00A0C90348F6
// Commands Count WORD 16 // number of Commands structures in the Script Commands Objects
// Command Types Count WORD 16 // number of Command Types structures in the Script Commands Objects
// Command Types array of: variable //
// * Command Type Name Length WORD 16 // number of Unicode characters for Command Type Name
// * Command Type Name WCHAR variable // array of Unicode characters - name of a type of command
// Commands array of: variable //
// * Presentation Time DWORD 32 // presentation time of that command, in milliseconds
// * Type Index WORD 16 // type of this command, as a zero-based index into the array of Command Types of this object
// * Command Name Length WORD 16 // number of Unicode characters for Command Name
// * Command Name WCHAR variable // array of Unicode characters - name of this command
// shortcut
$thisfile_asf['script_command_object'] = array();
$thisfile_asf_scriptcommandobject = &$thisfile_asf['script_command_object'];
$thisfile_asf_scriptcommandobject['offset'] = $NextObjectOffset + $offset;
$thisfile_asf_scriptcommandobject['objectid'] = $NextObjectGUID;
$thisfile_asf_scriptcommandobject['objectid_guid'] = $NextObjectGUIDtext;
$thisfile_asf_scriptcommandobject['objectsize'] = $NextObjectSize;
$thisfile_asf_scriptcommandobject['reserved'] = substr($ASFHeaderData, $offset, 16);
$offset += 16;
$thisfile_asf_scriptcommandobject['reserved_guid'] = $this->BytestringToGUID($thisfile_asf_scriptcommandobject['reserved']);
if ($thisfile_asf_scriptcommandobject['reserved'] != $this->GUIDtoBytestring('4B1ACBE3-100B-11D0-A39B-00A0C90348F6')) {
$info['warning'][] = 'script_command_object.reserved GUID {'.$this->BytestringToGUID($thisfile_asf_scriptcommandobject['reserved']).'} does not match expected "GETID3_ASF_Reserved_1" GUID {4B1ACBE3-100B-11D0-A39B-00A0C90348F6}';
//return false;
break;
}
$thisfile_asf_scriptcommandobject['commands_count'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
$offset += 2;
$thisfile_asf_scriptcommandobject['command_types_count'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
$offset += 2;
for ($CommandTypesCounter = 0; $CommandTypesCounter < $thisfile_asf_scriptcommandobject['command_types_count']; $CommandTypesCounter++) {
$CommandTypeNameLength = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2)) * 2; // 2 bytes per character
$offset += 2;
$thisfile_asf_scriptcommandobject['command_types'][$CommandTypesCounter]['name'] = substr($ASFHeaderData, $offset, $CommandTypeNameLength);
$offset += $CommandTypeNameLength;
}
for ($CommandsCounter = 0; $CommandsCounter < $thisfile_asf_scriptcommandobject['commands_count']; $CommandsCounter++) {
$thisfile_asf_scriptcommandobject['commands'][$CommandsCounter]['presentation_time'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 4));
$offset += 4;
$thisfile_asf_scriptcommandobject['commands'][$CommandsCounter]['type_index'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
$offset += 2;
$CommandTypeNameLength = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2)) * 2; // 2 bytes per character
$offset += 2;
$thisfile_asf_scriptcommandobject['commands'][$CommandsCounter]['name'] = substr($ASFHeaderData, $offset, $CommandTypeNameLength);
$offset += $CommandTypeNameLength;
}
break;
case GETID3_ASF_Marker_Object:
// Marker Object: (optional, one only)
// Field Name Field Type Size (bits)
// Object ID GUID 128 // GUID for Marker object - GETID3_ASF_Marker_Object
// Object Size QWORD 64 // size of Marker object, including 48 bytes of Marker Object header
// Reserved GUID 128 // hardcoded: 4CFEDB20-75F6-11CF-9C0F-00A0C90349CB
// Markers Count DWORD 32 // number of Marker structures in Marker Object
// Reserved WORD 16 // hardcoded: 0x0000
// Name Length WORD 16 // number of bytes in the Name field
// Name WCHAR variable // name of the Marker Object
// Markers array of: variable //
// * Offset QWORD 64 // byte offset into Data Object
// * Presentation Time QWORD 64 // in 100-nanosecond units
// * Entry Length WORD 16 // length in bytes of (Send Time + Flags + Marker Description Length + Marker Description + Padding)
// * Send Time DWORD 32 // in milliseconds
// * Flags DWORD 32 // hardcoded: 0x00000000
// * Marker Description Length DWORD 32 // number of bytes in Marker Description field
// * Marker Description WCHAR variable // array of Unicode characters - description of marker entry
// * Padding BYTESTREAM variable // optional padding bytes
// shortcut
$thisfile_asf['marker_object'] = array();
$thisfile_asf_markerobject = &$thisfile_asf['marker_object'];
$thisfile_asf_markerobject['offset'] = $NextObjectOffset + $offset;
$thisfile_asf_markerobject['objectid'] = $NextObjectGUID;
$thisfile_asf_markerobject['objectid_guid'] = $NextObjectGUIDtext;
$thisfile_asf_markerobject['objectsize'] = $NextObjectSize;
$thisfile_asf_markerobject['reserved'] = substr($ASFHeaderData, $offset, 16);
$offset += 16;
$thisfile_asf_markerobject['reserved_guid'] = $this->BytestringToGUID($thisfile_asf_markerobject['reserved']);
if ($thisfile_asf_markerobject['reserved'] != $this->GUIDtoBytestring('4CFEDB20-75F6-11CF-9C0F-00A0C90349CB')) {
$info['warning'][] = 'marker_object.reserved GUID {'.$this->BytestringToGUID($thisfile_asf_markerobject['reserved_1']).'} does not match expected "GETID3_ASF_Reserved_1" GUID {4CFEDB20-75F6-11CF-9C0F-00A0C90349CB}';
break;
}
$thisfile_asf_markerobject['markers_count'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 4));
$offset += 4;
$thisfile_asf_markerobject['reserved_2'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
$offset += 2;
if ($thisfile_asf_markerobject['reserved_2'] != 0) {
$info['warning'][] = 'marker_object.reserved_2 ('.getid3_lib::PrintHexBytes($thisfile_asf_markerobject['reserved_2']).') does not match expected value of "0"';
break;
}
$thisfile_asf_markerobject['name_length'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
$offset += 2;
$thisfile_asf_markerobject['name'] = substr($ASFHeaderData, $offset, $thisfile_asf_markerobject['name_length']);
$offset += $thisfile_asf_markerobject['name_length'];
for ($MarkersCounter = 0; $MarkersCounter < $thisfile_asf_markerobject['markers_count']; $MarkersCounter++) {
$thisfile_asf_markerobject['markers'][$MarkersCounter]['offset'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 8));
$offset += 8;
$thisfile_asf_markerobject['markers'][$MarkersCounter]['presentation_time'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 8));
$offset += 8;
$thisfile_asf_markerobject['markers'][$MarkersCounter]['entry_length'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
$offset += 2;
$thisfile_asf_markerobject['markers'][$MarkersCounter]['send_time'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 4));
$offset += 4;
$thisfile_asf_markerobject['markers'][$MarkersCounter]['flags'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 4));
$offset += 4;
$thisfile_asf_markerobject['markers'][$MarkersCounter]['marker_description_length'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 4));
$offset += 4;
$thisfile_asf_markerobject['markers'][$MarkersCounter]['marker_description'] = substr($ASFHeaderData, $offset, $thisfile_asf_markerobject['markers'][$MarkersCounter]['marker_description_length']);
$offset += $thisfile_asf_markerobject['markers'][$MarkersCounter]['marker_description_length'];
$PaddingLength = $thisfile_asf_markerobject['markers'][$MarkersCounter]['entry_length'] - 4 - 4 - 4 - $thisfile_asf_markerobject['markers'][$MarkersCounter]['marker_description_length'];
if ($PaddingLength > 0) {
$thisfile_asf_markerobject['markers'][$MarkersCounter]['padding'] = substr($ASFHeaderData, $offset, $PaddingLength);
$offset += $PaddingLength;
}
}
break;
case GETID3_ASF_Bitrate_Mutual_Exclusion_Object:
// Bitrate Mutual Exclusion Object: (optional)
// Field Name Field Type Size (bits)
// Object ID GUID 128 // GUID for Bitrate Mutual Exclusion object - GETID3_ASF_Bitrate_Mutual_Exclusion_Object
// Object Size QWORD 64 // size of Bitrate Mutual Exclusion object, including 42 bytes of Bitrate Mutual Exclusion Object header
// Exlusion Type GUID 128 // nature of mutual exclusion relationship. one of: (GETID3_ASF_Mutex_Bitrate, GETID3_ASF_Mutex_Unknown)
// Stream Numbers Count WORD 16 // number of video streams
// Stream Numbers WORD variable // array of mutually exclusive video stream numbers. 1 <= valid <= 127
// shortcut
$thisfile_asf['bitrate_mutual_exclusion_object'] = array();
$thisfile_asf_bitratemutualexclusionobject = &$thisfile_asf['bitrate_mutual_exclusion_object'];
$thisfile_asf_bitratemutualexclusionobject['offset'] = $NextObjectOffset + $offset;
$thisfile_asf_bitratemutualexclusionobject['objectid'] = $NextObjectGUID;
$thisfile_asf_bitratemutualexclusionobject['objectid_guid'] = $NextObjectGUIDtext;
$thisfile_asf_bitratemutualexclusionobject['objectsize'] = $NextObjectSize;
$thisfile_asf_bitratemutualexclusionobject['reserved'] = substr($ASFHeaderData, $offset, 16);
$thisfile_asf_bitratemutualexclusionobject['reserved_guid'] = $this->BytestringToGUID($thisfile_asf_bitratemutualexclusionobject['reserved']);
$offset += 16;
if (($thisfile_asf_bitratemutualexclusionobject['reserved'] != GETID3_ASF_Mutex_Bitrate) && ($thisfile_asf_bitratemutualexclusionobject['reserved'] != GETID3_ASF_Mutex_Unknown)) {
$info['warning'][] = 'bitrate_mutual_exclusion_object.reserved GUID {'.$this->BytestringToGUID($thisfile_asf_bitratemutualexclusionobject['reserved']).'} does not match expected "GETID3_ASF_Mutex_Bitrate" GUID {'.$this->BytestringToGUID(GETID3_ASF_Mutex_Bitrate).'} or "GETID3_ASF_Mutex_Unknown" GUID {'.$this->BytestringToGUID(GETID3_ASF_Mutex_Unknown).'}';
//return false;
break;
}
$thisfile_asf_bitratemutualexclusionobject['stream_numbers_count'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
$offset += 2;
for ($StreamNumberCounter = 0; $StreamNumberCounter < $thisfile_asf_bitratemutualexclusionobject['stream_numbers_count']; $StreamNumberCounter++) {
$thisfile_asf_bitratemutualexclusionobject['stream_numbers'][$StreamNumberCounter] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
$offset += 2;
}
break;
case GETID3_ASF_Error_Correction_Object:
// Error Correction Object: (optional, one only)
// Field Name Field Type Size (bits)
// Object ID GUID 128 // GUID for Error Correction object - GETID3_ASF_Error_Correction_Object
// Object Size QWORD 64 // size of Error Correction object, including 44 bytes of Error Correction Object header
// Error Correction Type GUID 128 // type of error correction. one of: (GETID3_ASF_No_Error_Correction, GETID3_ASF_Audio_Spread)
// Error Correction Data Length DWORD 32 // number of bytes in Error Correction Data field
// Error Correction Data BYTESTREAM variable // structure depends on value of Error Correction Type field
// shortcut
$thisfile_asf['error_correction_object'] = array();
$thisfile_asf_errorcorrectionobject = &$thisfile_asf['error_correction_object'];
$thisfile_asf_errorcorrectionobject['offset'] = $NextObjectOffset + $offset;
$thisfile_asf_errorcorrectionobject['objectid'] = $NextObjectGUID;
$thisfile_asf_errorcorrectionobject['objectid_guid'] = $NextObjectGUIDtext;
$thisfile_asf_errorcorrectionobject['objectsize'] = $NextObjectSize;
$thisfile_asf_errorcorrectionobject['error_correction_type'] = substr($ASFHeaderData, $offset, 16);
$offset += 16;
$thisfile_asf_errorcorrectionobject['error_correction_guid'] = $this->BytestringToGUID($thisfile_asf_errorcorrectionobject['error_correction_type']);
$thisfile_asf_errorcorrectionobject['error_correction_data_length'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 4));
$offset += 4;
switch ($thisfile_asf_errorcorrectionobject['error_correction_type']) {
case GETID3_ASF_No_Error_Correction:
// should be no data, but just in case there is, skip to the end of the field
$offset += $thisfile_asf_errorcorrectionobject['error_correction_data_length'];
break;
case GETID3_ASF_Audio_Spread:
// Field Name Field Type Size (bits)
// Span BYTE 8 // number of packets over which audio will be spread.
// Virtual Packet Length WORD 16 // size of largest audio payload found in audio stream
// Virtual Chunk Length WORD 16 // size of largest audio payload found in audio stream
// Silence Data Length WORD 16 // number of bytes in Silence Data field
// Silence Data BYTESTREAM variable // hardcoded: 0x00 * (Silence Data Length) bytes
$thisfile_asf_errorcorrectionobject['span'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 1));
$offset += 1;
$thisfile_asf_errorcorrectionobject['virtual_packet_length'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
$offset += 2;
$thisfile_asf_errorcorrectionobject['virtual_chunk_length'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
$offset += 2;
$thisfile_asf_errorcorrectionobject['silence_data_length'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
$offset += 2;
$thisfile_asf_errorcorrectionobject['silence_data'] = substr($ASFHeaderData, $offset, $thisfile_asf_errorcorrectionobject['silence_data_length']);
$offset += $thisfile_asf_errorcorrectionobject['silence_data_length'];
break;
default:
$info['warning'][] = 'error_correction_object.error_correction_type GUID {'.$this->BytestringToGUID($thisfile_asf_errorcorrectionobject['reserved']).'} does not match expected "GETID3_ASF_No_Error_Correction" GUID {'.$this->BytestringToGUID(GETID3_ASF_No_Error_Correction).'} or "GETID3_ASF_Audio_Spread" GUID {'.$this->BytestringToGUID(GETID3_ASF_Audio_Spread).'}';
//return false;
break;
}
break;
case GETID3_ASF_Content_Description_Object:
// Content Description Object: (optional, one only)
// Field Name Field Type Size (bits)
// Object ID GUID 128 // GUID for Content Description object - GETID3_ASF_Content_Description_Object
// Object Size QWORD 64 // size of Content Description object, including 34 bytes of Content Description Object header
// Title Length WORD 16 // number of bytes in Title field
// Author Length WORD 16 // number of bytes in Author field
// Copyright Length WORD 16 // number of bytes in Copyright field
// Description Length WORD 16 // number of bytes in Description field
// Rating Length WORD 16 // number of bytes in Rating field
// Title WCHAR 16 // array of Unicode characters - Title
// Author WCHAR 16 // array of Unicode characters - Author
// Copyright WCHAR 16 // array of Unicode characters - Copyright
// Description WCHAR 16 // array of Unicode characters - Description
// Rating WCHAR 16 // array of Unicode characters - Rating
// shortcut
$thisfile_asf['content_description_object'] = array();
$thisfile_asf_contentdescriptionobject = &$thisfile_asf['content_description_object'];
$thisfile_asf_contentdescriptionobject['offset'] = $NextObjectOffset + $offset;
$thisfile_asf_contentdescriptionobject['objectid'] = $NextObjectGUID;
$thisfile_asf_contentdescriptionobject['objectid_guid'] = $NextObjectGUIDtext;
$thisfile_asf_contentdescriptionobject['objectsize'] = $NextObjectSize;
$thisfile_asf_contentdescriptionobject['title_length'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
$offset += 2;
$thisfile_asf_contentdescriptionobject['author_length'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
$offset += 2;
$thisfile_asf_contentdescriptionobject['copyright_length'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
$offset += 2;
$thisfile_asf_contentdescriptionobject['description_length'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
$offset += 2;
$thisfile_asf_contentdescriptionobject['rating_length'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
$offset += 2;
$thisfile_asf_contentdescriptionobject['title'] = substr($ASFHeaderData, $offset, $thisfile_asf_contentdescriptionobject['title_length']);
$offset += $thisfile_asf_contentdescriptionobject['title_length'];
$thisfile_asf_contentdescriptionobject['author'] = substr($ASFHeaderData, $offset, $thisfile_asf_contentdescriptionobject['author_length']);
$offset += $thisfile_asf_contentdescriptionobject['author_length'];
$thisfile_asf_contentdescriptionobject['copyright'] = substr($ASFHeaderData, $offset, $thisfile_asf_contentdescriptionobject['copyright_length']);
$offset += $thisfile_asf_contentdescriptionobject['copyright_length'];
$thisfile_asf_contentdescriptionobject['description'] = substr($ASFHeaderData, $offset, $thisfile_asf_contentdescriptionobject['description_length']);
$offset += $thisfile_asf_contentdescriptionobject['description_length'];
$thisfile_asf_contentdescriptionobject['rating'] = substr($ASFHeaderData, $offset, $thisfile_asf_contentdescriptionobject['rating_length']);
$offset += $thisfile_asf_contentdescriptionobject['rating_length'];
$ASFcommentKeysToCopy = array('title'=>'title', 'author'=>'artist', 'copyright'=>'copyright', 'description'=>'comment', 'rating'=>'rating');
foreach ($ASFcommentKeysToCopy as $keytocopyfrom => $keytocopyto) {
if (!empty($thisfile_asf_contentdescriptionobject[$keytocopyfrom])) {
$thisfile_asf_comments[$keytocopyto][] = $this->TrimTerm($thisfile_asf_contentdescriptionobject[$keytocopyfrom]);
}
}
break;
case GETID3_ASF_Extended_Content_Description_Object:
// Extended Content Description Object: (optional, one only)
// Field Name Field Type Size (bits)
// Object ID GUID 128 // GUID for Extended Content Description object - GETID3_ASF_Extended_Content_Description_Object
// Object Size QWORD 64 // size of ExtendedContent Description object, including 26 bytes of Extended Content Description Object header
// Content Descriptors Count WORD 16 // number of entries in Content Descriptors list
// Content Descriptors array of: variable //
// * Descriptor Name Length WORD 16 // size in bytes of Descriptor Name field
// * Descriptor Name WCHAR variable // array of Unicode characters - Descriptor Name
// * Descriptor Value Data Type WORD 16 // Lookup array:
// 0x0000 = Unicode String (variable length)
// 0x0001 = BYTE array (variable length)
// 0x0002 = BOOL (DWORD, 32 bits)
// 0x0003 = DWORD (DWORD, 32 bits)
// 0x0004 = QWORD (QWORD, 64 bits)
// 0x0005 = WORD (WORD, 16 bits)
// * Descriptor Value Length WORD 16 // number of bytes stored in Descriptor Value field
// * Descriptor Value variable variable // value for Content Descriptor
// shortcut
$thisfile_asf['extended_content_description_object'] = array();
$thisfile_asf_extendedcontentdescriptionobject = &$thisfile_asf['extended_content_description_object'];
$thisfile_asf_extendedcontentdescriptionobject['offset'] = $NextObjectOffset + $offset;
$thisfile_asf_extendedcontentdescriptionobject['objectid'] = $NextObjectGUID;
$thisfile_asf_extendedcontentdescriptionobject['objectid_guid'] = $NextObjectGUIDtext;
$thisfile_asf_extendedcontentdescriptionobject['objectsize'] = $NextObjectSize;
$thisfile_asf_extendedcontentdescriptionobject['content_descriptors_count'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
$offset += 2;
for ($ExtendedContentDescriptorsCounter = 0; $ExtendedContentDescriptorsCounter < $thisfile_asf_extendedcontentdescriptionobject['content_descriptors_count']; $ExtendedContentDescriptorsCounter++) {
// shortcut
$thisfile_asf_extendedcontentdescriptionobject['content_descriptors'][$ExtendedContentDescriptorsCounter] = array();
$thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current = &$thisfile_asf_extendedcontentdescriptionobject['content_descriptors'][$ExtendedContentDescriptorsCounter];
$thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['base_offset'] = $offset + 30;
$thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['name_length'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
$offset += 2;
$thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['name'] = substr($ASFHeaderData, $offset, $thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['name_length']);
$offset += $thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['name_length'];
$thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value_type'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
$offset += 2;
$thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value_length'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
$offset += 2;
$thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value'] = substr($ASFHeaderData, $offset, $thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value_length']);
$offset += $thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value_length'];
switch ($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value_type']) {
case 0x0000: // Unicode string
break;
case 0x0001: // BYTE array
// do nothing
break;
case 0x0002: // BOOL
$thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value'] = (bool) getid3_lib::LittleEndian2Int($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value']);
break;
case 0x0003: // DWORD
case 0x0004: // QWORD
case 0x0005: // WORD
$thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value'] = getid3_lib::LittleEndian2Int($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value']);
break;
default:
$info['warning'][] = 'extended_content_description.content_descriptors.'.$ExtendedContentDescriptorsCounter.'.value_type is invalid ('.$thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value_type'].')';
//return false;
break;
}
switch ($this->TrimConvert(strtolower($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['name']))) {
case 'wm/albumartist':
case 'artist':
// Note: not 'artist', that comes from 'author' tag
$thisfile_asf_comments['albumartist'] = array($this->TrimTerm($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value']));
break;
case 'wm/albumtitle':
case 'album':
$thisfile_asf_comments['album'] = array($this->TrimTerm($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value']));
break;
case 'wm/genre':
case 'genre':
$thisfile_asf_comments['genre'] = array($this->TrimTerm($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value']));
break;
case 'wm/partofset':
$thisfile_asf_comments['partofset'] = array($this->TrimTerm($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value']));
break;
case 'wm/tracknumber':
case 'tracknumber':
// be careful casting to int: casting unicode strings to int gives unexpected results (stops parsing at first non-numeric character)
$thisfile_asf_comments['track'] = array($this->TrimTerm($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value']));
foreach ($thisfile_asf_comments['track'] as $key => $value) {
if (preg_match('/^[0-9\x00]+$/', $value)) {
$thisfile_asf_comments['track'][$key] = intval(str_replace("\x00", '', $value));
}
}
break;
case 'wm/track':
if (empty($thisfile_asf_comments['track'])) {
$thisfile_asf_comments['track'] = array(1 + $this->TrimConvert($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value']));
}
break;
case 'wm/year':
case 'year':
case 'date':
$thisfile_asf_comments['year'] = array( $this->TrimTerm($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value']));
break;
case 'wm/lyrics':
case 'lyrics':
$thisfile_asf_comments['lyrics'] = array($this->TrimTerm($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value']));
break;
case 'isvbr':
if ($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value']) {
$thisfile_audio['bitrate_mode'] = 'vbr';
$thisfile_video['bitrate_mode'] = 'vbr';
}
break;
case 'id3':
// id3v2 module might not be loaded
if (class_exists('getid3_id3v2')) {
$tempfile = tempnam(GETID3_TEMP_DIR, 'getID3');
$tempfilehandle = fopen($tempfile, 'wb');
$tempThisfileInfo = array('encoding'=>$info['encoding']);
fwrite($tempfilehandle, $thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value']);
fclose($tempfilehandle);
$getid3_temp = new getID3();
$getid3_temp->openfile($tempfile);
$getid3_id3v2 = new getid3_id3v2($getid3_temp);
$getid3_id3v2->Analyze();
$info['id3v2'] = $getid3_temp->info['id3v2'];
unset($getid3_temp, $getid3_id3v2);
unlink($tempfile);
}
break;
case 'wm/encodingtime':
$thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['encoding_time_unix'] = $this->FILETIMEtoUNIXtime($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value']);
$thisfile_asf_comments['encoding_time_unix'] = array($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['encoding_time_unix']);
break;
case 'wm/picture':
$WMpicture = $this->ASF_WMpicture($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value']);
foreach ($WMpicture as $key => $value) {
$thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current[$key] = $value;
}
unset($WMpicture);
/*
$wm_picture_offset = 0;
$thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['image_type_id'] = getid3_lib::LittleEndian2Int(substr($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value'], $wm_picture_offset, 1));
$wm_picture_offset += 1;
$thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['image_type'] = $this->WMpictureTypeLookup($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['image_type_id']);
$thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['image_size'] = getid3_lib::LittleEndian2Int(substr($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value'], $wm_picture_offset, 4));
$wm_picture_offset += 4;
$thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['image_mime'] = '';
do {
$next_byte_pair = substr($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value'], $wm_picture_offset, 2);
$wm_picture_offset += 2;
$thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['image_mime'] .= $next_byte_pair;
} while ($next_byte_pair !== "\x00\x00");
$thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['image_description'] = '';
do {
$next_byte_pair = substr($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value'], $wm_picture_offset, 2);
$wm_picture_offset += 2;
$thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['image_description'] .= $next_byte_pair;
} while ($next_byte_pair !== "\x00\x00");
$thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['dataoffset'] = $wm_picture_offset;
$thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['data'] = substr($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value'], $wm_picture_offset);
unset($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value']);
$imageinfo = array();
$thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['image_mime'] = '';
$imagechunkcheck = getid3_lib::GetDataImageSize($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['data'], $imageinfo);
unset($imageinfo);
if (!empty($imagechunkcheck)) {
$thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['image_mime'] = image_type_to_mime_type($imagechunkcheck[2]);
}
if (!isset($thisfile_asf_comments['picture'])) {
$thisfile_asf_comments['picture'] = array();
}
$thisfile_asf_comments['picture'][] = array('data'=>$thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['data'], 'image_mime'=>$thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['image_mime']);
*/
break;
default:
switch ($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value_type']) {
case 0: // Unicode string
if (substr($this->TrimConvert($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['name']), 0, 3) == 'WM/') {
$thisfile_asf_comments[str_replace('wm/', '', strtolower($this->TrimConvert($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['name'])))] = array($this->TrimTerm($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value']));
}
break;
case 1:
break;
}
break;
}
}
break;
case GETID3_ASF_Stream_Bitrate_Properties_Object:
// Stream Bitrate Properties Object: (optional, one only)
// Field Name Field Type Size (bits)
// Object ID GUID 128 // GUID for Stream Bitrate Properties object - GETID3_ASF_Stream_Bitrate_Properties_Object
// Object Size QWORD 64 // size of Extended Content Description object, including 26 bytes of Stream Bitrate Properties Object header
// Bitrate Records Count WORD 16 // number of records in Bitrate Records
// Bitrate Records array of: variable //
// * Flags WORD 16 //
// * * Stream Number bits 7 (0x007F) // number of this stream
// * * Reserved bits 9 (0xFF80) // hardcoded: 0
// * Average Bitrate DWORD 32 // in bits per second
// shortcut
$thisfile_asf['stream_bitrate_properties_object'] = array();
$thisfile_asf_streambitratepropertiesobject = &$thisfile_asf['stream_bitrate_properties_object'];
$thisfile_asf_streambitratepropertiesobject['offset'] = $NextObjectOffset + $offset;
$thisfile_asf_streambitratepropertiesobject['objectid'] = $NextObjectGUID;
$thisfile_asf_streambitratepropertiesobject['objectid_guid'] = $NextObjectGUIDtext;
$thisfile_asf_streambitratepropertiesobject['objectsize'] = $NextObjectSize;
$thisfile_asf_streambitratepropertiesobject['bitrate_records_count'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
$offset += 2;
for ($BitrateRecordsCounter = 0; $BitrateRecordsCounter < $thisfile_asf_streambitratepropertiesobject['bitrate_records_count']; $BitrateRecordsCounter++) {
$thisfile_asf_streambitratepropertiesobject['bitrate_records'][$BitrateRecordsCounter]['flags_raw'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
$offset += 2;
$thisfile_asf_streambitratepropertiesobject['bitrate_records'][$BitrateRecordsCounter]['flags']['stream_number'] = $thisfile_asf_streambitratepropertiesobject['bitrate_records'][$BitrateRecordsCounter]['flags_raw'] & 0x007F;
$thisfile_asf_streambitratepropertiesobject['bitrate_records'][$BitrateRecordsCounter]['bitrate'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 4));
$offset += 4;
}
break;
case GETID3_ASF_Padding_Object:
// Padding Object: (optional)
// Field Name Field Type Size (bits)
// Object ID GUID 128 // GUID for Padding object - GETID3_ASF_Padding_Object
// Object Size QWORD 64 // size of Padding object, including 24 bytes of ASF Padding Object header
// Padding Data BYTESTREAM variable // ignore
// shortcut
$thisfile_asf['padding_object'] = array();
$thisfile_asf_paddingobject = &$thisfile_asf['padding_object'];
$thisfile_asf_paddingobject['offset'] = $NextObjectOffset + $offset;
$thisfile_asf_paddingobject['objectid'] = $NextObjectGUID;
$thisfile_asf_paddingobject['objectid_guid'] = $NextObjectGUIDtext;
$thisfile_asf_paddingobject['objectsize'] = $NextObjectSize;
$thisfile_asf_paddingobject['padding_length'] = $thisfile_asf_paddingobject['objectsize'] - 16 - 8;
$thisfile_asf_paddingobject['padding'] = substr($ASFHeaderData, $offset, $thisfile_asf_paddingobject['padding_length']);
$offset += ($NextObjectSize - 16 - 8);
break;
case GETID3_ASF_Extended_Content_Encryption_Object:
case GETID3_ASF_Content_Encryption_Object:
// WMA DRM - just ignore
$offset += ($NextObjectSize - 16 - 8);
break;
default:
// Implementations shall ignore any standard or non-standard object that they do not know how to handle.
if ($this->GUIDname($NextObjectGUIDtext)) {
$info['warning'][] = 'unhandled GUID "'.$this->GUIDname($NextObjectGUIDtext).'" {'.$NextObjectGUIDtext.'} in ASF header at offset '.($offset - 16 - 8);
} else {
$info['warning'][] = 'unknown GUID {'.$NextObjectGUIDtext.'} in ASF header at offset '.($offset - 16 - 8);
}
$offset += ($NextObjectSize - 16 - 8);
break;
}
}
if (isset($thisfile_asf_streambitrateproperties['bitrate_records_count'])) {
$ASFbitrateAudio = 0;
$ASFbitrateVideo = 0;
for ($BitrateRecordsCounter = 0; $BitrateRecordsCounter < $thisfile_asf_streambitrateproperties['bitrate_records_count']; $BitrateRecordsCounter++) {
if (isset($thisfile_asf_codeclistobject['codec_entries'][$BitrateRecordsCounter])) {
switch ($thisfile_asf_codeclistobject['codec_entries'][$BitrateRecordsCounter]['type_raw']) {
case 1:
$ASFbitrateVideo += $thisfile_asf_streambitrateproperties['bitrate_records'][$BitrateRecordsCounter]['bitrate'];
break;
case 2:
$ASFbitrateAudio += $thisfile_asf_streambitrateproperties['bitrate_records'][$BitrateRecordsCounter]['bitrate'];
break;
default:
// do nothing
break;
}
}
}
if ($ASFbitrateAudio > 0) {
$thisfile_audio['bitrate'] = $ASFbitrateAudio;
}
if ($ASFbitrateVideo > 0) {
$thisfile_video['bitrate'] = $ASFbitrateVideo;
}
}
if (isset($thisfile_asf['stream_properties_object']) && is_array($thisfile_asf['stream_properties_object'])) {
$thisfile_audio['bitrate'] = 0;
$thisfile_video['bitrate'] = 0;
foreach ($thisfile_asf['stream_properties_object'] as $streamnumber => $streamdata) {
switch ($streamdata['stream_type']) {
case GETID3_ASF_Audio_Media:
// Field Name Field Type Size (bits)
// Codec ID / Format Tag WORD 16 // unique ID of audio codec - defined as wFormatTag field of WAVEFORMATEX structure
// Number of Channels WORD 16 // number of channels of audio - defined as nChannels field of WAVEFORMATEX structure
// Samples Per Second DWORD 32 // in Hertz - defined as nSamplesPerSec field of WAVEFORMATEX structure
// Average number of Bytes/sec DWORD 32 // bytes/sec of audio stream - defined as nAvgBytesPerSec field of WAVEFORMATEX structure
// Block Alignment WORD 16 // block size in bytes of audio codec - defined as nBlockAlign field of WAVEFORMATEX structure
// Bits per sample WORD 16 // bits per sample of mono data. set to zero for variable bitrate codecs. defined as wBitsPerSample field of WAVEFORMATEX structure
// Codec Specific Data Size WORD 16 // size in bytes of Codec Specific Data buffer - defined as cbSize field of WAVEFORMATEX structure
// Codec Specific Data BYTESTREAM variable // array of codec-specific data bytes
// shortcut
$thisfile_asf['audio_media'][$streamnumber] = array();
$thisfile_asf_audiomedia_currentstream = &$thisfile_asf['audio_media'][$streamnumber];
$audiomediaoffset = 0;
$thisfile_asf_audiomedia_currentstream = getid3_riff::parseWAVEFORMATex(substr($streamdata['type_specific_data'], $audiomediaoffset, 16));
$audiomediaoffset += 16;
$thisfile_audio['lossless'] = false;
switch ($thisfile_asf_audiomedia_currentstream['raw']['wFormatTag']) {
case 0x0001: // PCM
case 0x0163: // WMA9 Lossless
$thisfile_audio['lossless'] = true;
break;
}
if (!empty($thisfile_asf['stream_bitrate_properties_object']['bitrate_records'])) {
foreach ($thisfile_asf['stream_bitrate_properties_object']['bitrate_records'] as $dummy => $dataarray) {
if (isset($dataarray['flags']['stream_number']) && ($dataarray['flags']['stream_number'] == $streamnumber)) {
$thisfile_asf_audiomedia_currentstream['bitrate'] = $dataarray['bitrate'];
$thisfile_audio['bitrate'] += $dataarray['bitrate'];
break;
}
}
} else {
if (!empty($thisfile_asf_audiomedia_currentstream['bytes_sec'])) {
$thisfile_audio['bitrate'] += $thisfile_asf_audiomedia_currentstream['bytes_sec'] * 8;
} elseif (!empty($thisfile_asf_audiomedia_currentstream['bitrate'])) {
$thisfile_audio['bitrate'] += $thisfile_asf_audiomedia_currentstream['bitrate'];
}
}
$thisfile_audio['streams'][$streamnumber] = $thisfile_asf_audiomedia_currentstream;
$thisfile_audio['streams'][$streamnumber]['wformattag'] = $thisfile_asf_audiomedia_currentstream['raw']['wFormatTag'];
$thisfile_audio['streams'][$streamnumber]['lossless'] = $thisfile_audio['lossless'];
$thisfile_audio['streams'][$streamnumber]['bitrate'] = $thisfile_audio['bitrate'];
$thisfile_audio['streams'][$streamnumber]['dataformat'] = 'wma';
unset($thisfile_audio['streams'][$streamnumber]['raw']);
$thisfile_asf_audiomedia_currentstream['codec_data_size'] = getid3_lib::LittleEndian2Int(substr($streamdata['type_specific_data'], $audiomediaoffset, 2));
$audiomediaoffset += 2;
$thisfile_asf_audiomedia_currentstream['codec_data'] = substr($streamdata['type_specific_data'], $audiomediaoffset, $thisfile_asf_audiomedia_currentstream['codec_data_size']);
$audiomediaoffset += $thisfile_asf_audiomedia_currentstream['codec_data_size'];
break;
case GETID3_ASF_Video_Media:
// Field Name Field Type Size (bits)
// Encoded Image Width DWORD 32 // width of image in pixels
// Encoded Image Height DWORD 32 // height of image in pixels
// Reserved Flags BYTE 8 // hardcoded: 0x02
// Format Data Size WORD 16 // size of Format Data field in bytes
// Format Data array of: variable //
// * Format Data Size DWORD 32 // number of bytes in Format Data field, in bytes - defined as biSize field of BITMAPINFOHEADER structure
// * Image Width LONG 32 // width of encoded image in pixels - defined as biWidth field of BITMAPINFOHEADER structure
// * Image Height LONG 32 // height of encoded image in pixels - defined as biHeight field of BITMAPINFOHEADER structure
// * Reserved WORD 16 // hardcoded: 0x0001 - defined as biPlanes field of BITMAPINFOHEADER structure
// * Bits Per Pixel Count WORD 16 // bits per pixel - defined as biBitCount field of BITMAPINFOHEADER structure
// * Compression ID FOURCC 32 // fourcc of video codec - defined as biCompression field of BITMAPINFOHEADER structure
// * Image Size DWORD 32 // image size in bytes - defined as biSizeImage field of BITMAPINFOHEADER structure
// * Horizontal Pixels / Meter DWORD 32 // horizontal resolution of target device in pixels per meter - defined as biXPelsPerMeter field of BITMAPINFOHEADER structure
// * Vertical Pixels / Meter DWORD 32 // vertical resolution of target device in pixels per meter - defined as biYPelsPerMeter field of BITMAPINFOHEADER structure
// * Colors Used Count DWORD 32 // number of color indexes in the color table that are actually used - defined as biClrUsed field of BITMAPINFOHEADER structure
// * Important Colors Count DWORD 32 // number of color index required for displaying bitmap. if zero, all colors are required. defined as biClrImportant field of BITMAPINFOHEADER structure
// * Codec Specific Data BYTESTREAM variable // array of codec-specific data bytes
// shortcut
$thisfile_asf['video_media'][$streamnumber] = array();
$thisfile_asf_videomedia_currentstream = &$thisfile_asf['video_media'][$streamnumber];
$videomediaoffset = 0;
$thisfile_asf_videomedia_currentstream['image_width'] = getid3_lib::LittleEndian2Int(substr($streamdata['type_specific_data'], $videomediaoffset, 4));
$videomediaoffset += 4;
$thisfile_asf_videomedia_currentstream['image_height'] = getid3_lib::LittleEndian2Int(substr($streamdata['type_specific_data'], $videomediaoffset, 4));
$videomediaoffset += 4;
$thisfile_asf_videomedia_currentstream['flags'] = getid3_lib::LittleEndian2Int(substr($streamdata['type_specific_data'], $videomediaoffset, 1));
$videomediaoffset += 1;
$thisfile_asf_videomedia_currentstream['format_data_size'] = getid3_lib::LittleEndian2Int(substr($streamdata['type_specific_data'], $videomediaoffset, 2));
$videomediaoffset += 2;
$thisfile_asf_videomedia_currentstream['format_data']['format_data_size'] = getid3_lib::LittleEndian2Int(substr($streamdata['type_specific_data'], $videomediaoffset, 4));
$videomediaoffset += 4;
$thisfile_asf_videomedia_currentstream['format_data']['image_width'] = getid3_lib::LittleEndian2Int(substr($streamdata['type_specific_data'], $videomediaoffset, 4));
$videomediaoffset += 4;
$thisfile_asf_videomedia_currentstream['format_data']['image_height'] = getid3_lib::LittleEndian2Int(substr($streamdata['type_specific_data'], $videomediaoffset, 4));
$videomediaoffset += 4;
$thisfile_asf_videomedia_currentstream['format_data']['reserved'] = getid3_lib::LittleEndian2Int(substr($streamdata['type_specific_data'], $videomediaoffset, 2));
$videomediaoffset += 2;
$thisfile_asf_videomedia_currentstream['format_data']['bits_per_pixel'] = getid3_lib::LittleEndian2Int(substr($streamdata['type_specific_data'], $videomediaoffset, 2));
$videomediaoffset += 2;
$thisfile_asf_videomedia_currentstream['format_data']['codec_fourcc'] = substr($streamdata['type_specific_data'], $videomediaoffset, 4);
$videomediaoffset += 4;
$thisfile_asf_videomedia_currentstream['format_data']['image_size'] = getid3_lib::LittleEndian2Int(substr($streamdata['type_specific_data'], $videomediaoffset, 4));
$videomediaoffset += 4;
$thisfile_asf_videomedia_currentstream['format_data']['horizontal_pels'] = getid3_lib::LittleEndian2Int(substr($streamdata['type_specific_data'], $videomediaoffset, 4));
$videomediaoffset += 4;
$thisfile_asf_videomedia_currentstream['format_data']['vertical_pels'] = getid3_lib::LittleEndian2Int(substr($streamdata['type_specific_data'], $videomediaoffset, 4));
$videomediaoffset += 4;
$thisfile_asf_videomedia_currentstream['format_data']['colors_used'] = getid3_lib::LittleEndian2Int(substr($streamdata['type_specific_data'], $videomediaoffset, 4));
$videomediaoffset += 4;
$thisfile_asf_videomedia_currentstream['format_data']['colors_important'] = getid3_lib::LittleEndian2Int(substr($streamdata['type_specific_data'], $videomediaoffset, 4));
$videomediaoffset += 4;
$thisfile_asf_videomedia_currentstream['format_data']['codec_data'] = substr($streamdata['type_specific_data'], $videomediaoffset);
if (!empty($thisfile_asf['stream_bitrate_properties_object']['bitrate_records'])) {
foreach ($thisfile_asf['stream_bitrate_properties_object']['bitrate_records'] as $dummy => $dataarray) {
if (isset($dataarray['flags']['stream_number']) && ($dataarray['flags']['stream_number'] == $streamnumber)) {
$thisfile_asf_videomedia_currentstream['bitrate'] = $dataarray['bitrate'];
$thisfile_video['streams'][$streamnumber]['bitrate'] = $dataarray['bitrate'];
$thisfile_video['bitrate'] += $dataarray['bitrate'];
break;
}
}
}
$thisfile_asf_videomedia_currentstream['format_data']['codec'] = getid3_riff::fourccLookup($thisfile_asf_videomedia_currentstream['format_data']['codec_fourcc']);
$thisfile_video['streams'][$streamnumber]['fourcc'] = $thisfile_asf_videomedia_currentstream['format_data']['codec_fourcc'];
$thisfile_video['streams'][$streamnumber]['codec'] = $thisfile_asf_videomedia_currentstream['format_data']['codec'];
$thisfile_video['streams'][$streamnumber]['resolution_x'] = $thisfile_asf_videomedia_currentstream['image_width'];
$thisfile_video['streams'][$streamnumber]['resolution_y'] = $thisfile_asf_videomedia_currentstream['image_height'];
$thisfile_video['streams'][$streamnumber]['bits_per_sample'] = $thisfile_asf_videomedia_currentstream['format_data']['bits_per_pixel'];
break;
default:
break;
}
}
}
while (ftell($this->getid3->fp) < $info['avdataend']) {
$NextObjectDataHeader = fread($this->getid3->fp, 24);
$offset = 0;
$NextObjectGUID = substr($NextObjectDataHeader, 0, 16);
$offset += 16;
$NextObjectGUIDtext = $this->BytestringToGUID($NextObjectGUID);
$NextObjectSize = getid3_lib::LittleEndian2Int(substr($NextObjectDataHeader, $offset, 8));
$offset += 8;
switch ($NextObjectGUID) {
case GETID3_ASF_Data_Object:
// Data Object: (mandatory, one only)
// Field Name Field Type Size (bits)
// Object ID GUID 128 // GUID for Data object - GETID3_ASF_Data_Object
// Object Size QWORD 64 // size of Data object, including 50 bytes of Data Object header. may be 0 if FilePropertiesObject.BroadcastFlag == 1
// File ID GUID 128 // unique identifier. identical to File ID field in Header Object
// Total Data Packets QWORD 64 // number of Data Packet entries in Data Object. invalid if FilePropertiesObject.BroadcastFlag == 1
// Reserved WORD 16 // hardcoded: 0x0101
// shortcut
$thisfile_asf['data_object'] = array();
$thisfile_asf_dataobject = &$thisfile_asf['data_object'];
$DataObjectData = $NextObjectDataHeader.fread($this->getid3->fp, 50 - 24);
$offset = 24;
$thisfile_asf_dataobject['objectid'] = $NextObjectGUID;
$thisfile_asf_dataobject['objectid_guid'] = $NextObjectGUIDtext;
$thisfile_asf_dataobject['objectsize'] = $NextObjectSize;
$thisfile_asf_dataobject['fileid'] = substr($DataObjectData, $offset, 16);
$offset += 16;
$thisfile_asf_dataobject['fileid_guid'] = $this->BytestringToGUID($thisfile_asf_dataobject['fileid']);
$thisfile_asf_dataobject['total_data_packets'] = getid3_lib::LittleEndian2Int(substr($DataObjectData, $offset, 8));
$offset += 8;
$thisfile_asf_dataobject['reserved'] = getid3_lib::LittleEndian2Int(substr($DataObjectData, $offset, 2));
$offset += 2;
if ($thisfile_asf_dataobject['reserved'] != 0x0101) {
$info['warning'][] = 'data_object.reserved ('.getid3_lib::PrintHexBytes($thisfile_asf_dataobject['reserved']).') does not match expected value of "0x0101"';
//return false;
break;
}
// Data Packets array of: variable //
// * Error Correction Flags BYTE 8 //
// * * Error Correction Data Length bits 4 // if Error Correction Length Type == 00, size of Error Correction Data in bytes, else hardcoded: 0000
// * * Opaque Data Present bits 1 //
// * * Error Correction Length Type bits 2 // number of bits for size of the error correction data. hardcoded: 00
// * * Error Correction Present bits 1 // If set, use Opaque Data Packet structure, else use Payload structure
// * Error Correction Data
$info['avdataoffset'] = ftell($this->getid3->fp);
fseek($this->getid3->fp, ($thisfile_asf_dataobject['objectsize'] - 50), SEEK_CUR); // skip actual audio/video data
$info['avdataend'] = ftell($this->getid3->fp);
break;
case GETID3_ASF_Simple_Index_Object:
// Simple Index Object: (optional, recommended, one per video stream)
// Field Name Field Type Size (bits)
// Object ID GUID 128 // GUID for Simple Index object - GETID3_ASF_Data_Object
// Object Size QWORD 64 // size of Simple Index object, including 56 bytes of Simple Index Object header
// File ID GUID 128 // unique identifier. may be zero or identical to File ID field in Data Object and Header Object
// Index Entry Time Interval QWORD 64 // interval between index entries in 100-nanosecond units
// Maximum Packet Count DWORD 32 // maximum packet count for all index entries
// Index Entries Count DWORD 32 // number of Index Entries structures
// Index Entries array of: variable //
// * Packet Number DWORD 32 // number of the Data Packet associated with this index entry
// * Packet Count WORD 16 // number of Data Packets to sent at this index entry
// shortcut
$thisfile_asf['simple_index_object'] = array();
$thisfile_asf_simpleindexobject = &$thisfile_asf['simple_index_object'];
$SimpleIndexObjectData = $NextObjectDataHeader.fread($this->getid3->fp, 56 - 24);
$offset = 24;
$thisfile_asf_simpleindexobject['objectid'] = $NextObjectGUID;
$thisfile_asf_simpleindexobject['objectid_guid'] = $NextObjectGUIDtext;
$thisfile_asf_simpleindexobject['objectsize'] = $NextObjectSize;
$thisfile_asf_simpleindexobject['fileid'] = substr($SimpleIndexObjectData, $offset, 16);
$offset += 16;
$thisfile_asf_simpleindexobject['fileid_guid'] = $this->BytestringToGUID($thisfile_asf_simpleindexobject['fileid']);
$thisfile_asf_simpleindexobject['index_entry_time_interval'] = getid3_lib::LittleEndian2Int(substr($SimpleIndexObjectData, $offset, 8));
$offset += 8;
$thisfile_asf_simpleindexobject['maximum_packet_count'] = getid3_lib::LittleEndian2Int(substr($SimpleIndexObjectData, $offset, 4));
$offset += 4;
$thisfile_asf_simpleindexobject['index_entries_count'] = getid3_lib::LittleEndian2Int(substr($SimpleIndexObjectData, $offset, 4));
$offset += 4;
$IndexEntriesData = $SimpleIndexObjectData.fread($this->getid3->fp, 6 * $thisfile_asf_simpleindexobject['index_entries_count']);
for ($IndexEntriesCounter = 0; $IndexEntriesCounter < $thisfile_asf_simpleindexobject['index_entries_count']; $IndexEntriesCounter++) {
$thisfile_asf_simpleindexobject['index_entries'][$IndexEntriesCounter]['packet_number'] = getid3_lib::LittleEndian2Int(substr($IndexEntriesData, $offset, 4));
$offset += 4;
$thisfile_asf_simpleindexobject['index_entries'][$IndexEntriesCounter]['packet_count'] = getid3_lib::LittleEndian2Int(substr($IndexEntriesData, $offset, 4));
$offset += 2;
}
break;
case GETID3_ASF_Index_Object:
// 6.2 ASF top-level Index Object (optional but recommended when appropriate, 0 or 1)
// Field Name Field Type Size (bits)
// Object ID GUID 128 // GUID for the Index Object - GETID3_ASF_Index_Object
// Object Size QWORD 64 // Specifies the size, in bytes, of the Index Object, including at least 34 bytes of Index Object header
// Index Entry Time Interval DWORD 32 // Specifies the time interval between each index entry in ms.
// Index Specifiers Count WORD 16 // Specifies the number of Index Specifiers structures in this Index Object.
// Index Blocks Count DWORD 32 // Specifies the number of Index Blocks structures in this Index Object.
// Index Entry Time Interval DWORD 32 // Specifies the time interval between index entries in milliseconds. This value cannot be 0.
// Index Specifiers Count WORD 16 // Specifies the number of entries in the Index Specifiers list. Valid values are 1 and greater.
// Index Specifiers array of: varies //
// * Stream Number WORD 16 // Specifies the stream number that the Index Specifiers refer to. Valid values are between 1 and 127.
// * Index Type WORD 16 // Specifies Index Type values as follows:
// 1 = Nearest Past Data Packet - indexes point to the data packet whose presentation time is closest to the index entry time.
// 2 = Nearest Past Media Object - indexes point to the closest data packet containing an entire object or first fragment of an object.
// 3 = Nearest Past Cleanpoint. - indexes point to the closest data packet containing an entire object (or first fragment of an object) that has the Cleanpoint Flag set.
// Nearest Past Cleanpoint is the most common type of index.
// Index Entry Count DWORD 32 // Specifies the number of Index Entries in the block.
// * Block Positions QWORD varies // Specifies a list of byte offsets of the beginnings of the blocks relative to the beginning of the first Data Packet (i.e., the beginning of the Data Object + 50 bytes). The number of entries in this list is specified by the value of the Index Specifiers Count field. The order of those byte offsets is tied to the order in which Index Specifiers are listed.
// * Index Entries array of: varies //
// * * Offsets DWORD varies // An offset value of 0xffffffff indicates an invalid offset value
// shortcut
$thisfile_asf['asf_index_object'] = array();
$thisfile_asf_asfindexobject = &$thisfile_asf['asf_index_object'];
$ASFIndexObjectData = $NextObjectDataHeader.fread($this->getid3->fp, 34 - 24);
$offset = 24;
$thisfile_asf_asfindexobject['objectid'] = $NextObjectGUID;
$thisfile_asf_asfindexobject['objectid_guid'] = $NextObjectGUIDtext;
$thisfile_asf_asfindexobject['objectsize'] = $NextObjectSize;
$thisfile_asf_asfindexobject['entry_time_interval'] = getid3_lib::LittleEndian2Int(substr($ASFIndexObjectData, $offset, 4));
$offset += 4;
$thisfile_asf_asfindexobject['index_specifiers_count'] = getid3_lib::LittleEndian2Int(substr($ASFIndexObjectData, $offset, 2));
$offset += 2;
$thisfile_asf_asfindexobject['index_blocks_count'] = getid3_lib::LittleEndian2Int(substr($ASFIndexObjectData, $offset, 4));
$offset += 4;
$ASFIndexObjectData .= fread($this->getid3->fp, 4 * $thisfile_asf_asfindexobject['index_specifiers_count']);
for ($IndexSpecifiersCounter = 0; $IndexSpecifiersCounter < $thisfile_asf_asfindexobject['index_specifiers_count']; $IndexSpecifiersCounter++) {
$IndexSpecifierStreamNumber = getid3_lib::LittleEndian2Int(substr($ASFIndexObjectData, $offset, 2));
$offset += 2;
$thisfile_asf_asfindexobject['index_specifiers'][$IndexSpecifiersCounter]['stream_number'] = $IndexSpecifierStreamNumber;
$thisfile_asf_asfindexobject['index_specifiers'][$IndexSpecifiersCounter]['index_type'] = getid3_lib::LittleEndian2Int(substr($ASFIndexObjectData, $offset, 2));
$offset += 2;
$thisfile_asf_asfindexobject['index_specifiers'][$IndexSpecifiersCounter]['index_type_text'] = $this->ASFIndexObjectIndexTypeLookup($thisfile_asf_asfindexobject['index_specifiers'][$IndexSpecifiersCounter]['index_type']);
}
$ASFIndexObjectData .= fread($this->getid3->fp, 4);
$thisfile_asf_asfindexobject['index_entry_count'] = getid3_lib::LittleEndian2Int(substr($ASFIndexObjectData, $offset, 4));
$offset += 4;
$ASFIndexObjectData .= fread($this->getid3->fp, 8 * $thisfile_asf_asfindexobject['index_specifiers_count']);
for ($IndexSpecifiersCounter = 0; $IndexSpecifiersCounter < $thisfile_asf_asfindexobject['index_specifiers_count']; $IndexSpecifiersCounter++) {
$thisfile_asf_asfindexobject['block_positions'][$IndexSpecifiersCounter] = getid3_lib::LittleEndian2Int(substr($ASFIndexObjectData, $offset, 8));
$offset += 8;
}
$ASFIndexObjectData .= fread($this->getid3->fp, 4 * $thisfile_asf_asfindexobject['index_specifiers_count'] * $thisfile_asf_asfindexobject['index_entry_count']);
for ($IndexEntryCounter = 0; $IndexEntryCounter < $thisfile_asf_asfindexobject['index_entry_count']; $IndexEntryCounter++) {
for ($IndexSpecifiersCounter = 0; $IndexSpecifiersCounter < $thisfile_asf_asfindexobject['index_specifiers_count']; $IndexSpecifiersCounter++) {
$thisfile_asf_asfindexobject['offsets'][$IndexSpecifiersCounter][$IndexEntryCounter] = getid3_lib::LittleEndian2Int(substr($ASFIndexObjectData, $offset, 4));
$offset += 4;
}
}
break;
default:
// Implementations shall ignore any standard or non-standard object that they do not know how to handle.
if ($this->GUIDname($NextObjectGUIDtext)) {
$info['warning'][] = 'unhandled GUID "'.$this->GUIDname($NextObjectGUIDtext).'" {'.$NextObjectGUIDtext.'} in ASF body at offset '.($offset - 16 - 8);
} else {
$info['warning'][] = 'unknown GUID {'.$NextObjectGUIDtext.'} in ASF body at offset '.(ftell($this->getid3->fp) - 16 - 8);
}
fseek($this->getid3->fp, ($NextObjectSize - 16 - 8), SEEK_CUR);
break;
}
}
if (isset($thisfile_asf_codeclistobject['codec_entries']) && is_array($thisfile_asf_codeclistobject['codec_entries'])) {
foreach ($thisfile_asf_codeclistobject['codec_entries'] as $streamnumber => $streamdata) {
switch ($streamdata['information']) {
case 'WMV1':
case 'WMV2':
case 'WMV3':
case 'MSS1':
case 'MSS2':
case 'WMVA':
case 'WVC1':
case 'WMVP':
case 'WVP2':
$thisfile_video['dataformat'] = 'wmv';
$info['mime_type'] = 'video/x-ms-wmv';
break;
case 'MP42':
case 'MP43':
case 'MP4S':
case 'mp4s':
$thisfile_video['dataformat'] = 'asf';
$info['mime_type'] = 'video/x-ms-asf';
break;
default:
switch ($streamdata['type_raw']) {
case 1:
if (strstr($this->TrimConvert($streamdata['name']), 'Windows Media')) {
$thisfile_video['dataformat'] = 'wmv';
if ($info['mime_type'] == 'video/x-ms-asf') {
$info['mime_type'] = 'video/x-ms-wmv';
}
}
break;
case 2:
if (strstr($this->TrimConvert($streamdata['name']), 'Windows Media')) {
$thisfile_audio['dataformat'] = 'wma';
if ($info['mime_type'] == 'video/x-ms-asf') {
$info['mime_type'] = 'audio/x-ms-wma';
}
}
break;
}
break;
}
}
}
switch (isset($thisfile_audio['codec']) ? $thisfile_audio['codec'] : '') {
case 'MPEG Layer-3':
$thisfile_audio['dataformat'] = 'mp3';
break;
default:
break;
}
if (isset($thisfile_asf_codeclistobject['codec_entries'])) {
foreach ($thisfile_asf_codeclistobject['codec_entries'] as $streamnumber => $streamdata) {
switch ($streamdata['type_raw']) {
case 1: // video
$thisfile_video['encoder'] = $this->TrimConvert($thisfile_asf_codeclistobject['codec_entries'][$streamnumber]['name']);
break;
case 2: // audio
$thisfile_audio['encoder'] = $this->TrimConvert($thisfile_asf_codeclistobject['codec_entries'][$streamnumber]['name']);
// AH 2003-10-01
$thisfile_audio['encoder_options'] = $this->TrimConvert($thisfile_asf_codeclistobject['codec_entries'][0]['description']);
$thisfile_audio['codec'] = $thisfile_audio['encoder'];
break;
default:
$info['warning'][] = 'Unknown streamtype: [codec_list_object][codec_entries]['.$streamnumber.'][type_raw] == '.$streamdata['type_raw'];
break;
}
}
}
if (isset($info['audio'])) {
$thisfile_audio['lossless'] = (isset($thisfile_audio['lossless']) ? $thisfile_audio['lossless'] : false);
$thisfile_audio['dataformat'] = (!empty($thisfile_audio['dataformat']) ? $thisfile_audio['dataformat'] : 'asf');
}
if (!empty($thisfile_video['dataformat'])) {
$thisfile_video['lossless'] = (isset($thisfile_audio['lossless']) ? $thisfile_audio['lossless'] : false);
$thisfile_video['pixel_aspect_ratio'] = (isset($thisfile_audio['pixel_aspect_ratio']) ? $thisfile_audio['pixel_aspect_ratio'] : (float) 1);
$thisfile_video['dataformat'] = (!empty($thisfile_video['dataformat']) ? $thisfile_video['dataformat'] : 'asf');
}
if (!empty($thisfile_video['streams'])) {
$thisfile_video['streams']['resolution_x'] = 0;
$thisfile_video['streams']['resolution_y'] = 0;
foreach ($thisfile_video['streams'] as $key => $valuearray) {
if (($valuearray['resolution_x'] > $thisfile_video['streams']['resolution_x']) || ($valuearray['resolution_y'] > $thisfile_video['streams']['resolution_y'])) {
$thisfile_video['resolution_x'] = $valuearray['resolution_x'];
$thisfile_video['resolution_y'] = $valuearray['resolution_y'];
}
}
}
$info['bitrate'] = (isset($thisfile_audio['bitrate']) ? $thisfile_audio['bitrate'] : 0) + (isset($thisfile_video['bitrate']) ? $thisfile_video['bitrate'] : 0);
if ((!isset($info['playtime_seconds']) || ($info['playtime_seconds'] <= 0)) && ($info['bitrate'] > 0)) {
$info['playtime_seconds'] = ($info['filesize'] - $info['avdataoffset']) / ($info['bitrate'] / 8);
}
return true;
}
public static function ASFCodecListObjectTypeLookup($CodecListType) {
static $ASFCodecListObjectTypeLookup = array();
if (empty($ASFCodecListObjectTypeLookup)) {
$ASFCodecListObjectTypeLookup[0x0001] = 'Video Codec';
$ASFCodecListObjectTypeLookup[0x0002] = 'Audio Codec';
$ASFCodecListObjectTypeLookup[0xFFFF] = 'Unknown Codec';
}
return (isset($ASFCodecListObjectTypeLookup[$CodecListType]) ? $ASFCodecListObjectTypeLookup[$CodecListType] : 'Invalid Codec Type');
}
public static function KnownGUIDs() {
static $GUIDarray = array(
'GETID3_ASF_Extended_Stream_Properties_Object' => '14E6A5CB-C672-4332-8399-A96952065B5A',
'GETID3_ASF_Padding_Object' => '1806D474-CADF-4509-A4BA-9AABCB96AAE8',
'GETID3_ASF_Payload_Ext_Syst_Pixel_Aspect_Ratio' => '1B1EE554-F9EA-4BC8-821A-376B74E4C4B8',
'GETID3_ASF_Script_Command_Object' => '1EFB1A30-0B62-11D0-A39B-00A0C90348F6',
'GETID3_ASF_No_Error_Correction' => '20FB5700-5B55-11CF-A8FD-00805F5C442B',
'GETID3_ASF_Content_Branding_Object' => '2211B3FA-BD23-11D2-B4B7-00A0C955FC6E',
'GETID3_ASF_Content_Encryption_Object' => '2211B3FB-BD23-11D2-B4B7-00A0C955FC6E',
'GETID3_ASF_Digital_Signature_Object' => '2211B3FC-BD23-11D2-B4B7-00A0C955FC6E',
'GETID3_ASF_Extended_Content_Encryption_Object' => '298AE614-2622-4C17-B935-DAE07EE9289C',
'GETID3_ASF_Simple_Index_Object' => '33000890-E5B1-11CF-89F4-00A0C90349CB',
'GETID3_ASF_Degradable_JPEG_Media' => '35907DE0-E415-11CF-A917-00805F5C442B',
'GETID3_ASF_Payload_Extension_System_Timecode' => '399595EC-8667-4E2D-8FDB-98814CE76C1E',
'GETID3_ASF_Binary_Media' => '3AFB65E2-47EF-40F2-AC2C-70A90D71D343',
'GETID3_ASF_Timecode_Index_Object' => '3CB73FD0-0C4A-4803-953D-EDF7B6228F0C',
'GETID3_ASF_Metadata_Library_Object' => '44231C94-9498-49D1-A141-1D134E457054',
'GETID3_ASF_Reserved_3' => '4B1ACBE3-100B-11D0-A39B-00A0C90348F6',
'GETID3_ASF_Reserved_4' => '4CFEDB20-75F6-11CF-9C0F-00A0C90349CB',
'GETID3_ASF_Command_Media' => '59DACFC0-59E6-11D0-A3AC-00A0C90348F6',
'GETID3_ASF_Header_Extension_Object' => '5FBF03B5-A92E-11CF-8EE3-00C00C205365',
'GETID3_ASF_Media_Object_Index_Parameters_Obj' => '6B203BAD-3F11-4E84-ACA8-D7613DE2CFA7',
'GETID3_ASF_Header_Object' => '75B22630-668E-11CF-A6D9-00AA0062CE6C',
'GETID3_ASF_Content_Description_Object' => '75B22633-668E-11CF-A6D9-00AA0062CE6C',
'GETID3_ASF_Error_Correction_Object' => '75B22635-668E-11CF-A6D9-00AA0062CE6C',
'GETID3_ASF_Data_Object' => '75B22636-668E-11CF-A6D9-00AA0062CE6C',
'GETID3_ASF_Web_Stream_Media_Subtype' => '776257D4-C627-41CB-8F81-7AC7FF1C40CC',
'GETID3_ASF_Stream_Bitrate_Properties_Object' => '7BF875CE-468D-11D1-8D82-006097C9A2B2',
'GETID3_ASF_Language_List_Object' => '7C4346A9-EFE0-4BFC-B229-393EDE415C85',
'GETID3_ASF_Codec_List_Object' => '86D15240-311D-11D0-A3A4-00A0C90348F6',
'GETID3_ASF_Reserved_2' => '86D15241-311D-11D0-A3A4-00A0C90348F6',
'GETID3_ASF_File_Properties_Object' => '8CABDCA1-A947-11CF-8EE4-00C00C205365',
'GETID3_ASF_File_Transfer_Media' => '91BD222C-F21C-497A-8B6D-5AA86BFC0185',
'GETID3_ASF_Old_RTP_Extension_Data' => '96800C63-4C94-11D1-837B-0080C7A37F95',
'GETID3_ASF_Advanced_Mutual_Exclusion_Object' => 'A08649CF-4775-4670-8A16-6E35357566CD',
'GETID3_ASF_Bandwidth_Sharing_Object' => 'A69609E6-517B-11D2-B6AF-00C04FD908E9',
'GETID3_ASF_Reserved_1' => 'ABD3D211-A9BA-11cf-8EE6-00C00C205365',
'GETID3_ASF_Bandwidth_Sharing_Exclusive' => 'AF6060AA-5197-11D2-B6AF-00C04FD908E9',
'GETID3_ASF_Bandwidth_Sharing_Partial' => 'AF6060AB-5197-11D2-B6AF-00C04FD908E9',
'GETID3_ASF_JFIF_Media' => 'B61BE100-5B4E-11CF-A8FD-00805F5C442B',
'GETID3_ASF_Stream_Properties_Object' => 'B7DC0791-A9B7-11CF-8EE6-00C00C205365',
'GETID3_ASF_Video_Media' => 'BC19EFC0-5B4D-11CF-A8FD-00805F5C442B',
'GETID3_ASF_Audio_Spread' => 'BFC3CD50-618F-11CF-8BB2-00AA00B4E220',
'GETID3_ASF_Metadata_Object' => 'C5F8CBEA-5BAF-4877-8467-AA8C44FA4CCA',
'GETID3_ASF_Payload_Ext_Syst_Sample_Duration' => 'C6BD9450-867F-4907-83A3-C77921B733AD',
'GETID3_ASF_Group_Mutual_Exclusion_Object' => 'D1465A40-5A79-4338-B71B-E36B8FD6C249',
'GETID3_ASF_Extended_Content_Description_Object' => 'D2D0A440-E307-11D2-97F0-00A0C95EA850',
'GETID3_ASF_Stream_Prioritization_Object' => 'D4FED15B-88D3-454F-81F0-ED5C45999E24',
'GETID3_ASF_Payload_Ext_System_Content_Type' => 'D590DC20-07BC-436C-9CF7-F3BBFBF1A4DC',
'GETID3_ASF_Old_File_Properties_Object' => 'D6E229D0-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_ASF_Header_Object' => 'D6E229D1-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_ASF_Data_Object' => 'D6E229D2-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Index_Object' => 'D6E229D3-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_Stream_Properties_Object' => 'D6E229D4-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_Content_Description_Object' => 'D6E229D5-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_Script_Command_Object' => 'D6E229D6-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_Marker_Object' => 'D6E229D7-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_Component_Download_Object' => 'D6E229D8-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_Stream_Group_Object' => 'D6E229D9-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_Scalable_Object' => 'D6E229DA-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_Prioritization_Object' => 'D6E229DB-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Bitrate_Mutual_Exclusion_Object' => 'D6E229DC-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_Inter_Media_Dependency_Object' => 'D6E229DD-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_Rating_Object' => 'D6E229DE-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Index_Parameters_Object' => 'D6E229DF-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_Color_Table_Object' => 'D6E229E0-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_Language_List_Object' => 'D6E229E1-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_Audio_Media' => 'D6E229E2-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_Video_Media' => 'D6E229E3-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_Image_Media' => 'D6E229E4-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_Timecode_Media' => 'D6E229E5-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_Text_Media' => 'D6E229E6-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_MIDI_Media' => 'D6E229E7-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_Command_Media' => 'D6E229E8-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_No_Error_Concealment' => 'D6E229EA-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_Scrambled_Audio' => 'D6E229EB-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_No_Color_Table' => 'D6E229EC-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_SMPTE_Time' => 'D6E229ED-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_ASCII_Text' => 'D6E229EE-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_Unicode_Text' => 'D6E229EF-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_HTML_Text' => 'D6E229F0-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_URL_Command' => 'D6E229F1-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_Filename_Command' => 'D6E229F2-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_ACM_Codec' => 'D6E229F3-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_VCM_Codec' => 'D6E229F4-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_QuickTime_Codec' => 'D6E229F5-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_DirectShow_Transform_Filter' => 'D6E229F6-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_DirectShow_Rendering_Filter' => 'D6E229F7-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_No_Enhancement' => 'D6E229F8-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_Unknown_Enhancement_Type' => 'D6E229F9-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_Temporal_Enhancement' => 'D6E229FA-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_Spatial_Enhancement' => 'D6E229FB-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_Quality_Enhancement' => 'D6E229FC-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_Number_of_Channels_Enhancement' => 'D6E229FD-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_Frequency_Response_Enhancement' => 'D6E229FE-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_Media_Object' => 'D6E229FF-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Mutex_Language' => 'D6E22A00-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Mutex_Bitrate' => 'D6E22A01-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Mutex_Unknown' => 'D6E22A02-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_ASF_Placeholder_Object' => 'D6E22A0E-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Old_Data_Unit_Extension_Object' => 'D6E22A0F-35DA-11D1-9034-00A0C90349BE',
'GETID3_ASF_Web_Stream_Format' => 'DA1E6B13-8359-4050-B398-388E965BF00C',
'GETID3_ASF_Payload_Ext_System_File_Name' => 'E165EC0E-19ED-45D7-B4A7-25CBD1E28E9B',
'GETID3_ASF_Marker_Object' => 'F487CD01-A951-11CF-8EE6-00C00C205365',
'GETID3_ASF_Timecode_Index_Parameters_Object' => 'F55E496D-9797-4B5D-8C8B-604DFE9BFB24',
'GETID3_ASF_Audio_Media' => 'F8699E40-5B4D-11CF-A8FD-00805F5C442B',
'GETID3_ASF_Media_Object_Index_Object' => 'FEB103F8-12AD-4C64-840F-2A1D2F7AD48C',
'GETID3_ASF_Alt_Extended_Content_Encryption_Obj' => 'FF889EF1-ADEE-40DA-9E71-98704BB928CE',
'GETID3_ASF_Index_Placeholder_Object' => 'D9AADE20-7C17-4F9C-BC28-8555DD98E2A2', // http://cpan.uwinnipeg.ca/htdocs/Audio-WMA/Audio/WMA.pm.html
'GETID3_ASF_Compatibility_Object' => '26F18B5D-4584-47EC-9F5F-0E651F0452C9', // http://cpan.uwinnipeg.ca/htdocs/Audio-WMA/Audio/WMA.pm.html
);
return $GUIDarray;
}
public static function GUIDname($GUIDstring) {
static $GUIDarray = array();
if (empty($GUIDarray)) {
$GUIDarray = self::KnownGUIDs();
}
return array_search($GUIDstring, $GUIDarray);
}
public static function ASFIndexObjectIndexTypeLookup($id) {
static $ASFIndexObjectIndexTypeLookup = array();
if (empty($ASFIndexObjectIndexTypeLookup)) {
$ASFIndexObjectIndexTypeLookup[1] = 'Nearest Past Data Packet';
$ASFIndexObjectIndexTypeLookup[2] = 'Nearest Past Media Object';
$ASFIndexObjectIndexTypeLookup[3] = 'Nearest Past Cleanpoint';
}
return (isset($ASFIndexObjectIndexTypeLookup[$id]) ? $ASFIndexObjectIndexTypeLookup[$id] : 'invalid');
}
public static function GUIDtoBytestring($GUIDstring) {
// Microsoft defines these 16-byte (128-bit) GUIDs in the strangest way:
// first 4 bytes are in little-endian order
// next 2 bytes are appended in little-endian order
// next 2 bytes are appended in little-endian order
// next 2 bytes are appended in big-endian order
// next 6 bytes are appended in big-endian order
// AaBbCcDd-EeFf-GgHh-IiJj-KkLlMmNnOoPp is stored as this 16-byte string:
// $Dd $Cc $Bb $Aa $Ff $Ee $Hh $Gg $Ii $Jj $Kk $Ll $Mm $Nn $Oo $Pp
$hexbytecharstring = chr(hexdec(substr($GUIDstring, 6, 2)));
$hexbytecharstring .= chr(hexdec(substr($GUIDstring, 4, 2)));
$hexbytecharstring .= chr(hexdec(substr($GUIDstring, 2, 2)));
$hexbytecharstring .= chr(hexdec(substr($GUIDstring, 0, 2)));
$hexbytecharstring .= chr(hexdec(substr($GUIDstring, 11, 2)));
$hexbytecharstring .= chr(hexdec(substr($GUIDstring, 9, 2)));
$hexbytecharstring .= chr(hexdec(substr($GUIDstring, 16, 2)));
$hexbytecharstring .= chr(hexdec(substr($GUIDstring, 14, 2)));
$hexbytecharstring .= chr(hexdec(substr($GUIDstring, 19, 2)));
$hexbytecharstring .= chr(hexdec(substr($GUIDstring, 21, 2)));
$hexbytecharstring .= chr(hexdec(substr($GUIDstring, 24, 2)));
$hexbytecharstring .= chr(hexdec(substr($GUIDstring, 26, 2)));
$hexbytecharstring .= chr(hexdec(substr($GUIDstring, 28, 2)));
$hexbytecharstring .= chr(hexdec(substr($GUIDstring, 30, 2)));
$hexbytecharstring .= chr(hexdec(substr($GUIDstring, 32, 2)));
$hexbytecharstring .= chr(hexdec(substr($GUIDstring, 34, 2)));
return $hexbytecharstring;
}
public static function BytestringToGUID($Bytestring) {
$GUIDstring = str_pad(dechex(ord($Bytestring{3})), 2, '0', STR_PAD_LEFT);
$GUIDstring .= str_pad(dechex(ord($Bytestring{2})), 2, '0', STR_PAD_LEFT);
$GUIDstring .= str_pad(dechex(ord($Bytestring{1})), 2, '0', STR_PAD_LEFT);
$GUIDstring .= str_pad(dechex(ord($Bytestring{0})), 2, '0', STR_PAD_LEFT);
$GUIDstring .= '-';
$GUIDstring .= str_pad(dechex(ord($Bytestring{5})), 2, '0', STR_PAD_LEFT);
$GUIDstring .= str_pad(dechex(ord($Bytestring{4})), 2, '0', STR_PAD_LEFT);
$GUIDstring .= '-';
$GUIDstring .= str_pad(dechex(ord($Bytestring{7})), 2, '0', STR_PAD_LEFT);
$GUIDstring .= str_pad(dechex(ord($Bytestring{6})), 2, '0', STR_PAD_LEFT);
$GUIDstring .= '-';
$GUIDstring .= str_pad(dechex(ord($Bytestring{8})), 2, '0', STR_PAD_LEFT);
$GUIDstring .= str_pad(dechex(ord($Bytestring{9})), 2, '0', STR_PAD_LEFT);
$GUIDstring .= '-';
$GUIDstring .= str_pad(dechex(ord($Bytestring{10})), 2, '0', STR_PAD_LEFT);
$GUIDstring .= str_pad(dechex(ord($Bytestring{11})), 2, '0', STR_PAD_LEFT);
$GUIDstring .= str_pad(dechex(ord($Bytestring{12})), 2, '0', STR_PAD_LEFT);
$GUIDstring .= str_pad(dechex(ord($Bytestring{13})), 2, '0', STR_PAD_LEFT);
$GUIDstring .= str_pad(dechex(ord($Bytestring{14})), 2, '0', STR_PAD_LEFT);
$GUIDstring .= str_pad(dechex(ord($Bytestring{15})), 2, '0', STR_PAD_LEFT);
return strtoupper($GUIDstring);
}
public static function FILETIMEtoUNIXtime($FILETIME, $round=true) {
// FILETIME is a 64-bit unsigned integer representing
// the number of 100-nanosecond intervals since January 1, 1601
// UNIX timestamp is number of seconds since January 1, 1970
// 116444736000000000 = 10000000 * 60 * 60 * 24 * 365 * 369 + 89 leap days
if ($round) {
return intval(round(($FILETIME - 116444736000000000) / 10000000));
}
return ($FILETIME - 116444736000000000) / 10000000;
}
public static function WMpictureTypeLookup($WMpictureType) {
static $WMpictureTypeLookup = array();
if (empty($WMpictureTypeLookup)) {
$WMpictureTypeLookup[0x03] = getid3_lib::iconv_fallback('ISO-8859-1', 'UTF-16LE', 'Front Cover');
$WMpictureTypeLookup[0x04] = getid3_lib::iconv_fallback('ISO-8859-1', 'UTF-16LE', 'Back Cover');
$WMpictureTypeLookup[0x00] = getid3_lib::iconv_fallback('ISO-8859-1', 'UTF-16LE', 'User Defined');
$WMpictureTypeLookup[0x05] = getid3_lib::iconv_fallback('ISO-8859-1', 'UTF-16LE', 'Leaflet Page');
$WMpictureTypeLookup[0x06] = getid3_lib::iconv_fallback('ISO-8859-1', 'UTF-16LE', 'Media Label');
$WMpictureTypeLookup[0x07] = getid3_lib::iconv_fallback('ISO-8859-1', 'UTF-16LE', 'Lead Artist');
$WMpictureTypeLookup[0x08] = getid3_lib::iconv_fallback('ISO-8859-1', 'UTF-16LE', 'Artist');
$WMpictureTypeLookup[0x09] = getid3_lib::iconv_fallback('ISO-8859-1', 'UTF-16LE', 'Conductor');
$WMpictureTypeLookup[0x0A] = getid3_lib::iconv_fallback('ISO-8859-1', 'UTF-16LE', 'Band');
$WMpictureTypeLookup[0x0B] = getid3_lib::iconv_fallback('ISO-8859-1', 'UTF-16LE', 'Composer');
$WMpictureTypeLookup[0x0C] = getid3_lib::iconv_fallback('ISO-8859-1', 'UTF-16LE', 'Lyricist');
$WMpictureTypeLookup[0x0D] = getid3_lib::iconv_fallback('ISO-8859-1', 'UTF-16LE', 'Recording Location');
$WMpictureTypeLookup[0x0E] = getid3_lib::iconv_fallback('ISO-8859-1', 'UTF-16LE', 'During Recording');
$WMpictureTypeLookup[0x0F] = getid3_lib::iconv_fallback('ISO-8859-1', 'UTF-16LE', 'During Performance');
$WMpictureTypeLookup[0x10] = getid3_lib::iconv_fallback('ISO-8859-1', 'UTF-16LE', 'Video Screen Capture');
$WMpictureTypeLookup[0x12] = getid3_lib::iconv_fallback('ISO-8859-1', 'UTF-16LE', 'Illustration');
$WMpictureTypeLookup[0x13] = getid3_lib::iconv_fallback('ISO-8859-1', 'UTF-16LE', 'Band Logotype');
$WMpictureTypeLookup[0x14] = getid3_lib::iconv_fallback('ISO-8859-1', 'UTF-16LE', 'Publisher Logotype');
}
return (isset($WMpictureTypeLookup[$WMpictureType]) ? $WMpictureTypeLookup[$WMpictureType] : '');
}
public function ASF_HeaderExtensionObjectDataParse(&$asf_header_extension_object_data, &$unhandled_sections) {
// http://msdn.microsoft.com/en-us/library/bb643323.aspx
$offset = 0;
$objectOffset = 0;
$HeaderExtensionObjectParsed = array();
while ($objectOffset < strlen($asf_header_extension_object_data)) {
$offset = $objectOffset;
$thisObject = array();
$thisObject['guid'] = substr($asf_header_extension_object_data, $offset, 16);
$offset += 16;
$thisObject['guid_text'] = $this->BytestringToGUID($thisObject['guid']);
$thisObject['guid_name'] = $this->GUIDname($thisObject['guid_text']);
$thisObject['size'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 8));
$offset += 8;
if ($thisObject['size'] <= 0) {
break;
}
switch ($thisObject['guid']) {
case GETID3_ASF_Extended_Stream_Properties_Object:
$thisObject['start_time'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 8));
$offset += 8;
$thisObject['start_time_unix'] = $this->FILETIMEtoUNIXtime($thisObject['start_time']);
$thisObject['end_time'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 8));
$offset += 8;
$thisObject['end_time_unix'] = $this->FILETIMEtoUNIXtime($thisObject['end_time']);
$thisObject['data_bitrate'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 4));
$offset += 4;
$thisObject['buffer_size'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 4));
$offset += 4;
$thisObject['initial_buffer_fullness'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 4));
$offset += 4;
$thisObject['alternate_data_bitrate'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 4));
$offset += 4;
$thisObject['alternate_buffer_size'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 4));
$offset += 4;
$thisObject['alternate_initial_buffer_fullness'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 4));
$offset += 4;
$thisObject['maximum_object_size'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 4));
$offset += 4;
$thisObject['flags_raw'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 4));
$offset += 4;
$thisObject['flags']['reliable'] = (bool) $thisObject['flags_raw'] & 0x00000001;
$thisObject['flags']['seekable'] = (bool) $thisObject['flags_raw'] & 0x00000002;
$thisObject['flags']['no_cleanpoints'] = (bool) $thisObject['flags_raw'] & 0x00000004;
$thisObject['flags']['resend_live_cleanpoints'] = (bool) $thisObject['flags_raw'] & 0x00000008;
$thisObject['stream_number'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2));
$offset += 2;
$thisObject['stream_language_id_index'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2));
$offset += 2;
$thisObject['average_time_per_frame'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 4));
$offset += 4;
$thisObject['stream_name_count'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2));
$offset += 2;
$thisObject['payload_extension_system_count'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2));
$offset += 2;
for ($i = 0; $i < $thisObject['stream_name_count']; $i++) {
$streamName = array();
$streamName['language_id_index'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2));
$offset += 2;
$streamName['stream_name_length'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2));
$offset += 2;
$streamName['stream_name'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, $streamName['stream_name_length']));
$offset += $streamName['stream_name_length'];
$thisObject['stream_names'][$i] = $streamName;
}
for ($i = 0; $i < $thisObject['payload_extension_system_count']; $i++) {
$payloadExtensionSystem = array();
$payloadExtensionSystem['extension_system_id'] = substr($asf_header_extension_object_data, $offset, 16);
$offset += 16;
$payloadExtensionSystem['extension_system_id_text'] = $this->BytestringToGUID($payloadExtensionSystem['extension_system_id']);
$payloadExtensionSystem['extension_system_size'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2));
$offset += 2;
if ($payloadExtensionSystem['extension_system_size'] <= 0) {
break 2;
}
$payloadExtensionSystem['extension_system_info_length'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 4));
$offset += 4;
$payloadExtensionSystem['extension_system_info_length'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, $payloadExtensionSystem['extension_system_info_length']));
$offset += $payloadExtensionSystem['extension_system_info_length'];
$thisObject['payload_extension_systems'][$i] = $payloadExtensionSystem;
}
break;
case GETID3_ASF_Padding_Object:
// padding, skip it
break;
case GETID3_ASF_Metadata_Object:
$thisObject['description_record_counts'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2));
$offset += 2;
for ($i = 0; $i < $thisObject['description_record_counts']; $i++) {
$descriptionRecord = array();
$descriptionRecord['reserved_1'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2)); // must be zero
$offset += 2;
$descriptionRecord['stream_number'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2));
$offset += 2;
$descriptionRecord['name_length'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2));
$offset += 2;
$descriptionRecord['data_type'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2));
$offset += 2;
$descriptionRecord['data_type_text'] = $this->ASFmetadataLibraryObjectDataTypeLookup($descriptionRecord['data_type']);
$descriptionRecord['data_length'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 4));
$offset += 4;
$descriptionRecord['name'] = substr($asf_header_extension_object_data, $offset, $descriptionRecord['name_length']);
$offset += $descriptionRecord['name_length'];
$descriptionRecord['data'] = substr($asf_header_extension_object_data, $offset, $descriptionRecord['data_length']);
$offset += $descriptionRecord['data_length'];
switch ($descriptionRecord['data_type']) {
case 0x0000: // Unicode string
break;
case 0x0001: // BYTE array
// do nothing
break;
case 0x0002: // BOOL
$descriptionRecord['data'] = (bool) getid3_lib::LittleEndian2Int($descriptionRecord['data']);
break;
case 0x0003: // DWORD
case 0x0004: // QWORD
case 0x0005: // WORD
$descriptionRecord['data'] = getid3_lib::LittleEndian2Int($descriptionRecord['data']);
break;
case 0x0006: // GUID
$descriptionRecord['data_text'] = $this->BytestringToGUID($descriptionRecord['data']);
break;
}
$thisObject['description_record'][$i] = $descriptionRecord;
}
break;
case GETID3_ASF_Language_List_Object:
$thisObject['language_id_record_counts'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2));
$offset += 2;
for ($i = 0; $i < $thisObject['language_id_record_counts']; $i++) {
$languageIDrecord = array();
$languageIDrecord['language_id_length'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 1));
$offset += 1;
$languageIDrecord['language_id'] = substr($asf_header_extension_object_data, $offset, $languageIDrecord['language_id_length']);
$offset += $languageIDrecord['language_id_length'];
$thisObject['language_id_record'][$i] = $languageIDrecord;
}
break;
case GETID3_ASF_Metadata_Library_Object:
$thisObject['description_records_count'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2));
$offset += 2;
for ($i = 0; $i < $thisObject['description_records_count']; $i++) {
$descriptionRecord = array();
$descriptionRecord['language_list_index'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2));
$offset += 2;
$descriptionRecord['stream_number'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2));
$offset += 2;
$descriptionRecord['name_length'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2));
$offset += 2;
$descriptionRecord['data_type'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2));
$offset += 2;
$descriptionRecord['data_type_text'] = $this->ASFmetadataLibraryObjectDataTypeLookup($descriptionRecord['data_type']);
$descriptionRecord['data_length'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 4));
$offset += 4;
$descriptionRecord['name'] = substr($asf_header_extension_object_data, $offset, $descriptionRecord['name_length']);
$offset += $descriptionRecord['name_length'];
$descriptionRecord['data'] = substr($asf_header_extension_object_data, $offset, $descriptionRecord['data_length']);
$offset += $descriptionRecord['data_length'];
if (preg_match('#^WM/Picture$#', str_replace("\x00", '', trim($descriptionRecord['name'])))) {
$WMpicture = $this->ASF_WMpicture($descriptionRecord['data']);
foreach ($WMpicture as $key => $value) {
$descriptionRecord['data'] = $WMpicture;
}
unset($WMpicture);
}
$thisObject['description_record'][$i] = $descriptionRecord;
}
break;
default:
$unhandled_sections++;
if ($this->GUIDname($thisObject['guid_text'])) {
$this->getid3->info['warning'][] = 'unhandled Header Extension Object GUID "'.$this->GUIDname($thisObject['guid_text']).'" {'.$thisObject['guid_text'].'} at offset '.($offset - 16 - 8);
} else {
$this->getid3->info['warning'][] = 'unknown Header Extension Object GUID {'.$thisObject['guid_text'].'} in at offset '.($offset - 16 - 8);
}
break;
}
$HeaderExtensionObjectParsed[] = $thisObject;
$objectOffset += $thisObject['size'];
}
return $HeaderExtensionObjectParsed;
}
public static function ASFmetadataLibraryObjectDataTypeLookup($id) {
static $ASFmetadataLibraryObjectDataTypeLookup = array(
0x0000 => 'Unicode string', // The data consists of a sequence of Unicode characters
0x0001 => 'BYTE array', // The type of the data is implementation-specific
0x0002 => 'BOOL', // The data is 2 bytes long and should be interpreted as a 16-bit unsigned integer. Only 0x0000 or 0x0001 are permitted values
0x0003 => 'DWORD', // The data is 4 bytes long and should be interpreted as a 32-bit unsigned integer
0x0004 => 'QWORD', // The data is 8 bytes long and should be interpreted as a 64-bit unsigned integer
0x0005 => 'WORD', // The data is 2 bytes long and should be interpreted as a 16-bit unsigned integer
0x0006 => 'GUID', // The data is 16 bytes long and should be interpreted as a 128-bit GUID
);
return (isset($ASFmetadataLibraryObjectDataTypeLookup[$id]) ? $ASFmetadataLibraryObjectDataTypeLookup[$id] : 'invalid');
}
public function ASF_WMpicture(&$data) {
//typedef struct _WMPicture{
// LPWSTR pwszMIMEType;
// BYTE bPictureType;
// LPWSTR pwszDescription;
// DWORD dwDataLen;
// BYTE* pbData;
//} WM_PICTURE;
$WMpicture = array();
$offset = 0;
$WMpicture['image_type_id'] = getid3_lib::LittleEndian2Int(substr($data, $offset, 1));
$offset += 1;
$WMpicture['image_type'] = $this->WMpictureTypeLookup($WMpicture['image_type_id']);
$WMpicture['image_size'] = getid3_lib::LittleEndian2Int(substr($data, $offset, 4));
$offset += 4;
$WMpicture['image_mime'] = '';
do {
$next_byte_pair = substr($data, $offset, 2);
$offset += 2;
$WMpicture['image_mime'] .= $next_byte_pair;
} while ($next_byte_pair !== "\x00\x00");
$WMpicture['image_description'] = '';
do {
$next_byte_pair = substr($data, $offset, 2);
$offset += 2;
$WMpicture['image_description'] .= $next_byte_pair;
} while ($next_byte_pair !== "\x00\x00");
$WMpicture['dataoffset'] = $offset;
$WMpicture['data'] = substr($data, $offset);
$imageinfo = array();
$WMpicture['image_mime'] = '';
$imagechunkcheck = getid3_lib::GetDataImageSize($WMpicture['data'], $imageinfo);
unset($imageinfo);
if (!empty($imagechunkcheck)) {
$WMpicture['image_mime'] = image_type_to_mime_type($imagechunkcheck[2]);
}
if (!isset($this->getid3->info['asf']['comments']['picture'])) {
$this->getid3->info['asf']['comments']['picture'] = array();
}
$this->getid3->info['asf']['comments']['picture'][] = array('data'=>$WMpicture['data'], 'image_mime'=>$WMpicture['image_mime']);
return $WMpicture;
}
// Remove terminator 00 00 and convert UTF-16LE to Latin-1
public static function TrimConvert($string) {
return trim(getid3_lib::iconv_fallback('UTF-16LE', 'ISO-8859-1', self::TrimTerm($string)), ' ');
}
// Remove terminator 00 00
public static function TrimTerm($string) {
// remove terminator, only if present (it should be, but...)
if (substr($string, -2) === "\x00\x00") {
$string = substr($string, 0, -2);
}
return $string;
}
}
| PHP |
<?php
/////////////////////////////////////////////////////////////////
/// getID3() by James Heinrich <info@getid3.org> //
// available at http://getid3.sourceforge.net //
// or http://www.getid3.org //
// //
// FLV module by Seth Kaufman <sethØwhirl-i-gig*com> //
// //
// * version 0.1 (26 June 2005) //
// //
// //
// * version 0.1.1 (15 July 2005) //
// minor modifications by James Heinrich <info@getid3.org> //
// //
// * version 0.2 (22 February 2006) //
// Support for On2 VP6 codec and meta information //
// by Steve Webster <steve.websterØfeaturecreep*com> //
// //
// * version 0.3 (15 June 2006) //
// Modified to not read entire file into memory //
// by James Heinrich <info@getid3.org> //
// //
// * version 0.4 (07 December 2007) //
// Bugfixes for incorrectly parsed FLV dimensions //
// and incorrect parsing of onMetaTag //
// by Evgeny Moysevich <moysevichØgmail*com> //
// //
// * version 0.5 (21 May 2009) //
// Fixed parsing of audio tags and added additional codec //
// details. The duration is now read from onMetaTag (if //
// exists), rather than parsing whole file //
// by Nigel Barnes <ngbarnesØhotmail*com> //
// //
// * version 0.6 (24 May 2009) //
// Better parsing of files with h264 video //
// by Evgeny Moysevich <moysevichØgmail*com> //
// //
// * version 0.6.1 (30 May 2011) //
// prevent infinite loops in expGolombUe() //
// //
/////////////////////////////////////////////////////////////////
// //
// module.audio-video.flv.php //
// module for analyzing Shockwave Flash Video files //
// dependencies: NONE //
// ///
/////////////////////////////////////////////////////////////////
define('GETID3_FLV_TAG_AUDIO', 8);
define('GETID3_FLV_TAG_VIDEO', 9);
define('GETID3_FLV_TAG_META', 18);
define('GETID3_FLV_VIDEO_H263', 2);
define('GETID3_FLV_VIDEO_SCREEN', 3);
define('GETID3_FLV_VIDEO_VP6FLV', 4);
define('GETID3_FLV_VIDEO_VP6FLV_ALPHA', 5);
define('GETID3_FLV_VIDEO_SCREENV2', 6);
define('GETID3_FLV_VIDEO_H264', 7);
define('H264_AVC_SEQUENCE_HEADER', 0);
define('H264_PROFILE_BASELINE', 66);
define('H264_PROFILE_MAIN', 77);
define('H264_PROFILE_EXTENDED', 88);
define('H264_PROFILE_HIGH', 100);
define('H264_PROFILE_HIGH10', 110);
define('H264_PROFILE_HIGH422', 122);
define('H264_PROFILE_HIGH444', 144);
define('H264_PROFILE_HIGH444_PREDICTIVE', 244);
class getid3_flv extends getid3_handler
{
public $max_frames = 100000; // break out of the loop if too many frames have been scanned; only scan this many if meta frame does not contain useful duration
public function Analyze() {
$info = &$this->getid3->info;
fseek($this->getid3->fp, $info['avdataoffset'], SEEK_SET);
$FLVdataLength = $info['avdataend'] - $info['avdataoffset'];
$FLVheader = fread($this->getid3->fp, 5);
$info['fileformat'] = 'flv';
$info['flv']['header']['signature'] = substr($FLVheader, 0, 3);
$info['flv']['header']['version'] = getid3_lib::BigEndian2Int(substr($FLVheader, 3, 1));
$TypeFlags = getid3_lib::BigEndian2Int(substr($FLVheader, 4, 1));
$magic = 'FLV';
if ($info['flv']['header']['signature'] != $magic) {
$info['error'][] = 'Expecting "'.getid3_lib::PrintHexBytes($magic).'" at offset '.$info['avdataoffset'].', found "'.getid3_lib::PrintHexBytes($info['flv']['header']['signature']).'"';
unset($info['flv']);
unset($info['fileformat']);
return false;
}
$info['flv']['header']['hasAudio'] = (bool) ($TypeFlags & 0x04);
$info['flv']['header']['hasVideo'] = (bool) ($TypeFlags & 0x01);
$FrameSizeDataLength = getid3_lib::BigEndian2Int(fread($this->getid3->fp, 4));
$FLVheaderFrameLength = 9;
if ($FrameSizeDataLength > $FLVheaderFrameLength) {
fseek($this->getid3->fp, $FrameSizeDataLength - $FLVheaderFrameLength, SEEK_CUR);
}
$Duration = 0;
$found_video = false;
$found_audio = false;
$found_meta = false;
$found_valid_meta_playtime = false;
$tagParseCount = 0;
$info['flv']['framecount'] = array('total'=>0, 'audio'=>0, 'video'=>0);
$flv_framecount = &$info['flv']['framecount'];
while (((ftell($this->getid3->fp) + 16) < $info['avdataend']) && (($tagParseCount++ <= $this->max_frames) || !$found_valid_meta_playtime)) {
$ThisTagHeader = fread($this->getid3->fp, 16);
$PreviousTagLength = getid3_lib::BigEndian2Int(substr($ThisTagHeader, 0, 4));
$TagType = getid3_lib::BigEndian2Int(substr($ThisTagHeader, 4, 1));
$DataLength = getid3_lib::BigEndian2Int(substr($ThisTagHeader, 5, 3));
$Timestamp = getid3_lib::BigEndian2Int(substr($ThisTagHeader, 8, 3));
$LastHeaderByte = getid3_lib::BigEndian2Int(substr($ThisTagHeader, 15, 1));
$NextOffset = ftell($this->getid3->fp) - 1 + $DataLength;
if ($Timestamp > $Duration) {
$Duration = $Timestamp;
}
$flv_framecount['total']++;
switch ($TagType) {
case GETID3_FLV_TAG_AUDIO:
$flv_framecount['audio']++;
if (!$found_audio) {
$found_audio = true;
$info['flv']['audio']['audioFormat'] = ($LastHeaderByte >> 4) & 0x0F;
$info['flv']['audio']['audioRate'] = ($LastHeaderByte >> 2) & 0x03;
$info['flv']['audio']['audioSampleSize'] = ($LastHeaderByte >> 1) & 0x01;
$info['flv']['audio']['audioType'] = $LastHeaderByte & 0x01;
}
break;
case GETID3_FLV_TAG_VIDEO:
$flv_framecount['video']++;
if (!$found_video) {
$found_video = true;
$info['flv']['video']['videoCodec'] = $LastHeaderByte & 0x07;
$FLVvideoHeader = fread($this->getid3->fp, 11);
if ($info['flv']['video']['videoCodec'] == GETID3_FLV_VIDEO_H264) {
// this code block contributed by: moysevichØgmail*com
$AVCPacketType = getid3_lib::BigEndian2Int(substr($FLVvideoHeader, 0, 1));
if ($AVCPacketType == H264_AVC_SEQUENCE_HEADER) {
// read AVCDecoderConfigurationRecord
$configurationVersion = getid3_lib::BigEndian2Int(substr($FLVvideoHeader, 4, 1));
$AVCProfileIndication = getid3_lib::BigEndian2Int(substr($FLVvideoHeader, 5, 1));
$profile_compatibility = getid3_lib::BigEndian2Int(substr($FLVvideoHeader, 6, 1));
$lengthSizeMinusOne = getid3_lib::BigEndian2Int(substr($FLVvideoHeader, 7, 1));
$numOfSequenceParameterSets = getid3_lib::BigEndian2Int(substr($FLVvideoHeader, 8, 1));
if (($numOfSequenceParameterSets & 0x1F) != 0) {
// there is at least one SequenceParameterSet
// read size of the first SequenceParameterSet
//$spsSize = getid3_lib::BigEndian2Int(substr($FLVvideoHeader, 9, 2));
$spsSize = getid3_lib::LittleEndian2Int(substr($FLVvideoHeader, 9, 2));
// read the first SequenceParameterSet
$sps = fread($this->getid3->fp, $spsSize);
if (strlen($sps) == $spsSize) { // make sure that whole SequenceParameterSet was red
$spsReader = new AVCSequenceParameterSetReader($sps);
$spsReader->readData();
$info['video']['resolution_x'] = $spsReader->getWidth();
$info['video']['resolution_y'] = $spsReader->getHeight();
}
}
}
// end: moysevichØgmail*com
} elseif ($info['flv']['video']['videoCodec'] == GETID3_FLV_VIDEO_H263) {
$PictureSizeType = (getid3_lib::BigEndian2Int(substr($FLVvideoHeader, 3, 2))) >> 7;
$PictureSizeType = $PictureSizeType & 0x0007;
$info['flv']['header']['videoSizeType'] = $PictureSizeType;
switch ($PictureSizeType) {
case 0:
//$PictureSizeEnc = getid3_lib::BigEndian2Int(substr($FLVvideoHeader, 5, 2));
//$PictureSizeEnc <<= 1;
//$info['video']['resolution_x'] = ($PictureSizeEnc & 0xFF00) >> 8;
//$PictureSizeEnc = getid3_lib::BigEndian2Int(substr($FLVvideoHeader, 6, 2));
//$PictureSizeEnc <<= 1;
//$info['video']['resolution_y'] = ($PictureSizeEnc & 0xFF00) >> 8;
$PictureSizeEnc['x'] = getid3_lib::BigEndian2Int(substr($FLVvideoHeader, 4, 2));
$PictureSizeEnc['y'] = getid3_lib::BigEndian2Int(substr($FLVvideoHeader, 5, 2));
$PictureSizeEnc['x'] >>= 7;
$PictureSizeEnc['y'] >>= 7;
$info['video']['resolution_x'] = $PictureSizeEnc['x'] & 0xFF;
$info['video']['resolution_y'] = $PictureSizeEnc['y'] & 0xFF;
break;
case 1:
$PictureSizeEnc['x'] = getid3_lib::BigEndian2Int(substr($FLVvideoHeader, 4, 3));
$PictureSizeEnc['y'] = getid3_lib::BigEndian2Int(substr($FLVvideoHeader, 6, 3));
$PictureSizeEnc['x'] >>= 7;
$PictureSizeEnc['y'] >>= 7;
$info['video']['resolution_x'] = $PictureSizeEnc['x'] & 0xFFFF;
$info['video']['resolution_y'] = $PictureSizeEnc['y'] & 0xFFFF;
break;
case 2:
$info['video']['resolution_x'] = 352;
$info['video']['resolution_y'] = 288;
break;
case 3:
$info['video']['resolution_x'] = 176;
$info['video']['resolution_y'] = 144;
break;
case 4:
$info['video']['resolution_x'] = 128;
$info['video']['resolution_y'] = 96;
break;
case 5:
$info['video']['resolution_x'] = 320;
$info['video']['resolution_y'] = 240;
break;
case 6:
$info['video']['resolution_x'] = 160;
$info['video']['resolution_y'] = 120;
break;
default:
$info['video']['resolution_x'] = 0;
$info['video']['resolution_y'] = 0;
break;
}
}
$info['video']['pixel_aspect_ratio'] = $info['video']['resolution_x'] / $info['video']['resolution_y'];
}
break;
// Meta tag
case GETID3_FLV_TAG_META:
if (!$found_meta) {
$found_meta = true;
fseek($this->getid3->fp, -1, SEEK_CUR);
$datachunk = fread($this->getid3->fp, $DataLength);
$AMFstream = new AMFStream($datachunk);
$reader = new AMFReader($AMFstream);
$eventName = $reader->readData();
$info['flv']['meta'][$eventName] = $reader->readData();
unset($reader);
$copykeys = array('framerate'=>'frame_rate', 'width'=>'resolution_x', 'height'=>'resolution_y', 'audiodatarate'=>'bitrate', 'videodatarate'=>'bitrate');
foreach ($copykeys as $sourcekey => $destkey) {
if (isset($info['flv']['meta']['onMetaData'][$sourcekey])) {
switch ($sourcekey) {
case 'width':
case 'height':
$info['video'][$destkey] = intval(round($info['flv']['meta']['onMetaData'][$sourcekey]));
break;
case 'audiodatarate':
$info['audio'][$destkey] = getid3_lib::CastAsInt(round($info['flv']['meta']['onMetaData'][$sourcekey] * 1000));
break;
case 'videodatarate':
case 'frame_rate':
default:
$info['video'][$destkey] = $info['flv']['meta']['onMetaData'][$sourcekey];
break;
}
}
}
if (!empty($info['flv']['meta']['onMetaData']['duration'])) {
$found_valid_meta_playtime = true;
}
}
break;
default:
// noop
break;
}
fseek($this->getid3->fp, $NextOffset, SEEK_SET);
}
$info['playtime_seconds'] = $Duration / 1000;
if ($info['playtime_seconds'] > 0) {
$info['bitrate'] = (($info['avdataend'] - $info['avdataoffset']) * 8) / $info['playtime_seconds'];
}
if ($info['flv']['header']['hasAudio']) {
$info['audio']['codec'] = $this->FLVaudioFormat($info['flv']['audio']['audioFormat']);
$info['audio']['sample_rate'] = $this->FLVaudioRate($info['flv']['audio']['audioRate']);
$info['audio']['bits_per_sample'] = $this->FLVaudioBitDepth($info['flv']['audio']['audioSampleSize']);
$info['audio']['channels'] = $info['flv']['audio']['audioType'] + 1; // 0=mono,1=stereo
$info['audio']['lossless'] = ($info['flv']['audio']['audioFormat'] ? false : true); // 0=uncompressed
$info['audio']['dataformat'] = 'flv';
}
if (!empty($info['flv']['header']['hasVideo'])) {
$info['video']['codec'] = $this->FLVvideoCodec($info['flv']['video']['videoCodec']);
$info['video']['dataformat'] = 'flv';
$info['video']['lossless'] = false;
}
// Set information from meta
if (!empty($info['flv']['meta']['onMetaData']['duration'])) {
$info['playtime_seconds'] = $info['flv']['meta']['onMetaData']['duration'];
$info['bitrate'] = (($info['avdataend'] - $info['avdataoffset']) * 8) / $info['playtime_seconds'];
}
if (isset($info['flv']['meta']['onMetaData']['audiocodecid'])) {
$info['audio']['codec'] = $this->FLVaudioFormat($info['flv']['meta']['onMetaData']['audiocodecid']);
}
if (isset($info['flv']['meta']['onMetaData']['videocodecid'])) {
$info['video']['codec'] = $this->FLVvideoCodec($info['flv']['meta']['onMetaData']['videocodecid']);
}
return true;
}
public function FLVaudioFormat($id) {
$FLVaudioFormat = array(
0 => 'Linear PCM, platform endian',
1 => 'ADPCM',
2 => 'mp3',
3 => 'Linear PCM, little endian',
4 => 'Nellymoser 16kHz mono',
5 => 'Nellymoser 8kHz mono',
6 => 'Nellymoser',
7 => 'G.711A-law logarithmic PCM',
8 => 'G.711 mu-law logarithmic PCM',
9 => 'reserved',
10 => 'AAC',
11 => false, // unknown?
12 => false, // unknown?
13 => false, // unknown?
14 => 'mp3 8kHz',
15 => 'Device-specific sound',
);
return (isset($FLVaudioFormat[$id]) ? $FLVaudioFormat[$id] : false);
}
public function FLVaudioRate($id) {
$FLVaudioRate = array(
0 => 5500,
1 => 11025,
2 => 22050,
3 => 44100,
);
return (isset($FLVaudioRate[$id]) ? $FLVaudioRate[$id] : false);
}
public function FLVaudioBitDepth($id) {
$FLVaudioBitDepth = array(
0 => 8,
1 => 16,
);
return (isset($FLVaudioBitDepth[$id]) ? $FLVaudioBitDepth[$id] : false);
}
public function FLVvideoCodec($id) {
$FLVvideoCodec = array(
GETID3_FLV_VIDEO_H263 => 'Sorenson H.263',
GETID3_FLV_VIDEO_SCREEN => 'Screen video',
GETID3_FLV_VIDEO_VP6FLV => 'On2 VP6',
GETID3_FLV_VIDEO_VP6FLV_ALPHA => 'On2 VP6 with alpha channel',
GETID3_FLV_VIDEO_SCREENV2 => 'Screen video v2',
GETID3_FLV_VIDEO_H264 => 'Sorenson H.264',
);
return (isset($FLVvideoCodec[$id]) ? $FLVvideoCodec[$id] : false);
}
}
class AMFStream {
public $bytes;
public $pos;
public function AMFStream(&$bytes) {
$this->bytes =& $bytes;
$this->pos = 0;
}
public function readByte() {
return getid3_lib::BigEndian2Int(substr($this->bytes, $this->pos++, 1));
}
public function readInt() {
return ($this->readByte() << 8) + $this->readByte();
}
public function readLong() {
return ($this->readByte() << 24) + ($this->readByte() << 16) + ($this->readByte() << 8) + $this->readByte();
}
public function readDouble() {
return getid3_lib::BigEndian2Float($this->read(8));
}
public function readUTF() {
$length = $this->readInt();
return $this->read($length);
}
public function readLongUTF() {
$length = $this->readLong();
return $this->read($length);
}
public function read($length) {
$val = substr($this->bytes, $this->pos, $length);
$this->pos += $length;
return $val;
}
public function peekByte() {
$pos = $this->pos;
$val = $this->readByte();
$this->pos = $pos;
return $val;
}
public function peekInt() {
$pos = $this->pos;
$val = $this->readInt();
$this->pos = $pos;
return $val;
}
public function peekLong() {
$pos = $this->pos;
$val = $this->readLong();
$this->pos = $pos;
return $val;
}
public function peekDouble() {
$pos = $this->pos;
$val = $this->readDouble();
$this->pos = $pos;
return $val;
}
public function peekUTF() {
$pos = $this->pos;
$val = $this->readUTF();
$this->pos = $pos;
return $val;
}
public function peekLongUTF() {
$pos = $this->pos;
$val = $this->readLongUTF();
$this->pos = $pos;
return $val;
}
}
class AMFReader {
public $stream;
public function AMFReader(&$stream) {
$this->stream =& $stream;
}
public function readData() {
$value = null;
$type = $this->stream->readByte();
switch ($type) {
// Double
case 0:
$value = $this->readDouble();
break;
// Boolean
case 1:
$value = $this->readBoolean();
break;
// String
case 2:
$value = $this->readString();
break;
// Object
case 3:
$value = $this->readObject();
break;
// null
case 6:
return null;
break;
// Mixed array
case 8:
$value = $this->readMixedArray();
break;
// Array
case 10:
$value = $this->readArray();
break;
// Date
case 11:
$value = $this->readDate();
break;
// Long string
case 13:
$value = $this->readLongString();
break;
// XML (handled as string)
case 15:
$value = $this->readXML();
break;
// Typed object (handled as object)
case 16:
$value = $this->readTypedObject();
break;
// Long string
default:
$value = '(unknown or unsupported data type)';
break;
}
return $value;
}
public function readDouble() {
return $this->stream->readDouble();
}
public function readBoolean() {
return $this->stream->readByte() == 1;
}
public function readString() {
return $this->stream->readUTF();
}
public function readObject() {
// Get highest numerical index - ignored
// $highestIndex = $this->stream->readLong();
$data = array();
while ($key = $this->stream->readUTF()) {
$data[$key] = $this->readData();
}
// Mixed array record ends with empty string (0x00 0x00) and 0x09
if (($key == '') && ($this->stream->peekByte() == 0x09)) {
// Consume byte
$this->stream->readByte();
}
return $data;
}
public function readMixedArray() {
// Get highest numerical index - ignored
$highestIndex = $this->stream->readLong();
$data = array();
while ($key = $this->stream->readUTF()) {
if (is_numeric($key)) {
$key = (float) $key;
}
$data[$key] = $this->readData();
}
// Mixed array record ends with empty string (0x00 0x00) and 0x09
if (($key == '') && ($this->stream->peekByte() == 0x09)) {
// Consume byte
$this->stream->readByte();
}
return $data;
}
public function readArray() {
$length = $this->stream->readLong();
$data = array();
for ($i = 0; $i < $length; $i++) {
$data[] = $this->readData();
}
return $data;
}
public function readDate() {
$timestamp = $this->stream->readDouble();
$timezone = $this->stream->readInt();
return $timestamp;
}
public function readLongString() {
return $this->stream->readLongUTF();
}
public function readXML() {
return $this->stream->readLongUTF();
}
public function readTypedObject() {
$className = $this->stream->readUTF();
return $this->readObject();
}
}
class AVCSequenceParameterSetReader {
public $sps;
public $start = 0;
public $currentBytes = 0;
public $currentBits = 0;
public $width;
public $height;
public function AVCSequenceParameterSetReader($sps) {
$this->sps = $sps;
}
public function readData() {
$this->skipBits(8);
$this->skipBits(8);
$profile = $this->getBits(8); // read profile
$this->skipBits(16);
$this->expGolombUe(); // read sps id
if (in_array($profile, array(H264_PROFILE_HIGH, H264_PROFILE_HIGH10, H264_PROFILE_HIGH422, H264_PROFILE_HIGH444, H264_PROFILE_HIGH444_PREDICTIVE))) {
if ($this->expGolombUe() == 3) {
$this->skipBits(1);
}
$this->expGolombUe();
$this->expGolombUe();
$this->skipBits(1);
if ($this->getBit()) {
for ($i = 0; $i < 8; $i++) {
if ($this->getBit()) {
$size = $i < 6 ? 16 : 64;
$lastScale = 8;
$nextScale = 8;
for ($j = 0; $j < $size; $j++) {
if ($nextScale != 0) {
$deltaScale = $this->expGolombUe();
$nextScale = ($lastScale + $deltaScale + 256) % 256;
}
if ($nextScale != 0) {
$lastScale = $nextScale;
}
}
}
}
}
}
$this->expGolombUe();
$pocType = $this->expGolombUe();
if ($pocType == 0) {
$this->expGolombUe();
} elseif ($pocType == 1) {
$this->skipBits(1);
$this->expGolombSe();
$this->expGolombSe();
$pocCycleLength = $this->expGolombUe();
for ($i = 0; $i < $pocCycleLength; $i++) {
$this->expGolombSe();
}
}
$this->expGolombUe();
$this->skipBits(1);
$this->width = ($this->expGolombUe() + 1) * 16;
$heightMap = $this->expGolombUe() + 1;
$this->height = (2 - $this->getBit()) * $heightMap * 16;
}
public function skipBits($bits) {
$newBits = $this->currentBits + $bits;
$this->currentBytes += (int)floor($newBits / 8);
$this->currentBits = $newBits % 8;
}
public function getBit() {
$result = (getid3_lib::BigEndian2Int(substr($this->sps, $this->currentBytes, 1)) >> (7 - $this->currentBits)) & 0x01;
$this->skipBits(1);
return $result;
}
public function getBits($bits) {
$result = 0;
for ($i = 0; $i < $bits; $i++) {
$result = ($result << 1) + $this->getBit();
}
return $result;
}
public function expGolombUe() {
$significantBits = 0;
$bit = $this->getBit();
while ($bit == 0) {
$significantBits++;
$bit = $this->getBit();
if ($significantBits > 31) {
// something is broken, this is an emergency escape to prevent infinite loops
return 0;
}
}
return (1 << $significantBits) + $this->getBits($significantBits) - 1;
}
public function expGolombSe() {
$result = $this->expGolombUe();
if (($result & 0x01) == 0) {
return -($result >> 1);
} else {
return ($result + 1) >> 1;
}
}
public function getWidth() {
return $this->width;
}
public function getHeight() {
return $this->height;
}
}
| PHP |
<?php
/////////////////////////////////////////////////////////////////
/// getID3() by James Heinrich <info@getid3.org> //
// available at http://getid3.sourceforge.net //
// or http://www.getid3.org //
/////////////////////////////////////////////////////////////////
// //
// Please see readme.txt for more information //
// ///
/////////////////////////////////////////////////////////////////
// define a constant rather than looking up every time it is needed
if (!defined('GETID3_OS_ISWINDOWS')) {
define('GETID3_OS_ISWINDOWS', (stripos(PHP_OS, 'WIN') === 0));
}
// Get base path of getID3() - ONCE
if (!defined('GETID3_INCLUDEPATH')) {
define('GETID3_INCLUDEPATH', dirname(__FILE__).DIRECTORY_SEPARATOR);
}
// attempt to define temp dir as something flexible but reliable
$temp_dir = ini_get('upload_tmp_dir');
if ($temp_dir && (!is_dir($temp_dir) || !is_readable($temp_dir))) {
$temp_dir = '';
}
if (!$temp_dir && function_exists('sys_get_temp_dir')) {
// PHP v5.2.1+
// sys_get_temp_dir() may give inaccessible temp dir, e.g. with open_basedir on virtual hosts
$temp_dir = sys_get_temp_dir();
}
$temp_dir = realpath($temp_dir);
$open_basedir = ini_get('open_basedir');
if ($open_basedir) {
// e.g. "/var/www/vhosts/getid3.org/httpdocs/:/tmp/"
$temp_dir = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $temp_dir);
$open_basedir = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $open_basedir);
if (substr($temp_dir, -1, 1) != DIRECTORY_SEPARATOR) {
$temp_dir .= DIRECTORY_SEPARATOR;
}
$found_valid_tempdir = false;
$open_basedirs = explode(PATH_SEPARATOR, $open_basedir);
foreach ($open_basedirs as $basedir) {
if (substr($basedir, -1, 1) != DIRECTORY_SEPARATOR) {
$basedir .= DIRECTORY_SEPARATOR;
}
if (preg_match('#^'.preg_quote($basedir).'#', $temp_dir)) {
$found_valid_tempdir = true;
break;
}
}
if (!$found_valid_tempdir) {
$temp_dir = '';
}
unset($open_basedirs, $found_valid_tempdir, $basedir);
}
if (!$temp_dir) {
$temp_dir = '*'; // invalid directory name should force tempnam() to use system default temp dir
}
// $temp_dir = '/something/else/'; // feel free to override temp dir here if it works better for your system
define('GETID3_TEMP_DIR', $temp_dir);
unset($open_basedir, $temp_dir);
// End: Defines
class getID3
{
// public: Settings
public $encoding = 'UTF-8'; // CASE SENSITIVE! - i.e. (must be supported by iconv()). Examples: ISO-8859-1 UTF-8 UTF-16 UTF-16BE
public $encoding_id3v1 = 'ISO-8859-1'; // Should always be 'ISO-8859-1', but some tags may be written in other encodings such as 'EUC-CN' or 'CP1252'
// public: Optional tag checks - disable for speed.
public $option_tag_id3v1 = true; // Read and process ID3v1 tags
public $option_tag_id3v2 = true; // Read and process ID3v2 tags
public $option_tag_lyrics3 = true; // Read and process Lyrics3 tags
public $option_tag_apetag = true; // Read and process APE tags
public $option_tags_process = true; // Copy tags to root key 'tags' and encode to $this->encoding
public $option_tags_html = true; // Copy tags to root key 'tags_html' properly translated from various encodings to HTML entities
// public: Optional tag/comment calucations
public $option_extra_info = true; // Calculate additional info such as bitrate, channelmode etc
// public: Optional handling of embedded attachments (e.g. images)
public $option_save_attachments = true; // defaults to true (ATTACHMENTS_INLINE) for backward compatibility
// public: Optional calculations
public $option_md5_data = false; // Get MD5 sum of data part - slow
public $option_md5_data_source = false; // Use MD5 of source file if availble - only FLAC and OptimFROG
public $option_sha1_data = false; // Get SHA1 sum of data part - slow
public $option_max_2gb_check = null; // Check whether file is larger than 2GB and thus not supported by 32-bit PHP (null: auto-detect based on PHP_INT_MAX)
// public: Read buffer size in bytes
public $option_fread_buffer_size = 32768;
// Public variables
public $filename; // Filename of file being analysed.
public $fp; // Filepointer to file being analysed.
public $info; // Result array.
public $tempdir = GETID3_TEMP_DIR;
// Protected variables
protected $startup_error = '';
protected $startup_warning = '';
protected $memory_limit = 0;
const VERSION = '1.9.7-20130705';
const FREAD_BUFFER_SIZE = 32768;
const ATTACHMENTS_NONE = false;
const ATTACHMENTS_INLINE = true;
// public: constructor
public function __construct() {
// Check for PHP version
$required_php_version = '5.0.5';
if (version_compare(PHP_VERSION, $required_php_version, '<')) {
$this->startup_error .= 'getID3() requires PHP v'.$required_php_version.' or higher - you are running v'.PHP_VERSION;
return false;
}
// Check memory
$this->memory_limit = ini_get('memory_limit');
if (preg_match('#([0-9]+)M#i', $this->memory_limit, $matches)) {
// could be stored as "16M" rather than 16777216 for example
$this->memory_limit = $matches[1] * 1048576;
} elseif (preg_match('#([0-9]+)G#i', $this->memory_limit, $matches)) { // The 'G' modifier is available since PHP 5.1.0
// could be stored as "2G" rather than 2147483648 for example
$this->memory_limit = $matches[1] * 1073741824;
}
if ($this->memory_limit <= 0) {
// memory limits probably disabled
} elseif ($this->memory_limit <= 4194304) {
$this->startup_error .= 'PHP has less than 4MB available memory and will very likely run out. Increase memory_limit in php.ini';
} elseif ($this->memory_limit <= 12582912) {
$this->startup_warning .= 'PHP has less than 12MB available memory and might run out if all modules are loaded. Increase memory_limit in php.ini';
}
// Check safe_mode off
if (preg_match('#(1|ON)#i', ini_get('safe_mode'))) {
$this->warning('WARNING: Safe mode is on, shorten support disabled, md5data/sha1data for ogg vorbis disabled, ogg vorbos/flac tag writing disabled.');
}
if (intval(ini_get('mbstring.func_overload')) > 0) {
$this->warning('WARNING: php.ini contains "mbstring.func_overload = '.ini_get('mbstring.func_overload').'", this may break things.');
}
// Check for magic_quotes_runtime
if (function_exists('get_magic_quotes_runtime')) {
if (get_magic_quotes_runtime()) {
return $this->startup_error('magic_quotes_runtime must be disabled before running getID3(). Surround getid3 block by set_magic_quotes_runtime(0) and set_magic_quotes_runtime(1).');
}
}
// Check for magic_quotes_gpc
if (function_exists('magic_quotes_gpc')) {
if (get_magic_quotes_gpc()) {
return $this->startup_error('magic_quotes_gpc must be disabled before running getID3(). Surround getid3 block by set_magic_quotes_gpc(0) and set_magic_quotes_gpc(1).');
}
}
// Load support library
if (!include_once(GETID3_INCLUDEPATH.'getid3.lib.php')) {
$this->startup_error .= 'getid3.lib.php is missing or corrupt';
}
if ($this->option_max_2gb_check === null) {
$this->option_max_2gb_check = (PHP_INT_MAX <= 2147483647);
}
// Needed for Windows only:
// Define locations of helper applications for Shorten, VorbisComment, MetaFLAC
// as well as other helper functions such as head, tail, md5sum, etc
// This path cannot contain spaces, but the below code will attempt to get the
// 8.3-equivalent path automatically
// IMPORTANT: This path must include the trailing slash
if (GETID3_OS_ISWINDOWS && !defined('GETID3_HELPERAPPSDIR')) {
$helperappsdir = GETID3_INCLUDEPATH.'..'.DIRECTORY_SEPARATOR.'helperapps'; // must not have any space in this path
if (!is_dir($helperappsdir)) {
$this->startup_warning .= '"'.$helperappsdir.'" cannot be defined as GETID3_HELPERAPPSDIR because it does not exist';
} elseif (strpos(realpath($helperappsdir), ' ') !== false) {
$DirPieces = explode(DIRECTORY_SEPARATOR, realpath($helperappsdir));
$path_so_far = array();
foreach ($DirPieces as $key => $value) {
if (strpos($value, ' ') !== false) {
if (!empty($path_so_far)) {
$commandline = 'dir /x '.escapeshellarg(implode(DIRECTORY_SEPARATOR, $path_so_far));
$dir_listing = `$commandline`;
$lines = explode("\n", $dir_listing);
foreach ($lines as $line) {
$line = trim($line);
if (preg_match('#^([0-9/]{10}) +([0-9:]{4,5}( [AP]M)?) +(<DIR>|[0-9,]+) +([^ ]{0,11}) +(.+)$#', $line, $matches)) {
list($dummy, $date, $time, $ampm, $filesize, $shortname, $filename) = $matches;
if ((strtoupper($filesize) == '<DIR>') && (strtolower($filename) == strtolower($value))) {
$value = $shortname;
}
}
}
} else {
$this->startup_warning .= 'GETID3_HELPERAPPSDIR must not have any spaces in it - use 8dot3 naming convention if neccesary. You can run "dir /x" from the commandline to see the correct 8.3-style names.';
}
}
$path_so_far[] = $value;
}
$helperappsdir = implode(DIRECTORY_SEPARATOR, $path_so_far);
}
define('GETID3_HELPERAPPSDIR', $helperappsdir.DIRECTORY_SEPARATOR);
}
return true;
}
public function version() {
return self::VERSION;
}
public function fread_buffer_size() {
return $this->option_fread_buffer_size;
}
// public: setOption
public function setOption($optArray) {
if (!is_array($optArray) || empty($optArray)) {
return false;
}
foreach ($optArray as $opt => $val) {
if (isset($this->$opt) === false) {
continue;
}
$this->$opt = $val;
}
return true;
}
public function openfile($filename) {
try {
if (!empty($this->startup_error)) {
throw new getid3_exception($this->startup_error);
}
if (!empty($this->startup_warning)) {
$this->warning($this->startup_warning);
}
// init result array and set parameters
$this->filename = $filename;
$this->info = array();
$this->info['GETID3_VERSION'] = $this->version();
$this->info['php_memory_limit'] = $this->memory_limit;
// remote files not supported
if (preg_match('/^(ht|f)tp:\/\//', $filename)) {
throw new getid3_exception('Remote files are not supported - please copy the file locally first');
}
$filename = str_replace('/', DIRECTORY_SEPARATOR, $filename);
$filename = preg_replace('#(.+)'.preg_quote(DIRECTORY_SEPARATOR).'{2,}#U', '\1'.DIRECTORY_SEPARATOR, $filename);
// open local file
if (is_readable($filename) && is_file($filename) && ($this->fp = fopen($filename, 'rb'))) {
// great
} else {
throw new getid3_exception('Could not open "'.$filename.'" (does not exist, or is not a file)');
}
$this->info['filesize'] = filesize($filename);
// set redundant parameters - might be needed in some include file
$this->info['filename'] = basename($filename);
$this->info['filepath'] = str_replace('\\', '/', realpath(dirname($filename)));
$this->info['filenamepath'] = $this->info['filepath'].'/'.$this->info['filename'];
// option_max_2gb_check
if ($this->option_max_2gb_check) {
// PHP (32-bit all, and 64-bit Windows) doesn't support integers larger than 2^31 (~2GB)
// filesize() simply returns (filesize % (pow(2, 32)), no matter the actual filesize
// ftell() returns 0 if seeking to the end is beyond the range of unsigned integer
$fseek = fseek($this->fp, 0, SEEK_END);
if (($fseek < 0) || (($this->info['filesize'] != 0) && (ftell($this->fp) == 0)) ||
($this->info['filesize'] < 0) ||
(ftell($this->fp) < 0)) {
$real_filesize = getid3_lib::getFileSizeSyscall($this->info['filenamepath']);
if ($real_filesize === false) {
unset($this->info['filesize']);
fclose($this->fp);
throw new getid3_exception('Unable to determine actual filesize. File is most likely larger than '.round(PHP_INT_MAX / 1073741824).'GB and is not supported by PHP.');
} elseif (getid3_lib::intValueSupported($real_filesize)) {
unset($this->info['filesize']);
fclose($this->fp);
throw new getid3_exception('PHP seems to think the file is larger than '.round(PHP_INT_MAX / 1073741824).'GB, but filesystem reports it as '.number_format($real_filesize, 3).'GB, please report to info@getid3.org');
}
$this->info['filesize'] = $real_filesize;
$this->warning('File is larger than '.round(PHP_INT_MAX / 1073741824).'GB (filesystem reports it as '.number_format($real_filesize, 3).'GB) and is not properly supported by PHP.');
}
}
// set more parameters
$this->info['avdataoffset'] = 0;
$this->info['avdataend'] = $this->info['filesize'];
$this->info['fileformat'] = ''; // filled in later
$this->info['audio']['dataformat'] = ''; // filled in later, unset if not used
$this->info['video']['dataformat'] = ''; // filled in later, unset if not used
$this->info['tags'] = array(); // filled in later, unset if not used
$this->info['error'] = array(); // filled in later, unset if not used
$this->info['warning'] = array(); // filled in later, unset if not used
$this->info['comments'] = array(); // filled in later, unset if not used
$this->info['encoding'] = $this->encoding; // required by id3v2 and iso modules - can be unset at the end if desired
return true;
} catch (Exception $e) {
$this->error($e->getMessage());
}
return false;
}
// public: analyze file
public function analyze($filename) {
try {
if (!$this->openfile($filename)) {
return $this->info;
}
// Handle tags
foreach (array('id3v2'=>'id3v2', 'id3v1'=>'id3v1', 'apetag'=>'ape', 'lyrics3'=>'lyrics3') as $tag_name => $tag_key) {
$option_tag = 'option_tag_'.$tag_name;
if ($this->$option_tag) {
$this->include_module('tag.'.$tag_name);
try {
$tag_class = 'getid3_'.$tag_name;
$tag = new $tag_class($this);
$tag->Analyze();
}
catch (getid3_exception $e) {
throw $e;
}
}
}
if (isset($this->info['id3v2']['tag_offset_start'])) {
$this->info['avdataoffset'] = max($this->info['avdataoffset'], $this->info['id3v2']['tag_offset_end']);
}
foreach (array('id3v1'=>'id3v1', 'apetag'=>'ape', 'lyrics3'=>'lyrics3') as $tag_name => $tag_key) {
if (isset($this->info[$tag_key]['tag_offset_start'])) {
$this->info['avdataend'] = min($this->info['avdataend'], $this->info[$tag_key]['tag_offset_start']);
}
}
// ID3v2 detection (NOT parsing), even if ($this->option_tag_id3v2 == false) done to make fileformat easier
if (!$this->option_tag_id3v2) {
fseek($this->fp, 0, SEEK_SET);
$header = fread($this->fp, 10);
if ((substr($header, 0, 3) == 'ID3') && (strlen($header) == 10)) {
$this->info['id3v2']['header'] = true;
$this->info['id3v2']['majorversion'] = ord($header{3});
$this->info['id3v2']['minorversion'] = ord($header{4});
$this->info['avdataoffset'] += getid3_lib::BigEndian2Int(substr($header, 6, 4), 1) + 10; // length of ID3v2 tag in 10-byte header doesn't include 10-byte header length
}
}
// read 32 kb file data
fseek($this->fp, $this->info['avdataoffset'], SEEK_SET);
$formattest = fread($this->fp, 32774);
// determine format
$determined_format = $this->GetFileFormat($formattest, $filename);
// unable to determine file format
if (!$determined_format) {
fclose($this->fp);
return $this->error('unable to determine file format');
}
// check for illegal ID3 tags
if (isset($determined_format['fail_id3']) && (in_array('id3v1', $this->info['tags']) || in_array('id3v2', $this->info['tags']))) {
if ($determined_format['fail_id3'] === 'ERROR') {
fclose($this->fp);
return $this->error('ID3 tags not allowed on this file type.');
} elseif ($determined_format['fail_id3'] === 'WARNING') {
$this->warning('ID3 tags not allowed on this file type.');
}
}
// check for illegal APE tags
if (isset($determined_format['fail_ape']) && in_array('ape', $this->info['tags'])) {
if ($determined_format['fail_ape'] === 'ERROR') {
fclose($this->fp);
return $this->error('APE tags not allowed on this file type.');
} elseif ($determined_format['fail_ape'] === 'WARNING') {
$this->warning('APE tags not allowed on this file type.');
}
}
// set mime type
$this->info['mime_type'] = $determined_format['mime_type'];
// supported format signature pattern detected, but module deleted
if (!file_exists(GETID3_INCLUDEPATH.$determined_format['include'])) {
fclose($this->fp);
return $this->error('Format not supported, module "'.$determined_format['include'].'" was removed.');
}
// module requires iconv support
// Check encoding/iconv support
if (!empty($determined_format['iconv_req']) && !function_exists('iconv') && !in_array($this->encoding, array('ISO-8859-1', 'UTF-8', 'UTF-16LE', 'UTF-16BE', 'UTF-16'))) {
$errormessage = 'iconv() support is required for this module ('.$determined_format['include'].') for encodings other than ISO-8859-1, UTF-8, UTF-16LE, UTF16-BE, UTF-16. ';
if (GETID3_OS_ISWINDOWS) {
$errormessage .= 'PHP does not have iconv() support. Please enable php_iconv.dll in php.ini, and copy iconv.dll from c:/php/dlls to c:/windows/system32';
} else {
$errormessage .= 'PHP is not compiled with iconv() support. Please recompile with the --with-iconv switch';
}
return $this->error($errormessage);
}
// include module
include_once(GETID3_INCLUDEPATH.$determined_format['include']);
// instantiate module class
$class_name = 'getid3_'.$determined_format['module'];
if (!class_exists($class_name)) {
return $this->error('Format not supported, module "'.$determined_format['include'].'" is corrupt.');
}
$class = new $class_name($this);
$class->Analyze();
unset($class);
// close file
fclose($this->fp);
// process all tags - copy to 'tags' and convert charsets
if ($this->option_tags_process) {
$this->HandleAllTags();
}
// perform more calculations
if ($this->option_extra_info) {
$this->ChannelsBitratePlaytimeCalculations();
$this->CalculateCompressionRatioVideo();
$this->CalculateCompressionRatioAudio();
$this->CalculateReplayGain();
$this->ProcessAudioStreams();
}
// get the MD5 sum of the audio/video portion of the file - without ID3/APE/Lyrics3/etc header/footer tags
if ($this->option_md5_data) {
// do not calc md5_data if md5_data_source is present - set by flac only - future MPC/SV8 too
if (!$this->option_md5_data_source || empty($this->info['md5_data_source'])) {
$this->getHashdata('md5');
}
}
// get the SHA1 sum of the audio/video portion of the file - without ID3/APE/Lyrics3/etc header/footer tags
if ($this->option_sha1_data) {
$this->getHashdata('sha1');
}
// remove undesired keys
$this->CleanUp();
} catch (Exception $e) {
$this->error('Caught exception: '.$e->getMessage());
}
// return info array
return $this->info;
}
// private: error handling
public function error($message) {
$this->CleanUp();
if (!isset($this->info['error'])) {
$this->info['error'] = array();
}
$this->info['error'][] = $message;
return $this->info;
}
// private: warning handling
public function warning($message) {
$this->info['warning'][] = $message;
return true;
}
// private: CleanUp
private function CleanUp() {
// remove possible empty keys
$AVpossibleEmptyKeys = array('dataformat', 'bits_per_sample', 'encoder_options', 'streams', 'bitrate');
foreach ($AVpossibleEmptyKeys as $dummy => $key) {
if (empty($this->info['audio'][$key]) && isset($this->info['audio'][$key])) {
unset($this->info['audio'][$key]);
}
if (empty($this->info['video'][$key]) && isset($this->info['video'][$key])) {
unset($this->info['video'][$key]);
}
}
// remove empty root keys
if (!empty($this->info)) {
foreach ($this->info as $key => $value) {
if (empty($this->info[$key]) && ($this->info[$key] !== 0) && ($this->info[$key] !== '0')) {
unset($this->info[$key]);
}
}
}
// remove meaningless entries from unknown-format files
if (empty($this->info['fileformat'])) {
if (isset($this->info['avdataoffset'])) {
unset($this->info['avdataoffset']);
}
if (isset($this->info['avdataend'])) {
unset($this->info['avdataend']);
}
}
// remove possible duplicated identical entries
if (!empty($this->info['error'])) {
$this->info['error'] = array_values(array_unique($this->info['error']));
}
if (!empty($this->info['warning'])) {
$this->info['warning'] = array_values(array_unique($this->info['warning']));
}
// remove "global variable" type keys
unset($this->info['php_memory_limit']);
return true;
}
// return array containing information about all supported formats
public function GetFileFormatArray() {
static $format_info = array();
if (empty($format_info)) {
$format_info = array(
// Audio formats
// AC-3 - audio - Dolby AC-3 / Dolby Digital
'ac3' => array(
'pattern' => '^\x0B\x77',
'group' => 'audio',
'module' => 'ac3',
'mime_type' => 'audio/ac3',
),
// AAC - audio - Advanced Audio Coding (AAC) - ADIF format
'adif' => array(
'pattern' => '^ADIF',
'group' => 'audio',
'module' => 'aac',
'mime_type' => 'application/octet-stream',
'fail_ape' => 'WARNING',
),
/*
// AA - audio - Audible Audiobook
'aa' => array(
'pattern' => '^.{4}\x57\x90\x75\x36',
'group' => 'audio',
'module' => 'aa',
'mime_type' => 'audio/audible',
),
*/
// AAC - audio - Advanced Audio Coding (AAC) - ADTS format (very similar to MP3)
'adts' => array(
'pattern' => '^\xFF[\xF0-\xF1\xF8-\xF9]',
'group' => 'audio',
'module' => 'aac',
'mime_type' => 'application/octet-stream',
'fail_ape' => 'WARNING',
),
// AU - audio - NeXT/Sun AUdio (AU)
'au' => array(
'pattern' => '^\.snd',
'group' => 'audio',
'module' => 'au',
'mime_type' => 'audio/basic',
),
// AVR - audio - Audio Visual Research
'avr' => array(
'pattern' => '^2BIT',
'group' => 'audio',
'module' => 'avr',
'mime_type' => 'application/octet-stream',
),
// BONK - audio - Bonk v0.9+
'bonk' => array(
'pattern' => '^\x00(BONK|INFO|META| ID3)',
'group' => 'audio',
'module' => 'bonk',
'mime_type' => 'audio/xmms-bonk',
),
// DSS - audio - Digital Speech Standard
'dss' => array(
'pattern' => '^[\x02-\x03]ds[s2]',
'group' => 'audio',
'module' => 'dss',
'mime_type' => 'application/octet-stream',
),
// DTS - audio - Dolby Theatre System
'dts' => array(
'pattern' => '^\x7F\xFE\x80\x01',
'group' => 'audio',
'module' => 'dts',
'mime_type' => 'audio/dts',
),
// FLAC - audio - Free Lossless Audio Codec
'flac' => array(
'pattern' => '^fLaC',
'group' => 'audio',
'module' => 'flac',
'mime_type' => 'audio/x-flac',
),
// LA - audio - Lossless Audio (LA)
'la' => array(
'pattern' => '^LA0[2-4]',
'group' => 'audio',
'module' => 'la',
'mime_type' => 'application/octet-stream',
),
// LPAC - audio - Lossless Predictive Audio Compression (LPAC)
'lpac' => array(
'pattern' => '^LPAC',
'group' => 'audio',
'module' => 'lpac',
'mime_type' => 'application/octet-stream',
),
// MIDI - audio - MIDI (Musical Instrument Digital Interface)
'midi' => array(
'pattern' => '^MThd',
'group' => 'audio',
'module' => 'midi',
'mime_type' => 'audio/midi',
),
// MAC - audio - Monkey's Audio Compressor
'mac' => array(
'pattern' => '^MAC ',
'group' => 'audio',
'module' => 'monkey',
'mime_type' => 'application/octet-stream',
),
// has been known to produce false matches in random files (e.g. JPEGs), leave out until more precise matching available
// // MOD - audio - MODule (assorted sub-formats)
// 'mod' => array(
// 'pattern' => '^.{1080}(M\\.K\\.|M!K!|FLT4|FLT8|[5-9]CHN|[1-3][0-9]CH)',
// 'group' => 'audio',
// 'module' => 'mod',
// 'option' => 'mod',
// 'mime_type' => 'audio/mod',
// ),
// MOD - audio - MODule (Impulse Tracker)
'it' => array(
'pattern' => '^IMPM',
'group' => 'audio',
'module' => 'mod',
//'option' => 'it',
'mime_type' => 'audio/it',
),
// MOD - audio - MODule (eXtended Module, various sub-formats)
'xm' => array(
'pattern' => '^Extended Module',
'group' => 'audio',
'module' => 'mod',
//'option' => 'xm',
'mime_type' => 'audio/xm',
),
// MOD - audio - MODule (ScreamTracker)
's3m' => array(
'pattern' => '^.{44}SCRM',
'group' => 'audio',
'module' => 'mod',
//'option' => 's3m',
'mime_type' => 'audio/s3m',
),
// MPC - audio - Musepack / MPEGplus
'mpc' => array(
'pattern' => '^(MPCK|MP\+|[\x00\x01\x10\x11\x40\x41\x50\x51\x80\x81\x90\x91\xC0\xC1\xD0\xD1][\x20-37][\x00\x20\x40\x60\x80\xA0\xC0\xE0])',
'group' => 'audio',
'module' => 'mpc',
'mime_type' => 'audio/x-musepack',
),
// MP3 - audio - MPEG-audio Layer 3 (very similar to AAC-ADTS)
'mp3' => array(
'pattern' => '^\xFF[\xE2-\xE7\xF2-\xF7\xFA-\xFF][\x00-\x0B\x10-\x1B\x20-\x2B\x30-\x3B\x40-\x4B\x50-\x5B\x60-\x6B\x70-\x7B\x80-\x8B\x90-\x9B\xA0-\xAB\xB0-\xBB\xC0-\xCB\xD0-\xDB\xE0-\xEB\xF0-\xFB]',
'group' => 'audio',
'module' => 'mp3',
'mime_type' => 'audio/mpeg',
),
// OFR - audio - OptimFROG
'ofr' => array(
'pattern' => '^(\*RIFF|OFR)',
'group' => 'audio',
'module' => 'optimfrog',
'mime_type' => 'application/octet-stream',
),
// RKAU - audio - RKive AUdio compressor
'rkau' => array(
'pattern' => '^RKA',
'group' => 'audio',
'module' => 'rkau',
'mime_type' => 'application/octet-stream',
),
// SHN - audio - Shorten
'shn' => array(
'pattern' => '^ajkg',
'group' => 'audio',
'module' => 'shorten',
'mime_type' => 'audio/xmms-shn',
'fail_id3' => 'ERROR',
'fail_ape' => 'ERROR',
),
// TTA - audio - TTA Lossless Audio Compressor (http://tta.corecodec.org)
'tta' => array(
'pattern' => '^TTA', // could also be '^TTA(\x01|\x02|\x03|2|1)'
'group' => 'audio',
'module' => 'tta',
'mime_type' => 'application/octet-stream',
),
// VOC - audio - Creative Voice (VOC)
'voc' => array(
'pattern' => '^Creative Voice File',
'group' => 'audio',
'module' => 'voc',
'mime_type' => 'audio/voc',
),
// VQF - audio - transform-domain weighted interleave Vector Quantization Format (VQF)
'vqf' => array(
'pattern' => '^TWIN',
'group' => 'audio',
'module' => 'vqf',
'mime_type' => 'application/octet-stream',
),
// WV - audio - WavPack (v4.0+)
'wv' => array(
'pattern' => '^wvpk',
'group' => 'audio',
'module' => 'wavpack',
'mime_type' => 'application/octet-stream',
),
// Audio-Video formats
// ASF - audio/video - Advanced Streaming Format, Windows Media Video, Windows Media Audio
'asf' => array(
'pattern' => '^\x30\x26\xB2\x75\x8E\x66\xCF\x11\xA6\xD9\x00\xAA\x00\x62\xCE\x6C',
'group' => 'audio-video',
'module' => 'asf',
'mime_type' => 'video/x-ms-asf',
'iconv_req' => false,
),
// BINK - audio/video - Bink / Smacker
'bink' => array(
'pattern' => '^(BIK|SMK)',
'group' => 'audio-video',
'module' => 'bink',
'mime_type' => 'application/octet-stream',
),
// FLV - audio/video - FLash Video
'flv' => array(
'pattern' => '^FLV\x01',
'group' => 'audio-video',
'module' => 'flv',
'mime_type' => 'video/x-flv',
),
// MKAV - audio/video - Mastroka
'matroska' => array(
'pattern' => '^\x1A\x45\xDF\xA3',
'group' => 'audio-video',
'module' => 'matroska',
'mime_type' => 'video/x-matroska', // may also be audio/x-matroska
),
// MPEG - audio/video - MPEG (Moving Pictures Experts Group)
'mpeg' => array(
'pattern' => '^\x00\x00\x01(\xBA|\xB3)',
'group' => 'audio-video',
'module' => 'mpeg',
'mime_type' => 'video/mpeg',
),
// NSV - audio/video - Nullsoft Streaming Video (NSV)
'nsv' => array(
'pattern' => '^NSV[sf]',
'group' => 'audio-video',
'module' => 'nsv',
'mime_type' => 'application/octet-stream',
),
// Ogg - audio/video - Ogg (Ogg-Vorbis, Ogg-FLAC, Speex, Ogg-Theora(*), Ogg-Tarkin(*))
'ogg' => array(
'pattern' => '^OggS',
'group' => 'audio',
'module' => 'ogg',
'mime_type' => 'application/ogg',
'fail_id3' => 'WARNING',
'fail_ape' => 'WARNING',
),
// QT - audio/video - Quicktime
'quicktime' => array(
'pattern' => '^.{4}(cmov|free|ftyp|mdat|moov|pnot|skip|wide)',
'group' => 'audio-video',
'module' => 'quicktime',
'mime_type' => 'video/quicktime',
),
// RIFF - audio/video - Resource Interchange File Format (RIFF) / WAV / AVI / CD-audio / SDSS = renamed variant used by SmartSound QuickTracks (www.smartsound.com) / FORM = Audio Interchange File Format (AIFF)
'riff' => array(
'pattern' => '^(RIFF|SDSS|FORM)',
'group' => 'audio-video',
'module' => 'riff',
'mime_type' => 'audio/x-wave',
'fail_ape' => 'WARNING',
),
// Real - audio/video - RealAudio, RealVideo
'real' => array(
'pattern' => '^(\\.RMF|\\.ra)',
'group' => 'audio-video',
'module' => 'real',
'mime_type' => 'audio/x-realaudio',
),
// SWF - audio/video - ShockWave Flash
'swf' => array(
'pattern' => '^(F|C)WS',
'group' => 'audio-video',
'module' => 'swf',
'mime_type' => 'application/x-shockwave-flash',
),
// TS - audio/video - MPEG-2 Transport Stream
'ts' => array(
'pattern' => '^(\x47.{187}){10,}', // packets are 188 bytes long and start with 0x47 "G". Check for at least 10 packets matching this pattern
'group' => 'audio-video',
'module' => 'ts',
'mime_type' => 'video/MP2T',
),
// Still-Image formats
// BMP - still image - Bitmap (Windows, OS/2; uncompressed, RLE8, RLE4)
'bmp' => array(
'pattern' => '^BM',
'group' => 'graphic',
'module' => 'bmp',
'mime_type' => 'image/bmp',
'fail_id3' => 'ERROR',
'fail_ape' => 'ERROR',
),
// GIF - still image - Graphics Interchange Format
'gif' => array(
'pattern' => '^GIF',
'group' => 'graphic',
'module' => 'gif',
'mime_type' => 'image/gif',
'fail_id3' => 'ERROR',
'fail_ape' => 'ERROR',
),
// JPEG - still image - Joint Photographic Experts Group (JPEG)
'jpg' => array(
'pattern' => '^\xFF\xD8\xFF',
'group' => 'graphic',
'module' => 'jpg',
'mime_type' => 'image/jpeg',
'fail_id3' => 'ERROR',
'fail_ape' => 'ERROR',
),
// PCD - still image - Kodak Photo CD
'pcd' => array(
'pattern' => '^.{2048}PCD_IPI\x00',
'group' => 'graphic',
'module' => 'pcd',
'mime_type' => 'image/x-photo-cd',
'fail_id3' => 'ERROR',
'fail_ape' => 'ERROR',
),
// PNG - still image - Portable Network Graphics (PNG)
'png' => array(
'pattern' => '^\x89\x50\x4E\x47\x0D\x0A\x1A\x0A',
'group' => 'graphic',
'module' => 'png',
'mime_type' => 'image/png',
'fail_id3' => 'ERROR',
'fail_ape' => 'ERROR',
),
// SVG - still image - Scalable Vector Graphics (SVG)
'svg' => array(
'pattern' => '(<!DOCTYPE svg PUBLIC |xmlns="http:\/\/www\.w3\.org\/2000\/svg")',
'group' => 'graphic',
'module' => 'svg',
'mime_type' => 'image/svg+xml',
'fail_id3' => 'ERROR',
'fail_ape' => 'ERROR',
),
// TIFF - still image - Tagged Information File Format (TIFF)
'tiff' => array(
'pattern' => '^(II\x2A\x00|MM\x00\x2A)',
'group' => 'graphic',
'module' => 'tiff',
'mime_type' => 'image/tiff',
'fail_id3' => 'ERROR',
'fail_ape' => 'ERROR',
),
// EFAX - still image - eFax (TIFF derivative)
'efax' => array(
'pattern' => '^\xDC\xFE',
'group' => 'graphic',
'module' => 'efax',
'mime_type' => 'image/efax',
'fail_id3' => 'ERROR',
'fail_ape' => 'ERROR',
),
// Data formats
// ISO - data - International Standards Organization (ISO) CD-ROM Image
'iso' => array(
'pattern' => '^.{32769}CD001',
'group' => 'misc',
'module' => 'iso',
'mime_type' => 'application/octet-stream',
'fail_id3' => 'ERROR',
'fail_ape' => 'ERROR',
'iconv_req' => false,
),
// RAR - data - RAR compressed data
'rar' => array(
'pattern' => '^Rar\!',
'group' => 'archive',
'module' => 'rar',
'mime_type' => 'application/octet-stream',
'fail_id3' => 'ERROR',
'fail_ape' => 'ERROR',
),
// SZIP - audio/data - SZIP compressed data
'szip' => array(
'pattern' => '^SZ\x0A\x04',
'group' => 'archive',
'module' => 'szip',
'mime_type' => 'application/octet-stream',
'fail_id3' => 'ERROR',
'fail_ape' => 'ERROR',
),
// TAR - data - TAR compressed data
'tar' => array(
'pattern' => '^.{100}[0-9\x20]{7}\x00[0-9\x20]{7}\x00[0-9\x20]{7}\x00[0-9\x20\x00]{12}[0-9\x20\x00]{12}',
'group' => 'archive',
'module' => 'tar',
'mime_type' => 'application/x-tar',
'fail_id3' => 'ERROR',
'fail_ape' => 'ERROR',
),
// GZIP - data - GZIP compressed data
'gz' => array(
'pattern' => '^\x1F\x8B\x08',
'group' => 'archive',
'module' => 'gzip',
'mime_type' => 'application/x-gzip',
'fail_id3' => 'ERROR',
'fail_ape' => 'ERROR',
),
// ZIP - data - ZIP compressed data
'zip' => array(
'pattern' => '^PK\x03\x04',
'group' => 'archive',
'module' => 'zip',
'mime_type' => 'application/zip',
'fail_id3' => 'ERROR',
'fail_ape' => 'ERROR',
),
// Misc other formats
// PAR2 - data - Parity Volume Set Specification 2.0
'par2' => array (
'pattern' => '^PAR2\x00PKT',
'group' => 'misc',
'module' => 'par2',
'mime_type' => 'application/octet-stream',
'fail_id3' => 'ERROR',
'fail_ape' => 'ERROR',
),
// PDF - data - Portable Document Format
'pdf' => array(
'pattern' => '^\x25PDF',
'group' => 'misc',
'module' => 'pdf',
'mime_type' => 'application/pdf',
'fail_id3' => 'ERROR',
'fail_ape' => 'ERROR',
),
// MSOFFICE - data - ZIP compressed data
'msoffice' => array(
'pattern' => '^\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1', // D0CF11E == DOCFILE == Microsoft Office Document
'group' => 'misc',
'module' => 'msoffice',
'mime_type' => 'application/octet-stream',
'fail_id3' => 'ERROR',
'fail_ape' => 'ERROR',
),
// CUE - data - CUEsheet (index to single-file disc images)
'cue' => array(
'pattern' => '', // empty pattern means cannot be automatically detected, will fall through all other formats and match based on filename and very basic file contents
'group' => 'misc',
'module' => 'cue',
'mime_type' => 'application/octet-stream',
),
);
}
return $format_info;
}
public function GetFileFormat(&$filedata, $filename='') {
// this function will determine the format of a file based on usually
// the first 2-4 bytes of the file (8 bytes for PNG, 16 bytes for JPG,
// and in the case of ISO CD image, 6 bytes offset 32kb from the start
// of the file).
// Identify file format - loop through $format_info and detect with reg expr
foreach ($this->GetFileFormatArray() as $format_name => $info) {
// The /s switch on preg_match() forces preg_match() NOT to treat
// newline (0x0A) characters as special chars but do a binary match
if (!empty($info['pattern']) && preg_match('#'.$info['pattern'].'#s', $filedata)) {
$info['include'] = 'module.'.$info['group'].'.'.$info['module'].'.php';
return $info;
}
}
if (preg_match('#\.mp[123a]$#i', $filename)) {
// Too many mp3 encoders on the market put gabage in front of mpeg files
// use assume format on these if format detection failed
$GetFileFormatArray = $this->GetFileFormatArray();
$info = $GetFileFormatArray['mp3'];
$info['include'] = 'module.'.$info['group'].'.'.$info['module'].'.php';
return $info;
} elseif (preg_match('/\.cue$/i', $filename) && preg_match('#FILE "[^"]+" (BINARY|MOTOROLA|AIFF|WAVE|MP3)#', $filedata)) {
// there's not really a useful consistent "magic" at the beginning of .cue files to identify them
// so until I think of something better, just go by filename if all other format checks fail
// and verify there's at least one instance of "TRACK xx AUDIO" in the file
$GetFileFormatArray = $this->GetFileFormatArray();
$info = $GetFileFormatArray['cue'];
$info['include'] = 'module.'.$info['group'].'.'.$info['module'].'.php';
return $info;
}
return false;
}
// converts array to $encoding charset from $this->encoding
public function CharConvert(&$array, $encoding) {
// identical encoding - end here
if ($encoding == $this->encoding) {
return;
}
// loop thru array
foreach ($array as $key => $value) {
// go recursive
if (is_array($value)) {
$this->CharConvert($array[$key], $encoding);
}
// convert string
elseif (is_string($value)) {
$array[$key] = trim(getid3_lib::iconv_fallback($encoding, $this->encoding, $value));
}
}
}
public function HandleAllTags() {
// key name => array (tag name, character encoding)
static $tags;
if (empty($tags)) {
$tags = array(
'asf' => array('asf' , 'UTF-16LE'),
'midi' => array('midi' , 'ISO-8859-1'),
'nsv' => array('nsv' , 'ISO-8859-1'),
'ogg' => array('vorbiscomment' , 'UTF-8'),
'png' => array('png' , 'UTF-8'),
'tiff' => array('tiff' , 'ISO-8859-1'),
'quicktime' => array('quicktime' , 'UTF-8'),
'real' => array('real' , 'ISO-8859-1'),
'vqf' => array('vqf' , 'ISO-8859-1'),
'zip' => array('zip' , 'ISO-8859-1'),
'riff' => array('riff' , 'ISO-8859-1'),
'lyrics3' => array('lyrics3' , 'ISO-8859-1'),
'id3v1' => array('id3v1' , $this->encoding_id3v1),
'id3v2' => array('id3v2' , 'UTF-8'), // not according to the specs (every frame can have a different encoding), but getID3() force-converts all encodings to UTF-8
'ape' => array('ape' , 'UTF-8'),
'cue' => array('cue' , 'ISO-8859-1'),
'matroska' => array('matroska' , 'UTF-8'),
'flac' => array('vorbiscomment' , 'UTF-8'),
'divxtag' => array('divx' , 'ISO-8859-1'),
);
}
// loop through comments array
foreach ($tags as $comment_name => $tagname_encoding_array) {
list($tag_name, $encoding) = $tagname_encoding_array;
// fill in default encoding type if not already present
if (isset($this->info[$comment_name]) && !isset($this->info[$comment_name]['encoding'])) {
$this->info[$comment_name]['encoding'] = $encoding;
}
// copy comments if key name set
if (!empty($this->info[$comment_name]['comments'])) {
foreach ($this->info[$comment_name]['comments'] as $tag_key => $valuearray) {
foreach ($valuearray as $key => $value) {
if (is_string($value)) {
$value = trim($value, " \r\n\t"); // do not trim nulls from $value!! Unicode characters will get mangled if trailing nulls are removed!
}
if ($value) {
$this->info['tags'][trim($tag_name)][trim($tag_key)][] = $value;
}
}
if ($tag_key == 'picture') {
unset($this->info[$comment_name]['comments'][$tag_key]);
}
}
if (!isset($this->info['tags'][$tag_name])) {
// comments are set but contain nothing but empty strings, so skip
continue;
}
if ($this->option_tags_html) {
foreach ($this->info['tags'][$tag_name] as $tag_key => $valuearray) {
foreach ($valuearray as $key => $value) {
if (is_string($value)) {
//$this->info['tags_html'][$tag_name][$tag_key][$key] = getid3_lib::MultiByteCharString2HTML($value, $encoding);
$this->info['tags_html'][$tag_name][$tag_key][$key] = str_replace('�', '', trim(getid3_lib::MultiByteCharString2HTML($value, $encoding)));
} else {
$this->info['tags_html'][$tag_name][$tag_key][$key] = $value;
}
}
}
}
$this->CharConvert($this->info['tags'][$tag_name], $encoding); // only copy gets converted!
}
}
// pictures can take up a lot of space, and we don't need multiple copies of them
// let there be a single copy in [comments][picture], and not elsewhere
if (!empty($this->info['tags'])) {
$unset_keys = array('tags', 'tags_html');
foreach ($this->info['tags'] as $tagtype => $tagarray) {
foreach ($tagarray as $tagname => $tagdata) {
if ($tagname == 'picture') {
foreach ($tagdata as $key => $tagarray) {
$this->info['comments']['picture'][] = $tagarray;
if (isset($tagarray['data']) && isset($tagarray['image_mime'])) {
if (isset($this->info['tags'][$tagtype][$tagname][$key])) {
unset($this->info['tags'][$tagtype][$tagname][$key]);
}
if (isset($this->info['tags_html'][$tagtype][$tagname][$key])) {
unset($this->info['tags_html'][$tagtype][$tagname][$key]);
}
}
}
}
}
foreach ($unset_keys as $unset_key) {
// remove possible empty keys from (e.g. [tags][id3v2][picture])
if (empty($this->info[$unset_key][$tagtype]['picture'])) {
unset($this->info[$unset_key][$tagtype]['picture']);
}
if (empty($this->info[$unset_key][$tagtype])) {
unset($this->info[$unset_key][$tagtype]);
}
if (empty($this->info[$unset_key])) {
unset($this->info[$unset_key]);
}
}
// remove duplicate copy of picture data from (e.g. [id3v2][comments][picture])
if (isset($this->info[$tagtype]['comments']['picture'])) {
unset($this->info[$tagtype]['comments']['picture']);
}
if (empty($this->info[$tagtype]['comments'])) {
unset($this->info[$tagtype]['comments']);
}
if (empty($this->info[$tagtype])) {
unset($this->info[$tagtype]);
}
}
}
return true;
}
public function getHashdata($algorithm) {
switch ($algorithm) {
case 'md5':
case 'sha1':
break;
default:
return $this->error('bad algorithm "'.$algorithm.'" in getHashdata()');
break;
}
if (!empty($this->info['fileformat']) && !empty($this->info['dataformat']) && ($this->info['fileformat'] == 'ogg') && ($this->info['audio']['dataformat'] == 'vorbis')) {
// We cannot get an identical md5_data value for Ogg files where the comments
// span more than 1 Ogg page (compared to the same audio data with smaller
// comments) using the normal getID3() method of MD5'ing the data between the
// end of the comments and the end of the file (minus any trailing tags),
// because the page sequence numbers of the pages that the audio data is on
// do not match. Under normal circumstances, where comments are smaller than
// the nominal 4-8kB page size, then this is not a problem, but if there are
// very large comments, the only way around it is to strip off the comment
// tags with vorbiscomment and MD5 that file.
// This procedure must be applied to ALL Ogg files, not just the ones with
// comments larger than 1 page, because the below method simply MD5's the
// whole file with the comments stripped, not just the portion after the
// comments block (which is the standard getID3() method.
// The above-mentioned problem of comments spanning multiple pages and changing
// page sequence numbers likely happens for OggSpeex and OggFLAC as well, but
// currently vorbiscomment only works on OggVorbis files.
if (preg_match('#(1|ON)#i', ini_get('safe_mode'))) {
$this->warning('Failed making system call to vorbiscomment.exe - '.$algorithm.'_data is incorrect - error returned: PHP running in Safe Mode (backtick operator not available)');
$this->info[$algorithm.'_data'] = false;
} else {
// Prevent user from aborting script
$old_abort = ignore_user_abort(true);
// Create empty file
$empty = tempnam(GETID3_TEMP_DIR, 'getID3');
touch($empty);
// Use vorbiscomment to make temp file without comments
$temp = tempnam(GETID3_TEMP_DIR, 'getID3');
$file = $this->info['filenamepath'];
if (GETID3_OS_ISWINDOWS) {
if (file_exists(GETID3_HELPERAPPSDIR.'vorbiscomment.exe')) {
$commandline = '"'.GETID3_HELPERAPPSDIR.'vorbiscomment.exe" -w -c "'.$empty.'" "'.$file.'" "'.$temp.'"';
$VorbisCommentError = `$commandline`;
} else {
$VorbisCommentError = 'vorbiscomment.exe not found in '.GETID3_HELPERAPPSDIR;
}
} else {
$commandline = 'vorbiscomment -w -c "'.$empty.'" "'.$file.'" "'.$temp.'" 2>&1';
$commandline = 'vorbiscomment -w -c '.escapeshellarg($empty).' '.escapeshellarg($file).' '.escapeshellarg($temp).' 2>&1';
$VorbisCommentError = `$commandline`;
}
if (!empty($VorbisCommentError)) {
$this->info['warning'][] = 'Failed making system call to vorbiscomment(.exe) - '.$algorithm.'_data will be incorrect. If vorbiscomment is unavailable, please download from http://www.vorbis.com/download.psp and put in the getID3() directory. Error returned: '.$VorbisCommentError;
$this->info[$algorithm.'_data'] = false;
} else {
// Get hash of newly created file
switch ($algorithm) {
case 'md5':
$this->info[$algorithm.'_data'] = md5_file($temp);
break;
case 'sha1':
$this->info[$algorithm.'_data'] = sha1_file($temp);
break;
}
}
// Clean up
unlink($empty);
unlink($temp);
// Reset abort setting
ignore_user_abort($old_abort);
}
} else {
if (!empty($this->info['avdataoffset']) || (isset($this->info['avdataend']) && ($this->info['avdataend'] < $this->info['filesize']))) {
// get hash from part of file
$this->info[$algorithm.'_data'] = getid3_lib::hash_data($this->info['filenamepath'], $this->info['avdataoffset'], $this->info['avdataend'], $algorithm);
} else {
// get hash from whole file
switch ($algorithm) {
case 'md5':
$this->info[$algorithm.'_data'] = md5_file($this->info['filenamepath']);
break;
case 'sha1':
$this->info[$algorithm.'_data'] = sha1_file($this->info['filenamepath']);
break;
}
}
}
return true;
}
public function ChannelsBitratePlaytimeCalculations() {
// set channelmode on audio
if (!empty($this->info['audio']['channelmode']) || !isset($this->info['audio']['channels'])) {
// ignore
} elseif ($this->info['audio']['channels'] == 1) {
$this->info['audio']['channelmode'] = 'mono';
} elseif ($this->info['audio']['channels'] == 2) {
$this->info['audio']['channelmode'] = 'stereo';
}
// Calculate combined bitrate - audio + video
$CombinedBitrate = 0;
$CombinedBitrate += (isset($this->info['audio']['bitrate']) ? $this->info['audio']['bitrate'] : 0);
$CombinedBitrate += (isset($this->info['video']['bitrate']) ? $this->info['video']['bitrate'] : 0);
if (($CombinedBitrate > 0) && empty($this->info['bitrate'])) {
$this->info['bitrate'] = $CombinedBitrate;
}
//if ((isset($this->info['video']) && !isset($this->info['video']['bitrate'])) || (isset($this->info['audio']) && !isset($this->info['audio']['bitrate']))) {
// // for example, VBR MPEG video files cannot determine video bitrate:
// // should not set overall bitrate and playtime from audio bitrate only
// unset($this->info['bitrate']);
//}
// video bitrate undetermined, but calculable
if (isset($this->info['video']['dataformat']) && $this->info['video']['dataformat'] && (!isset($this->info['video']['bitrate']) || ($this->info['video']['bitrate'] == 0))) {
// if video bitrate not set
if (isset($this->info['audio']['bitrate']) && ($this->info['audio']['bitrate'] > 0) && ($this->info['audio']['bitrate'] == $this->info['bitrate'])) {
// AND if audio bitrate is set to same as overall bitrate
if (isset($this->info['playtime_seconds']) && ($this->info['playtime_seconds'] > 0)) {
// AND if playtime is set
if (isset($this->info['avdataend']) && isset($this->info['avdataoffset'])) {
// AND if AV data offset start/end is known
// THEN we can calculate the video bitrate
$this->info['bitrate'] = round((($this->info['avdataend'] - $this->info['avdataoffset']) * 8) / $this->info['playtime_seconds']);
$this->info['video']['bitrate'] = $this->info['bitrate'] - $this->info['audio']['bitrate'];
}
}
}
}
if ((!isset($this->info['playtime_seconds']) || ($this->info['playtime_seconds'] <= 0)) && !empty($this->info['bitrate'])) {
$this->info['playtime_seconds'] = (($this->info['avdataend'] - $this->info['avdataoffset']) * 8) / $this->info['bitrate'];
}
if (!isset($this->info['bitrate']) && !empty($this->info['playtime_seconds'])) {
$this->info['bitrate'] = (($this->info['avdataend'] - $this->info['avdataoffset']) * 8) / $this->info['playtime_seconds'];
}
if (isset($this->info['bitrate']) && empty($this->info['audio']['bitrate']) && empty($this->info['video']['bitrate'])) {
if (isset($this->info['audio']['dataformat']) && empty($this->info['video']['resolution_x'])) {
// audio only
$this->info['audio']['bitrate'] = $this->info['bitrate'];
} elseif (isset($this->info['video']['resolution_x']) && empty($this->info['audio']['dataformat'])) {
// video only
$this->info['video']['bitrate'] = $this->info['bitrate'];
}
}
// Set playtime string
if (!empty($this->info['playtime_seconds']) && empty($this->info['playtime_string'])) {
$this->info['playtime_string'] = getid3_lib::PlaytimeString($this->info['playtime_seconds']);
}
}
public function CalculateCompressionRatioVideo() {
if (empty($this->info['video'])) {
return false;
}
if (empty($this->info['video']['resolution_x']) || empty($this->info['video']['resolution_y'])) {
return false;
}
if (empty($this->info['video']['bits_per_sample'])) {
return false;
}
switch ($this->info['video']['dataformat']) {
case 'bmp':
case 'gif':
case 'jpeg':
case 'jpg':
case 'png':
case 'tiff':
$FrameRate = 1;
$PlaytimeSeconds = 1;
$BitrateCompressed = $this->info['filesize'] * 8;
break;
default:
if (!empty($this->info['video']['frame_rate'])) {
$FrameRate = $this->info['video']['frame_rate'];
} else {
return false;
}
if (!empty($this->info['playtime_seconds'])) {
$PlaytimeSeconds = $this->info['playtime_seconds'];
} else {
return false;
}
if (!empty($this->info['video']['bitrate'])) {
$BitrateCompressed = $this->info['video']['bitrate'];
} else {
return false;
}
break;
}
$BitrateUncompressed = $this->info['video']['resolution_x'] * $this->info['video']['resolution_y'] * $this->info['video']['bits_per_sample'] * $FrameRate;
$this->info['video']['compression_ratio'] = $BitrateCompressed / $BitrateUncompressed;
return true;
}
public function CalculateCompressionRatioAudio() {
if (empty($this->info['audio']['bitrate']) || empty($this->info['audio']['channels']) || empty($this->info['audio']['sample_rate']) || !is_numeric($this->info['audio']['sample_rate'])) {
return false;
}
$this->info['audio']['compression_ratio'] = $this->info['audio']['bitrate'] / ($this->info['audio']['channels'] * $this->info['audio']['sample_rate'] * (!empty($this->info['audio']['bits_per_sample']) ? $this->info['audio']['bits_per_sample'] : 16));
if (!empty($this->info['audio']['streams'])) {
foreach ($this->info['audio']['streams'] as $streamnumber => $streamdata) {
if (!empty($streamdata['bitrate']) && !empty($streamdata['channels']) && !empty($streamdata['sample_rate'])) {
$this->info['audio']['streams'][$streamnumber]['compression_ratio'] = $streamdata['bitrate'] / ($streamdata['channels'] * $streamdata['sample_rate'] * (!empty($streamdata['bits_per_sample']) ? $streamdata['bits_per_sample'] : 16));
}
}
}
return true;
}
public function CalculateReplayGain() {
if (isset($this->info['replay_gain'])) {
if (!isset($this->info['replay_gain']['reference_volume'])) {
$this->info['replay_gain']['reference_volume'] = (double) 89.0;
}
if (isset($this->info['replay_gain']['track']['adjustment'])) {
$this->info['replay_gain']['track']['volume'] = $this->info['replay_gain']['reference_volume'] - $this->info['replay_gain']['track']['adjustment'];
}
if (isset($this->info['replay_gain']['album']['adjustment'])) {
$this->info['replay_gain']['album']['volume'] = $this->info['replay_gain']['reference_volume'] - $this->info['replay_gain']['album']['adjustment'];
}
if (isset($this->info['replay_gain']['track']['peak'])) {
$this->info['replay_gain']['track']['max_noclip_gain'] = 0 - getid3_lib::RGADamplitude2dB($this->info['replay_gain']['track']['peak']);
}
if (isset($this->info['replay_gain']['album']['peak'])) {
$this->info['replay_gain']['album']['max_noclip_gain'] = 0 - getid3_lib::RGADamplitude2dB($this->info['replay_gain']['album']['peak']);
}
}
return true;
}
public function ProcessAudioStreams() {
if (!empty($this->info['audio']['bitrate']) || !empty($this->info['audio']['channels']) || !empty($this->info['audio']['sample_rate'])) {
if (!isset($this->info['audio']['streams'])) {
foreach ($this->info['audio'] as $key => $value) {
if ($key != 'streams') {
$this->info['audio']['streams'][0][$key] = $value;
}
}
}
}
return true;
}
public function getid3_tempnam() {
return tempnam($this->tempdir, 'gI3');
}
public function include_module($name) {
//if (!file_exists($this->include_path.'module.'.$name.'.php')) {
if (!file_exists(GETID3_INCLUDEPATH.'module.'.$name.'.php')) {
throw new getid3_exception('Required module.'.$name.'.php is missing.');
}
include_once(GETID3_INCLUDEPATH.'module.'.$name.'.php');
return true;
}
}
abstract class getid3_handler
{
protected $getid3; // pointer
protected $data_string_flag = false; // analyzing filepointer or string
protected $data_string = ''; // string to analyze
protected $data_string_position = 0; // seek position in string
protected $data_string_length = 0; // string length
private $dependency_to = null;
public function __construct(getID3 $getid3, $call_module=null) {
$this->getid3 = $getid3;
if ($call_module) {
$this->dependency_to = str_replace('getid3_', '', $call_module);
}
}
// Analyze from file pointer
abstract public function Analyze();
// Analyze from string instead
public function AnalyzeString($string) {
// Enter string mode
$this->setStringMode($string);
// Save info
$saved_avdataoffset = $this->getid3->info['avdataoffset'];
$saved_avdataend = $this->getid3->info['avdataend'];
$saved_filesize = (isset($this->getid3->info['filesize']) ? $this->getid3->info['filesize'] : null); // may be not set if called as dependency without openfile() call
// Reset some info
$this->getid3->info['avdataoffset'] = 0;
$this->getid3->info['avdataend'] = $this->getid3->info['filesize'] = $this->data_string_length;
// Analyze
$this->Analyze();
// Restore some info
$this->getid3->info['avdataoffset'] = $saved_avdataoffset;
$this->getid3->info['avdataend'] = $saved_avdataend;
$this->getid3->info['filesize'] = $saved_filesize;
// Exit string mode
$this->data_string_flag = false;
}
public function setStringMode($string) {
$this->data_string_flag = true;
$this->data_string = $string;
$this->data_string_length = strlen($string);
}
protected function ftell() {
if ($this->data_string_flag) {
return $this->data_string_position;
}
return ftell($this->getid3->fp);
}
protected function fread($bytes) {
if ($this->data_string_flag) {
$this->data_string_position += $bytes;
return substr($this->data_string, $this->data_string_position - $bytes, $bytes);
}
$pos = $this->ftell() + $bytes;
if (!getid3_lib::intValueSupported($pos)) {
throw new getid3_exception('cannot fread('.$bytes.' from '.$this->ftell().') because beyond PHP filesystem limit', 10);
}
return fread($this->getid3->fp, $bytes);
}
protected function fseek($bytes, $whence=SEEK_SET) {
if ($this->data_string_flag) {
switch ($whence) {
case SEEK_SET:
$this->data_string_position = $bytes;
break;
case SEEK_CUR:
$this->data_string_position += $bytes;
break;
case SEEK_END:
$this->data_string_position = $this->data_string_length + $bytes;
break;
}
return 0;
} else {
$pos = $bytes;
if ($whence == SEEK_CUR) {
$pos = $this->ftell() + $bytes;
} elseif ($whence == SEEK_END) {
$pos = $this->info['filesize'] + $bytes;
}
if (!getid3_lib::intValueSupported($pos)) {
throw new getid3_exception('cannot fseek('.$pos.') because beyond PHP filesystem limit', 10);
}
}
return fseek($this->getid3->fp, $bytes, $whence);
}
protected function feof() {
if ($this->data_string_flag) {
return $this->data_string_position >= $this->data_string_length;
}
return feof($this->getid3->fp);
}
final protected function isDependencyFor($module) {
return $this->dependency_to == $module;
}
protected function error($text)
{
$this->getid3->info['error'][] = $text;
return false;
}
protected function warning($text)
{
return $this->getid3->warning($text);
}
protected function notice($text)
{
// does nothing for now
}
public function saveAttachment($name, $offset, $length, $image_mime=null) {
try {
// do not extract at all
if ($this->getid3->option_save_attachments === getID3::ATTACHMENTS_NONE) {
$attachment = null; // do not set any
// extract to return array
} elseif ($this->getid3->option_save_attachments === getID3::ATTACHMENTS_INLINE) {
$this->fseek($offset);
$attachment = $this->fread($length); // get whole data in one pass, till it is anyway stored in memory
if ($attachment === false || strlen($attachment) != $length) {
throw new Exception('failed to read attachment data');
}
// assume directory path is given
} else {
// set up destination path
$dir = rtrim(str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $this->getid3->option_save_attachments), DIRECTORY_SEPARATOR);
if (!is_dir($dir) || !is_writable($dir)) { // check supplied directory
throw new Exception('supplied path ('.$dir.') does not exist, or is not writable');
}
$dest = $dir.DIRECTORY_SEPARATOR.$name.($image_mime ? '.'.getid3_lib::ImageExtFromMime($image_mime) : '');
// create dest file
if (($fp_dest = fopen($dest, 'wb')) == false) {
throw new Exception('failed to create file '.$dest);
}
// copy data
$this->fseek($offset);
$buffersize = ($this->data_string_flag ? $length : $this->getid3->fread_buffer_size());
$bytesleft = $length;
while ($bytesleft > 0) {
if (($buffer = $this->fread(min($buffersize, $bytesleft))) === false || ($byteswritten = fwrite($fp_dest, $buffer)) === false || ($byteswritten === 0)) {
throw new Exception($buffer === false ? 'not enough data to read' : 'failed to write to destination file, may be not enough disk space');
}
$bytesleft -= $byteswritten;
}
fclose($fp_dest);
$attachment = $dest;
}
} catch (Exception $e) {
// close and remove dest file if created
if (isset($fp_dest) && is_resource($fp_dest)) {
fclose($fp_dest);
unlink($dest);
}
// do not set any is case of error
$attachment = null;
$this->warning('Failed to extract attachment '.$name.': '.$e->getMessage());
}
// seek to the end of attachment
$this->fseek($offset + $length);
return $attachment;
}
}
class getid3_exception extends Exception
{
public $message;
} | PHP |
<?php
/////////////////////////////////////////////////////////////////
/// getID3() by James Heinrich <info@getid3.org> //
// available at http://getid3.sourceforge.net //
// or http://www.getid3.org //
/////////////////////////////////////////////////////////////////
// See readme.txt for more details //
/////////////////////////////////////////////////////////////////
/// //
// module.tag.lyrics3.php //
// module for analyzing Lyrics3 tags //
// dependencies: module.tag.apetag.php (optional) //
// ///
/////////////////////////////////////////////////////////////////
class getid3_lyrics3 extends getid3_handler
{
public function Analyze() {
$info = &$this->getid3->info;
// http://www.volweb.cz/str/tags.htm
if (!getid3_lib::intValueSupported($info['filesize'])) {
$info['warning'][] = 'Unable to check for Lyrics3 because file is larger than '.round(PHP_INT_MAX / 1073741824).'GB';
return false;
}
fseek($this->getid3->fp, (0 - 128 - 9 - 6), SEEK_END); // end - ID3v1 - "LYRICSEND" - [Lyrics3size]
$lyrics3_id3v1 = fread($this->getid3->fp, 128 + 9 + 6);
$lyrics3lsz = substr($lyrics3_id3v1, 0, 6); // Lyrics3size
$lyrics3end = substr($lyrics3_id3v1, 6, 9); // LYRICSEND or LYRICS200
$id3v1tag = substr($lyrics3_id3v1, 15, 128); // ID3v1
if ($lyrics3end == 'LYRICSEND') {
// Lyrics3v1, ID3v1, no APE
$lyrics3size = 5100;
$lyrics3offset = $info['filesize'] - 128 - $lyrics3size;
$lyrics3version = 1;
} elseif ($lyrics3end == 'LYRICS200') {
// Lyrics3v2, ID3v1, no APE
// LSZ = lyrics + 'LYRICSBEGIN'; add 6-byte size field; add 'LYRICS200'
$lyrics3size = $lyrics3lsz + 6 + strlen('LYRICS200');
$lyrics3offset = $info['filesize'] - 128 - $lyrics3size;
$lyrics3version = 2;
} elseif (substr(strrev($lyrics3_id3v1), 0, 9) == strrev('LYRICSEND')) {
// Lyrics3v1, no ID3v1, no APE
$lyrics3size = 5100;
$lyrics3offset = $info['filesize'] - $lyrics3size;
$lyrics3version = 1;
$lyrics3offset = $info['filesize'] - $lyrics3size;
} elseif (substr(strrev($lyrics3_id3v1), 0, 9) == strrev('LYRICS200')) {
// Lyrics3v2, no ID3v1, no APE
$lyrics3size = strrev(substr(strrev($lyrics3_id3v1), 9, 6)) + 6 + strlen('LYRICS200'); // LSZ = lyrics + 'LYRICSBEGIN'; add 6-byte size field; add 'LYRICS200'
$lyrics3offset = $info['filesize'] - $lyrics3size;
$lyrics3version = 2;
} else {
if (isset($info['ape']['tag_offset_start']) && ($info['ape']['tag_offset_start'] > 15)) {
fseek($this->getid3->fp, $info['ape']['tag_offset_start'] - 15, SEEK_SET);
$lyrics3lsz = fread($this->getid3->fp, 6);
$lyrics3end = fread($this->getid3->fp, 9);
if ($lyrics3end == 'LYRICSEND') {
// Lyrics3v1, APE, maybe ID3v1
$lyrics3size = 5100;
$lyrics3offset = $info['ape']['tag_offset_start'] - $lyrics3size;
$info['avdataend'] = $lyrics3offset;
$lyrics3version = 1;
$info['warning'][] = 'APE tag located after Lyrics3, will probably break Lyrics3 compatability';
} elseif ($lyrics3end == 'LYRICS200') {
// Lyrics3v2, APE, maybe ID3v1
$lyrics3size = $lyrics3lsz + 6 + strlen('LYRICS200'); // LSZ = lyrics + 'LYRICSBEGIN'; add 6-byte size field; add 'LYRICS200'
$lyrics3offset = $info['ape']['tag_offset_start'] - $lyrics3size;
$lyrics3version = 2;
$info['warning'][] = 'APE tag located after Lyrics3, will probably break Lyrics3 compatability';
}
}
}
if (isset($lyrics3offset)) {
$info['avdataend'] = $lyrics3offset;
$this->getLyrics3Data($lyrics3offset, $lyrics3version, $lyrics3size);
if (!isset($info['ape'])) {
$GETID3_ERRORARRAY = &$info['warning'];
if (getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.tag.apetag.php', __FILE__, false)) {
$getid3_temp = new getID3();
$getid3_temp->openfile($this->getid3->filename);
$getid3_apetag = new getid3_apetag($getid3_temp);
$getid3_apetag->overrideendoffset = $info['lyrics3']['tag_offset_start'];
$getid3_apetag->Analyze();
if (!empty($getid3_temp->info['ape'])) {
$info['ape'] = $getid3_temp->info['ape'];
}
if (!empty($getid3_temp->info['replay_gain'])) {
$info['replay_gain'] = $getid3_temp->info['replay_gain'];
}
unset($getid3_temp, $getid3_apetag);
}
}
}
return true;
}
public function getLyrics3Data($endoffset, $version, $length) {
// http://www.volweb.cz/str/tags.htm
$info = &$this->getid3->info;
if (!getid3_lib::intValueSupported($endoffset)) {
$info['warning'][] = 'Unable to check for Lyrics3 because file is larger than '.round(PHP_INT_MAX / 1073741824).'GB';
return false;
}
fseek($this->getid3->fp, $endoffset, SEEK_SET);
if ($length <= 0) {
return false;
}
$rawdata = fread($this->getid3->fp, $length);
$ParsedLyrics3['raw']['lyrics3version'] = $version;
$ParsedLyrics3['raw']['lyrics3tagsize'] = $length;
$ParsedLyrics3['tag_offset_start'] = $endoffset;
$ParsedLyrics3['tag_offset_end'] = $endoffset + $length - 1;
if (substr($rawdata, 0, 11) != 'LYRICSBEGIN') {
if (strpos($rawdata, 'LYRICSBEGIN') !== false) {
$info['warning'][] = '"LYRICSBEGIN" expected at '.$endoffset.' but actually found at '.($endoffset + strpos($rawdata, 'LYRICSBEGIN')).' - this is invalid for Lyrics3 v'.$version;
$info['avdataend'] = $endoffset + strpos($rawdata, 'LYRICSBEGIN');
$rawdata = substr($rawdata, strpos($rawdata, 'LYRICSBEGIN'));
$length = strlen($rawdata);
$ParsedLyrics3['tag_offset_start'] = $info['avdataend'];
$ParsedLyrics3['raw']['lyrics3tagsize'] = $length;
} else {
$info['error'][] = '"LYRICSBEGIN" expected at '.$endoffset.' but found "'.substr($rawdata, 0, 11).'" instead';
return false;
}
}
switch ($version) {
case 1:
if (substr($rawdata, strlen($rawdata) - 9, 9) == 'LYRICSEND') {
$ParsedLyrics3['raw']['LYR'] = trim(substr($rawdata, 11, strlen($rawdata) - 11 - 9));
$this->Lyrics3LyricsTimestampParse($ParsedLyrics3);
} else {
$info['error'][] = '"LYRICSEND" expected at '.(ftell($this->getid3->fp) - 11 + $length - 9).' but found "'.substr($rawdata, strlen($rawdata) - 9, 9).'" instead';
return false;
}
break;
case 2:
if (substr($rawdata, strlen($rawdata) - 9, 9) == 'LYRICS200') {
$ParsedLyrics3['raw']['unparsed'] = substr($rawdata, 11, strlen($rawdata) - 11 - 9 - 6); // LYRICSBEGIN + LYRICS200 + LSZ
$rawdata = $ParsedLyrics3['raw']['unparsed'];
while (strlen($rawdata) > 0) {
$fieldname = substr($rawdata, 0, 3);
$fieldsize = (int) substr($rawdata, 3, 5);
$ParsedLyrics3['raw'][$fieldname] = substr($rawdata, 8, $fieldsize);
$rawdata = substr($rawdata, 3 + 5 + $fieldsize);
}
if (isset($ParsedLyrics3['raw']['IND'])) {
$i = 0;
$flagnames = array('lyrics', 'timestamps', 'inhibitrandom');
foreach ($flagnames as $flagname) {
if (strlen($ParsedLyrics3['raw']['IND']) > $i++) {
$ParsedLyrics3['flags'][$flagname] = $this->IntString2Bool(substr($ParsedLyrics3['raw']['IND'], $i, 1 - 1));
}
}
}
$fieldnametranslation = array('ETT'=>'title', 'EAR'=>'artist', 'EAL'=>'album', 'INF'=>'comment', 'AUT'=>'author');
foreach ($fieldnametranslation as $key => $value) {
if (isset($ParsedLyrics3['raw'][$key])) {
$ParsedLyrics3['comments'][$value][] = trim($ParsedLyrics3['raw'][$key]);
}
}
if (isset($ParsedLyrics3['raw']['IMG'])) {
$imagestrings = explode("\r\n", $ParsedLyrics3['raw']['IMG']);
foreach ($imagestrings as $key => $imagestring) {
if (strpos($imagestring, '||') !== false) {
$imagearray = explode('||', $imagestring);
$ParsedLyrics3['images'][$key]['filename'] = (isset($imagearray[0]) ? $imagearray[0] : '');
$ParsedLyrics3['images'][$key]['description'] = (isset($imagearray[1]) ? $imagearray[1] : '');
$ParsedLyrics3['images'][$key]['timestamp'] = $this->Lyrics3Timestamp2Seconds(isset($imagearray[2]) ? $imagearray[2] : '');
}
}
}
if (isset($ParsedLyrics3['raw']['LYR'])) {
$this->Lyrics3LyricsTimestampParse($ParsedLyrics3);
}
} else {
$info['error'][] = '"LYRICS200" expected at '.(ftell($this->getid3->fp) - 11 + $length - 9).' but found "'.substr($rawdata, strlen($rawdata) - 9, 9).'" instead';
return false;
}
break;
default:
$info['error'][] = 'Cannot process Lyrics3 version '.$version.' (only v1 and v2)';
return false;
break;
}
if (isset($info['id3v1']['tag_offset_start']) && ($info['id3v1']['tag_offset_start'] <= $ParsedLyrics3['tag_offset_end'])) {
$info['warning'][] = 'ID3v1 tag information ignored since it appears to be a false synch in Lyrics3 tag data';
unset($info['id3v1']);
foreach ($info['warning'] as $key => $value) {
if ($value == 'Some ID3v1 fields do not use NULL characters for padding') {
unset($info['warning'][$key]);
sort($info['warning']);
break;
}
}
}
$info['lyrics3'] = $ParsedLyrics3;
return true;
}
public function Lyrics3Timestamp2Seconds($rawtimestamp) {
if (preg_match('#^\\[([0-9]{2}):([0-9]{2})\\]$#', $rawtimestamp, $regs)) {
return (int) (($regs[1] * 60) + $regs[2]);
}
return false;
}
public function Lyrics3LyricsTimestampParse(&$Lyrics3data) {
$lyricsarray = explode("\r\n", $Lyrics3data['raw']['LYR']);
foreach ($lyricsarray as $key => $lyricline) {
$regs = array();
unset($thislinetimestamps);
while (preg_match('#^(\\[[0-9]{2}:[0-9]{2}\\])#', $lyricline, $regs)) {
$thislinetimestamps[] = $this->Lyrics3Timestamp2Seconds($regs[0]);
$lyricline = str_replace($regs[0], '', $lyricline);
}
$notimestamplyricsarray[$key] = $lyricline;
if (isset($thislinetimestamps) && is_array($thislinetimestamps)) {
sort($thislinetimestamps);
foreach ($thislinetimestamps as $timestampkey => $timestamp) {
if (isset($Lyrics3data['synchedlyrics'][$timestamp])) {
// timestamps only have a 1-second resolution, it's possible that multiple lines
// could have the same timestamp, if so, append
$Lyrics3data['synchedlyrics'][$timestamp] .= "\r\n".$lyricline;
} else {
$Lyrics3data['synchedlyrics'][$timestamp] = $lyricline;
}
}
}
}
$Lyrics3data['unsynchedlyrics'] = implode("\r\n", $notimestamplyricsarray);
if (isset($Lyrics3data['synchedlyrics']) && is_array($Lyrics3data['synchedlyrics'])) {
ksort($Lyrics3data['synchedlyrics']);
}
return true;
}
public function IntString2Bool($char) {
if ($char == '1') {
return true;
} elseif ($char == '0') {
return false;
}
return null;
}
}
| PHP |
<?php
/**
* WordPress Post Thumbnail Template Functions.
*
* Support for post thumbnails
* Themes function.php must call add_theme_support( 'post-thumbnails' ) to use these.
*
* @package WordPress
* @subpackage Template
*/
/**
* Check if post has an image attached.
*
* @since 2.9.0
*
* @param int $post_id Optional. Post ID.
* @return bool Whether post has an image attached.
*/
function has_post_thumbnail( $post_id = null ) {
return (bool) get_post_thumbnail_id( $post_id );
}
/**
* Retrieve Post Thumbnail ID.
*
* @since 2.9.0
*
* @param int $post_id Optional. Post ID.
* @return int
*/
function get_post_thumbnail_id( $post_id = null ) {
$post_id = ( null === $post_id ) ? get_the_ID() : $post_id;
return get_post_meta( $post_id, '_thumbnail_id', true );
}
/**
* Display Post Thumbnail.
*
* @since 2.9.0
*
* @param string|array $size Optional. Image size. Defaults to 'post-thumbnail', which theme sets using set_post_thumbnail_size( $width, $height, $crop_flag );.
* @param string|array $attr Optional. Query string or array of attributes.
*/
function the_post_thumbnail( $size = 'post-thumbnail', $attr = '' ) {
echo get_the_post_thumbnail( null, $size, $attr );
}
/**
* Update cache for thumbnails in the current loop
*
* @since 3.2.0
*
* @param object $wp_query Optional. A WP_Query instance. Defaults to the $wp_query global.
*/
function update_post_thumbnail_cache( $wp_query = null ) {
if ( ! $wp_query )
$wp_query = $GLOBALS['wp_query'];
if ( $wp_query->thumbnails_cached )
return;
$thumb_ids = array();
foreach ( $wp_query->posts as $post ) {
if ( $id = get_post_thumbnail_id( $post->ID ) )
$thumb_ids[] = $id;
}
if ( ! empty ( $thumb_ids ) ) {
_prime_post_caches( $thumb_ids, false, true );
}
$wp_query->thumbnails_cached = true;
}
/**
* Retrieve Post Thumbnail.
*
* @since 2.9.0
*
* @param int $post_id Optional. Post ID.
* @param string $size Optional. Image size. Defaults to 'post-thumbnail'.
* @param string|array $attr Optional. Query string or array of attributes.
*/
function get_the_post_thumbnail( $post_id = null, $size = 'post-thumbnail', $attr = '' ) {
$post_id = ( null === $post_id ) ? get_the_ID() : $post_id;
$post_thumbnail_id = get_post_thumbnail_id( $post_id );
/**
* Filter the post thumbnail size.
*
* @since 2.9.0
*
* @param string $size The post thumbnail size.
*/
$size = apply_filters( 'post_thumbnail_size', $size );
if ( $post_thumbnail_id ) {
/**
* Fires before fetching the post thumbnail HTML.
*
* Provides "just in time" filtering of all filters in wp_get_attachment_image().
*
* @since 2.9.0
*
* @param string $post_id The post ID.
* @param string $post_thumbnail_id The post thumbnail ID.
* @param string $size The post thumbnail size.
*/
do_action( 'begin_fetch_post_thumbnail_html', $post_id, $post_thumbnail_id, $size );
if ( in_the_loop() )
update_post_thumbnail_cache();
$html = wp_get_attachment_image( $post_thumbnail_id, $size, false, $attr );
/**
* Fires after fetching the post thumbnail HTML.
*
* @since 2.9.0
*
* @param string $post_id The post ID.
* @param string $post_thumbnail_id The post thumbnail ID.
* @param string $size The post thumbnail size.
*/
do_action( 'end_fetch_post_thumbnail_html', $post_id, $post_thumbnail_id, $size );
} else {
$html = '';
}
/**
* Filter the post thumbnail HTML.
*
* @since 2.9.0
*
* @param string $html The post thumbnail HTML.
* @param string $post_id The post ID.
* @param string $post_thumbnail_id The post thumbnail ID.
* @param string $size The post thumbnail size.
* @param string $attr Query string of attributes.
*/
return apply_filters( 'post_thumbnail_html', $html, $post_id, $post_thumbnail_id, $size, $attr );
}
| PHP |
<?php
/**
* Sets up the default filters and actions for most
* of the WordPress hooks.
*
* If you need to remove a default hook, this file will
* give you the priority for which to use to remove the
* hook.
*
* Not all of the default hooks are found in default-filters.php
*
* @package WordPress
*/
// Strip, trim, kses, special chars for string saves
foreach ( array( 'pre_term_name', 'pre_comment_author_name', 'pre_link_name', 'pre_link_target', 'pre_link_rel', 'pre_user_display_name', 'pre_user_first_name', 'pre_user_last_name', 'pre_user_nickname' ) as $filter ) {
add_filter( $filter, 'sanitize_text_field' );
add_filter( $filter, 'wp_filter_kses' );
add_filter( $filter, '_wp_specialchars', 30 );
}
// Strip, kses, special chars for string display
foreach ( array( 'term_name', 'comment_author_name', 'link_name', 'link_target', 'link_rel', 'user_display_name', 'user_first_name', 'user_last_name', 'user_nickname' ) as $filter ) {
if ( is_admin() ) {
// These are expensive. Run only on admin pages for defense in depth.
add_filter( $filter, 'sanitize_text_field' );
add_filter( $filter, 'wp_kses_data' );
}
add_filter( $filter, '_wp_specialchars', 30 );
}
// Kses only for textarea saves
foreach ( array( 'pre_term_description', 'pre_link_description', 'pre_link_notes', 'pre_user_description' ) as $filter ) {
add_filter( $filter, 'wp_filter_kses' );
}
// Kses only for textarea admin displays
if ( is_admin() ) {
foreach ( array( 'term_description', 'link_description', 'link_notes', 'user_description' ) as $filter ) {
add_filter( $filter, 'wp_kses_data' );
}
add_filter( 'comment_text', 'wp_kses_post' );
}
// Email saves
foreach ( array( 'pre_comment_author_email', 'pre_user_email' ) as $filter ) {
add_filter( $filter, 'trim' );
add_filter( $filter, 'sanitize_email' );
add_filter( $filter, 'wp_filter_kses' );
}
// Email admin display
foreach ( array( 'comment_author_email', 'user_email' ) as $filter ) {
add_filter( $filter, 'sanitize_email' );
if ( is_admin() )
add_filter( $filter, 'wp_kses_data' );
}
// Save URL
foreach ( array( 'pre_comment_author_url', 'pre_user_url', 'pre_link_url', 'pre_link_image',
'pre_link_rss', 'pre_post_guid' ) as $filter ) {
add_filter( $filter, 'wp_strip_all_tags' );
add_filter( $filter, 'esc_url_raw' );
add_filter( $filter, 'wp_filter_kses' );
}
// Display URL
foreach ( array( 'user_url', 'link_url', 'link_image', 'link_rss', 'comment_url', 'post_guid' ) as $filter ) {
if ( is_admin() )
add_filter( $filter, 'wp_strip_all_tags' );
add_filter( $filter, 'esc_url' );
if ( is_admin() )
add_filter( $filter, 'wp_kses_data' );
}
// Slugs
add_filter( 'pre_term_slug', 'sanitize_title' );
// Keys
foreach ( array( 'pre_post_type', 'pre_post_status', 'pre_post_comment_status', 'pre_post_ping_status' ) as $filter ) {
add_filter( $filter, 'sanitize_key' );
}
// Mime types
add_filter( 'pre_post_mime_type', 'sanitize_mime_type' );
add_filter( 'post_mime_type', 'sanitize_mime_type' );
// Places to balance tags on input
foreach ( array( 'content_save_pre', 'excerpt_save_pre', 'comment_save_pre', 'pre_comment_content' ) as $filter ) {
add_filter( $filter, 'balanceTags', 50 );
}
// Format strings for display.
foreach ( array( 'comment_author', 'term_name', 'link_name', 'link_description', 'link_notes', 'bloginfo', 'wp_title', 'widget_title' ) as $filter ) {
add_filter( $filter, 'wptexturize' );
add_filter( $filter, 'convert_chars' );
add_filter( $filter, 'esc_html' );
}
// Format WordPress
foreach ( array( 'the_content', 'the_title', 'wp_title' ) as $filter )
add_filter( $filter, 'capital_P_dangit', 11 );
add_filter( 'comment_text', 'capital_P_dangit', 31 );
// Format titles
foreach ( array( 'single_post_title', 'single_cat_title', 'single_tag_title', 'single_month_title', 'nav_menu_attr_title', 'nav_menu_description' ) as $filter ) {
add_filter( $filter, 'wptexturize' );
add_filter( $filter, 'strip_tags' );
}
// Format text area for display.
foreach ( array( 'term_description' ) as $filter ) {
add_filter( $filter, 'wptexturize' );
add_filter( $filter, 'convert_chars' );
add_filter( $filter, 'wpautop' );
add_filter( $filter, 'shortcode_unautop');
}
// Format for RSS
add_filter( 'term_name_rss', 'convert_chars' );
// Pre save hierarchy
add_filter( 'wp_insert_post_parent', 'wp_check_post_hierarchy_for_loops', 10, 2 );
add_filter( 'wp_update_term_parent', 'wp_check_term_hierarchy_for_loops', 10, 3 );
// Display filters
add_filter( 'the_title', 'wptexturize' );
add_filter( 'the_title', 'convert_chars' );
add_filter( 'the_title', 'trim' );
add_filter( 'the_content', 'wptexturize' );
add_filter( 'the_content', 'convert_smilies' );
add_filter( 'the_content', 'convert_chars' );
add_filter( 'the_content', 'wpautop' );
add_filter( 'the_content', 'shortcode_unautop' );
add_filter( 'the_content', 'prepend_attachment' );
add_filter( 'the_excerpt', 'wptexturize' );
add_filter( 'the_excerpt', 'convert_smilies' );
add_filter( 'the_excerpt', 'convert_chars' );
add_filter( 'the_excerpt', 'wpautop' );
add_filter( 'the_excerpt', 'shortcode_unautop');
add_filter( 'get_the_excerpt', 'wp_trim_excerpt' );
add_filter( 'comment_text', 'wptexturize' );
add_filter( 'comment_text', 'convert_chars' );
add_filter( 'comment_text', 'make_clickable', 9 );
add_filter( 'comment_text', 'force_balance_tags', 25 );
add_filter( 'comment_text', 'convert_smilies', 20 );
add_filter( 'comment_text', 'wpautop', 30 );
add_filter( 'comment_excerpt', 'convert_chars' );
add_filter( 'list_cats', 'wptexturize' );
add_filter( 'wp_sprintf', 'wp_sprintf_l', 10, 2 );
// RSS filters
add_filter( 'the_title_rss', 'strip_tags' );
add_filter( 'the_title_rss', 'ent2ncr', 8 );
add_filter( 'the_title_rss', 'esc_html' );
add_filter( 'the_content_rss', 'ent2ncr', 8 );
add_filter( 'the_excerpt_rss', 'convert_chars' );
add_filter( 'the_excerpt_rss', 'ent2ncr', 8 );
add_filter( 'comment_author_rss', 'ent2ncr', 8 );
add_filter( 'comment_text_rss', 'ent2ncr', 8 );
add_filter( 'comment_text_rss', 'esc_html' );
add_filter( 'bloginfo_rss', 'ent2ncr', 8 );
add_filter( 'the_author', 'ent2ncr', 8 );
// Misc filters
add_filter( 'option_ping_sites', 'privacy_ping_filter' );
add_filter( 'option_blog_charset', '_wp_specialchars' ); // IMPORTANT: This must not be wp_specialchars() or esc_html() or it'll cause an infinite loop
add_filter( 'option_blog_charset', '_canonical_charset' );
add_filter( 'option_home', '_config_wp_home' );
add_filter( 'option_siteurl', '_config_wp_siteurl' );
add_filter( 'tiny_mce_before_init', '_mce_set_direction' );
add_filter( 'pre_kses', 'wp_pre_kses_less_than' );
add_filter( 'sanitize_title', 'sanitize_title_with_dashes', 10, 3 );
add_action( 'check_comment_flood', 'check_comment_flood_db', 10, 3 );
add_filter( 'comment_flood_filter', 'wp_throttle_comment_flood', 10, 3 );
add_filter( 'pre_comment_content', 'wp_rel_nofollow', 15 );
add_filter( 'comment_email', 'antispambot' );
add_filter( 'option_tag_base', '_wp_filter_taxonomy_base' );
add_filter( 'option_category_base', '_wp_filter_taxonomy_base' );
add_filter( 'the_posts', '_close_comments_for_old_posts', 10, 2);
add_filter( 'comments_open', '_close_comments_for_old_post', 10, 2 );
add_filter( 'pings_open', '_close_comments_for_old_post', 10, 2 );
add_filter( 'editable_slug', 'urldecode' );
add_filter( 'editable_slug', 'esc_textarea' );
add_filter( 'nav_menu_meta_box_object', '_wp_nav_menu_meta_box_object' );
add_filter( 'pingback_ping_source_uri', 'pingback_ping_source_uri' );
add_filter( 'xmlrpc_pingback_error', 'xmlrpc_pingback_error' );
add_filter( 'http_request_host_is_external', 'allowed_http_request_hosts', 10, 2 );
// Actions
add_action( 'wp_head', 'wp_enqueue_scripts', 1 );
add_action( 'wp_head', 'feed_links', 2 );
add_action( 'wp_head', 'feed_links_extra', 3 );
add_action( 'wp_head', 'rsd_link' );
add_action( 'wp_head', 'wlwmanifest_link' );
add_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0 );
add_action( 'wp_head', 'locale_stylesheet' );
add_action( 'publish_future_post', 'check_and_publish_future_post', 10, 1 );
add_action( 'wp_head', 'noindex', 1 );
add_action( 'wp_head', 'wp_print_styles', 8 );
add_action( 'wp_head', 'wp_print_head_scripts', 9 );
add_action( 'wp_head', 'wp_generator' );
add_action( 'wp_head', 'rel_canonical' );
add_action( 'wp_footer', 'wp_print_footer_scripts', 20 );
add_action( 'wp_head', 'wp_shortlink_wp_head', 10, 0 );
add_action( 'template_redirect', 'wp_shortlink_header', 11, 0 );
add_action( 'wp_print_footer_scripts', '_wp_footer_scripts' );
add_action( 'init', 'check_theme_switched', 99 );
add_action( 'after_switch_theme', '_wp_sidebars_changed' );
if ( isset( $_GET['replytocom'] ) )
add_action( 'wp_head', 'wp_no_robots' );
// Login actions
add_action( 'login_head', 'wp_print_head_scripts', 9 );
add_action( 'login_footer', 'wp_print_footer_scripts', 20 );
add_action( 'login_init', 'send_frame_options_header', 10, 0 );
// Feed Generator Tags
foreach ( array( 'rss2_head', 'commentsrss2_head', 'rss_head', 'rdf_header', 'atom_head', 'comments_atom_head', 'opml_head', 'app_head' ) as $action ) {
add_action( $action, 'the_generator' );
}
// WP Cron
if ( !defined( 'DOING_CRON' ) )
add_action( 'init', 'wp_cron' );
// 2 Actions 2 Furious
add_action( 'do_feed_rdf', 'do_feed_rdf', 10, 1 );
add_action( 'do_feed_rss', 'do_feed_rss', 10, 1 );
add_action( 'do_feed_rss2', 'do_feed_rss2', 10, 1 );
add_action( 'do_feed_atom', 'do_feed_atom', 10, 1 );
add_action( 'do_pings', 'do_all_pings', 10, 1 );
add_action( 'do_robots', 'do_robots' );
add_action( 'set_comment_cookies', 'wp_set_comment_cookies', 10, 2 );
add_action( 'sanitize_comment_cookies', 'sanitize_comment_cookies' );
add_action( 'admin_print_scripts', 'print_head_scripts', 20 );
add_action( 'admin_print_footer_scripts', '_wp_footer_scripts' );
add_action( 'admin_print_styles', 'print_admin_styles', 20 );
add_action( 'init', 'smilies_init', 5 );
add_action( 'plugins_loaded', 'wp_maybe_load_widgets', 0 );
add_action( 'plugins_loaded', 'wp_maybe_load_embeds', 0 );
add_action( 'shutdown', 'wp_ob_end_flush_all', 1 );
add_action( 'post_updated', 'wp_save_post_revision', 10, 1 );
add_action( 'publish_post', '_publish_post_hook', 5, 1 );
add_action( 'transition_post_status', '_transition_post_status', 5, 3 );
add_action( 'transition_post_status', '_update_term_count_on_transition_post_status', 10, 3 );
add_action( 'comment_form', 'wp_comment_form_unfiltered_html_nonce' );
add_action( 'wp_scheduled_delete', 'wp_scheduled_delete' );
add_action( 'wp_scheduled_auto_draft_delete', 'wp_delete_auto_drafts' );
add_action( 'admin_init', 'send_frame_options_header', 10, 0 );
add_action( 'importer_scheduled_cleanup', 'wp_delete_attachment' );
add_action( 'upgrader_scheduled_cleanup', 'wp_delete_attachment' );
add_action( 'welcome_panel', 'wp_welcome_panel' );
// Navigation menu actions
add_action( 'delete_post', '_wp_delete_post_menu_item' );
add_action( 'delete_term', '_wp_delete_tax_menu_item', 10, 3 );
add_action( 'transition_post_status', '_wp_auto_add_pages_to_menu', 10, 3 );
// Post Thumbnail CSS class filtering
add_action( 'begin_fetch_post_thumbnail_html', '_wp_post_thumbnail_class_filter_add' );
add_action( 'end_fetch_post_thumbnail_html', '_wp_post_thumbnail_class_filter_remove' );
// Redirect Old Slugs
add_action( 'template_redirect', 'wp_old_slug_redirect' );
add_action( 'post_updated', 'wp_check_for_changed_slugs', 12, 3 );
// Nonce check for Post Previews
add_action( 'init', '_show_post_preview' );
// Timezone
add_filter( 'pre_option_gmt_offset','wp_timezone_override_offset' );
// Admin Color Schemes
add_action( 'admin_init', 'register_admin_color_schemes', 1);
add_action( 'admin_color_scheme_picker', 'admin_color_scheme_picker' );
// If the upgrade hasn't run yet, assume link manager is used.
add_filter( 'default_option_link_manager_enabled', '__return_true' );
// This option no longer exists; tell plugins we always support auto-embedding.
add_filter( 'default_option_embed_autourls', '__return_true' );
// Default settings for heartbeat
add_filter( 'heartbeat_settings', 'wp_heartbeat_settings' );
// Check if the user is logged out
add_action( 'admin_enqueue_scripts', 'wp_auth_check_load' );
add_filter( 'heartbeat_send', 'wp_auth_check' );
add_filter( 'heartbeat_nopriv_send', 'wp_auth_check' );
// Default authentication filters
add_filter( 'authenticate', 'wp_authenticate_username_password', 20, 3 );
add_filter( 'authenticate', 'wp_authenticate_spam_check', 99 );
add_filter( 'determine_current_user', 'wp_validate_auth_cookie' );
add_filter( 'determine_current_user', 'wp_validate_logged_in_cookie', 20 );
unset($filter, $action);
| PHP |
<?php
/**
* Site/blog functions that work with the blogs table and related data.
*
* @package WordPress
* @subpackage Multisite
* @since MU
*/
/**
* Update the last_updated field for the current blog.
*
* @since MU
*/
function wpmu_update_blogs_date() {
global $wpdb;
update_blog_details( $wpdb->blogid, array('last_updated' => current_time('mysql', true)) );
/**
* Fires after the blog details are updated.
*
* @since MU
*
* @param int $blog_id Blog ID.
*/
do_action( 'wpmu_blog_updated', $wpdb->blogid );
}
/**
* Get a full blog URL, given a blog id.
*
* @since MU
*
* @param int $blog_id Blog ID
* @return string
*/
function get_blogaddress_by_id( $blog_id ) {
$bloginfo = get_blog_details( (int) $blog_id, false ); // only get bare details!
return esc_url( 'http://' . $bloginfo->domain . $bloginfo->path );
}
/**
* Get a full blog URL, given a blog name.
*
* @since MU
*
* @param string $blogname The (subdomain or directory) name
* @return string
*/
function get_blogaddress_by_name( $blogname ) {
if ( is_subdomain_install() ) {
if ( $blogname == 'main' )
$blogname = 'www';
$url = rtrim( network_home_url(), '/' );
if ( !empty( $blogname ) )
$url = preg_replace( '|^([^\.]+://)|', "\${1}" . $blogname . '.', $url );
} else {
$url = network_home_url( $blogname );
}
return esc_url( $url . '/' );
}
/**
* Given a blog's (subdomain or directory) slug, retrieve its id.
*
* @since MU
*
* @param string $slug
* @return int A blog id
*/
function get_id_from_blogname( $slug ) {
global $wpdb;
$current_site = get_current_site();
$slug = trim( $slug, '/' );
$blog_id = wp_cache_get( 'get_id_from_blogname_' . $slug, 'blog-details' );
if ( $blog_id )
return $blog_id;
if ( is_subdomain_install() ) {
$domain = $slug . '.' . $current_site->domain;
$path = $current_site->path;
} else {
$domain = $current_site->domain;
$path = $current_site->path . $slug . '/';
}
$blog_id = $wpdb->get_var( $wpdb->prepare("SELECT blog_id FROM {$wpdb->blogs} WHERE domain = %s AND path = %s", $domain, $path) );
wp_cache_set( 'get_id_from_blogname_' . $slug, $blog_id, 'blog-details' );
return $blog_id;
}
/**
* Retrieve the details for a blog from the blogs table and blog options.
*
* @since MU
*
* @param int|string|array $fields A blog ID, a blog slug, or an array of fields to query against. Optional. If not specified the current blog ID is used.
* @param bool $get_all Whether to retrieve all details or only the details in the blogs table. Default is true.
* @return object Blog details.
*/
function get_blog_details( $fields = null, $get_all = true ) {
global $wpdb;
if ( is_array($fields ) ) {
if ( isset($fields['blog_id']) ) {
$blog_id = $fields['blog_id'];
} elseif ( isset($fields['domain']) && isset($fields['path']) ) {
$key = md5( $fields['domain'] . $fields['path'] );
$blog = wp_cache_get($key, 'blog-lookup');
if ( false !== $blog )
return $blog;
if ( substr( $fields['domain'], 0, 4 ) == 'www.' ) {
$nowww = substr( $fields['domain'], 4 );
$blog = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->blogs WHERE domain IN (%s,%s) AND path = %s ORDER BY CHAR_LENGTH(domain) DESC", $nowww, $fields['domain'], $fields['path'] ) );
} else {
$blog = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->blogs WHERE domain = %s AND path = %s", $fields['domain'], $fields['path'] ) );
}
if ( $blog ) {
wp_cache_set($blog->blog_id . 'short', $blog, 'blog-details');
$blog_id = $blog->blog_id;
} else {
return false;
}
} elseif ( isset($fields['domain']) && is_subdomain_install() ) {
$key = md5( $fields['domain'] );
$blog = wp_cache_get($key, 'blog-lookup');
if ( false !== $blog )
return $blog;
if ( substr( $fields['domain'], 0, 4 ) == 'www.' ) {
$nowww = substr( $fields['domain'], 4 );
$blog = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->blogs WHERE domain IN (%s,%s) ORDER BY CHAR_LENGTH(domain) DESC", $nowww, $fields['domain'] ) );
} else {
$blog = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->blogs WHERE domain = %s", $fields['domain'] ) );
}
if ( $blog ) {
wp_cache_set($blog->blog_id . 'short', $blog, 'blog-details');
$blog_id = $blog->blog_id;
} else {
return false;
}
} else {
return false;
}
} else {
if ( ! $fields )
$blog_id = get_current_blog_id();
elseif ( ! is_numeric( $fields ) )
$blog_id = get_id_from_blogname( $fields );
else
$blog_id = $fields;
}
$blog_id = (int) $blog_id;
$all = $get_all == true ? '' : 'short';
$details = wp_cache_get( $blog_id . $all, 'blog-details' );
if ( $details ) {
if ( ! is_object( $details ) ) {
if ( $details == -1 ) {
return false;
} else {
// Clear old pre-serialized objects. Cache clients do better with that.
wp_cache_delete( $blog_id . $all, 'blog-details' );
unset($details);
}
} else {
return $details;
}
}
// Try the other cache.
if ( $get_all ) {
$details = wp_cache_get( $blog_id . 'short', 'blog-details' );
} else {
$details = wp_cache_get( $blog_id, 'blog-details' );
// If short was requested and full cache is set, we can return.
if ( $details ) {
if ( ! is_object( $details ) ) {
if ( $details == -1 ) {
return false;
} else {
// Clear old pre-serialized objects. Cache clients do better with that.
wp_cache_delete( $blog_id, 'blog-details' );
unset($details);
}
} else {
return $details;
}
}
}
if ( empty($details) ) {
$details = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->blogs WHERE blog_id = %d /* get_blog_details */", $blog_id ) );
if ( ! $details ) {
// Set the full cache.
wp_cache_set( $blog_id, -1, 'blog-details' );
return false;
}
}
if ( ! $get_all ) {
wp_cache_set( $blog_id . $all, $details, 'blog-details' );
return $details;
}
switch_to_blog( $blog_id );
$details->blogname = get_option( 'blogname' );
$details->siteurl = get_option( 'siteurl' );
$details->post_count = get_option( 'post_count' );
restore_current_blog();
/**
* Filter a blog's details.
*
* @since MU
*
* @param object $details The blog details.
*/
$details = apply_filters( 'blog_details', $details );
wp_cache_set( $blog_id . $all, $details, 'blog-details' );
$key = md5( $details->domain . $details->path );
wp_cache_set( $key, $details, 'blog-lookup' );
return $details;
}
/**
* Clear the blog details cache.
*
* @since MU
*
* @param int $blog_id Blog ID
*/
function refresh_blog_details( $blog_id ) {
$blog_id = (int) $blog_id;
$details = get_blog_details( $blog_id, false );
if ( ! $details ) {
// Make sure clean_blog_cache() gets the blog ID
// when the blog has been previously cached as
// non-existent.
$details = (object) array(
'blog_id' => $blog_id,
'domain' => null,
'path' => null
);
}
clean_blog_cache( $details );
/**
* Fires after the blog details cache is cleared.
*
* @since 3.4.0
*
* @param int $blog_id Blog ID.
*/
do_action( 'refresh_blog_details', $blog_id );
}
/**
* Update the details for a blog. Updates the blogs table for a given blog id.
*
* @since MU
*
* @param int $blog_id Blog ID
* @param array $details Array of details keyed by blogs table field names.
* @return bool True if update succeeds, false otherwise.
*/
function update_blog_details( $blog_id, $details = array() ) {
global $wpdb;
if ( empty($details) )
return false;
if ( is_object($details) )
$details = get_object_vars($details);
$current_details = get_blog_details($blog_id, false);
if ( empty($current_details) )
return false;
$current_details = get_object_vars($current_details);
$details = array_merge($current_details, $details);
$details['last_updated'] = current_time('mysql', true);
$update_details = array();
$fields = array( 'site_id', 'domain', 'path', 'registered', 'last_updated', 'public', 'archived', 'mature', 'spam', 'deleted', 'lang_id');
foreach ( array_intersect( array_keys( $details ), $fields ) as $field )
$update_details[$field] = $details[$field];
$result = $wpdb->update( $wpdb->blogs, $update_details, array('blog_id' => $blog_id) );
if ( false === $result )
return false;
// If spam status changed, issue actions.
if ( $details['spam'] != $current_details['spam'] ) {
if ( $details['spam'] == 1 ) {
/**
* Fires when the blog status is changed to 'spam'.
*
* @since MU
*
* @param int $blog_id Blog ID.
*/
do_action( 'make_spam_blog', $blog_id );
} else {
/**
* Fires when the blog status is changed to 'ham'.
*
* @since MU
*
* @param int $blog_id Blog ID.
*/
do_action( 'make_ham_blog', $blog_id );
}
}
// If mature status changed, issue actions.
if ( $details['mature'] != $current_details['mature'] ) {
if ( $details['mature'] == 1 ) {
/**
* Fires when the blog status is changed to 'mature'.
*
* @since 3.1.0
*
* @param int $blog_id Blog ID.
*/
do_action( 'mature_blog', $blog_id );
} else {
/**
* Fires when the blog status is changed to 'unmature'.
*
* @since 3.1.0
*
* @param int $blog_id Blog ID.
*/
do_action( 'unmature_blog', $blog_id );
}
}
// If archived status changed, issue actions.
if ( $details['archived'] != $current_details['archived'] ) {
if ( $details['archived'] == 1 ) {
/**
* Fires when the blog status is changed to 'archived'.
*
* @since MU
*
* @param int $blog_id Blog ID.
*/
do_action( 'archive_blog', $blog_id );
} else {
/**
* Fires when the blog status is changed to 'unarchived'.
*
* @since MU
*
* @param int $blog_id Blog ID.
*/
do_action( 'unarchive_blog', $blog_id );
}
}
// If deleted status changed, issue actions.
if ( $details['deleted'] != $current_details['deleted'] ) {
if ( $details['deleted'] == 1 ) {
/**
* Fires when the blog status is changed to 'deleted'.
*
* @since 3.5.0
*
* @param int $blog_id Blog ID.
*/
do_action( 'make_delete_blog', $blog_id );
} else {
/**
* Fires when the blog status is changed to 'undeleted'.
*
* @since 3.5.0
*
* @param int $blog_id Blog ID.
*/
do_action( 'make_undelete_blog', $blog_id );
}
}
if ( isset( $details['public'] ) ) {
switch_to_blog( $blog_id );
update_option( 'blog_public', $details['public'] );
restore_current_blog();
}
refresh_blog_details($blog_id);
return true;
}
/**
* Clean the blog cache
*
* @since 3.5.0
*
* @param stdClass $blog The blog details as returned from get_blog_details()
*/
function clean_blog_cache( $blog ) {
$blog_id = $blog->blog_id;
$domain_path_key = md5( $blog->domain . $blog->path );
wp_cache_delete( $blog_id , 'blog-details' );
wp_cache_delete( $blog_id . 'short' , 'blog-details' );
wp_cache_delete( $domain_path_key, 'blog-lookup' );
wp_cache_delete( 'current_blog_' . $blog->domain, 'site-options' );
wp_cache_delete( 'current_blog_' . $blog->domain . $blog->path, 'site-options' );
wp_cache_delete( 'get_id_from_blogname_' . trim( $blog->path, '/' ), 'blog-details' );
wp_cache_delete( $domain_path_key, 'blog-id-cache' );
}
/**
* Retrieve option value for a given blog id based on name of option.
*
* If the option does not exist or does not have a value, then the return value
* will be false. This is useful to check whether you need to install an option
* and is commonly used during installation of plugin options and to test
* whether upgrading is required.
*
* If the option was serialized then it will be unserialized when it is returned.
*
* @since MU
*
* @param int $id A blog ID. Can be null to refer to the current blog.
* @param string $option Name of option to retrieve. Expected to not be SQL-escaped.
* @param mixed $default Optional. Default value to return if the option does not exist.
* @return mixed Value set for the option.
*/
function get_blog_option( $id, $option, $default = false ) {
$id = (int) $id;
if ( empty( $id ) )
$id = get_current_blog_id();
if ( get_current_blog_id() == $id )
return get_option( $option, $default );
switch_to_blog( $id );
$value = get_option( $option, $default );
restore_current_blog();
/**
* Filter a blog option value.
*
* The dynamic portion of the hook name, $option, refers to the blog option name.
*
* @since 3.5.0
*
* @param string $value The option value.
* @param int $id Blog ID.
*/
return apply_filters( "blog_option_{$option}", $value, $id );
}
/**
* Add a new option for a given blog id.
*
* You do not need to serialize values. If the value needs to be serialized, then
* it will be serialized before it is inserted into the database. Remember,
* resources can not be serialized or added as an option.
*
* You can create options without values and then update the values later.
* Existing options will not be updated and checks are performed to ensure that you
* aren't adding a protected WordPress option. Care should be taken to not name
* options the same as the ones which are protected.
*
* @since MU
*
* @param int $id A blog ID. Can be null to refer to the current blog.
* @param string $option Name of option to add. Expected to not be SQL-escaped.
* @param mixed $value Optional. Option value, can be anything. Expected to not be SQL-escaped.
* @return bool False if option was not added and true if option was added.
*/
function add_blog_option( $id, $option, $value ) {
$id = (int) $id;
if ( empty( $id ) )
$id = get_current_blog_id();
if ( get_current_blog_id() == $id )
return add_option( $option, $value );
switch_to_blog( $id );
$return = add_option( $option, $value );
restore_current_blog();
return $return;
}
/**
* Removes option by name for a given blog id. Prevents removal of protected WordPress options.
*
* @since MU
*
* @param int $id A blog ID. Can be null to refer to the current blog.
* @param string $option Name of option to remove. Expected to not be SQL-escaped.
* @return bool True, if option is successfully deleted. False on failure.
*/
function delete_blog_option( $id, $option ) {
$id = (int) $id;
if ( empty( $id ) )
$id = get_current_blog_id();
if ( get_current_blog_id() == $id )
return delete_option( $option );
switch_to_blog( $id );
$return = delete_option( $option );
restore_current_blog();
return $return;
}
/**
* Update an option for a particular blog.
*
* @since MU
*
* @param int $id The blog id
* @param string $option The option key
* @param mixed $value The option value
* @return bool True on success, false on failure.
*/
function update_blog_option( $id, $option, $value, $deprecated = null ) {
$id = (int) $id;
if ( null !== $deprecated )
_deprecated_argument( __FUNCTION__, '3.1' );
if ( get_current_blog_id() == $id )
return update_option( $option, $value );
switch_to_blog( $id );
$return = update_option( $option, $value );
restore_current_blog();
refresh_blog_details( $id );
return $return;
}
/**
* Switch the current blog.
*
* This function is useful if you need to pull posts, or other information,
* from other blogs. You can switch back afterwards using restore_current_blog().
*
* Things that aren't switched:
* - autoloaded options. See #14992
* - plugins. See #14941
*
* @see restore_current_blog()
* @since MU
*
* @param int $new_blog The id of the blog you want to switch to. Default: current blog
* @param bool $deprecated Deprecated argument
* @return bool Always returns True.
*/
function switch_to_blog( $new_blog, $deprecated = null ) {
global $wpdb, $wp_roles;
if ( empty( $new_blog ) )
$new_blog = $GLOBALS['blog_id'];
$GLOBALS['_wp_switched_stack'][] = $GLOBALS['blog_id'];
/*
* If we're switching to the same blog id that we're on,
* set the right vars, do the associated actions, but skip
* the extra unnecessary work
*/
if ( $new_blog == $GLOBALS['blog_id'] ) {
/**
* Fires when the blog is switched.
*
* @since MU
*
* @param int $new_blog New blog ID.
* @param int $new_blog Blog ID.
*/
do_action( 'switch_blog', $new_blog, $new_blog );
$GLOBALS['switched'] = true;
return true;
}
$wpdb->set_blog_id( $new_blog );
$GLOBALS['table_prefix'] = $wpdb->get_blog_prefix();
$prev_blog_id = $GLOBALS['blog_id'];
$GLOBALS['blog_id'] = $new_blog;
if ( function_exists( 'wp_cache_switch_to_blog' ) ) {
wp_cache_switch_to_blog( $new_blog );
} else {
global $wp_object_cache;
if ( is_object( $wp_object_cache ) && isset( $wp_object_cache->global_groups ) )
$global_groups = $wp_object_cache->global_groups;
else
$global_groups = false;
wp_cache_init();
if ( function_exists( 'wp_cache_add_global_groups' ) ) {
if ( is_array( $global_groups ) )
wp_cache_add_global_groups( $global_groups );
else
wp_cache_add_global_groups( array( 'users', 'userlogins', 'usermeta', 'user_meta', 'site-transient', 'site-options', 'site-lookup', 'blog-lookup', 'blog-details', 'rss', 'global-posts', ' blog-id-cache' ) );
wp_cache_add_non_persistent_groups( array( 'comment', 'counts', 'plugins' ) );
}
}
if ( did_action( 'init' ) ) {
$wp_roles->reinit();
$current_user = wp_get_current_user();
$current_user->for_blog( $new_blog );
}
/** This filter is documented in wp-includes/ms-blogs.php */
do_action( 'switch_blog', $new_blog, $prev_blog_id );
$GLOBALS['switched'] = true;
return true;
}
/**
* Restore the current blog, after calling switch_to_blog()
*
* @see switch_to_blog()
* @since MU
*
* @return bool True on success, false if we're already on the current blog
*/
function restore_current_blog() {
global $wpdb, $wp_roles;
if ( empty( $GLOBALS['_wp_switched_stack'] ) )
return false;
$blog = array_pop( $GLOBALS['_wp_switched_stack'] );
if ( $GLOBALS['blog_id'] == $blog ) {
/** This filter is documented in wp-includes/ms-blogs.php */
do_action( 'switch_blog', $blog, $blog );
// If we still have items in the switched stack, consider ourselves still 'switched'
$GLOBALS['switched'] = ! empty( $GLOBALS['_wp_switched_stack'] );
return true;
}
$wpdb->set_blog_id( $blog );
$prev_blog_id = $GLOBALS['blog_id'];
$GLOBALS['blog_id'] = $blog;
$GLOBALS['table_prefix'] = $wpdb->get_blog_prefix();
if ( function_exists( 'wp_cache_switch_to_blog' ) ) {
wp_cache_switch_to_blog( $blog );
} else {
global $wp_object_cache;
if ( is_object( $wp_object_cache ) && isset( $wp_object_cache->global_groups ) )
$global_groups = $wp_object_cache->global_groups;
else
$global_groups = false;
wp_cache_init();
if ( function_exists( 'wp_cache_add_global_groups' ) ) {
if ( is_array( $global_groups ) )
wp_cache_add_global_groups( $global_groups );
else
wp_cache_add_global_groups( array( 'users', 'userlogins', 'usermeta', 'user_meta', 'site-transient', 'site-options', 'site-lookup', 'blog-lookup', 'blog-details', 'rss', 'global-posts', ' blog-id-cache' ) );
wp_cache_add_non_persistent_groups( array( 'comment', 'counts', 'plugins' ) );
}
}
if ( did_action( 'init' ) ) {
$wp_roles->reinit();
$current_user = wp_get_current_user();
$current_user->for_blog( $blog );
}
/** This filter is documented in wp-includes/ms-blogs.php */
do_action( 'switch_blog', $blog, $prev_blog_id );
// If we still have items in the switched stack, consider ourselves still 'switched'
$GLOBALS['switched'] = ! empty( $GLOBALS['_wp_switched_stack'] );
return true;
}
/**
* Determines if switch_to_blog() is in effect
*
* @since 3.5.0
*
* @return bool True if switched, false otherwise.
*/
function ms_is_switched() {
return ! empty( $GLOBALS['_wp_switched_stack'] );
}
/**
* Check if a particular blog is archived.
*
* @since MU
*
* @param int $id The blog id
* @return string Whether the blog is archived or not
*/
function is_archived( $id ) {
return get_blog_status($id, 'archived');
}
/**
* Update the 'archived' status of a particular blog.
*
* @since MU
*
* @param int $id The blog id
* @param string $archived The new status
* @return string $archived
*/
function update_archived( $id, $archived ) {
update_blog_status($id, 'archived', $archived);
return $archived;
}
/**
* Update a blog details field.
*
* @since MU
*
* @param int $blog_id BLog ID
* @param string $pref A field name
* @param string $value Value for $pref
* @return string $value
*/
function update_blog_status( $blog_id, $pref, $value, $deprecated = null ) {
global $wpdb;
if ( null !== $deprecated )
_deprecated_argument( __FUNCTION__, '3.1' );
if ( ! in_array( $pref, array( 'site_id', 'domain', 'path', 'registered', 'last_updated', 'public', 'archived', 'mature', 'spam', 'deleted', 'lang_id') ) )
return $value;
$result = $wpdb->update( $wpdb->blogs, array($pref => $value, 'last_updated' => current_time('mysql', true)), array('blog_id' => $blog_id) );
if ( false === $result )
return false;
refresh_blog_details( $blog_id );
if ( 'spam' == $pref ) {
if ( $value == 1 ) {
/** This filter is documented in wp-includes/ms-blogs.php */
do_action( 'make_spam_blog', $blog_id );
} else {
/** This filter is documented in wp-includes/ms-blogs.php */
do_action( 'make_ham_blog', $blog_id );
}
} elseif ( 'mature' == $pref ) {
if ( $value == 1 ) {
/** This filter is documented in wp-includes/ms-blogs.php */
do_action( 'mature_blog', $blog_id );
} else {
/** This filter is documented in wp-includes/ms-blogs.php */
do_action( 'unmature_blog', $blog_id );
}
} elseif ( 'archived' == $pref ) {
if ( $value == 1 ) {
/** This filter is documented in wp-includes/ms-blogs.php */
do_action( 'archive_blog', $blog_id );
} else {
/** This filter is documented in wp-includes/ms-blogs.php */
do_action( 'unarchive_blog', $blog_id );
}
} elseif ( 'deleted' == $pref ) {
if ( $value == 1 ) {
/** This filter is documented in wp-includes/ms-blogs.php */
do_action( 'make_delete_blog', $blog_id );
} else {
/** This filter is documented in wp-includes/ms-blogs.php */
do_action( 'make_undelete_blog', $blog_id );
}
} elseif ( 'public' == $pref ) {
/**
* Fires after the current blog's 'public' setting is updated.
*
* @since MU
*
* @param int $blog_id Blog ID.
* @param string $value The value of blog status.
*/
do_action( 'update_blog_public', $blog_id, $value ); // Moved here from update_blog_public().
}
return $value;
}
/**
* Get a blog details field.
*
* @since MU
*
* @param int $id The blog id
* @param string $pref A field name
* @return bool $value
*/
function get_blog_status( $id, $pref ) {
global $wpdb;
$details = get_blog_details( $id, false );
if ( $details )
return $details->$pref;
return $wpdb->get_var( $wpdb->prepare("SELECT %s FROM {$wpdb->blogs} WHERE blog_id = %d", $pref, $id) );
}
/**
* Get a list of most recently updated blogs.
*
* @since MU
*
* @param mixed $deprecated Not used
* @param int $start The offset
* @param int $quantity The maximum number of blogs to retrieve. Default is 40.
* @return array The list of blogs
*/
function get_last_updated( $deprecated = '', $start = 0, $quantity = 40 ) {
global $wpdb;
if ( ! empty( $deprecated ) )
_deprecated_argument( __FUNCTION__, 'MU' ); // never used
return $wpdb->get_results( $wpdb->prepare("SELECT blog_id, domain, path FROM $wpdb->blogs WHERE site_id = %d AND public = '1' AND archived = '0' AND mature = '0' AND spam = '0' AND deleted = '0' AND last_updated != '0000-00-00 00:00:00' ORDER BY last_updated DESC limit %d, %d", $wpdb->siteid, $start, $quantity ) , ARRAY_A );
}
/**
* Handler for updating the blog date when a post is published or an already published post is changed.
*
* @since 3.3.0
*
* @param string $new_status The new post status
* @param string $old_status The old post status
* @param object $post Post object
*/
function _update_blog_date_on_post_publish( $new_status, $old_status, $post ) {
$post_type_obj = get_post_type_object( $post->post_type );
if ( ! $post_type_obj->public )
return;
if ( 'publish' != $new_status && 'publish' != $old_status )
return;
// Post was freshly published, published post was saved, or published post was unpublished.
wpmu_update_blogs_date();
}
/**
* Handler for updating the blog date when a published post is deleted.
*
* @since 3.4.0
*
* @param int $post_id Post ID
*/
function _update_blog_date_on_post_delete( $post_id ) {
$post = get_post( $post_id );
$post_type_obj = get_post_type_object( $post->post_type );
if ( ! $post_type_obj->public )
return;
if ( 'publish' != $post->post_status )
return;
wpmu_update_blogs_date();
}
| PHP |
<?php
/**
* Post format functions.
*
* @package WordPress
* @subpackage Post
*/
/**
* Retrieve the format slug for a post
*
* @since 3.1.0
*
* @param int|object $post Post ID or post object. Optional, default is the current post from the loop.
* @return mixed The format if successful. False otherwise.
*/
function get_post_format( $post = null ) {
if ( ! $post = get_post( $post ) )
return false;
if ( ! post_type_supports( $post->post_type, 'post-formats' ) )
return false;
$_format = get_the_terms( $post->ID, 'post_format' );
if ( empty( $_format ) )
return false;
$format = array_shift( $_format );
return str_replace('post-format-', '', $format->slug );
}
/**
* Check if a post has any of the given formats, or any format.
*
* @since 3.1.0
*
* @uses has_term()
*
* @param string|array $format Optional. The format or formats to check.
* @param object|int $post Optional. The post to check. If not supplied, defaults to the current post if used in the loop.
* @return bool True if the post has any of the given formats (or any format, if no format specified), false otherwise.
*/
function has_post_format( $format = array(), $post = null ) {
$prefixed = array();
if ( $format ) {
foreach ( (array) $format as $single ) {
$prefixed[] = 'post-format-' . sanitize_key( $single );
}
}
return has_term( $prefixed, 'post_format', $post );
}
/**
* Assign a format to a post
*
* @since 3.1.0
*
* @param int|object $post The post for which to assign a format.
* @param string $format A format to assign. Use an empty string or array to remove all formats from the post.
* @return mixed WP_Error on error. Array of affected term IDs on success.
*/
function set_post_format( $post, $format ) {
$post = get_post( $post );
if ( empty( $post ) )
return new WP_Error( 'invalid_post', __( 'Invalid post' ) );
if ( ! empty( $format ) ) {
$format = sanitize_key( $format );
if ( 'standard' === $format || ! in_array( $format, get_post_format_slugs() ) )
$format = '';
else
$format = 'post-format-' . $format;
}
return wp_set_post_terms( $post->ID, $format, 'post_format' );
}
/**
* Returns an array of post format slugs to their translated and pretty display versions
*
* @since 3.1.0
*
* @return array The array of translated post format names.
*/
function get_post_format_strings() {
$strings = array(
'standard' => _x( 'Standard', 'Post format' ), // Special case. any value that evals to false will be considered standard
'aside' => _x( 'Aside', 'Post format' ),
'chat' => _x( 'Chat', 'Post format' ),
'gallery' => _x( 'Gallery', 'Post format' ),
'link' => _x( 'Link', 'Post format' ),
'image' => _x( 'Image', 'Post format' ),
'quote' => _x( 'Quote', 'Post format' ),
'status' => _x( 'Status', 'Post format' ),
'video' => _x( 'Video', 'Post format' ),
'audio' => _x( 'Audio', 'Post format' ),
);
return $strings;
}
/**
* Retrieves an array of post format slugs.
*
* @since 3.1.0
*
* @uses get_post_format_strings()
*
* @return array The array of post format slugs.
*/
function get_post_format_slugs() {
$slugs = array_keys( get_post_format_strings() );
return array_combine( $slugs, $slugs );
}
/**
* Returns a pretty, translated version of a post format slug
*
* @since 3.1.0
*
* @uses get_post_format_strings()
*
* @param string $slug A post format slug.
* @return string The translated post format name.
*/
function get_post_format_string( $slug ) {
$strings = get_post_format_strings();
if ( !$slug )
return $strings['standard'];
else
return ( isset( $strings[$slug] ) ) ? $strings[$slug] : '';
}
/**
* Returns a link to a post format index.
*
* @since 3.1.0
*
* @param string $format The post format slug.
* @return string The post format term link.
*/
function get_post_format_link( $format ) {
$term = get_term_by('slug', 'post-format-' . $format, 'post_format' );
if ( ! $term || is_wp_error( $term ) )
return false;
return get_term_link( $term );
}
/**
* Filters the request to allow for the format prefix.
*
* @access private
* @since 3.1.0
*/
function _post_format_request( $qvs ) {
if ( ! isset( $qvs['post_format'] ) )
return $qvs;
$slugs = get_post_format_slugs();
if ( isset( $slugs[ $qvs['post_format'] ] ) )
$qvs['post_format'] = 'post-format-' . $slugs[ $qvs['post_format'] ];
$tax = get_taxonomy( 'post_format' );
if ( ! is_admin() )
$qvs['post_type'] = $tax->object_type;
return $qvs;
}
add_filter( 'request', '_post_format_request' );
/**
* Filters the post format term link to remove the format prefix.
*
* @access private
* @since 3.1.0
*/
function _post_format_link( $link, $term, $taxonomy ) {
global $wp_rewrite;
if ( 'post_format' != $taxonomy )
return $link;
if ( $wp_rewrite->get_extra_permastruct( $taxonomy ) ) {
return str_replace( "/{$term->slug}", '/' . str_replace( 'post-format-', '', $term->slug ), $link );
} else {
$link = remove_query_arg( 'post_format', $link );
return add_query_arg( 'post_format', str_replace( 'post-format-', '', $term->slug ), $link );
}
}
add_filter( 'term_link', '_post_format_link', 10, 3 );
/**
* Remove the post format prefix from the name property of the term object created by get_term().
*
* @access private
* @since 3.1.0
*/
function _post_format_get_term( $term ) {
if ( isset( $term->slug ) ) {
$term->name = get_post_format_string( str_replace( 'post-format-', '', $term->slug ) );
}
return $term;
}
add_filter( 'get_post_format', '_post_format_get_term' );
/**
* Remove the post format prefix from the name property of the term objects created by get_terms().
*
* @access private
* @since 3.1.0
*/
function _post_format_get_terms( $terms, $taxonomies, $args ) {
if ( in_array( 'post_format', (array) $taxonomies ) ) {
if ( isset( $args['fields'] ) && 'names' == $args['fields'] ) {
foreach( $terms as $order => $name ) {
$terms[$order] = get_post_format_string( str_replace( 'post-format-', '', $name ) );
}
} else {
foreach ( (array) $terms as $order => $term ) {
if ( isset( $term->taxonomy ) && 'post_format' == $term->taxonomy ) {
$terms[$order]->name = get_post_format_string( str_replace( 'post-format-', '', $term->slug ) );
}
}
}
}
return $terms;
}
add_filter( 'get_terms', '_post_format_get_terms', 10, 3 );
/**
* Remove the post format prefix from the name property of the term objects created by wp_get_object_terms().
*
* @access private
* @since 3.1.0
*/
function _post_format_wp_get_object_terms( $terms ) {
foreach ( (array) $terms as $order => $term ) {
if ( isset( $term->taxonomy ) && 'post_format' == $term->taxonomy ) {
$terms[$order]->name = get_post_format_string( str_replace( 'post-format-', '', $term->slug ) );
}
}
return $terms;
}
add_filter( 'wp_get_object_terms', '_post_format_wp_get_object_terms' );
| PHP |
<?php
/**
* PHPMailer RFC821 SMTP email transport class.
* Version 5.2.7
* PHP version 5.0.0
* @category PHP
* @package PHPMailer
* @link https://github.com/PHPMailer/PHPMailer/
* @author Marcus Bointon (coolbru) <phpmailer@synchromedia.co.uk>
* @author Jim Jagielski (jimjag) <jimjag@gmail.com>
* @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
* @copyright 2013 Marcus Bointon
* @copyright 2004 - 2008 Andy Prevost
* @copyright 2010 - 2012 Jim Jagielski
* @license http://www.gnu.org/copyleft/lesser.html Distributed under the Lesser General Public License (LGPL)
*/
/**
* PHPMailer RFC821 SMTP email transport class.
*
* Implements RFC 821 SMTP commands
* and provides some utility methods for sending mail to an SMTP server.
*
* PHP Version 5.0.0
*
* @category PHP
* @package PHPMailer
* @link https://github.com/PHPMailer/PHPMailer/blob/master/class.smtp.php
* @author Chris Ryan <unknown@example.com>
* @author Marcus Bointon <phpmailer@synchromedia.co.uk>
* @license http://www.gnu.org/copyleft/lesser.html Distributed under the Lesser General Public License (LGPL)
*/
class SMTP
{
/**
* The PHPMailer SMTP Version number.
*/
const VERSION = '5.2.7';
/**
* SMTP line break constant.
*/
const CRLF = "\r\n";
/**
* The SMTP port to use if one is not specified.
*/
const DEFAULT_SMTP_PORT = 25;
/**
* The PHPMailer SMTP Version number.
* @type string
* @deprecated This should be a constant
* @see SMTP::VERSION
*/
public $Version = '5.2.7';
/**
* SMTP server port number.
* @type int
* @deprecated This is only ever ued as default value, so should be a constant
* @see SMTP::DEFAULT_SMTP_PORT
*/
public $SMTP_PORT = 25;
/**
* SMTP reply line ending
* @type string
* @deprecated Use the class constant instead
* @see SMTP::CRLF
*/
public $CRLF = "\r\n";
/**
* Debug output level.
* Options: 0 for no output, 1 for commands, 2 for data and commands
* @type int
*/
public $do_debug = 0;
/**
* The function/method to use for debugging output.
* Options: 'echo', 'html' or 'error_log'
* @type string
*/
public $Debugoutput = 'echo';
/**
* Whether to use VERP.
* @type bool
*/
public $do_verp = false;
/**
* The SMTP timeout value for reads, in seconds.
* @type int
*/
public $Timeout = 15;
/**
* The SMTP timelimit value for reads, in seconds.
* @type int
*/
public $Timelimit = 30;
/**
* The socket for the server connection.
* @type resource
*/
protected $smtp_conn;
/**
* Error message, if any, for the last call.
* @type string
*/
protected $error = '';
/**
* The reply the server sent to us for HELO.
* @type string
*/
protected $helo_rply = '';
/**
* The most recent reply received from the server.
* @type string
*/
protected $last_reply = '';
/**
* Constructor.
* @access public
*/
public function __construct()
{
$this->smtp_conn = 0;
$this->error = null;
$this->helo_rply = null;
$this->do_debug = 0;
}
/**
* Output debugging info via a user-selected method.
* @param string $str Debug string to output
* @return void
*/
protected function edebug($str)
{
switch ($this->Debugoutput) {
case 'error_log':
//Don't output, just log
error_log($str);
break;
case 'html':
//Cleans up output a bit for a better looking, HTML-safe output
echo htmlentities(
preg_replace('/[\r\n]+/', '', $str),
ENT_QUOTES,
'UTF-8'
)
. "<br>\n";
break;
case 'echo':
default:
//Just echoes whatever was received
echo $str;
}
}
/**
* Connect to an SMTP server.
* @param string $host SMTP server IP or host name
* @param int $port The port number to connect to
* @param int $timeout How long to wait for the connection to open
* @param array $options An array of options for stream_context_create()
* @access public
* @return bool
*/
public function connect($host, $port = null, $timeout = 30, $options = array())
{
// Clear errors to avoid confusion
$this->error = null;
// Make sure we are __not__ connected
if ($this->connected()) {
// Already connected, generate error
$this->error = array('error' => 'Already connected to a server');
return false;
}
if (empty($port)) {
$port = self::DEFAULT_SMTP_PORT;
}
// Connect to the SMTP server
$errno = 0;
$errstr = '';
$socket_context = stream_context_create($options);
//Suppress errors; connection failures are handled at a higher level
$this->smtp_conn = @stream_socket_client(
$host . ":" . $port,
$errno,
$errstr,
$timeout,
STREAM_CLIENT_CONNECT,
$socket_context
);
// Verify we connected properly
if (empty($this->smtp_conn)) {
$this->error = array(
'error' => 'Failed to connect to server',
'errno' => $errno,
'errstr' => $errstr
);
if ($this->do_debug >= 1) {
$this->edebug(
'SMTP -> ERROR: ' . $this->error['error']
. ": $errstr ($errno)"
);
}
return false;
}
// SMTP server can take longer to respond, give longer timeout for first read
// Windows does not have support for this timeout function
if (substr(PHP_OS, 0, 3) != 'WIN') {
$max = ini_get('max_execution_time');
if ($max != 0 && $timeout > $max) { // Don't bother if unlimited
@set_time_limit($timeout);
}
stream_set_timeout($this->smtp_conn, $timeout, 0);
}
// Get any announcement
$announce = $this->get_lines();
if ($this->do_debug >= 2) {
$this->edebug('SMTP -> FROM SERVER:' . $announce);
}
return true;
}
/**
* Initiate a TLS (encrypted) session.
* @access public
* @return bool
*/
public function startTLS()
{
if (!$this->sendCommand("STARTTLS", "STARTTLS", 220)) {
return false;
}
// Begin encrypted connection
if (!stream_socket_enable_crypto(
$this->smtp_conn,
true,
STREAM_CRYPTO_METHOD_TLS_CLIENT
)
) {
return false;
}
return true;
}
/**
* Perform SMTP authentication.
* Must be run after hello().
* @see hello()
* @param string $username The user name
* @param string $password The password
* @param string $authtype The auth type (PLAIN, LOGIN, NTLM, CRAM-MD5)
* @param string $realm The auth realm for NTLM
* @param string $workstation The auth workstation for NTLM
* @access public
* @return bool True if successfully authenticated.
*/
public function authenticate(
$username,
$password,
$authtype = 'LOGIN',
$realm = '',
$workstation = ''
) {
if (empty($authtype)) {
$authtype = 'LOGIN';
}
switch ($authtype) {
case 'PLAIN':
// Start authentication
if (!$this->sendCommand('AUTH', 'AUTH PLAIN', 334)) {
return false;
}
// Send encoded username and password
if (!$this->sendCommand(
'User & Password',
base64_encode("\0" . $username . "\0" . $password),
235
)
) {
return false;
}
break;
case 'LOGIN':
// Start authentication
if (!$this->sendCommand('AUTH', 'AUTH LOGIN', 334)) {
return false;
}
if (!$this->sendCommand("Username", base64_encode($username), 334)) {
return false;
}
if (!$this->sendCommand("Password", base64_encode($password), 235)) {
return false;
}
break;
case 'NTLM':
/*
* ntlm_sasl_client.php
* Bundled with Permission
*
* How to telnet in windows:
* http://technet.microsoft.com/en-us/library/aa995718%28EXCHG.65%29.aspx
* PROTOCOL Docs http://curl.haxx.se/rfc/ntlm.html#ntlmSmtpAuthentication
*/
require_once 'extras/ntlm_sasl_client.php';
$temp = new stdClass();
$ntlm_client = new ntlm_sasl_client_class;
//Check that functions are available
if (!$ntlm_client->Initialize($temp)) {
$this->error = array('error' => $temp->error);
if ($this->do_debug >= 1) {
$this->edebug(
'You need to enable some modules in your php.ini file: '
. $this->error['error']
);
}
return false;
}
//msg1
$msg1 = $ntlm_client->TypeMsg1($realm, $workstation); //msg1
if (!$this->sendCommand(
'AUTH NTLM',
'AUTH NTLM ' . base64_encode($msg1),
334
)
) {
return false;
}
//Though 0 based, there is a white space after the 3 digit number
//msg2
$challenge = substr($this->last_reply, 3);
$challenge = base64_decode($challenge);
$ntlm_res = $ntlm_client->NTLMResponse(
substr($challenge, 24, 8),
$password
);
//msg3
$msg3 = $ntlm_client->TypeMsg3(
$ntlm_res,
$username,
$realm,
$workstation
);
// send encoded username
return $this->sendCommand('Username', base64_encode($msg3), 235);
break;
case 'CRAM-MD5':
// Start authentication
if (!$this->sendCommand('AUTH CRAM-MD5', 'AUTH CRAM-MD5', 334)) {
return false;
}
// Get the challenge
$challenge = base64_decode(substr($this->last_reply, 4));
// Build the response
$response = $username . ' ' . $this->hmac($challenge, $password);
// send encoded credentials
return $this->sendCommand('Username', base64_encode($response), 235);
break;
}
return true;
}
/**
* Calculate an MD5 HMAC hash.
* Works like hash_hmac('md5', $data, $key)
* in case that function is not available
* @param string $data The data to hash
* @param string $key The key to hash with
* @access protected
* @return string
*/
protected function hmac($data, $key)
{
if (function_exists('hash_hmac')) {
return hash_hmac('md5', $data, $key);
}
// The following borrowed from
// http://php.net/manual/en/function.mhash.php#27225
// RFC 2104 HMAC implementation for php.
// Creates an md5 HMAC.
// Eliminates the need to install mhash to compute a HMAC
// Hacked by Lance Rushing
$b = 64; // byte length for md5
if (strlen($key) > $b) {
$key = pack('H*', md5($key));
}
$key = str_pad($key, $b, chr(0x00));
$ipad = str_pad('', $b, chr(0x36));
$opad = str_pad('', $b, chr(0x5c));
$k_ipad = $key ^ $ipad;
$k_opad = $key ^ $opad;
return md5($k_opad . pack('H*', md5($k_ipad . $data)));
}
/**
* Check connection state.
* @access public
* @return bool True if connected.
*/
public function connected()
{
if (!empty($this->smtp_conn)) {
$sock_status = stream_get_meta_data($this->smtp_conn);
if ($sock_status['eof']) {
// the socket is valid but we are not connected
if ($this->do_debug >= 1) {
$this->edebug(
'SMTP -> NOTICE: EOF caught while checking if connected'
);
}
$this->close();
return false;
}
return true; // everything looks good
}
return false;
}
/**
* Close the socket and clean up the state of the class.
* Don't use this function without first trying to use QUIT.
* @see quit()
* @access public
* @return void
*/
public function close()
{
$this->error = null; // so there is no confusion
$this->helo_rply = null;
if (!empty($this->smtp_conn)) {
// close the connection and cleanup
fclose($this->smtp_conn);
$this->smtp_conn = 0;
}
}
/**
* Send an SMTP DATA command.
* Issues a data command and sends the msg_data to the server,
* finializing the mail transaction. $msg_data is the message
* that is to be send with the headers. Each header needs to be
* on a single line followed by a <CRLF> with the message headers
* and the message body being separated by and additional <CRLF>.
* Implements rfc 821: DATA <CRLF>
* @param string $msg_data Message data to send
* @access public
* @return bool
*/
public function data($msg_data)
{
if (!$this->sendCommand('DATA', 'DATA', 354)) {
return false;
}
/* The server is ready to accept data!
* according to rfc821 we should not send more than 1000
* including the CRLF
* characters on a single line so we will break the data up
* into lines by \r and/or \n then if needed we will break
* each of those into smaller lines to fit within the limit.
* in addition we will be looking for lines that start with
* a period '.' and append and additional period '.' to that
* line. NOTE: this does not count towards limit.
*/
// Normalize the line breaks before exploding
$msg_data = str_replace("\r\n", "\n", $msg_data);
$msg_data = str_replace("\r", "\n", $msg_data);
$lines = explode("\n", $msg_data);
/* We need to find a good way to determine if headers are
* in the msg_data or if it is a straight msg body
* currently I am assuming rfc822 definitions of msg headers
* and if the first field of the first line (':' separated)
* does not contain a space then it _should_ be a header
* and we can process all lines before a blank "" line as
* headers.
*/
$field = substr($lines[0], 0, strpos($lines[0], ':'));
$in_headers = false;
if (!empty($field) && !strstr($field, ' ')) {
$in_headers = true;
}
//RFC 2822 section 2.1.1 limit
$max_line_length = 998;
foreach ($lines as $line) {
$lines_out = null;
if ($line == '' && $in_headers) {
$in_headers = false;
}
// ok we need to break this line up into several smaller lines
while (strlen($line) > $max_line_length) {
$pos = strrpos(substr($line, 0, $max_line_length), ' ');
// Patch to fix DOS attack
if (!$pos) {
$pos = $max_line_length - 1;
$lines_out[] = substr($line, 0, $pos);
$line = substr($line, $pos);
} else {
$lines_out[] = substr($line, 0, $pos);
$line = substr($line, $pos + 1);
}
/* If processing headers add a LWSP-char to the front of new line
* rfc822 on long msg headers
*/
if ($in_headers) {
$line = "\t" . $line;
}
}
$lines_out[] = $line;
// send the lines to the server
while (list(, $line_out) = @each($lines_out)) {
if (strlen($line_out) > 0) {
if (substr($line_out, 0, 1) == '.') {
$line_out = '.' . $line_out;
}
}
$this->client_send($line_out . self::CRLF);
}
}
// Message data has been sent, complete the command
return $this->sendCommand('DATA END', '.', 250);
}
/**
* Send an SMTP HELO or EHLO command.
* Used to identify the sending server to the receiving server.
* This makes sure that client and server are in a known state.
* Implements from RFC 821: HELO <SP> <domain> <CRLF>
* and RFC 2821 EHLO.
* @param string $host The host name or IP to connect to
* @access public
* @return bool
*/
public function hello($host = '')
{
// Try extended hello first (RFC 2821)
if (!$this->sendHello('EHLO', $host)) {
if (!$this->sendHello('HELO', $host)) {
return false;
}
}
return true;
}
/**
* Send an SMTP HELO or EHLO command.
* Low-level implementation used by hello()
* @see hello()
* @param string $hello The HELO string
* @param string $host The hostname to say we are
* @access protected
* @return bool
*/
protected function sendHello($hello, $host)
{
$noerror = $this->sendCommand($hello, $hello . ' ' . $host, 250);
$this->helo_rply = $this->last_reply;
return $noerror;
}
/**
* Send an SMTP MAIL command.
* Starts a mail transaction from the email address specified in
* $from. Returns true if successful or false otherwise. If True
* the mail transaction is started and then one or more recipient
* commands may be called followed by a data command.
* Implements rfc 821: MAIL <SP> FROM:<reverse-path> <CRLF>
* @param string $from Source address of this message
* @access public
* @return bool
*/
public function mail($from)
{
$useVerp = ($this->do_verp ? ' XVERP' : '');
return $this->sendCommand(
'MAIL FROM',
'MAIL FROM:<' . $from . '>' . $useVerp,
250
);
}
/**
* Send an SMTP QUIT command.
* Closes the socket if there is no error or the $close_on_error argument is true.
* Implements from rfc 821: QUIT <CRLF>
* @param bool $close_on_error Should the connection close if an error occurs?
* @access public
* @return bool
*/
public function quit($close_on_error = true)
{
$noerror = $this->sendCommand('QUIT', 'QUIT', 221);
$e = $this->error; //Save any error
if ($noerror or $close_on_error) {
$this->close();
$this->error = $e; //Restore any error from the quit command
}
return $noerror;
}
/**
* Send an SMTP RCPT command.
* Sets the TO argument to $to.
* Returns true if the recipient was accepted false if it was rejected.
* Implements from rfc 821: RCPT <SP> TO:<forward-path> <CRLF>
* @param string $to The address the message is being sent to
* @access public
* @return bool
*/
public function recipient($to)
{
return $this->sendCommand(
'RCPT TO ',
'RCPT TO:<' . $to . '>',
array(250, 251)
);
}
/**
* Send an SMTP RSET command.
* Abort any transaction that is currently in progress.
* Implements rfc 821: RSET <CRLF>
* @access public
* @return bool True on success.
*/
public function reset()
{
return $this->sendCommand('RSET', 'RSET', 250);
}
/**
* Send a command to an SMTP server and check its return code.
* @param string $command The command name - not sent to the server
* @param string $commandstring The actual command to send
* @param int|array $expect One or more expected integer success codes
* @access protected
* @return bool True on success.
*/
protected function sendCommand($command, $commandstring, $expect)
{
if (!$this->connected()) {
$this->error = array(
"error" => "Called $command without being connected"
);
return false;
}
$this->client_send($commandstring . self::CRLF);
$reply = $this->get_lines();
$code = substr($reply, 0, 3);
if ($this->do_debug >= 2) {
$this->edebug('SMTP -> FROM SERVER:' . $reply);
}
if (!in_array($code, (array)$expect)) {
$this->last_reply = null;
$this->error = array(
"error" => "$command command failed",
"smtp_code" => $code,
"detail" => substr($reply, 4)
);
if ($this->do_debug >= 1) {
$this->edebug(
'SMTP -> ERROR: ' . $this->error['error'] . ': ' . $reply
);
}
return false;
}
$this->last_reply = $reply;
$this->error = null;
return true;
}
/**
* Send an SMTP SAML command.
* Starts a mail transaction from the email address specified in $from.
* Returns true if successful or false otherwise. If True
* the mail transaction is started and then one or more recipient
* commands may be called followed by a data command. This command
* will send the message to the users terminal if they are logged
* in and send them an email.
* Implements rfc 821: SAML <SP> FROM:<reverse-path> <CRLF>
* @param string $from The address the message is from
* @access public
* @return bool
*/
public function sendAndMail($from)
{
return $this->sendCommand("SAML", "SAML FROM:$from", 250);
}
/**
* Send an SMTP VRFY command.
* @param string $name The name to verify
* @access public
* @return bool
*/
public function verify($name)
{
return $this->sendCommand("VRFY", "VRFY $name", array(250, 251));
}
/**
* Send an SMTP NOOP command.
* Used to keep keep-alives alive, doesn't actually do anything
* @access public
* @return bool
*/
public function noop()
{
return $this->sendCommand("NOOP", "NOOP", 250);
}
/**
* Send an SMTP TURN command.
* This is an optional command for SMTP that this class does not support.
* This method is here to make the RFC821 Definition
* complete for this class and __may__ be implemented in future
* Implements from rfc 821: TURN <CRLF>
* @access public
* @return bool
*/
public function turn()
{
$this->error = array(
'error' => 'The SMTP TURN command is not implemented'
);
if ($this->do_debug >= 1) {
$this->edebug('SMTP -> NOTICE: ' . $this->error['error']);
}
return false;
}
/**
* Send raw data to the server.
* @param string $data The data to send
* @access public
* @return int|bool The number of bytes sent to the server or FALSE on error
*/
public function client_send($data)
{
if ($this->do_debug >= 1) {
$this->edebug("CLIENT -> SMTP: $data");
}
return fwrite($this->smtp_conn, $data);
}
/**
* Get the latest error.
* @access public
* @return array
*/
public function getError()
{
return $this->error;
}
/**
* Get the last reply from the server.
* @access public
* @return string
*/
public function getLastReply()
{
return $this->last_reply;
}
/**
* Read the SMTP server's response.
* Either before eof or socket timeout occurs on the operation.
* With SMTP we can tell if we have more lines to read if the
* 4th character is '-' symbol. If it is a space then we don't
* need to read anything else.
* @access protected
* @return string
*/
protected function get_lines()
{
$data = '';
$endtime = 0;
// If the connection is bad, give up now
if (!is_resource($this->smtp_conn)) {
return $data;
}
stream_set_timeout($this->smtp_conn, $this->Timeout);
if ($this->Timelimit > 0) {
$endtime = time() + $this->Timelimit;
}
while (is_resource($this->smtp_conn) && !feof($this->smtp_conn)) {
$str = @fgets($this->smtp_conn, 515);
if ($this->do_debug >= 4) {
$this->edebug("SMTP -> get_lines(): \$data was \"$data\"");
$this->edebug("SMTP -> get_lines(): \$str is \"$str\"");
}
$data .= $str;
if ($this->do_debug >= 4) {
$this->edebug("SMTP -> get_lines(): \$data is \"$data\"");
}
// if 4th character is a space, we are done reading, break the loop
if (substr($str, 3, 1) == ' ') {
break;
}
// Timed-out? Log and break
$info = stream_get_meta_data($this->smtp_conn);
if ($info['timed_out']) {
if ($this->do_debug >= 4) {
$this->edebug(
'SMTP -> get_lines(): timed-out (' . $this->Timeout . ' sec)'
);
}
break;
}
// Now check if reads took too long
if ($endtime) {
if (time() > $endtime) {
if ($this->do_debug >= 4) {
$this->edebug(
'SMTP -> get_lines(): timelimit reached ('
. $this->Timelimit . ' sec)'
);
}
break;
}
}
}
return $data;
}
/**
* Enable or disable VERP address generation.
* @param bool $enabled
*/
public function setVerp($enabled = false)
{
$this->do_verp = $enabled;
}
/**
* Get VERP address generation mode.
* @return bool
*/
public function getVerp()
{
return $this->do_verp;
}
/**
* Set debug output method.
* @param string $method The function/method to use for debugging output.
*/
public function setDebugOutput($method = 'echo')
{
$this->Debugoutput = $method;
}
/**
* Get debug output method.
* @return string
*/
public function getDebugOutput()
{
return $this->Debugoutput;
}
/**
* Set debug output level.
* @param int $level
*/
public function setDebugLevel($level = 0)
{
$this->do_debug = $level;
}
/**
* Get debug output level.
* @return int
*/
public function getDebugLevel()
{
return $this->do_debug;
}
/**
* Set SMTP timeout.
* @param int $timeout
*/
public function setTimeout($timeout = 0)
{
$this->Timeout = $timeout;
}
/**
* Get SMTP timeout.
* @return int
*/
public function getTimeout()
{
return $this->Timeout;
}
}
| PHP |
<?php
/**
* Object Cache API
*
* @link http://codex.wordpress.org/Function_Reference/WP_Cache
*
* @package WordPress
* @subpackage Cache
*/
/**
* Adds data to the cache, if the cache key doesn't already exist.
*
* @since 2.0.0
* @uses $wp_object_cache Object Cache Class
* @see WP_Object_Cache::add()
*
* @param int|string $key The cache key to use for retrieval later
* @param mixed $data The data to add to the cache store
* @param string $group The group to add the cache to
* @param int $expire When the cache data should be expired
* @return bool False if cache key and group already exist, true on success
*/
function wp_cache_add( $key, $data, $group = '', $expire = 0 ) {
global $wp_object_cache;
return $wp_object_cache->add( $key, $data, $group, (int) $expire );
}
/**
* Closes the cache.
*
* This function has ceased to do anything since WordPress 2.5. The
* functionality was removed along with the rest of the persistent cache. This
* does not mean that plugins can't implement this function when they need to
* make sure that the cache is cleaned up after WordPress no longer needs it.
*
* @since 2.0.0
*
* @return bool Always returns True
*/
function wp_cache_close() {
return true;
}
/**
* Decrement numeric cache item's value
*
* @since 3.3.0
* @uses $wp_object_cache Object Cache Class
* @see WP_Object_Cache::decr()
*
* @param int|string $key The cache key to increment
* @param int $offset The amount by which to decrement the item's value. Default is 1.
* @param string $group The group the key is in.
* @return false|int False on failure, the item's new value on success.
*/
function wp_cache_decr( $key, $offset = 1, $group = '' ) {
global $wp_object_cache;
return $wp_object_cache->decr( $key, $offset, $group );
}
/**
* Removes the cache contents matching key and group.
*
* @since 2.0.0
* @uses $wp_object_cache Object Cache Class
* @see WP_Object_Cache::delete()
*
* @param int|string $key What the contents in the cache are called
* @param string $group Where the cache contents are grouped
* @return bool True on successful removal, false on failure
*/
function wp_cache_delete($key, $group = '') {
global $wp_object_cache;
return $wp_object_cache->delete($key, $group);
}
/**
* Removes all cache items.
*
* @since 2.0.0
* @uses $wp_object_cache Object Cache Class
* @see WP_Object_Cache::flush()
*
* @return bool False on failure, true on success
*/
function wp_cache_flush() {
global $wp_object_cache;
return $wp_object_cache->flush();
}
/**
* Retrieves the cache contents from the cache by key and group.
*
* @since 2.0.0
* @uses $wp_object_cache Object Cache Class
* @see WP_Object_Cache::get()
*
* @param int|string $key What the contents in the cache are called
* @param string $group Where the cache contents are grouped
* @param bool $force Whether to force an update of the local cache from the persistent cache (default is false)
* @param &bool $found Whether key was found in the cache. Disambiguates a return of false, a storable value.
* @return bool|mixed False on failure to retrieve contents or the cache
* contents on success
*/
function wp_cache_get( $key, $group = '', $force = false, &$found = null ) {
global $wp_object_cache;
return $wp_object_cache->get( $key, $group, $force, $found );
}
/**
* Increment numeric cache item's value
*
* @since 3.3.0
* @uses $wp_object_cache Object Cache Class
* @see WP_Object_Cache::incr()
*
* @param int|string $key The cache key to increment
* @param int $offset The amount by which to increment the item's value. Default is 1.
* @param string $group The group the key is in.
* @return false|int False on failure, the item's new value on success.
*/
function wp_cache_incr( $key, $offset = 1, $group = '' ) {
global $wp_object_cache;
return $wp_object_cache->incr( $key, $offset, $group );
}
/**
* Sets up Object Cache Global and assigns it.
*
* @since 2.0.0
* @global WP_Object_Cache $wp_object_cache WordPress Object Cache
*/
function wp_cache_init() {
$GLOBALS['wp_object_cache'] = new WP_Object_Cache();
}
/**
* Replaces the contents of the cache with new data.
*
* @since 2.0.0
* @uses $wp_object_cache Object Cache Class
* @see WP_Object_Cache::replace()
*
* @param int|string $key What to call the contents in the cache
* @param mixed $data The contents to store in the cache
* @param string $group Where to group the cache contents
* @param int $expire When to expire the cache contents
* @return bool False if not exists, true if contents were replaced
*/
function wp_cache_replace( $key, $data, $group = '', $expire = 0 ) {
global $wp_object_cache;
return $wp_object_cache->replace( $key, $data, $group, (int) $expire );
}
/**
* Saves the data to the cache.
*
* @since 2.0.0
*
* @uses $wp_object_cache Object Cache Class
* @see WP_Object_Cache::set()
*
* @param int|string $key What to call the contents in the cache
* @param mixed $data The contents to store in the cache
* @param string $group Where to group the cache contents
* @param int $expire When to expire the cache contents
* @return bool False on failure, true on success
*/
function wp_cache_set( $key, $data, $group = '', $expire = 0 ) {
global $wp_object_cache;
return $wp_object_cache->set( $key, $data, $group, (int) $expire );
}
/**
* Switch the interal blog id.
*
* This changes the blog id used to create keys in blog specific groups.
*
* @since 3.5.0
*
* @param int $blog_id Blog ID
*/
function wp_cache_switch_to_blog( $blog_id ) {
global $wp_object_cache;
return $wp_object_cache->switch_to_blog( $blog_id );
}
/**
* Adds a group or set of groups to the list of global groups.
*
* @since 2.6.0
*
* @param string|array $groups A group or an array of groups to add
*/
function wp_cache_add_global_groups( $groups ) {
global $wp_object_cache;
return $wp_object_cache->add_global_groups( $groups );
}
/**
* Adds a group or set of groups to the list of non-persistent groups.
*
* @since 2.6.0
*
* @param string|array $groups A group or an array of groups to add
*/
function wp_cache_add_non_persistent_groups( $groups ) {
// Default cache doesn't persist so nothing to do here.
return;
}
/**
* Reset internal cache keys and structures. If the cache backend uses global
* blog or site IDs as part of its cache keys, this function instructs the
* backend to reset those keys and perform any cleanup since blog or site IDs
* have changed since cache init.
*
* This function is deprecated. Use wp_cache_switch_to_blog() instead of this
* function when preparing the cache for a blog switch. For clearing the cache
* during unit tests, consider using wp_cache_init(). wp_cache_init() is not
* recommended outside of unit tests as the performance penality for using it is
* high.
*
* @since 2.6.0
* @deprecated 3.5.0
*/
function wp_cache_reset() {
_deprecated_function( __FUNCTION__, '3.5' );
global $wp_object_cache;
return $wp_object_cache->reset();
}
/**
* WordPress Object Cache
*
* The WordPress Object Cache is used to save on trips to the database. The
* Object Cache stores all of the cache data to memory and makes the cache
* contents available by using a key, which is used to name and later retrieve
* the cache contents.
*
* The Object Cache can be replaced by other caching mechanisms by placing files
* in the wp-content folder which is looked at in wp-settings. If that file
* exists, then this file will not be included.
*
* @package WordPress
* @subpackage Cache
* @since 2.0.0
*/
class WP_Object_Cache {
/**
* Holds the cached objects
*
* @var array
* @access private
* @since 2.0.0
*/
var $cache = array ();
/**
* The amount of times the cache data was already stored in the cache.
*
* @since 2.5.0
* @access private
* @var int
*/
var $cache_hits = 0;
/**
* Amount of times the cache did not have the request in cache
*
* @var int
* @access public
* @since 2.0.0
*/
var $cache_misses = 0;
/**
* List of global groups
*
* @var array
* @access protected
* @since 3.0.0
*/
var $global_groups = array();
/**
* The blog prefix to prepend to keys in non-global groups.
*
* @var int
* @access private
* @since 3.5.0
*/
var $blog_prefix;
/**
* Adds data to the cache if it doesn't already exist.
*
* @uses WP_Object_Cache::_exists Checks to see if the cache already has data.
* @uses WP_Object_Cache::set Sets the data after the checking the cache
* contents existence.
*
* @since 2.0.0
*
* @param int|string $key What to call the contents in the cache
* @param mixed $data The contents to store in the cache
* @param string $group Where to group the cache contents
* @param int $expire When to expire the cache contents
* @return bool False if cache key and group already exist, true on success
*/
function add( $key, $data, $group = 'default', $expire = 0 ) {
if ( wp_suspend_cache_addition() )
return false;
if ( empty( $group ) )
$group = 'default';
$id = $key;
if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) )
$id = $this->blog_prefix . $key;
if ( $this->_exists( $id, $group ) )
return false;
return $this->set( $key, $data, $group, (int) $expire );
}
/**
* Sets the list of global groups.
*
* @since 3.0.0
*
* @param array $groups List of groups that are global.
*/
function add_global_groups( $groups ) {
$groups = (array) $groups;
$groups = array_fill_keys( $groups, true );
$this->global_groups = array_merge( $this->global_groups, $groups );
}
/**
* Decrement numeric cache item's value
*
* @since 3.3.0
*
* @param int|string $key The cache key to increment
* @param int $offset The amount by which to decrement the item's value. Default is 1.
* @param string $group The group the key is in.
* @return false|int False on failure, the item's new value on success.
*/
function decr( $key, $offset = 1, $group = 'default' ) {
if ( empty( $group ) )
$group = 'default';
if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) )
$key = $this->blog_prefix . $key;
if ( ! $this->_exists( $key, $group ) )
return false;
if ( ! is_numeric( $this->cache[ $group ][ $key ] ) )
$this->cache[ $group ][ $key ] = 0;
$offset = (int) $offset;
$this->cache[ $group ][ $key ] -= $offset;
if ( $this->cache[ $group ][ $key ] < 0 )
$this->cache[ $group ][ $key ] = 0;
return $this->cache[ $group ][ $key ];
}
/**
* Remove the contents of the cache key in the group
*
* If the cache key does not exist in the group, then nothing will happen.
*
* @since 2.0.0
*
* @param int|string $key What the contents in the cache are called
* @param string $group Where the cache contents are grouped
* @param bool $deprecated Deprecated.
*
* @return bool False if the contents weren't deleted and true on success
*/
function delete( $key, $group = 'default', $deprecated = false ) {
if ( empty( $group ) )
$group = 'default';
if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) )
$key = $this->blog_prefix . $key;
if ( ! $this->_exists( $key, $group ) )
return false;
unset( $this->cache[$group][$key] );
return true;
}
/**
* Clears the object cache of all data
*
* @since 2.0.0
*
* @return bool Always returns true
*/
function flush() {
$this->cache = array ();
return true;
}
/**
* Retrieves the cache contents, if it exists
*
* The contents will be first attempted to be retrieved by searching by the
* key in the cache group. If the cache is hit (success) then the contents
* are returned.
*
* On failure, the number of cache misses will be incremented.
*
* @since 2.0.0
*
* @param int|string $key What the contents in the cache are called
* @param string $group Where the cache contents are grouped
* @param string $force Whether to force a refetch rather than relying on the local cache (default is false)
* @return bool|mixed False on failure to retrieve contents or the cache
* contents on success
*/
function get( $key, $group = 'default', $force = false, &$found = null ) {
if ( empty( $group ) )
$group = 'default';
if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) )
$key = $this->blog_prefix . $key;
if ( $this->_exists( $key, $group ) ) {
$found = true;
$this->cache_hits += 1;
if ( is_object($this->cache[$group][$key]) )
return clone $this->cache[$group][$key];
else
return $this->cache[$group][$key];
}
$found = false;
$this->cache_misses += 1;
return false;
}
/**
* Increment numeric cache item's value
*
* @since 3.3.0
*
* @param int|string $key The cache key to increment
* @param int $offset The amount by which to increment the item's value. Default is 1.
* @param string $group The group the key is in.
* @return false|int False on failure, the item's new value on success.
*/
function incr( $key, $offset = 1, $group = 'default' ) {
if ( empty( $group ) )
$group = 'default';
if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) )
$key = $this->blog_prefix . $key;
if ( ! $this->_exists( $key, $group ) )
return false;
if ( ! is_numeric( $this->cache[ $group ][ $key ] ) )
$this->cache[ $group ][ $key ] = 0;
$offset = (int) $offset;
$this->cache[ $group ][ $key ] += $offset;
if ( $this->cache[ $group ][ $key ] < 0 )
$this->cache[ $group ][ $key ] = 0;
return $this->cache[ $group ][ $key ];
}
/**
* Replace the contents in the cache, if contents already exist
*
* @since 2.0.0
* @see WP_Object_Cache::set()
*
* @param int|string $key What to call the contents in the cache
* @param mixed $data The contents to store in the cache
* @param string $group Where to group the cache contents
* @param int $expire When to expire the cache contents
* @return bool False if not exists, true if contents were replaced
*/
function replace( $key, $data, $group = 'default', $expire = 0 ) {
if ( empty( $group ) )
$group = 'default';
$id = $key;
if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) )
$id = $this->blog_prefix . $key;
if ( ! $this->_exists( $id, $group ) )
return false;
return $this->set( $key, $data, $group, (int) $expire );
}
/**
* Reset keys
*
* @since 3.0.0
* @deprecated 3.5.0
*/
function reset() {
_deprecated_function( __FUNCTION__, '3.5', 'switch_to_blog()' );
// Clear out non-global caches since the blog ID has changed.
foreach ( array_keys( $this->cache ) as $group ) {
if ( ! isset( $this->global_groups[ $group ] ) )
unset( $this->cache[ $group ] );
}
}
/**
* Sets the data contents into the cache
*
* The cache contents is grouped by the $group parameter followed by the
* $key. This allows for duplicate ids in unique groups. Therefore, naming of
* the group should be used with care and should follow normal function
* naming guidelines outside of core WordPress usage.
*
* The $expire parameter is not used, because the cache will automatically
* expire for each time a page is accessed and PHP finishes. The method is
* more for cache plugins which use files.
*
* @since 2.0.0
*
* @param int|string $key What to call the contents in the cache
* @param mixed $data The contents to store in the cache
* @param string $group Where to group the cache contents
* @param int $expire Not Used
* @return bool Always returns true
*/
function set( $key, $data, $group = 'default', $expire = 0 ) {
if ( empty( $group ) )
$group = 'default';
if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) )
$key = $this->blog_prefix . $key;
if ( is_object( $data ) )
$data = clone $data;
$this->cache[$group][$key] = $data;
return true;
}
/**
* Echoes the stats of the caching.
*
* Gives the cache hits, and cache misses. Also prints every cached group,
* key and the data.
*
* @since 2.0.0
*/
function stats() {
echo "<p>";
echo "<strong>Cache Hits:</strong> {$this->cache_hits}<br />";
echo "<strong>Cache Misses:</strong> {$this->cache_misses}<br />";
echo "</p>";
echo '<ul>';
foreach ($this->cache as $group => $cache) {
echo "<li><strong>Group:</strong> $group - ( " . number_format( strlen( serialize( $cache ) ) / 1024, 2 ) . 'k )</li>';
}
echo '</ul>';
}
/**
* Switch the interal blog id.
*
* This changes the blog id used to create keys in blog specific groups.
*
* @since 3.5.0
*
* @param int $blog_id Blog ID
*/
function switch_to_blog( $blog_id ) {
$blog_id = (int) $blog_id;
$this->blog_prefix = $this->multisite ? $blog_id . ':' : '';
}
/**
* Utility function to determine whether a key exists in the cache.
*
* @since 3.4.0
*
* @access protected
*/
protected function _exists( $key, $group ) {
return isset( $this->cache[ $group ] ) && ( isset( $this->cache[ $group ][ $key ] ) || array_key_exists( $key, $this->cache[ $group ] ) );
}
/**
* Sets up object properties; PHP 5 style constructor
*
* @since 2.0.8
* @return null|WP_Object_Cache If cache is disabled, returns null.
*/
function __construct() {
global $blog_id;
$this->multisite = is_multisite();
$this->blog_prefix = $this->multisite ? $blog_id . ':' : '';
/**
* @todo This should be moved to the PHP4 style constructor, PHP5
* already calls __destruct()
*/
register_shutdown_function( array( $this, '__destruct' ) );
}
/**
* Will save the object cache before object is completely destroyed.
*
* Called upon object destruction, which should be when PHP ends.
*
* @since 2.0.8
*
* @return bool True value. Won't be used by PHP
*/
function __destruct() {
return true;
}
}
| PHP |
<?php
/**
* Customize Manager.
*
* Bootstraps the Customize experience on the server-side.
*
* Sets up the theme-switching process if a theme other than the active one is
* being previewed and customized.
*
* Serves as a factory for Customize Controls and Settings, and
* instantiates default Customize Controls and Settings.
*
* @package WordPress
* @subpackage Customize
* @since 3.4.0
*/
final class WP_Customize_Manager {
/**
* An instance of the theme that is being customized.
*
* @var WP_Theme
*/
protected $theme;
/**
* The directory name of the previously active theme (within the theme_root).
*
* @var string
*/
protected $original_stylesheet;
/**
* Whether filters have been set to change the active theme to the theme being
* customized.
*
* @var boolean
*/
protected $previewing = false;
/**
* Methods and properties deailing with managing widgets in the customizer.
*
* @var WP_Customize_Widgets
*/
public $widgets;
protected $settings = array();
protected $sections = array();
protected $controls = array();
protected $nonce_tick;
protected $customized;
/**
* $_POST values for Customize Settings.
*
* @var array
*/
private $_post_values;
/**
* Constructor.
*
* @since 3.4.0
*/
public function __construct() {
require( ABSPATH . WPINC . '/class-wp-customize-setting.php' );
require( ABSPATH . WPINC . '/class-wp-customize-section.php' );
require( ABSPATH . WPINC . '/class-wp-customize-control.php' );
require( ABSPATH . WPINC . '/class-wp-customize-widgets.php' );
$this->widgets = new WP_Customize_Widgets( $this );
add_filter( 'wp_die_handler', array( $this, 'wp_die_handler' ) );
add_action( 'setup_theme', array( $this, 'setup_theme' ) );
add_action( 'wp_loaded', array( $this, 'wp_loaded' ) );
// Run wp_redirect_status late to make sure we override the status last.
add_action( 'wp_redirect_status', array( $this, 'wp_redirect_status' ), 1000 );
// Do not spawn cron (especially the alternate cron) while running the customizer.
remove_action( 'init', 'wp_cron' );
// Do not run update checks when rendering the controls.
remove_action( 'admin_init', '_maybe_update_core' );
remove_action( 'admin_init', '_maybe_update_plugins' );
remove_action( 'admin_init', '_maybe_update_themes' );
add_action( 'wp_ajax_customize_save', array( $this, 'save' ) );
add_action( 'customize_register', array( $this, 'register_controls' ) );
add_action( 'customize_controls_init', array( $this, 'prepare_controls' ) );
add_action( 'customize_controls_enqueue_scripts', array( $this, 'enqueue_control_scripts' ) );
}
/**
* Return true if it's an AJAX request.
*
* @since 3.4.0
*
* @return bool
*/
public function doing_ajax() {
return isset( $_POST['customized'] ) || ( defined( 'DOING_AJAX' ) && DOING_AJAX );
}
/**
* Custom wp_die wrapper. Returns either the standard message for UI
* or the AJAX message.
*
* @since 3.4.0
*
* @param mixed $ajax_message AJAX return
* @param mixed $message UI message
*/
protected function wp_die( $ajax_message, $message = null ) {
if ( $this->doing_ajax() )
wp_die( $ajax_message );
if ( ! $message )
$message = __( 'Cheatin’ uh?' );
wp_die( $message );
}
/**
* Return the AJAX wp_die() handler if it's a customized request.
*
* @since 3.4.0
*
* @return string
*/
public function wp_die_handler() {
if ( $this->doing_ajax() )
return '_ajax_wp_die_handler';
return '_default_wp_die_handler';
}
/**
* Start preview and customize theme.
*
* Check if customize query variable exist. Init filters to filter the current theme.
*
* @since 3.4.0
*/
public function setup_theme() {
send_origin_headers();
if ( is_admin() && ! $this->doing_ajax() )
auth_redirect();
elseif ( $this->doing_ajax() && ! is_user_logged_in() )
$this->wp_die( 0 );
show_admin_bar( false );
if ( ! current_user_can( 'edit_theme_options' ) )
$this->wp_die( -1 );
$this->original_stylesheet = get_stylesheet();
$this->theme = wp_get_theme( isset( $_REQUEST['theme'] ) ? $_REQUEST['theme'] : null );
if ( $this->is_theme_active() ) {
// Once the theme is loaded, we'll validate it.
add_action( 'after_setup_theme', array( $this, 'after_setup_theme' ) );
} else {
// If the requested theme is not the active theme and the user doesn't have the
// switch_themes cap, bail.
if ( ! current_user_can( 'switch_themes' ) )
$this->wp_die( -1 );
// If the theme has errors while loading, bail.
if ( $this->theme()->errors() )
$this->wp_die( -1 );
// If the theme isn't allowed per multisite settings, bail.
if ( ! $this->theme()->is_allowed() )
$this->wp_die( -1 );
}
// All good, let's do some internal business to preview the theme.
$this->start_previewing_theme();
}
/**
* Callback to validate a theme once it is loaded
*
* @since 3.4.0
*/
function after_setup_theme() {
if ( ! $this->doing_ajax() && ! validate_current_theme() ) {
wp_redirect( 'themes.php?broken=true' );
exit;
}
}
/**
* Start previewing the selected theme by adding filters to change the current theme.
*
* @since 3.4.0
*/
public function start_previewing_theme() {
// Bail if we're already previewing.
if ( $this->is_preview() )
return;
$this->previewing = true;
if ( ! $this->is_theme_active() ) {
add_filter( 'template', array( $this, 'get_template' ) );
add_filter( 'stylesheet', array( $this, 'get_stylesheet' ) );
add_filter( 'pre_option_current_theme', array( $this, 'current_theme' ) );
// @link: http://core.trac.wordpress.org/ticket/20027
add_filter( 'pre_option_stylesheet', array( $this, 'get_stylesheet' ) );
add_filter( 'pre_option_template', array( $this, 'get_template' ) );
// Handle custom theme roots.
add_filter( 'pre_option_stylesheet_root', array( $this, 'get_stylesheet_root' ) );
add_filter( 'pre_option_template_root', array( $this, 'get_template_root' ) );
}
/**
* Fires once the Customizer theme preview has started.
*
* @since 3.4.0
*
* @param WP_Customize_Manager $this WP_Customize_Manager instance.
*/
do_action( 'start_previewing_theme', $this );
}
/**
* Stop previewing the selected theme.
*
* Removes filters to change the current theme.
*
* @since 3.4.0
*/
public function stop_previewing_theme() {
if ( ! $this->is_preview() )
return;
$this->previewing = false;
if ( ! $this->is_theme_active() ) {
remove_filter( 'template', array( $this, 'get_template' ) );
remove_filter( 'stylesheet', array( $this, 'get_stylesheet' ) );
remove_filter( 'pre_option_current_theme', array( $this, 'current_theme' ) );
// @link: http://core.trac.wordpress.org/ticket/20027
remove_filter( 'pre_option_stylesheet', array( $this, 'get_stylesheet' ) );
remove_filter( 'pre_option_template', array( $this, 'get_template' ) );
// Handle custom theme roots.
remove_filter( 'pre_option_stylesheet_root', array( $this, 'get_stylesheet_root' ) );
remove_filter( 'pre_option_template_root', array( $this, 'get_template_root' ) );
}
/**
* Fires once the Customizer theme preview has stopped.
*
* @since 3.4.0
*
* @param WP_Customize_Manager $this WP_Customize_Manager instance.
*/
do_action( 'stop_previewing_theme', $this );
}
/**
* Get the theme being customized.
*
* @since 3.4.0
*
* @return WP_Theme
*/
public function theme() {
return $this->theme;
}
/**
* Get the registered settings.
*
* @since 3.4.0
*
* @return array
*/
public function settings() {
return $this->settings;
}
/**
* Get the registered controls.
*
* @since 3.4.0
*
* @return array
*/
public function controls() {
return $this->controls;
}
/**
* Get the registered sections.
*
* @since 3.4.0
*
* @return array
*/
public function sections() {
return $this->sections;
}
/**
* Checks if the current theme is active.
*
* @since 3.4.0
*
* @return bool
*/
public function is_theme_active() {
return $this->get_stylesheet() == $this->original_stylesheet;
}
/**
* Register styles/scripts and initialize the preview of each setting
*
* @since 3.4.0
*/
public function wp_loaded() {
/**
* Fires once WordPress has loaded, allowing scripts and styles to be initialized.
*
* @since 3.4.0
*
* @param WP_Customize_Manager $this WP_Customize_Manager instance.
*/
do_action( 'customize_register', $this );
if ( $this->is_preview() && ! is_admin() )
$this->customize_preview_init();
}
/**
* Prevents AJAX requests from following redirects when previewing a theme
* by issuing a 200 response instead of a 30x.
*
* Instead, the JS will sniff out the location header.
*
* @since 3.4.0
*
* @param $status
* @return int
*/
public function wp_redirect_status( $status ) {
if ( $this->is_preview() && ! is_admin() )
return 200;
return $status;
}
/**
* Decode the $_POST['customized'] values for a specific Customize Setting.
*
* @since 3.4.0
*
* @param mixed $setting A WP_Customize_Setting derived object
* @return string $post_value Sanitized value
*/
public function post_value( $setting ) {
if ( ! isset( $this->_post_values ) ) {
if ( isset( $_POST['customized'] ) )
$this->_post_values = json_decode( wp_unslash( $_POST['customized'] ), true );
else
$this->_post_values = false;
}
if ( isset( $this->_post_values[ $setting->id ] ) )
return $setting->sanitize( $this->_post_values[ $setting->id ] );
}
/**
* Print javascript settings.
*
* @since 3.4.0
*/
public function customize_preview_init() {
$this->nonce_tick = check_ajax_referer( 'preview-customize_' . $this->get_stylesheet(), 'nonce' );
$this->prepare_controls();
wp_enqueue_script( 'customize-preview' );
add_action( 'wp_head', array( $this, 'customize_preview_base' ) );
add_action( 'wp_head', array( $this, 'customize_preview_html5' ) );
add_action( 'wp_footer', array( $this, 'customize_preview_settings' ), 20 );
add_action( 'shutdown', array( $this, 'customize_preview_signature' ), 1000 );
add_filter( 'wp_die_handler', array( $this, 'remove_preview_signature' ) );
foreach ( $this->settings as $setting ) {
$setting->preview();
}
/**
* Fires once the Customizer preview has initialized and JavaScript
* settings have been printed.
*
* @since 3.4.0
*
* @param WP_Customize_Manager $this WP_Customize_Manager instance.
*/
do_action( 'customize_preview_init', $this );
}
/**
* Print base element for preview frame.
*
* @since 3.4.0
*/
public function customize_preview_base() {
?><base href="<?php echo home_url( '/' ); ?>" /><?php
}
/**
* Print a workaround to handle HTML5 tags in IE < 9
*
* @since 3.4.0
*/
public function customize_preview_html5() { ?>
<!--[if lt IE 9]>
<script type="text/javascript">
var e = [ 'abbr', 'article', 'aside', 'audio', 'canvas', 'datalist', 'details',
'figure', 'footer', 'header', 'hgroup', 'mark', 'menu', 'meter', 'nav',
'output', 'progress', 'section', 'time', 'video' ];
for ( var i = 0; i < e.length; i++ ) {
document.createElement( e[i] );
}
</script>
<![endif]--><?php
}
/**
* Print javascript settings for preview frame.
*
* @since 3.4.0
*/
public function customize_preview_settings() {
$settings = array(
'values' => array(),
'channel' => esc_js( $_POST['customize_messenger_channel'] ),
);
if ( 2 == $this->nonce_tick ) {
$settings['nonce'] = array(
'save' => wp_create_nonce( 'save-customize_' . $this->get_stylesheet() ),
'preview' => wp_create_nonce( 'preview-customize_' . $this->get_stylesheet() )
);
}
foreach ( $this->settings as $id => $setting ) {
$settings['values'][ $id ] = $setting->js_value();
}
?>
<script type="text/javascript">
var _wpCustomizeSettings = <?php echo json_encode( $settings ); ?>;
</script>
<?php
}
/**
* Prints a signature so we can ensure the customizer was properly executed.
*
* @since 3.4.0
*/
public function customize_preview_signature() {
echo 'WP_CUSTOMIZER_SIGNATURE';
}
/**
* Removes the signature in case we experience a case where the customizer was not properly executed.
*
* @since 3.4.0
*/
public function remove_preview_signature( $return = null ) {
remove_action( 'shutdown', array( $this, 'customize_preview_signature' ), 1000 );
return $return;
}
/**
* Is it a theme preview?
*
* @since 3.4.0
*
* @return bool True if it's a preview, false if not.
*/
public function is_preview() {
return (bool) $this->previewing;
}
/**
* Retrieve the template name of the previewed theme.
*
* @since 3.4.0
*
* @return string Template name.
*/
public function get_template() {
return $this->theme()->get_template();
}
/**
* Retrieve the stylesheet name of the previewed theme.
*
* @since 3.4.0
*
* @return string Stylesheet name.
*/
public function get_stylesheet() {
return $this->theme()->get_stylesheet();
}
/**
* Retrieve the template root of the previewed theme.
*
* @since 3.4.0
*
* @return string Theme root.
*/
public function get_template_root() {
return get_raw_theme_root( $this->get_template(), true );
}
/**
* Retrieve the stylesheet root of the previewed theme.
*
* @since 3.4.0
*
* @return string Theme root.
*/
public function get_stylesheet_root() {
return get_raw_theme_root( $this->get_stylesheet(), true );
}
/**
* Filter the current theme and return the name of the previewed theme.
*
* @since 3.4.0
*
* @param $current_theme {@internal Parameter is not used}
* @return string Theme name.
*/
public function current_theme( $current_theme ) {
return $this->theme()->display('Name');
}
/**
* Switch the theme and trigger the save() method on each setting.
*
* @since 3.4.0
*/
public function save() {
if ( ! $this->is_preview() )
die;
check_ajax_referer( 'save-customize_' . $this->get_stylesheet(), 'nonce' );
// Do we have to switch themes?
if ( ! $this->is_theme_active() ) {
// Temporarily stop previewing the theme to allow switch_themes()
// to operate properly.
$this->stop_previewing_theme();
switch_theme( $this->get_stylesheet() );
update_option( 'theme_switched_via_customizer', true );
$this->start_previewing_theme();
}
/**
* Fires once the theme has switched in the Customizer, but before settings
* have been saved.
*
* @since 3.4.0
*
* @param WP_Customize_Manager $this WP_Customize_Manager instance.
*/
do_action( 'customize_save', $this );
foreach ( $this->settings as $setting ) {
$setting->save();
}
/**
* Fires after Customize settings have been saved.
*
* @since 3.6.0
*
* @param WP_Customize_Manager $this WP_Customize_Manager instance.
*/
do_action( 'customize_save_after', $this );
die;
}
/**
* Add a customize setting.
*
* @since 3.4.0
*
* @param WP_Customize_Setting|string $id Customize Setting object, or ID.
* @param array $args Setting arguments; passed to WP_Customize_Setting
* constructor.
*/
public function add_setting( $id, $args = array() ) {
if ( is_a( $id, 'WP_Customize_Setting' ) )
$setting = $id;
else
$setting = new WP_Customize_Setting( $this, $id, $args );
$this->settings[ $setting->id ] = $setting;
}
/**
* Retrieve a customize setting.
*
* @since 3.4.0
*
* @param string $id Customize Setting ID.
* @return WP_Customize_Setting
*/
public function get_setting( $id ) {
if ( isset( $this->settings[ $id ] ) )
return $this->settings[ $id ];
}
/**
* Remove a customize setting.
*
* @since 3.4.0
*
* @param string $id Customize Setting ID.
*/
public function remove_setting( $id ) {
unset( $this->settings[ $id ] );
}
/**
* Add a customize section.
*
* @since 3.4.0
*
* @param WP_Customize_Section|string $id Customize Section object, or Section ID.
* @param array $args Section arguments.
*/
public function add_section( $id, $args = array() ) {
if ( is_a( $id, 'WP_Customize_Section' ) )
$section = $id;
else
$section = new WP_Customize_Section( $this, $id, $args );
$this->sections[ $section->id ] = $section;
}
/**
* Retrieve a customize section.
*
* @since 3.4.0
*
* @param string $id Section ID.
* @return WP_Customize_Section
*/
public function get_section( $id ) {
if ( isset( $this->sections[ $id ] ) )
return $this->sections[ $id ];
}
/**
* Remove a customize section.
*
* @since 3.4.0
*
* @param string $id Section ID.
*/
public function remove_section( $id ) {
unset( $this->sections[ $id ] );
}
/**
* Add a customize control.
*
* @since 3.4.0
*
* @param WP_Customize_Control|string $id Customize Control object, or ID.
* @param array $args Control arguments; passed to WP_Customize_Control
* constructor.
*/
public function add_control( $id, $args = array() ) {
if ( is_a( $id, 'WP_Customize_Control' ) )
$control = $id;
else
$control = new WP_Customize_Control( $this, $id, $args );
$this->controls[ $control->id ] = $control;
}
/**
* Retrieve a customize control.
*
* @since 3.4.0
*
* @param string $id ID of the control.
* @return WP_Customize_Control $control The control object.
*/
public function get_control( $id ) {
if ( isset( $this->controls[ $id ] ) )
return $this->controls[ $id ];
}
/**
* Remove a customize control.
*
* @since 3.4.0
*
* @param string $id ID of the control.
*/
public function remove_control( $id ) {
unset( $this->controls[ $id ] );
}
/**
* Helper function to compare two objects by priority.
*
* @since 3.4.0
*
* @param object $a Object A.
* @param object $b Object B.
* @return int
*/
protected final function _cmp_priority( $a, $b ) {
$ap = $a->priority;
$bp = $b->priority;
if ( $ap == $bp )
return 0;
return ( $ap > $bp ) ? 1 : -1;
}
/**
* Prepare settings and sections.
*
* For each, check if required related components exist,
* whether the user has the necessary capabilities,
* and sort by priority.
*
* @since 3.4.0
*/
public function prepare_controls() {
$this->controls = array_reverse( $this->controls );
$controls = array();
foreach ( $this->controls as $id => $control ) {
if ( ! isset( $this->sections[ $control->section ] ) || ! $control->check_capabilities() )
continue;
$this->sections[ $control->section ]->controls[] = $control;
$controls[ $id ] = $control;
}
$this->controls = $controls;
// Prepare sections.
// Reversing makes uasort sort by time added when conflicts occur.
$this->sections = array_reverse( $this->sections );
uasort( $this->sections, array( $this, '_cmp_priority' ) );
$sections = array();
foreach ( $this->sections as $section ) {
if ( ! $section->check_capabilities() || ! $section->controls )
continue;
usort( $section->controls, array( $this, '_cmp_priority' ) );
$sections[] = $section;
}
$this->sections = $sections;
}
/**
* Enqueue scripts for customize controls.
*
* @since 3.4.0
*/
public function enqueue_control_scripts() {
foreach ( $this->controls as $control ) {
$control->enqueue();
}
}
/**
* Register some default controls.
*
* @since 3.4.0
*/
public function register_controls() {
/* Site Title & Tagline */
$this->add_section( 'title_tagline', array(
'title' => __( 'Site Title & Tagline' ),
'priority' => 20,
) );
$this->add_setting( 'blogname', array(
'default' => get_option( 'blogname' ),
'type' => 'option',
'capability' => 'manage_options',
) );
$this->add_control( 'blogname', array(
'label' => __( 'Site Title' ),
'section' => 'title_tagline',
) );
$this->add_setting( 'blogdescription', array(
'default' => get_option( 'blogdescription' ),
'type' => 'option',
'capability' => 'manage_options',
) );
$this->add_control( 'blogdescription', array(
'label' => __( 'Tagline' ),
'section' => 'title_tagline',
) );
/* Colors */
$this->add_section( 'colors', array(
'title' => __( 'Colors' ),
'priority' => 40,
) );
$this->add_setting( 'header_textcolor', array(
'theme_supports' => array( 'custom-header', 'header-text' ),
'default' => get_theme_support( 'custom-header', 'default-text-color' ),
'sanitize_callback' => array( $this, '_sanitize_header_textcolor' ),
'sanitize_js_callback' => 'maybe_hash_hex_color',
) );
// Input type: checkbox
// With custom value
$this->add_control( 'display_header_text', array(
'settings' => 'header_textcolor',
'label' => __( 'Display Header Text' ),
'section' => 'title_tagline',
'type' => 'checkbox',
) );
$this->add_control( new WP_Customize_Color_Control( $this, 'header_textcolor', array(
'label' => __( 'Header Text Color' ),
'section' => 'colors',
) ) );
// Input type: Color
// With sanitize_callback
$this->add_setting( 'background_color', array(
'default' => get_theme_support( 'custom-background', 'default-color' ),
'theme_supports' => 'custom-background',
'sanitize_callback' => 'sanitize_hex_color_no_hash',
'sanitize_js_callback' => 'maybe_hash_hex_color',
) );
$this->add_control( new WP_Customize_Color_Control( $this, 'background_color', array(
'label' => __( 'Background Color' ),
'section' => 'colors',
) ) );
/* Custom Header */
$this->add_section( 'header_image', array(
'title' => __( 'Header Image' ),
'theme_supports' => 'custom-header',
'priority' => 60,
) );
$this->add_setting( new WP_Customize_Filter_Setting( $this, 'header_image', array(
'default' => get_theme_support( 'custom-header', 'default-image' ),
'theme_supports' => 'custom-header',
) ) );
$this->add_setting( new WP_Customize_Header_Image_Setting( $this, 'header_image_data', array(
// 'default' => get_theme_support( 'custom-header', 'default-image' ),
'theme_supports' => 'custom-header',
) ) );
$this->add_control( new WP_Customize_Header_Image_Control( $this ) );
/* Custom Background */
$this->add_section( 'background_image', array(
'title' => __( 'Background Image' ),
'theme_supports' => 'custom-background',
'priority' => 80,
) );
$this->add_setting( 'background_image', array(
'default' => get_theme_support( 'custom-background', 'default-image' ),
'theme_supports' => 'custom-background',
) );
$this->add_setting( new WP_Customize_Background_Image_Setting( $this, 'background_image_thumb', array(
'theme_supports' => 'custom-background',
) ) );
$this->add_control( new WP_Customize_Background_Image_Control( $this ) );
$this->add_setting( 'background_repeat', array(
'default' => 'repeat',
'theme_supports' => 'custom-background',
) );
$this->add_control( 'background_repeat', array(
'label' => __( 'Background Repeat' ),
'section' => 'background_image',
'type' => 'radio',
'choices' => array(
'no-repeat' => __('No Repeat'),
'repeat' => __('Tile'),
'repeat-x' => __('Tile Horizontally'),
'repeat-y' => __('Tile Vertically'),
),
) );
$this->add_setting( 'background_position_x', array(
'default' => 'left',
'theme_supports' => 'custom-background',
) );
$this->add_control( 'background_position_x', array(
'label' => __( 'Background Position' ),
'section' => 'background_image',
'type' => 'radio',
'choices' => array(
'left' => __('Left'),
'center' => __('Center'),
'right' => __('Right'),
),
) );
$this->add_setting( 'background_attachment', array(
'default' => 'fixed',
'theme_supports' => 'custom-background',
) );
$this->add_control( 'background_attachment', array(
'label' => __( 'Background Attachment' ),
'section' => 'background_image',
'type' => 'radio',
'choices' => array(
'fixed' => __('Fixed'),
'scroll' => __('Scroll'),
),
) );
// If the theme is using the default background callback, we can update
// the background CSS using postMessage.
if ( get_theme_support( 'custom-background', 'wp-head-callback' ) === '_custom_background_cb' ) {
foreach ( array( 'color', 'image', 'position_x', 'repeat', 'attachment' ) as $prop ) {
$this->get_setting( 'background_' . $prop )->transport = 'postMessage';
}
}
/* Nav Menus */
$locations = get_registered_nav_menus();
$menus = wp_get_nav_menus();
$menu_locations = get_nav_menu_locations();
$num_locations = count( array_keys( $locations ) );
$this->add_section( 'nav', array(
'title' => __( 'Navigation' ),
'theme_supports' => 'menus',
'priority' => 100,
'description' => sprintf( _n('Your theme supports %s menu. Select which menu you would like to use.', 'Your theme supports %s menus. Select which menu appears in each location.', $num_locations ), number_format_i18n( $num_locations ) ) . "\n\n" . __('You can edit your menu content on the Menus screen in the Appearance section.'),
) );
if ( $menus ) {
$choices = array( 0 => __( '— Select —' ) );
foreach ( $menus as $menu ) {
$choices[ $menu->term_id ] = wp_html_excerpt( $menu->name, 40, '…' );
}
foreach ( $locations as $location => $description ) {
$menu_setting_id = "nav_menu_locations[{$location}]";
$this->add_setting( $menu_setting_id, array(
'sanitize_callback' => 'absint',
'theme_supports' => 'menus',
) );
$this->add_control( $menu_setting_id, array(
'label' => $description,
'section' => 'nav',
'type' => 'select',
'choices' => $choices,
) );
}
}
/* Static Front Page */
// #WP19627
$this->add_section( 'static_front_page', array(
'title' => __( 'Static Front Page' ),
// 'theme_supports' => 'static-front-page',
'priority' => 120,
'description' => __( 'Your theme supports a static front page.' ),
) );
$this->add_setting( 'show_on_front', array(
'default' => get_option( 'show_on_front' ),
'capability' => 'manage_options',
'type' => 'option',
// 'theme_supports' => 'static-front-page',
) );
$this->add_control( 'show_on_front', array(
'label' => __( 'Front page displays' ),
'section' => 'static_front_page',
'type' => 'radio',
'choices' => array(
'posts' => __( 'Your latest posts' ),
'page' => __( 'A static page' ),
),
) );
$this->add_setting( 'page_on_front', array(
'type' => 'option',
'capability' => 'manage_options',
// 'theme_supports' => 'static-front-page',
) );
$this->add_control( 'page_on_front', array(
'label' => __( 'Front page' ),
'section' => 'static_front_page',
'type' => 'dropdown-pages',
) );
$this->add_setting( 'page_for_posts', array(
'type' => 'option',
'capability' => 'manage_options',
// 'theme_supports' => 'static-front-page',
) );
$this->add_control( 'page_for_posts', array(
'label' => __( 'Posts page' ),
'section' => 'static_front_page',
'type' => 'dropdown-pages',
) );
}
/**
* Callback for validating the header_textcolor value.
*
* Accepts 'blank', and otherwise uses sanitize_hex_color_no_hash().
* Returns default text color if hex color is empty.
*
* @since 3.4.0
*
* @param string $color
* @return string
*/
public function _sanitize_header_textcolor( $color ) {
if ( 'blank' === $color )
return 'blank';
$color = sanitize_hex_color_no_hash( $color );
if ( empty( $color ) )
$color = get_theme_support( 'custom-header', 'default-text-color' );
return $color;
}
};
/**
* Sanitizes a hex color.
*
* Returns either '', a 3 or 6 digit hex color (with #), or null.
* For sanitizing values without a #, see sanitize_hex_color_no_hash().
*
* @since 3.4.0
*
* @param string $color
* @return string|null
*/
function sanitize_hex_color( $color ) {
if ( '' === $color )
return '';
// 3 or 6 hex digits, or the empty string.
if ( preg_match('|^#([A-Fa-f0-9]{3}){1,2}$|', $color ) )
return $color;
return null;
}
/**
* Sanitizes a hex color without a hash. Use sanitize_hex_color() when possible.
*
* Saving hex colors without a hash puts the burden of adding the hash on the
* UI, which makes it difficult to use or upgrade to other color types such as
* rgba, hsl, rgb, and html color names.
*
* Returns either '', a 3 or 6 digit hex color (without a #), or null.
*
* @since 3.4.0
* @uses sanitize_hex_color()
*
* @param string $color
* @return string|null
*/
function sanitize_hex_color_no_hash( $color ) {
$color = ltrim( $color, '#' );
if ( '' === $color )
return '';
return sanitize_hex_color( '#' . $color ) ? $color : null;
}
/**
* Ensures that any hex color is properly hashed.
* Otherwise, returns value untouched.
*
* This method should only be necessary if using sanitize_hex_color_no_hash().
*
* @since 3.4.0
*
* @param string $color
* @return string
*/
function maybe_hash_hex_color( $color ) {
if ( $unhashed = sanitize_hex_color_no_hash( $color ) )
return '#' . $unhashed;
return $color;
}
| PHP |
<?php
/**
* Post functions and post utility function.
*
* @package WordPress
* @subpackage Post
* @since 1.5.0
*/
//
// Post Type Registration
//
/**
* Creates the initial post types when 'init' action is fired.
*
* @since 2.9.0
*/
function create_initial_post_types() {
register_post_type( 'post', array(
'labels' => array(
'name_admin_bar' => _x( 'Post', 'add new on admin bar' ),
),
'public' => true,
'_builtin' => true, /* internal use only. don't use this when registering your own post type. */
'_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */
'capability_type' => 'post',
'map_meta_cap' => true,
'hierarchical' => false,
'rewrite' => false,
'query_var' => false,
'delete_with_user' => true,
'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'comments', 'revisions', 'post-formats' ),
) );
register_post_type( 'page', array(
'labels' => array(
'name_admin_bar' => _x( 'Page', 'add new on admin bar' ),
),
'public' => true,
'publicly_queryable' => false,
'_builtin' => true, /* internal use only. don't use this when registering your own post type. */
'_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */
'capability_type' => 'page',
'map_meta_cap' => true,
'hierarchical' => true,
'rewrite' => false,
'query_var' => false,
'delete_with_user' => true,
'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'page-attributes', 'custom-fields', 'comments', 'revisions' ),
) );
register_post_type( 'attachment', array(
'labels' => array(
'name' => _x('Media', 'post type general name'),
'name_admin_bar' => _x( 'Media', 'add new from admin bar' ),
'add_new' => _x( 'Add New', 'add new media' ),
'edit_item' => __( 'Edit Media' ),
'view_item' => __( 'View Attachment Page' ),
),
'public' => true,
'show_ui' => true,
'_builtin' => true, /* internal use only. don't use this when registering your own post type. */
'_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */
'capability_type' => 'post',
'capabilities' => array(
'create_posts' => 'upload_files',
),
'map_meta_cap' => true,
'hierarchical' => false,
'rewrite' => false,
'query_var' => false,
'show_in_nav_menus' => false,
'delete_with_user' => true,
'supports' => array( 'title', 'author', 'comments' ),
) );
add_post_type_support( 'attachment:audio', 'thumbnail' );
add_post_type_support( 'attachment:video', 'thumbnail' );
register_post_type( 'revision', array(
'labels' => array(
'name' => __( 'Revisions' ),
'singular_name' => __( 'Revision' ),
),
'public' => false,
'_builtin' => true, /* internal use only. don't use this when registering your own post type. */
'_edit_link' => 'revision.php?revision=%d', /* internal use only. don't use this when registering your own post type. */
'capability_type' => 'post',
'map_meta_cap' => true,
'hierarchical' => false,
'rewrite' => false,
'query_var' => false,
'can_export' => false,
'delete_with_user' => true,
'supports' => array( 'author' ),
) );
register_post_type( 'nav_menu_item', array(
'labels' => array(
'name' => __( 'Navigation Menu Items' ),
'singular_name' => __( 'Navigation Menu Item' ),
),
'public' => false,
'_builtin' => true, /* internal use only. don't use this when registering your own post type. */
'hierarchical' => false,
'rewrite' => false,
'delete_with_user' => false,
'query_var' => false,
) );
register_post_status( 'publish', array(
'label' => _x( 'Published', 'post' ),
'public' => true,
'_builtin' => true, /* internal use only. */
'label_count' => _n_noop( 'Published <span class="count">(%s)</span>', 'Published <span class="count">(%s)</span>' ),
) );
register_post_status( 'future', array(
'label' => _x( 'Scheduled', 'post' ),
'protected' => true,
'_builtin' => true, /* internal use only. */
'label_count' => _n_noop('Scheduled <span class="count">(%s)</span>', 'Scheduled <span class="count">(%s)</span>' ),
) );
register_post_status( 'draft', array(
'label' => _x( 'Draft', 'post' ),
'protected' => true,
'_builtin' => true, /* internal use only. */
'label_count' => _n_noop( 'Draft <span class="count">(%s)</span>', 'Drafts <span class="count">(%s)</span>' ),
) );
register_post_status( 'pending', array(
'label' => _x( 'Pending', 'post' ),
'protected' => true,
'_builtin' => true, /* internal use only. */
'label_count' => _n_noop( 'Pending <span class="count">(%s)</span>', 'Pending <span class="count">(%s)</span>' ),
) );
register_post_status( 'private', array(
'label' => _x( 'Private', 'post' ),
'private' => true,
'_builtin' => true, /* internal use only. */
'label_count' => _n_noop( 'Private <span class="count">(%s)</span>', 'Private <span class="count">(%s)</span>' ),
) );
register_post_status( 'trash', array(
'label' => _x( 'Trash', 'post' ),
'internal' => true,
'_builtin' => true, /* internal use only. */
'label_count' => _n_noop( 'Trash <span class="count">(%s)</span>', 'Trash <span class="count">(%s)</span>' ),
'show_in_admin_status_list' => true,
) );
register_post_status( 'auto-draft', array(
'label' => 'auto-draft',
'internal' => true,
'_builtin' => true, /* internal use only. */
) );
register_post_status( 'inherit', array(
'label' => 'inherit',
'internal' => true,
'_builtin' => true, /* internal use only. */
'exclude_from_search' => false,
) );
}
add_action( 'init', 'create_initial_post_types', 0 ); // highest priority
/**
* Retrieve attached file path based on attachment ID.
*
* By default the path will go through the 'get_attached_file' filter, but
* passing a true to the $unfiltered argument of get_attached_file() will
* return the file path unfiltered.
*
* The function works by getting the single post meta name, named
* '_wp_attached_file' and returning it. This is a convenience function to
* prevent looking up the meta name and provide a mechanism for sending the
* attached filename through a filter.
*
* @since 2.0.0
*
* @param int $attachment_id Attachment ID.
* @param bool $unfiltered Whether to apply filters.
* @return string|bool The file path to where the attached file should be, false otherwise.
*/
function get_attached_file( $attachment_id, $unfiltered = false ) {
$file = get_post_meta( $attachment_id, '_wp_attached_file', true );
// If the file is relative, prepend upload dir
if ( $file && 0 !== strpos($file, '/') && !preg_match('|^.:\\\|', $file) && ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) )
$file = $uploads['basedir'] . "/$file";
if ( $unfiltered )
return $file;
/**
* Filter the attached file based on the given ID.
*
* @since 2.1.0
*
* @param string $file Path to attached file.
* @param int $attachment_id Attachment ID.
*/
return apply_filters( 'get_attached_file', $file, $attachment_id );
}
/**
* Update attachment file path based on attachment ID.
*
* Used to update the file path of the attachment, which uses post meta name
* '_wp_attached_file' to store the path of the attachment.
*
* @since 2.1.0
*
* @param int $attachment_id Attachment ID
* @param string $file File path for the attachment
* @return bool True on success, false on failure.
*/
function update_attached_file( $attachment_id, $file ) {
if ( !get_post( $attachment_id ) )
return false;
/**
* Filter the path to the attached file to update.
*
* @since 2.1.0
*
* @param string $file Path to the attached file to update.
* @param int $attachment_id Attachment ID.
*/
$file = apply_filters( 'update_attached_file', $file, $attachment_id );
if ( $file = _wp_relative_upload_path( $file ) )
return update_post_meta( $attachment_id, '_wp_attached_file', $file );
else
return delete_post_meta( $attachment_id, '_wp_attached_file' );
}
/**
* Return relative path to an uploaded file.
*
* The path is relative to the current upload dir.
*
* @since 2.9.0
*
* @param string $path Full path to the file
* @return string relative path on success, unchanged path on failure.
*/
function _wp_relative_upload_path( $path ) {
$new_path = $path;
$uploads = wp_upload_dir();
if ( 0 === strpos( $new_path, $uploads['basedir'] ) ) {
$new_path = str_replace( $uploads['basedir'], '', $new_path );
$new_path = ltrim( $new_path, '/' );
}
/**
* Filter the relative path to an uploaded file.
*
* @since 2.9.0
*
* @param string $new_path Relative path to the file.
* @param string $path Full path to the file.
*/
return apply_filters( '_wp_relative_upload_path', $new_path, $path );
}
/**
* Retrieve all children of the post parent ID.
*
* Normally, without any enhancements, the children would apply to pages. In the
* context of the inner workings of WordPress, pages, posts, and attachments
* share the same table, so therefore the functionality could apply to any one
* of them. It is then noted that while this function does not work on posts, it
* does not mean that it won't work on posts. It is recommended that you know
* what context you wish to retrieve the children of.
*
* Attachments may also be made the child of a post, so if that is an accurate
* statement (which needs to be verified), it would then be possible to get
* all of the attachments for a post. Attachments have since changed since
* version 2.5, so this is most likely unaccurate, but serves generally as an
* example of what is possible.
*
* The arguments listed as defaults are for this function and also of the
* {@link get_posts()} function. The arguments are combined with the
* get_children defaults and are then passed to the {@link get_posts()}
* function, which accepts additional arguments. You can replace the defaults in
* this function, listed below and the additional arguments listed in the
* {@link get_posts()} function.
*
* The 'post_parent' is the most important argument and important attention
* needs to be paid to the $args parameter. If you pass either an object or an
* integer (number), then just the 'post_parent' is grabbed and everything else
* is lost. If you don't specify any arguments, then it is assumed that you are
* in The Loop and the post parent will be grabbed for from the current post.
*
* The 'post_parent' argument is the ID to get the children. The 'numberposts'
* is the amount of posts to retrieve that has a default of '-1', which is
* used to get all of the posts. Giving a number higher than 0 will only
* retrieve that amount of posts.
*
* The 'post_type' and 'post_status' arguments can be used to choose what
* criteria of posts to retrieve. The 'post_type' can be anything, but WordPress
* post types are 'post', 'pages', and 'attachments'. The 'post_status'
* argument will accept any post status within the write administration panels.
*
* @see get_posts() Has additional arguments that can be replaced.
* @internal Claims made in the long description might be inaccurate.
*
* @since 2.0.0
*
* @param mixed $args Optional. User defined arguments for replacing the defaults.
* @param string $output Optional. Constant for return type, either OBJECT (default), ARRAY_A, ARRAY_N.
* @return array|bool False on failure and the type will be determined by $output parameter.
*/
function get_children($args = '', $output = OBJECT) {
$kids = array();
if ( empty( $args ) ) {
if ( isset( $GLOBALS['post'] ) ) {
$args = array('post_parent' => (int) $GLOBALS['post']->post_parent );
} else {
return $kids;
}
} elseif ( is_object( $args ) ) {
$args = array('post_parent' => (int) $args->post_parent );
} elseif ( is_numeric( $args ) ) {
$args = array('post_parent' => (int) $args);
}
$defaults = array(
'numberposts' => -1, 'post_type' => 'any',
'post_status' => 'any', 'post_parent' => 0,
);
$r = wp_parse_args( $args, $defaults );
$children = get_posts( $r );
if ( ! $children )
return $kids;
if ( ! empty( $r['fields'] ) )
return $children;
update_post_cache($children);
foreach ( $children as $key => $child )
$kids[$child->ID] = $children[$key];
if ( $output == OBJECT ) {
return $kids;
} elseif ( $output == ARRAY_A ) {
foreach ( (array) $kids as $kid )
$weeuns[$kid->ID] = get_object_vars($kids[$kid->ID]);
return $weeuns;
} elseif ( $output == ARRAY_N ) {
foreach ( (array) $kids as $kid )
$babes[$kid->ID] = array_values(get_object_vars($kids[$kid->ID]));
return $babes;
} else {
return $kids;
}
}
/**
* Get extended entry info (<!--more-->).
*
* There should not be any space after the second dash and before the word
* 'more'. There can be text or space(s) after the word 'more', but won't be
* referenced.
*
* The returned array has 'main', 'extended', and 'more_text' keys. Main has the text before
* the <code><!--more--></code>. The 'extended' key has the content after the
* <code><!--more--></code> comment. The 'more_text' key has the custom "Read More" text.
*
* @since 1.0.0
*
* @param string $post Post content.
* @return array Post before ('main'), after ('extended'), and custom readmore ('more_text').
*/
function get_extended($post) {
//Match the new style more links
if ( preg_match('/<!--more(.*?)?-->/', $post, $matches) ) {
list($main, $extended) = explode($matches[0], $post, 2);
$more_text = $matches[1];
} else {
$main = $post;
$extended = '';
$more_text = '';
}
// ` leading and trailing whitespace
$main = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $main);
$extended = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $extended);
$more_text = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $more_text);
return array( 'main' => $main, 'extended' => $extended, 'more_text' => $more_text );
}
/**
* Retrieves post data given a post ID or post object.
*
* See {@link sanitize_post()} for optional $filter values. Also, the parameter
* $post, must be given as a variable, since it is passed by reference.
*
* @since 1.5.1
* @link http://codex.wordpress.org/Function_Reference/get_post
*
* @param int|WP_Post $post Optional. Post ID or post object.
* @param string $output Optional, default is Object. Either OBJECT, ARRAY_A, or ARRAY_N.
* @param string $filter Optional, default is raw.
* @return WP_Post|null WP_Post on success or null on failure
*/
function get_post( $post = null, $output = OBJECT, $filter = 'raw' ) {
if ( empty( $post ) && isset( $GLOBALS['post'] ) )
$post = $GLOBALS['post'];
if ( is_a( $post, 'WP_Post' ) ) {
$_post = $post;
} elseif ( is_object( $post ) ) {
if ( empty( $post->filter ) ) {
$_post = sanitize_post( $post, 'raw' );
$_post = new WP_Post( $_post );
} elseif ( 'raw' == $post->filter ) {
$_post = new WP_Post( $post );
} else {
$_post = WP_Post::get_instance( $post->ID );
}
} else {
$_post = WP_Post::get_instance( $post );
}
if ( ! $_post )
return null;
$_post = $_post->filter( $filter );
if ( $output == ARRAY_A )
return $_post->to_array();
elseif ( $output == ARRAY_N )
return array_values( $_post->to_array() );
return $_post;
}
/**
* WordPress Post class.
*
* @since 3.5.0
*
*/
final class WP_Post {
/**
* Post ID.
*
* @var int
*/
public $ID;
/**
* ID of post author.
*
* A numeric string, for compatibility reasons.
*
* @var string
*/
public $post_author = 0;
/**
* The post's local publication time.
*
* @var string
*/
public $post_date = '0000-00-00 00:00:00';
/**
* The post's GMT publication time.
*
* @var string
*/
public $post_date_gmt = '0000-00-00 00:00:00';
/**
* The post's content.
*
* @var string
*/
public $post_content = '';
/**
* The post's title.
*
* @var string
*/
public $post_title = '';
/**
* The post's excerpt.
*
* @var string
*/
public $post_excerpt = '';
/**
* The post's status.
*
* @var string
*/
public $post_status = 'publish';
/**
* Whether comments are allowed.
*
* @var string
*/
public $comment_status = 'open';
/**
* Whether pings are allowed.
*
* @var string
*/
public $ping_status = 'open';
/**
* The post's password in plain text.
*
* @var string
*/
public $post_password = '';
/**
* The post's slug.
*
* @var string
*/
public $post_name = '';
/**
* URLs queued to be pinged.
*
* @var string
*/
public $to_ping = '';
/**
* URLs that have been pinged.
*
* @var string
*/
public $pinged = '';
/**
* The post's local modified time.
*
* @var string
*/
public $post_modified = '0000-00-00 00:00:00';
/**
* The post's GMT modified time.
*
* @var string
*/
public $post_modified_gmt = '0000-00-00 00:00:00';
/**
* A utility DB field for post content.
*
*
* @var string
*/
public $post_content_filtered = '';
/**
* ID of a post's parent post.
*
* @var int
*/
public $post_parent = 0;
/**
* The unique identifier for a post, not necessarily a URL, used as the feed GUID.
*
* @var string
*/
public $guid = '';
/**
* A field used for ordering posts.
*
* @var int
*/
public $menu_order = 0;
/**
* The post's type, like post or page.
*
* @var string
*/
public $post_type = 'post';
/**
* An attachment's mime type.
*
* @var string
*/
public $post_mime_type = '';
/**
* Cached comment count.
*
* A numeric string, for compatibility reasons.
*
* @var string
*/
public $comment_count = 0;
/**
* Stores the post object's sanitization level.
*
* Does not correspond to a DB field.
*
* @var string
*/
public $filter;
public static function get_instance( $post_id ) {
global $wpdb;
$post_id = (int) $post_id;
if ( ! $post_id )
return false;
$_post = wp_cache_get( $post_id, 'posts' );
if ( ! $_post ) {
$_post = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE ID = %d LIMIT 1", $post_id ) );
if ( ! $_post )
return false;
$_post = sanitize_post( $_post, 'raw' );
wp_cache_add( $_post->ID, $_post, 'posts' );
} elseif ( empty( $_post->filter ) ) {
$_post = sanitize_post( $_post, 'raw' );
}
return new WP_Post( $_post );
}
public function __construct( $post ) {
foreach ( get_object_vars( $post ) as $key => $value )
$this->$key = $value;
}
public function __isset( $key ) {
if ( 'ancestors' == $key )
return true;
if ( 'page_template' == $key )
return ( 'page' == $this->post_type );
if ( 'post_category' == $key )
return true;
if ( 'tags_input' == $key )
return true;
return metadata_exists( 'post', $this->ID, $key );
}
public function __get( $key ) {
if ( 'page_template' == $key && $this->__isset( $key ) ) {
return get_post_meta( $this->ID, '_wp_page_template', true );
}
if ( 'post_category' == $key ) {
if ( is_object_in_taxonomy( $this->post_type, 'category' ) )
$terms = get_the_terms( $this, 'category' );
if ( empty( $terms ) )
return array();
return wp_list_pluck( $terms, 'term_id' );
}
if ( 'tags_input' == $key ) {
if ( is_object_in_taxonomy( $this->post_type, 'post_tag' ) )
$terms = get_the_terms( $this, 'post_tag' );
if ( empty( $terms ) )
return array();
return wp_list_pluck( $terms, 'name' );
}
// Rest of the values need filtering
if ( 'ancestors' == $key )
$value = get_post_ancestors( $this );
else
$value = get_post_meta( $this->ID, $key, true );
if ( $this->filter )
$value = sanitize_post_field( $key, $value, $this->ID, $this->filter );
return $value;
}
public function filter( $filter ) {
if ( $this->filter == $filter )
return $this;
if ( $filter == 'raw' )
return self::get_instance( $this->ID );
return sanitize_post( $this, $filter );
}
public function to_array() {
$post = get_object_vars( $this );
foreach ( array( 'ancestors', 'page_template', 'post_category', 'tags_input' ) as $key ) {
if ( $this->__isset( $key ) )
$post[ $key ] = $this->__get( $key );
}
return $post;
}
}
/**
* Retrieve ancestors of a post.
*
* @since 2.5.0
*
* @param int|WP_Post $post Post ID or post object.
* @return array Ancestor IDs or empty array if none are found.
*/
function get_post_ancestors( $post ) {
$post = get_post( $post );
if ( ! $post || empty( $post->post_parent ) || $post->post_parent == $post->ID )
return array();
$ancestors = array();
$id = $ancestors[] = $post->post_parent;
while ( $ancestor = get_post( $id ) ) {
// Loop detection: If the ancestor has been seen before, break.
if ( empty( $ancestor->post_parent ) || ( $ancestor->post_parent == $post->ID ) || in_array( $ancestor->post_parent, $ancestors ) )
break;
$id = $ancestors[] = $ancestor->post_parent;
}
return $ancestors;
}
/**
* Retrieve data from a post field based on Post ID.
*
* Examples of the post field will be, 'post_type', 'post_status', 'post_content',
* etc and based off of the post object property or key names.
*
* The context values are based off of the taxonomy filter functions and
* supported values are found within those functions.
*
* @since 2.3.0
* @uses sanitize_post_field() See for possible $context values.
*
* @param string $field Post field name.
* @param int|WP_Post $post Post ID or post object.
* @param string $context Optional. How to filter the field. Default is 'display'.
* @return string The value of the post field on success, empty string on failure.
*/
function get_post_field( $field, $post, $context = 'display' ) {
$post = get_post( $post );
if ( !$post )
return '';
if ( !isset($post->$field) )
return '';
return sanitize_post_field($field, $post->$field, $post->ID, $context);
}
/**
* Retrieve the mime type of an attachment based on the ID.
*
* This function can be used with any post type, but it makes more sense with
* attachments.
*
* @since 2.0.0
*
* @param int|WP_Post $ID Optional. Post ID or post object.
* @return string|bool The mime type on success, false on failure.
*/
function get_post_mime_type($ID = '') {
$post = get_post($ID);
if ( is_object($post) )
return $post->post_mime_type;
return false;
}
/**
* Retrieve the post status based on the Post ID.
*
* If the post ID is of an attachment, then the parent post status will be given
* instead.
*
* @since 2.0.0
*
* @param int|WP_Post $ID Optional. Post ID or post object.
* @return string|bool Post status on success, false on failure.
*/
function get_post_status($ID = '') {
$post = get_post($ID);
if ( !is_object($post) )
return false;
if ( 'attachment' == $post->post_type ) {
if ( 'private' == $post->post_status )
return 'private';
// Unattached attachments are assumed to be published
if ( ( 'inherit' == $post->post_status ) && ( 0 == $post->post_parent) )
return 'publish';
// Inherit status from the parent
if ( $post->post_parent && ( $post->ID != $post->post_parent ) )
return get_post_status($post->post_parent);
}
return $post->post_status;
}
/**
* Retrieve all of the WordPress supported post statuses.
*
* Posts have a limited set of valid status values, this provides the
* post_status values and descriptions.
*
* @since 2.5.0
*
* @return array List of post statuses.
*/
function get_post_statuses() {
$status = array(
'draft' => __('Draft'),
'pending' => __('Pending Review'),
'private' => __('Private'),
'publish' => __('Published')
);
return $status;
}
/**
* Retrieve all of the WordPress support page statuses.
*
* Pages have a limited set of valid status values, this provides the
* post_status values and descriptions.
*
* @since 2.5.0
*
* @return array List of page statuses.
*/
function get_page_statuses() {
$status = array(
'draft' => __('Draft'),
'private' => __('Private'),
'publish' => __('Published')
);
return $status;
}
/**
* Register a post status. Do not use before init.
*
* A simple function for creating or modifying a post status based on the
* parameters given. The function will accept an array (second optional
* parameter), along with a string for the post status name.
*
*
* Optional $args contents:
*
* label - A descriptive name for the post status marked for translation. Defaults to $post_status.
* public - Whether posts of this status should be shown in the front end of the site. Defaults to true.
* exclude_from_search - Whether to exclude posts with this post status from search results. Defaults to false.
* show_in_admin_all_list - Whether to include posts in the edit listing for their post type
* show_in_admin_status_list - Show in the list of statuses with post counts at the top of the edit
* listings, e.g. All (12) | Published (9) | My Custom Status (2) ...
*
* Arguments prefixed with an _underscore shouldn't be used by plugins and themes.
*
* @since 3.0.0
* @uses $wp_post_statuses Inserts new post status object into the list
*
* @param string $post_status Name of the post status.
* @param array|string $args See above description.
*/
function register_post_status($post_status, $args = array()) {
global $wp_post_statuses;
if (!is_array($wp_post_statuses))
$wp_post_statuses = array();
// Args prefixed with an underscore are reserved for internal use.
$defaults = array(
'label' => false,
'label_count' => false,
'exclude_from_search' => null,
'_builtin' => false,
'public' => null,
'internal' => null,
'protected' => null,
'private' => null,
'publicly_queryable' => null,
'show_in_admin_status_list' => null,
'show_in_admin_all_list' => null,
);
$args = wp_parse_args($args, $defaults);
$args = (object) $args;
$post_status = sanitize_key($post_status);
$args->name = $post_status;
if ( null === $args->public && null === $args->internal && null === $args->protected && null === $args->private )
$args->internal = true;
if ( null === $args->public )
$args->public = false;
if ( null === $args->private )
$args->private = false;
if ( null === $args->protected )
$args->protected = false;
if ( null === $args->internal )
$args->internal = false;
if ( null === $args->publicly_queryable )
$args->publicly_queryable = $args->public;
if ( null === $args->exclude_from_search )
$args->exclude_from_search = $args->internal;
if ( null === $args->show_in_admin_all_list )
$args->show_in_admin_all_list = !$args->internal;
if ( null === $args->show_in_admin_status_list )
$args->show_in_admin_status_list = !$args->internal;
if ( false === $args->label )
$args->label = $post_status;
if ( false === $args->label_count )
$args->label_count = array( $args->label, $args->label );
$wp_post_statuses[$post_status] = $args;
return $args;
}
/**
* Retrieve a post status object by name
*
* @since 3.0.0
* @uses $wp_post_statuses
* @see register_post_status
* @see get_post_statuses
*
* @param string $post_status The name of a registered post status
* @return object A post status object
*/
function get_post_status_object( $post_status ) {
global $wp_post_statuses;
if ( empty($wp_post_statuses[$post_status]) )
return null;
return $wp_post_statuses[$post_status];
}
/**
* Get a list of all registered post status objects.
*
* @since 3.0.0
* @uses $wp_post_statuses
* @see register_post_status
* @see get_post_status_object
*
* @param array|string $args An array of key => value arguments to match against the post status objects.
* @param string $output The type of output to return, either post status 'names' or 'objects'. 'names' is the default.
* @param string $operator The logical operation to perform. 'or' means only one element
* from the array needs to match; 'and' means all elements must match. The default is 'and'.
* @return array A list of post status names or objects
*/
function get_post_stati( $args = array(), $output = 'names', $operator = 'and' ) {
global $wp_post_statuses;
$field = ('names' == $output) ? 'name' : false;
return wp_filter_object_list($wp_post_statuses, $args, $operator, $field);
}
/**
* Whether the post type is hierarchical.
*
* A false return value might also mean that the post type does not exist.
*
* @since 3.0.0
* @see get_post_type_object
*
* @param string $post_type Post type name
* @return bool Whether post type is hierarchical.
*/
function is_post_type_hierarchical( $post_type ) {
if ( ! post_type_exists( $post_type ) )
return false;
$post_type = get_post_type_object( $post_type );
return $post_type->hierarchical;
}
/**
* Checks if a post type is registered.
*
* @since 3.0.0
* @uses get_post_type_object()
*
* @param string $post_type Post type name
* @return bool Whether post type is registered.
*/
function post_type_exists( $post_type ) {
return (bool) get_post_type_object( $post_type );
}
/**
* Retrieve the post type of the current post or of a given post.
*
* @since 2.1.0
*
* @param int|WP_Post $post Optional. Post ID or post object.
* @return string|bool Post type on success, false on failure.
*/
function get_post_type( $post = null ) {
if ( $post = get_post( $post ) )
return $post->post_type;
return false;
}
/**
* Retrieve a post type object by name
*
* @since 3.0.0
* @uses $wp_post_types
* @see register_post_type
* @see get_post_types
*
* @param string $post_type The name of a registered post type
* @return object A post type object
*/
function get_post_type_object( $post_type ) {
global $wp_post_types;
if ( empty($wp_post_types[$post_type]) )
return null;
return $wp_post_types[$post_type];
}
/**
* Get a list of all registered post type objects.
*
* @since 2.9.0
* @uses $wp_post_types
* @see register_post_type
*
* @param array|string $args An array of key => value arguments to match against the post type objects.
* @param string $output The type of output to return, either post type 'names' or 'objects'. 'names' is the default.
* @param string $operator The logical operation to perform. 'or' means only one element
* from the array needs to match; 'and' means all elements must match. The default is 'and'.
* @return array A list of post type names or objects
*/
function get_post_types( $args = array(), $output = 'names', $operator = 'and' ) {
global $wp_post_types;
$field = ('names' == $output) ? 'name' : false;
return wp_filter_object_list($wp_post_types, $args, $operator, $field);
}
/**
* Register a post type. Do not use before init.
*
* A function for creating or modifying a post type based on the
* parameters given. The function will accept an array (second optional
* parameter), along with a string for the post type name.
*
* Optional $args contents:
*
* - label - Name of the post type shown in the menu. Usually plural. If not set, labels['name'] will be used.
* - labels - An array of labels for this post type.
* * If not set, post labels are inherited for non-hierarchical types and page labels for hierarchical ones.
* * You can see accepted values in {@link get_post_type_labels()}.
* - description - A short descriptive summary of what the post type is. Defaults to blank.
* - public - Whether a post type is intended for use publicly either via the admin interface or by front-end users.
* * Defaults to false.
* * While the default settings of exclude_from_search, publicly_queryable, show_ui, and show_in_nav_menus are
* inherited from public, each does not rely on this relationship and controls a very specific intention.
* - hierarchical - Whether the post type is hierarchical (e.g. page). Defaults to false.
* - exclude_from_search - Whether to exclude posts with this post type from front end search results.
* * If not set, the opposite of public's current value is used.
* - publicly_queryable - Whether queries can be performed on the front end for the post type as part of parse_request().
* * ?post_type={post_type_key}
* * ?{post_type_key}={single_post_slug}
* * ?{post_type_query_var}={single_post_slug}
* * If not set, the default is inherited from public.
* - show_ui - Whether to generate a default UI for managing this post type in the admin.
* * If not set, the default is inherited from public.
* - show_in_menu - Where to show the post type in the admin menu.
* * If true, the post type is shown in its own top level menu.
* * If false, no menu is shown
* * If a string of an existing top level menu (eg. 'tools.php' or 'edit.php?post_type=page'), the post type will
* be placed as a sub menu of that.
* * show_ui must be true.
* * If not set, the default is inherited from show_ui
* - show_in_nav_menus - Makes this post type available for selection in navigation menus.
* * If not set, the default is inherited from public.
* - show_in_admin_bar - Makes this post type available via the admin bar.
* * If not set, the default is inherited from show_in_menu
* - menu_position - The position in the menu order the post type should appear.
* * show_in_menu must be true
* * Defaults to null, which places it at the bottom of its area.
* - menu_icon - The url to the icon to be used for this menu. Defaults to use the posts icon.
* * Pass a base64-encoded SVG using a data URI, which will be colored to match the color scheme.
* This should begin with 'data:image/svg+xml;base64,'.
* * Pass the name of a Dashicons helper class to use a font icon, e.g. 'dashicons-chart-pie'.
* * Pass 'none' to leave div.wp-menu-image empty so an icon can be added via CSS.
* - capability_type - The string to use to build the read, edit, and delete capabilities. Defaults to 'post'.
* * May be passed as an array to allow for alternative plurals when using this argument as a base to construct the
* capabilities, e.g. array('story', 'stories').
* - capabilities - Array of capabilities for this post type.
* * By default the capability_type is used as a base to construct capabilities.
* * You can see accepted values in {@link get_post_type_capabilities()}.
* - map_meta_cap - Whether to use the internal default meta capability handling. Defaults to false.
* - supports - An alias for calling add_post_type_support() directly. Defaults to title and editor.
* * See {@link add_post_type_support()} for documentation.
* - register_meta_box_cb - Provide a callback function that sets up the meta boxes
* for the edit form. Do remove_meta_box() and add_meta_box() calls in the callback.
* - taxonomies - An array of taxonomy identifiers that will be registered for the post type.
* * Default is no taxonomies.
* * Taxonomies can be registered later with register_taxonomy() or register_taxonomy_for_object_type().
* - has_archive - True to enable post type archives. Default is false.
* * Will generate the proper rewrite rules if rewrite is enabled.
* - rewrite - Triggers the handling of rewrites for this post type. Defaults to true, using $post_type as slug.
* * To prevent rewrite, set to false.
* * To specify rewrite rules, an array can be passed with any of these keys
* * 'slug' => string Customize the permastruct slug. Defaults to $post_type key
* * 'with_front' => bool Should the permastruct be prepended with WP_Rewrite::$front. Defaults to true.
* * 'feeds' => bool Should a feed permastruct be built for this post type. Inherits default from has_archive.
* * 'pages' => bool Should the permastruct provide for pagination. Defaults to true.
* * 'ep_mask' => const Assign an endpoint mask.
* * If not specified and permalink_epmask is set, inherits from permalink_epmask.
* * If not specified and permalink_epmask is not set, defaults to EP_PERMALINK
* - query_var - Sets the query_var key for this post type. Defaults to $post_type key
* * If false, a post type cannot be loaded at ?{query_var}={post_slug}
* * If specified as a string, the query ?{query_var_string}={post_slug} will be valid.
* - can_export - Allows this post type to be exported. Defaults to true.
* - delete_with_user - Whether to delete posts of this type when deleting a user.
* * If true, posts of this type belonging to the user will be moved to trash when then user is deleted.
* * If false, posts of this type belonging to the user will *not* be trashed or deleted.
* * If not set (the default), posts are trashed if post_type_supports('author'). Otherwise posts are not trashed or deleted.
* - _builtin - true if this post type is a native or "built-in" post_type. THIS IS FOR INTERNAL USE ONLY!
* - _edit_link - URL segement to use for edit link of this post type. THIS IS FOR INTERNAL USE ONLY!
*
* @since 2.9.0
* @uses $wp_post_types Inserts new post type object into the list
* @uses $wp_rewrite Gets default feeds
* @uses $wp Adds query vars
*
* @param string $post_type Post type key, must not exceed 20 characters.
* @param array|string $args See optional args description above.
* @return object|WP_Error the registered post type object, or an error object.
*/
function register_post_type( $post_type, $args = array() ) {
global $wp_post_types, $wp_rewrite, $wp;
if ( ! is_array( $wp_post_types ) )
$wp_post_types = array();
// Args prefixed with an underscore are reserved for internal use.
$defaults = array(
'labels' => array(),
'description' => '',
'public' => false,
'hierarchical' => false,
'exclude_from_search' => null,
'publicly_queryable' => null,
'show_ui' => null,
'show_in_menu' => null,
'show_in_nav_menus' => null,
'show_in_admin_bar' => null,
'menu_position' => null,
'menu_icon' => null,
'capability_type' => 'post',
'capabilities' => array(),
'map_meta_cap' => null,
'supports' => array(),
'register_meta_box_cb' => null,
'taxonomies' => array(),
'has_archive' => false,
'rewrite' => true,
'query_var' => true,
'can_export' => true,
'delete_with_user' => null,
'_builtin' => false,
'_edit_link' => 'post.php?post=%d',
);
$args = wp_parse_args( $args, $defaults );
$args = (object) $args;
$post_type = sanitize_key( $post_type );
$args->name = $post_type;
if ( strlen( $post_type ) > 20 )
return new WP_Error( 'post_type_too_long', __( 'Post types cannot exceed 20 characters in length' ) );
// If not set, default to the setting for public.
if ( null === $args->publicly_queryable )
$args->publicly_queryable = $args->public;
// If not set, default to the setting for public.
if ( null === $args->show_ui )
$args->show_ui = $args->public;
// If not set, default to the setting for show_ui.
if ( null === $args->show_in_menu || ! $args->show_ui )
$args->show_in_menu = $args->show_ui;
// If not set, default to the whether the full UI is shown.
if ( null === $args->show_in_admin_bar )
$args->show_in_admin_bar = true === $args->show_in_menu;
// If not set, default to the setting for public.
if ( null === $args->show_in_nav_menus )
$args->show_in_nav_menus = $args->public;
// If not set, default to true if not public, false if public.
if ( null === $args->exclude_from_search )
$args->exclude_from_search = !$args->public;
// Back compat with quirky handling in version 3.0. #14122
if ( empty( $args->capabilities ) && null === $args->map_meta_cap && in_array( $args->capability_type, array( 'post', 'page' ) ) )
$args->map_meta_cap = true;
// If not set, default to false.
if ( null === $args->map_meta_cap )
$args->map_meta_cap = false;
$args->cap = get_post_type_capabilities( $args );
unset( $args->capabilities );
if ( is_array( $args->capability_type ) )
$args->capability_type = $args->capability_type[0];
if ( ! empty( $args->supports ) ) {
add_post_type_support( $post_type, $args->supports );
unset( $args->supports );
} elseif ( false !== $args->supports ) {
// Add default features
add_post_type_support( $post_type, array( 'title', 'editor' ) );
}
if ( false !== $args->query_var && ! empty( $wp ) ) {
if ( true === $args->query_var )
$args->query_var = $post_type;
else
$args->query_var = sanitize_title_with_dashes( $args->query_var );
$wp->add_query_var( $args->query_var );
}
if ( false !== $args->rewrite && ( is_admin() || '' != get_option( 'permalink_structure' ) ) ) {
if ( ! is_array( $args->rewrite ) )
$args->rewrite = array();
if ( empty( $args->rewrite['slug'] ) )
$args->rewrite['slug'] = $post_type;
if ( ! isset( $args->rewrite['with_front'] ) )
$args->rewrite['with_front'] = true;
if ( ! isset( $args->rewrite['pages'] ) )
$args->rewrite['pages'] = true;
if ( ! isset( $args->rewrite['feeds'] ) || ! $args->has_archive )
$args->rewrite['feeds'] = (bool) $args->has_archive;
if ( ! isset( $args->rewrite['ep_mask'] ) ) {
if ( isset( $args->permalink_epmask ) )
$args->rewrite['ep_mask'] = $args->permalink_epmask;
else
$args->rewrite['ep_mask'] = EP_PERMALINK;
}
if ( $args->hierarchical )
add_rewrite_tag( "%$post_type%", '(.+?)', $args->query_var ? "{$args->query_var}=" : "post_type=$post_type&pagename=" );
else
add_rewrite_tag( "%$post_type%", '([^/]+)', $args->query_var ? "{$args->query_var}=" : "post_type=$post_type&name=" );
if ( $args->has_archive ) {
$archive_slug = $args->has_archive === true ? $args->rewrite['slug'] : $args->has_archive;
if ( $args->rewrite['with_front'] )
$archive_slug = substr( $wp_rewrite->front, 1 ) . $archive_slug;
else
$archive_slug = $wp_rewrite->root . $archive_slug;
add_rewrite_rule( "{$archive_slug}/?$", "index.php?post_type=$post_type", 'top' );
if ( $args->rewrite['feeds'] && $wp_rewrite->feeds ) {
$feeds = '(' . trim( implode( '|', $wp_rewrite->feeds ) ) . ')';
add_rewrite_rule( "{$archive_slug}/feed/$feeds/?$", "index.php?post_type=$post_type" . '&feed=$matches[1]', 'top' );
add_rewrite_rule( "{$archive_slug}/$feeds/?$", "index.php?post_type=$post_type" . '&feed=$matches[1]', 'top' );
}
if ( $args->rewrite['pages'] )
add_rewrite_rule( "{$archive_slug}/{$wp_rewrite->pagination_base}/([0-9]{1,})/?$", "index.php?post_type=$post_type" . '&paged=$matches[1]', 'top' );
}
$permastruct_args = $args->rewrite;
$permastruct_args['feed'] = $permastruct_args['feeds'];
add_permastruct( $post_type, "{$args->rewrite['slug']}/%$post_type%", $permastruct_args );
}
if ( $args->register_meta_box_cb )
add_action( 'add_meta_boxes_' . $post_type, $args->register_meta_box_cb, 10, 1 );
$args->labels = get_post_type_labels( $args );
$args->label = $args->labels->name;
$wp_post_types[ $post_type ] = $args;
add_action( 'future_' . $post_type, '_future_post_hook', 5, 2 );
foreach ( $args->taxonomies as $taxonomy ) {
register_taxonomy_for_object_type( $taxonomy, $post_type );
}
/**
* Fires after a post type is registered.
*
* @since 3.3.0
*
* @param string $post_type Post type.
* @param array $args Arguments used to register the post type.
*/
do_action( 'registered_post_type', $post_type, $args );
return $args;
}
/**
* Builds an object with all post type capabilities out of a post type object
*
* Post type capabilities use the 'capability_type' argument as a base, if the
* capability is not set in the 'capabilities' argument array or if the
* 'capabilities' argument is not supplied.
*
* The capability_type argument can optionally be registered as an array, with
* the first value being singular and the second plural, e.g. array('story, 'stories')
* Otherwise, an 's' will be added to the value for the plural form. After
* registration, capability_type will always be a string of the singular value.
*
* By default, seven keys are accepted as part of the capabilities array:
*
* - edit_post, read_post, and delete_post are meta capabilities, which are then
* generally mapped to corresponding primitive capabilities depending on the
* context, which would be the post being edited/read/deleted and the user or
* role being checked. Thus these capabilities would generally not be granted
* directly to users or roles.
*
* - edit_posts - Controls whether objects of this post type can be edited.
* - edit_others_posts - Controls whether objects of this type owned by other users
* can be edited. If the post type does not support an author, then this will
* behave like edit_posts.
* - publish_posts - Controls publishing objects of this post type.
* - read_private_posts - Controls whether private objects can be read.
*
* These four primitive capabilities are checked in core in various locations.
* There are also seven other primitive capabilities which are not referenced
* directly in core, except in map_meta_cap(), which takes the three aforementioned
* meta capabilities and translates them into one or more primitive capabilities
* that must then be checked against the user or role, depending on the context.
*
* - read - Controls whether objects of this post type can be read.
* - delete_posts - Controls whether objects of this post type can be deleted.
* - delete_private_posts - Controls whether private objects can be deleted.
* - delete_published_posts - Controls whether published objects can be deleted.
* - delete_others_posts - Controls whether objects owned by other users can be
* can be deleted. If the post type does not support an author, then this will
* behave like delete_posts.
* - edit_private_posts - Controls whether private objects can be edited.
* - edit_published_posts - Controls whether published objects can be edited.
*
* These additional capabilities are only used in map_meta_cap(). Thus, they are
* only assigned by default if the post type is registered with the 'map_meta_cap'
* argument set to true (default is false).
*
* @see map_meta_cap()
* @since 3.0.0
*
* @param object $args Post type registration arguments
* @return object object with all the capabilities as member variables
*/
function get_post_type_capabilities( $args ) {
if ( ! is_array( $args->capability_type ) )
$args->capability_type = array( $args->capability_type, $args->capability_type . 's' );
// Singular base for meta capabilities, plural base for primitive capabilities.
list( $singular_base, $plural_base ) = $args->capability_type;
$default_capabilities = array(
// Meta capabilities
'edit_post' => 'edit_' . $singular_base,
'read_post' => 'read_' . $singular_base,
'delete_post' => 'delete_' . $singular_base,
// Primitive capabilities used outside of map_meta_cap():
'edit_posts' => 'edit_' . $plural_base,
'edit_others_posts' => 'edit_others_' . $plural_base,
'publish_posts' => 'publish_' . $plural_base,
'read_private_posts' => 'read_private_' . $plural_base,
);
// Primitive capabilities used within map_meta_cap():
if ( $args->map_meta_cap ) {
$default_capabilities_for_mapping = array(
'read' => 'read',
'delete_posts' => 'delete_' . $plural_base,
'delete_private_posts' => 'delete_private_' . $plural_base,
'delete_published_posts' => 'delete_published_' . $plural_base,
'delete_others_posts' => 'delete_others_' . $plural_base,
'edit_private_posts' => 'edit_private_' . $plural_base,
'edit_published_posts' => 'edit_published_' . $plural_base,
);
$default_capabilities = array_merge( $default_capabilities, $default_capabilities_for_mapping );
}
$capabilities = array_merge( $default_capabilities, $args->capabilities );
// Post creation capability simply maps to edit_posts by default:
if ( ! isset( $capabilities['create_posts'] ) )
$capabilities['create_posts'] = $capabilities['edit_posts'];
// Remember meta capabilities for future reference.
if ( $args->map_meta_cap )
_post_type_meta_capabilities( $capabilities );
return (object) $capabilities;
}
/**
* Stores or returns a list of post type meta caps for map_meta_cap().
*
* @since 3.1.0
* @access private
*/
function _post_type_meta_capabilities( $capabilities = null ) {
static $meta_caps = array();
if ( null === $capabilities )
return $meta_caps;
foreach ( $capabilities as $core => $custom ) {
if ( in_array( $core, array( 'read_post', 'delete_post', 'edit_post' ) ) )
$meta_caps[ $custom ] = $core;
}
}
/**
* Builds an object with all post type labels out of a post type object
*
* Accepted keys of the label array in the post type object:
* - name - general name for the post type, usually plural. The same and overridden by $post_type_object->label. Default is Posts/Pages
* - singular_name - name for one object of this post type. Default is Post/Page
* - add_new - Default is Add New for both hierarchical and non-hierarchical types. When internationalizing this string, please use a {@link http://codex.wordpress.org/I18n_for_WordPress_Developers#Disambiguation_by_context gettext context} matching your post type. Example: <code>_x('Add New', 'product');</code>
* - add_new_item - Default is Add New Post/Add New Page
* - edit_item - Default is Edit Post/Edit Page
* - new_item - Default is New Post/New Page
* - view_item - Default is View Post/View Page
* - search_items - Default is Search Posts/Search Pages
* - not_found - Default is No posts found/No pages found
* - not_found_in_trash - Default is No posts found in Trash/No pages found in Trash
* - parent_item_colon - This string isn't used on non-hierarchical types. In hierarchical ones the default is Parent Page:
* - all_items - String for the submenu. Default is All Posts/All Pages
* - menu_name - Default is the same as <code>name</code>
*
* Above, the first default value is for non-hierarchical post types (like posts) and the second one is for hierarchical post types (like pages).
*
* @since 3.0.0
* @access private
*
* @param object $post_type_object
* @return object object with all the labels as member variables
*/
function get_post_type_labels( $post_type_object ) {
$nohier_vs_hier_defaults = array(
'name' => array( _x('Posts', 'post type general name'), _x('Pages', 'post type general name') ),
'singular_name' => array( _x('Post', 'post type singular name'), _x('Page', 'post type singular name') ),
'add_new' => array( _x('Add New', 'post'), _x('Add New', 'page') ),
'add_new_item' => array( __('Add New Post'), __('Add New Page') ),
'edit_item' => array( __('Edit Post'), __('Edit Page') ),
'new_item' => array( __('New Post'), __('New Page') ),
'view_item' => array( __('View Post'), __('View Page') ),
'search_items' => array( __('Search Posts'), __('Search Pages') ),
'not_found' => array( __('No posts found.'), __('No pages found.') ),
'not_found_in_trash' => array( __('No posts found in Trash.'), __('No pages found in Trash.') ),
'parent_item_colon' => array( null, __('Parent Page:') ),
'all_items' => array( __( 'All Posts' ), __( 'All Pages' ) )
);
$nohier_vs_hier_defaults['menu_name'] = $nohier_vs_hier_defaults['name'];
$labels = _get_custom_object_labels( $post_type_object, $nohier_vs_hier_defaults );
$post_type = $post_type_object->name;
/**
* Filter the labels of a specific post type.
*
* The dynamic portion of the hook name, $post_type, refers to
* the post type slug.
*
* @since 3.5.0
*
* @see get_post_type_labels() for the full list of labels.
*
* @param array $labels Array of labels for the given post type.
*/
return apply_filters( "post_type_labels_{$post_type}", $labels );
}
/**
* Builds an object with custom-something object (post type, taxonomy) labels out of a custom-something object
*
* @access private
* @since 3.0.0
*/
function _get_custom_object_labels( $object, $nohier_vs_hier_defaults ) {
$object->labels = (array) $object->labels;
if ( isset( $object->label ) && empty( $object->labels['name'] ) )
$object->labels['name'] = $object->label;
if ( !isset( $object->labels['singular_name'] ) && isset( $object->labels['name'] ) )
$object->labels['singular_name'] = $object->labels['name'];
if ( ! isset( $object->labels['name_admin_bar'] ) )
$object->labels['name_admin_bar'] = isset( $object->labels['singular_name'] ) ? $object->labels['singular_name'] : $object->name;
if ( !isset( $object->labels['menu_name'] ) && isset( $object->labels['name'] ) )
$object->labels['menu_name'] = $object->labels['name'];
if ( !isset( $object->labels['all_items'] ) && isset( $object->labels['menu_name'] ) )
$object->labels['all_items'] = $object->labels['menu_name'];
foreach ( $nohier_vs_hier_defaults as $key => $value )
$defaults[$key] = $object->hierarchical ? $value[1] : $value[0];
$labels = array_merge( $defaults, $object->labels );
return (object)$labels;
}
/**
* Adds submenus for post types.
*
* @access private
* @since 3.1.0
*/
function _add_post_type_submenus() {
foreach ( get_post_types( array( 'show_ui' => true ) ) as $ptype ) {
$ptype_obj = get_post_type_object( $ptype );
// Submenus only.
if ( ! $ptype_obj->show_in_menu || $ptype_obj->show_in_menu === true )
continue;
add_submenu_page( $ptype_obj->show_in_menu, $ptype_obj->labels->name, $ptype_obj->labels->all_items, $ptype_obj->cap->edit_posts, "edit.php?post_type=$ptype" );
}
}
add_action( 'admin_menu', '_add_post_type_submenus' );
/**
* Register support of certain features for a post type.
*
* All core features are directly associated with a functional area of the edit
* screen, such as the editor or a meta box. Features include: 'title', 'editor',
* 'comments', 'revisions', 'trackbacks', 'author', 'excerpt', 'page-attributes',
* 'thumbnail', 'custom-fields', and 'post-formats'.
*
* Additionally, the 'revisions' feature dictates whether the post type will
* store revisions, and the 'comments' feature dictates whether the comments
* count will show on the edit screen.
*
* @since 3.0.0
*
* @param string $post_type The post type for which to add the feature.
* @param string|array $feature The feature being added, accpets an array of
* feature strings or a single string.
*/
function add_post_type_support( $post_type, $feature ) {
global $_wp_post_type_features;
$features = (array) $feature;
foreach ($features as $feature) {
if ( func_num_args() == 2 )
$_wp_post_type_features[$post_type][$feature] = true;
else
$_wp_post_type_features[$post_type][$feature] = array_slice( func_get_args(), 2 );
}
}
/**
* Remove support for a feature from a post type.
*
* @since 3.0.0
* @param string $post_type The post type for which to remove the feature
* @param string $feature The feature being removed
*/
function remove_post_type_support( $post_type, $feature ) {
global $_wp_post_type_features;
if ( isset( $_wp_post_type_features[$post_type][$feature] ) )
unset( $_wp_post_type_features[$post_type][$feature] );
}
/**
* Get all the post type features
*
* @since 3.4.0
* @param string $post_type The post type
* @return array
*/
function get_all_post_type_supports( $post_type ) {
global $_wp_post_type_features;
if ( isset( $_wp_post_type_features[$post_type] ) )
return $_wp_post_type_features[$post_type];
return array();
}
/**
* Checks a post type's support for a given feature
*
* @since 3.0.0
* @param string $post_type The post type being checked
* @param string $feature the feature being checked
* @return boolean
*/
function post_type_supports( $post_type, $feature ) {
global $_wp_post_type_features;
return ( isset( $_wp_post_type_features[$post_type][$feature] ) );
}
/**
* Updates the post type for the post ID.
*
* The page or post cache will be cleaned for the post ID.
*
* @since 2.5.0
*
* @uses $wpdb
*
* @param int $post_id Post ID to change post type. Not actually optional.
* @param string $post_type Optional, default is post. Supported values are 'post' or 'page' to
* name a few.
* @return int Amount of rows changed. Should be 1 for success and 0 for failure.
*/
function set_post_type( $post_id = 0, $post_type = 'post' ) {
global $wpdb;
$post_type = sanitize_post_field('post_type', $post_type, $post_id, 'db');
$return = $wpdb->update( $wpdb->posts, array('post_type' => $post_type), array('ID' => $post_id) );
clean_post_cache( $post_id );
return $return;
}
/**
* Retrieve list of latest posts or posts matching criteria.
*
* The defaults are as follows:
* 'numberposts' - Default is 5. Total number of posts to retrieve.
* 'offset' - Default is 0. See {@link WP_Query::query()} for more.
* 'category' - What category to pull the posts from.
* 'orderby' - Default is 'date', which orders based on post_date. How to order the posts.
* 'order' - Default is 'DESC'. The order to retrieve the posts.
* 'include' - See {@link WP_Query::query()} for more.
* 'exclude' - See {@link WP_Query::query()} for more.
* 'meta_key' - See {@link WP_Query::query()} for more.
* 'meta_value' - See {@link WP_Query::query()} for more.
* 'post_type' - Default is 'post'. Can be 'page', or 'attachment' to name a few.
* 'post_parent' - The parent of the post or post type.
* 'post_status' - Default is 'publish'. Post status to retrieve.
*
* @since 1.2.0
* @uses WP_Query::query() See for more default arguments and information.
* @link http://codex.wordpress.org/Template_Tags/get_posts
*
* @param array $args Optional. Overrides defaults.
* @return array List of posts.
*/
function get_posts($args = null) {
$defaults = array(
'numberposts' => 5, 'offset' => 0,
'category' => 0, 'orderby' => 'date',
'order' => 'DESC', 'include' => array(),
'exclude' => array(), 'meta_key' => '',
'meta_value' =>'', 'post_type' => 'post',
'suppress_filters' => true
);
$r = wp_parse_args( $args, $defaults );
if ( empty( $r['post_status'] ) )
$r['post_status'] = ( 'attachment' == $r['post_type'] ) ? 'inherit' : 'publish';
if ( ! empty($r['numberposts']) && empty($r['posts_per_page']) )
$r['posts_per_page'] = $r['numberposts'];
if ( ! empty($r['category']) )
$r['cat'] = $r['category'];
if ( ! empty($r['include']) ) {
$incposts = wp_parse_id_list( $r['include'] );
$r['posts_per_page'] = count($incposts); // only the number of posts included
$r['post__in'] = $incposts;
} elseif ( ! empty($r['exclude']) )
$r['post__not_in'] = wp_parse_id_list( $r['exclude'] );
$r['ignore_sticky_posts'] = true;
$r['no_found_rows'] = true;
$get_posts = new WP_Query;
return $get_posts->query($r);
}
//
// Post meta functions
//
/**
* Add meta data field to a post.
*
* Post meta data is called "Custom Fields" on the Administration Screen.
*
* @since 1.5.0
* @link http://codex.wordpress.org/Function_Reference/add_post_meta
*
* @param int $post_id Post ID.
* @param string $meta_key Metadata name.
* @param mixed $meta_value Metadata value. Must be serializable if non-scalar.
* @param bool $unique Optional, default is false. Whether the same key should not be added.
* @return int|bool Meta ID on success, false on failure.
*/
function add_post_meta($post_id, $meta_key, $meta_value, $unique = false) {
// make sure meta is added to the post, not a revision
if ( $the_post = wp_is_post_revision($post_id) )
$post_id = $the_post;
return add_metadata('post', $post_id, $meta_key, $meta_value, $unique);
}
/**
* Remove metadata matching criteria from a post.
*
* You can match based on the key, or key and value. Removing based on key and
* value, will keep from removing duplicate metadata with the same key. It also
* allows removing all metadata matching key, if needed.
*
* @since 1.5.0
* @link http://codex.wordpress.org/Function_Reference/delete_post_meta
*
* @param int $post_id post ID
* @param string $meta_key Metadata name.
* @param mixed $meta_value Optional. Metadata value. Must be serializable if non-scalar.
* @return bool True on success, false on failure.
*/
function delete_post_meta($post_id, $meta_key, $meta_value = '') {
// make sure meta is added to the post, not a revision
if ( $the_post = wp_is_post_revision($post_id) )
$post_id = $the_post;
return delete_metadata('post', $post_id, $meta_key, $meta_value);
}
/**
* Retrieve post meta field for a post.
*
* @since 1.5.0
* @link http://codex.wordpress.org/Function_Reference/get_post_meta
*
* @param int $post_id Post ID.
* @param string $key Optional. The meta key to retrieve. By default, returns data for all keys.
* @param bool $single Whether to return a single value.
* @return mixed Will be an array if $single is false. Will be value of meta data field if $single
* is true.
*/
function get_post_meta($post_id, $key = '', $single = false) {
return get_metadata('post', $post_id, $key, $single);
}
/**
* Update post meta field based on post ID.
*
* Use the $prev_value parameter to differentiate between meta fields with the
* same key and post ID.
*
* If the meta field for the post does not exist, it will be added.
*
* @since 1.5.0
* @link http://codex.wordpress.org/Function_Reference/update_post_meta
*
* @param int $post_id Post ID.
* @param string $meta_key Metadata key.
* @param mixed $meta_value Metadata value. Must be serializable if non-scalar.
* @param mixed $prev_value Optional. Previous value to check before removing.
* @return int|bool Meta ID if the key didn't exist, true on successful update, false on failure.
*/
function update_post_meta($post_id, $meta_key, $meta_value, $prev_value = '') {
// make sure meta is added to the post, not a revision
if ( $the_post = wp_is_post_revision($post_id) )
$post_id = $the_post;
return update_metadata('post', $post_id, $meta_key, $meta_value, $prev_value);
}
/**
* Delete everything from post meta matching meta key.
*
* @since 2.3.0
*
* @param string $post_meta_key Key to search for when deleting.
* @return bool Whether the post meta key was deleted from the database
*/
function delete_post_meta_by_key($post_meta_key) {
return delete_metadata( 'post', null, $post_meta_key, '', true );
}
/**
* Retrieve post meta fields, based on post ID.
*
* The post meta fields are retrieved from the cache where possible,
* so the function is optimized to be called more than once.
*
* @since 1.2.0
* @link http://codex.wordpress.org/Function_Reference/get_post_custom
*
* @param int $post_id Post ID.
* @return array
*/
function get_post_custom( $post_id = 0 ) {
$post_id = absint( $post_id );
if ( ! $post_id )
$post_id = get_the_ID();
return get_post_meta( $post_id );
}
/**
* Retrieve meta field names for a post.
*
* If there are no meta fields, then nothing (null) will be returned.
*
* @since 1.2.0
* @link http://codex.wordpress.org/Function_Reference/get_post_custom_keys
*
* @param int $post_id post ID
* @return array|null Either array of the keys, or null if keys could not be retrieved.
*/
function get_post_custom_keys( $post_id = 0 ) {
$custom = get_post_custom( $post_id );
if ( !is_array($custom) )
return;
if ( $keys = array_keys($custom) )
return $keys;
}
/**
* Retrieve values for a custom post field.
*
* The parameters must not be considered optional. All of the post meta fields
* will be retrieved and only the meta field key values returned.
*
* @since 1.2.0
* @link http://codex.wordpress.org/Function_Reference/get_post_custom_values
*
* @param string $key Meta field key.
* @param int $post_id Post ID
* @return array Meta field values.
*/
function get_post_custom_values( $key = '', $post_id = 0 ) {
if ( !$key )
return null;
$custom = get_post_custom($post_id);
return isset($custom[$key]) ? $custom[$key] : null;
}
/**
* Check if post is sticky.
*
* Sticky posts should remain at the top of The Loop. If the post ID is not
* given, then The Loop ID for the current post will be used.
*
* @since 2.7.0
*
* @param int $post_id Optional. Post ID.
* @return bool Whether post is sticky.
*/
function is_sticky( $post_id = 0 ) {
$post_id = absint( $post_id );
if ( ! $post_id )
$post_id = get_the_ID();
$stickies = get_option( 'sticky_posts' );
if ( ! is_array( $stickies ) )
return false;
if ( in_array( $post_id, $stickies ) )
return true;
return false;
}
/**
* Sanitize every post field.
*
* If the context is 'raw', then the post object or array will get minimal santization of the int fields.
*
* @since 2.3.0
* @uses sanitize_post_field() Used to sanitize the fields.
*
* @param object|WP_Post|array $post The Post Object or Array
* @param string $context Optional, default is 'display'. How to sanitize post fields.
* @return object|WP_Post|array The now sanitized Post Object or Array (will be the same type as $post)
*/
function sanitize_post($post, $context = 'display') {
if ( is_object($post) ) {
// Check if post already filtered for this context
if ( isset($post->filter) && $context == $post->filter )
return $post;
if ( !isset($post->ID) )
$post->ID = 0;
foreach ( array_keys(get_object_vars($post)) as $field )
$post->$field = sanitize_post_field($field, $post->$field, $post->ID, $context);
$post->filter = $context;
} else {
// Check if post already filtered for this context
if ( isset($post['filter']) && $context == $post['filter'] )
return $post;
if ( !isset($post['ID']) )
$post['ID'] = 0;
foreach ( array_keys($post) as $field )
$post[$field] = sanitize_post_field($field, $post[$field], $post['ID'], $context);
$post['filter'] = $context;
}
return $post;
}
/**
* Sanitize post field based on context.
*
* Possible context values are: 'raw', 'edit', 'db', 'display', 'attribute' and 'js'. The
* 'display' context is used by default. 'attribute' and 'js' contexts are treated like 'display'
* when calling filters.
*
* @since 2.3.0
*
* @param string $field The Post Object field name.
* @param mixed $value The Post Object value.
* @param int $post_id Post ID.
* @param string $context How to sanitize post fields. Looks for 'raw', 'edit', 'db', 'display',
* 'attribute' and 'js'.
* @return mixed Sanitized value.
*/
function sanitize_post_field($field, $value, $post_id, $context) {
$int_fields = array('ID', 'post_parent', 'menu_order');
if ( in_array($field, $int_fields) )
$value = (int) $value;
// Fields which contain arrays of ints.
$array_int_fields = array( 'ancestors' );
if ( in_array($field, $array_int_fields) ) {
$value = array_map( 'absint', $value);
return $value;
}
if ( 'raw' == $context )
return $value;
$prefixed = false;
if ( false !== strpos($field, 'post_') ) {
$prefixed = true;
$field_no_prefix = str_replace('post_', '', $field);
}
if ( 'edit' == $context ) {
$format_to_edit = array('post_content', 'post_excerpt', 'post_title', 'post_password');
if ( $prefixed ) {
/**
* Filter the value of a specific post field to edit.
*
* The dynamic portion of the hook name, $field, refers to the post field name.
*
* @since 2.3.0
*
* @param mixed $value Value of the post field.
* @param int $post_id Post ID.
*/
$value = apply_filters( "edit_{$field}", $value, $post_id );
/**
* Filter the value of a specific post field to edit.
*
* The dynamic portion of the hook name, $field_no_prefix, refers to
* the post field name.
*
* @since 2.3.0
*
* @param mixed $value Value of the post field.
* @param int $post_id Post ID.
*/
$value = apply_filters( "{$field_no_prefix}_edit_pre", $value, $post_id );
} else {
$value = apply_filters( "edit_post_{$field}", $value, $post_id );
}
if ( in_array($field, $format_to_edit) ) {
if ( 'post_content' == $field )
$value = format_to_edit($value, user_can_richedit());
else
$value = format_to_edit($value);
} else {
$value = esc_attr($value);
}
} else if ( 'db' == $context ) {
if ( $prefixed ) {
/**
* Filter the value of a specific post field before saving.
*
* The dynamic portion of the hook name, $field, refers to the post field name.
*
* @since 2.3.0
*
* @param mixed $value Value of the post field.
*/
$value = apply_filters( "pre_{$field}", $value );
/**
* Filter the value of a specific field before saving.
*
* The dynamic portion of the hook name, $field_no_prefix, refers
* to the post field name.
*
* @since 2.3.0
*
* @param mixed $value Value of the post field.
*/
$value = apply_filters( "{$field_no_prefix}_save_pre", $value );
} else {
$value = apply_filters( "pre_post_{$field}", $value );
/**
* Filter the value of a specific post field before saving.
*
* The dynamic portion of the hook name, $field, refers to the post field name.
*
* @since 2.3.0
*
* @param mixed $value Value of the post field.
*/
$value = apply_filters( "{$field}_pre", $value );
}
} else {
// Use display filters by default.
if ( $prefixed ) {
/**
* Filter the value of a specific post field for display.
*
* The dynamic portion of the hook name, $field, refers to the post field name.
*
* @since 2.3.0
*
* @param mixed $value Value of the prefixed post field.
* @param int $post_id Post ID.
* @param string $context Context for how to sanitize the field. Possible
* values include 'raw', 'edit', 'db', 'display',
* 'attribute' and 'js'.
*/
$value = apply_filters( $field, $value, $post_id, $context );
} else {
$value = apply_filters( "post_{$field}", $value, $post_id, $context );
}
}
if ( 'attribute' == $context )
$value = esc_attr($value);
else if ( 'js' == $context )
$value = esc_js($value);
return $value;
}
/**
* Make a post sticky.
*
* Sticky posts should be displayed at the top of the front page.
*
* @since 2.7.0
*
* @param int $post_id Post ID.
*/
function stick_post($post_id) {
$stickies = get_option('sticky_posts');
if ( !is_array($stickies) )
$stickies = array($post_id);
if ( ! in_array($post_id, $stickies) )
$stickies[] = $post_id;
update_option('sticky_posts', $stickies);
}
/**
* Unstick a post.
*
* Sticky posts should be displayed at the top of the front page.
*
* @since 2.7.0
*
* @param int $post_id Post ID.
*/
function unstick_post($post_id) {
$stickies = get_option('sticky_posts');
if ( !is_array($stickies) )
return;
if ( ! in_array($post_id, $stickies) )
return;
$offset = array_search($post_id, $stickies);
if ( false === $offset )
return;
array_splice($stickies, $offset, 1);
update_option('sticky_posts', $stickies);
}
/**
* Return the cache key for wp_count_posts() based on the passed arguments
*
* @since 3.9.0
*
* @param string $type Optional. Post type to retrieve count
* @param string $perm Optional. 'readable' or empty.
* @return string The cache key.
*/
function _count_posts_cache_key( $type = 'post', $perm = '' ) {
$cache_key = 'posts-' . $type;
if ( 'readable' == $perm && is_user_logged_in() ) {
$post_type_object = get_post_type_object( $type );
if ( ! current_user_can( $post_type_object->cap->read_private_posts ) ) {
$cache_key .= '_' . $perm . '_' . get_current_user_id();
}
}
return $cache_key;
}
/**
* Count number of posts of a post type and if user has permissions to view.
*
* This function provides an efficient method of finding the amount of post's
* type a blog has. Another method is to count the amount of items in
* get_posts(), but that method has a lot of overhead with doing so. Therefore,
* when developing for 2.5+, use this function instead.
*
* The $perm parameter checks for 'readable' value and if the user can read
* private posts, it will display that for the user that is signed in.
*
* @link http://codex.wordpress.org/Template_Tags/wp_count_posts
*
* @since 2.5.0
*
* @param string $type Optional. Post type to retrieve count
* @param string $perm Optional. 'readable' or empty.
* @return object Number of posts for each status
*/
function wp_count_posts( $type = 'post', $perm = '' ) {
global $wpdb;
if ( ! post_type_exists( $type ) )
return new stdClass;
$cache_key = _count_posts_cache_key( $type, $perm );
$query = "SELECT post_status, COUNT( * ) AS num_posts FROM {$wpdb->posts} WHERE post_type = %s";
if ( 'readable' == $perm && is_user_logged_in() ) {
$post_type_object = get_post_type_object($type);
if ( ! current_user_can( $post_type_object->cap->read_private_posts ) ) {
$query .= $wpdb->prepare( " AND (post_status != 'private' OR ( post_author = %d AND post_status = 'private' ))",
get_current_user_id()
);
}
}
$query .= ' GROUP BY post_status';
$counts = wp_cache_get( $cache_key, 'counts' );
if ( false === $counts ) {
$results = (array) $wpdb->get_results( $wpdb->prepare( $query, $type ), ARRAY_A );
$counts = array_fill_keys( get_post_stati(), 0 );
foreach ( $results as $row )
$counts[ $row['post_status'] ] = $row['num_posts'];
$counts = (object) $counts;
wp_cache_set( $cache_key, $counts, 'counts' );
}
/**
* Modify returned post counts by status for the current post type.
*
* @since 3.7.0
*
* @param object $counts An object containing the current post_type's post
* counts by status.
* @param string $type Post type.
* @param string $perm The permission to determine if the posts are 'readable'
* by the current user.
*/
return apply_filters( 'wp_count_posts', $counts, $type, $perm );
}
/**
* Count number of attachments for the mime type(s).
*
* If you set the optional mime_type parameter, then an array will still be
* returned, but will only have the item you are looking for. It does not give
* you the number of attachments that are children of a post. You can get that
* by counting the number of children that post has.
*
* @since 2.5.0
*
* @param string|array $mime_type Optional. Array or comma-separated list of MIME patterns.
* @return object An object containing the attachment counts by mime type.
*/
function wp_count_attachments( $mime_type = '' ) {
global $wpdb;
$and = wp_post_mime_type_where( $mime_type );
$count = $wpdb->get_results( "SELECT post_mime_type, COUNT( * ) AS num_posts FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status != 'trash' $and GROUP BY post_mime_type", ARRAY_A );
$counts = array();
foreach( (array) $count as $row ) {
$counts[ $row['post_mime_type'] ] = $row['num_posts'];
}
$counts['trash'] = $wpdb->get_var( "SELECT COUNT( * ) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status = 'trash' $and");
/**
* Modify returned attachment counts by mime type.
*
* @since 3.7.0
*
* @param object $counts An object containing the attachment counts by mime type.
* @param string $mime_type The mime type pattern used to filter the attachments counted.
*/
return apply_filters( 'wp_count_attachments', (object) $counts, $mime_type );
}
/**
* Get default post mime types
*
* @since 2.9.0
*
* @return array
*/
function get_post_mime_types() {
$post_mime_types = array( // array( adj, noun )
'image' => array(__('Images'), __('Manage Images'), _n_noop('Image <span class="count">(%s)</span>', 'Images <span class="count">(%s)</span>')),
'audio' => array(__('Audio'), __('Manage Audio'), _n_noop('Audio <span class="count">(%s)</span>', 'Audio <span class="count">(%s)</span>')),
'video' => array(__('Video'), __('Manage Video'), _n_noop('Video <span class="count">(%s)</span>', 'Video <span class="count">(%s)</span>')),
);
/**
* Filter the default list of post mime types.
*
* @since 2.5.0
*
* @param array $post_mime_types Default list of post mime types.
*/
return apply_filters( 'post_mime_types', $post_mime_types );
}
/**
* Check a MIME-Type against a list.
*
* If the wildcard_mime_types parameter is a string, it must be comma separated
* list. If the real_mime_types is a string, it is also comma separated to
* create the list.
*
* @since 2.5.0
*
* @param string|array $wildcard_mime_types e.g. audio/mpeg or image (same as image/*) or
* flash (same as *flash*).
* @param string|array $real_mime_types post_mime_type values
* @return array array(wildcard=>array(real types))
*/
function wp_match_mime_types($wildcard_mime_types, $real_mime_types) {
$matches = array();
if ( is_string($wildcard_mime_types) )
$wildcard_mime_types = array_map('trim', explode(',', $wildcard_mime_types));
if ( is_string($real_mime_types) )
$real_mime_types = array_map('trim', explode(',', $real_mime_types));
$wild = '[-._a-z0-9]*';
foreach ( (array) $wildcard_mime_types as $type ) {
$type = str_replace('*', $wild, $type);
$patternses[1][$type] = "^$type$";
if ( false === strpos($type, '/') ) {
$patternses[2][$type] = "^$type/";
$patternses[3][$type] = $type;
}
}
asort($patternses);
foreach ( $patternses as $patterns )
foreach ( $patterns as $type => $pattern )
foreach ( (array) $real_mime_types as $real )
if ( preg_match("#$pattern#", $real) && ( empty($matches[$type]) || false === array_search($real, $matches[$type]) ) )
$matches[$type][] = $real;
return $matches;
}
/**
* Convert MIME types into SQL.
*
* @since 2.5.0
*
* @param string|array $post_mime_types List of mime types or comma separated string of mime types.
* @param string $table_alias Optional. Specify a table alias, if needed.
* @return string The SQL AND clause for mime searching.
*/
function wp_post_mime_type_where($post_mime_types, $table_alias = '') {
$where = '';
$wildcards = array('', '%', '%/%');
if ( is_string($post_mime_types) )
$post_mime_types = array_map('trim', explode(',', $post_mime_types));
foreach ( (array) $post_mime_types as $mime_type ) {
$mime_type = preg_replace('/\s/', '', $mime_type);
$slashpos = strpos($mime_type, '/');
if ( false !== $slashpos ) {
$mime_group = preg_replace('/[^-*.a-zA-Z0-9]/', '', substr($mime_type, 0, $slashpos));
$mime_subgroup = preg_replace('/[^-*.+a-zA-Z0-9]/', '', substr($mime_type, $slashpos + 1));
if ( empty($mime_subgroup) )
$mime_subgroup = '*';
else
$mime_subgroup = str_replace('/', '', $mime_subgroup);
$mime_pattern = "$mime_group/$mime_subgroup";
} else {
$mime_pattern = preg_replace('/[^-*.a-zA-Z0-9]/', '', $mime_type);
if ( false === strpos($mime_pattern, '*') )
$mime_pattern .= '/*';
}
$mime_pattern = preg_replace('/\*+/', '%', $mime_pattern);
if ( in_array( $mime_type, $wildcards ) )
return '';
if ( false !== strpos($mime_pattern, '%') )
$wheres[] = empty($table_alias) ? "post_mime_type LIKE '$mime_pattern'" : "$table_alias.post_mime_type LIKE '$mime_pattern'";
else
$wheres[] = empty($table_alias) ? "post_mime_type = '$mime_pattern'" : "$table_alias.post_mime_type = '$mime_pattern'";
}
if ( !empty($wheres) )
$where = ' AND (' . join(' OR ', $wheres) . ') ';
return $where;
}
/**
* Trashes or deletes a post or page.
*
* When the post and page is permanently deleted, everything that is tied to it is deleted also.
* This includes comments, post meta fields, and terms associated with the post.
*
* The post or page is moved to trash instead of permanently deleted unless trash is
* disabled, item is already in the trash, or $force_delete is true.
*
* @since 1.0.0
*
* @uses wp_delete_attachment() if post type is 'attachment'.
* @uses wp_trash_post() if item should be trashed.
*
* @param int $postid Post ID.
* @param bool $force_delete Whether to bypass trash and force deletion. Defaults to false.
* @return mixed False on failure
*/
function wp_delete_post( $postid = 0, $force_delete = false ) {
global $wpdb;
if ( !$post = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $postid)) )
return $post;
if ( !$force_delete && ( $post->post_type == 'post' || $post->post_type == 'page') && get_post_status( $postid ) != 'trash' && EMPTY_TRASH_DAYS )
return wp_trash_post($postid);
if ( $post->post_type == 'attachment' )
return wp_delete_attachment( $postid, $force_delete );
/**
* Fires before a post is deleted, at the start of wp_delete_post().
*
* @since 3.2.0
*
* @see wp_delete_post()
*
* @param int $postid Post ID.
*/
do_action( 'before_delete_post', $postid );
delete_post_meta($postid,'_wp_trash_meta_status');
delete_post_meta($postid,'_wp_trash_meta_time');
wp_delete_object_term_relationships($postid, get_object_taxonomies($post->post_type));
$parent_data = array( 'post_parent' => $post->post_parent );
$parent_where = array( 'post_parent' => $postid );
if ( is_post_type_hierarchical( $post->post_type ) ) {
// Point children of this page to its parent, also clean the cache of affected children
$children_query = $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_parent = %d AND post_type = %s", $postid, $post->post_type );
$children = $wpdb->get_results( $children_query );
$wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => $post->post_type ) );
}
// Do raw query. wp_get_post_revisions() is filtered
$revision_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'revision'", $postid ) );
// Use wp_delete_post (via wp_delete_post_revision) again. Ensures any meta/misplaced data gets cleaned up.
foreach ( $revision_ids as $revision_id )
wp_delete_post_revision( $revision_id );
// Point all attachments to this post up one level
$wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => 'attachment' ) );
$comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $postid ));
foreach ( $comment_ids as $comment_id )
wp_delete_comment( $comment_id, true );
$post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $postid ));
foreach ( $post_meta_ids as $mid )
delete_metadata_by_mid( 'post', $mid );
/**
* Fires immediately before a post is deleted from the database.
*
* @since 1.2.0
*
* @param int $postid Post ID.
*/
do_action( 'delete_post', $postid );
$result = $wpdb->delete( $wpdb->posts, array( 'ID' => $postid ) );
if ( ! $result ) {
return false;
}
/**
* Fires immediately after a post is deleted from the database.
*
* @since 2.2.0
*
* @param int $postid Post ID.
*/
do_action( 'deleted_post', $postid );
clean_post_cache( $post );
if ( is_post_type_hierarchical( $post->post_type ) && $children ) {
foreach ( $children as $child )
clean_post_cache( $child );
}
wp_clear_scheduled_hook('publish_future_post', array( $postid ) );
/**
* Fires after a post is deleted, at the conclusion of wp_delete_post().
*
* @since 3.2.0
*
* @see wp_delete_post()
*
* @param int $postid Post ID.
*/
do_action( 'after_delete_post', $postid );
return $post;
}
/**
* Resets the page_on_front, show_on_front, and page_for_post settings when a
* linked page is deleted or trashed.
*
* Also ensures the post is no longer sticky.
*
* @access private
* @since 3.7.0
* @param $post_id
*/
function _reset_front_page_settings_for_post( $post_id ) {
$post = get_post( $post_id );
if ( 'page' == $post->post_type ) {
// If the page is defined in option page_on_front or post_for_posts,
// adjust the corresponding options
if ( get_option( 'page_on_front' ) == $post->ID ) {
update_option( 'show_on_front', 'posts' );
update_option( 'page_on_front', 0 );
}
if ( get_option( 'page_for_posts' ) == $post->ID ) {
delete_option( 'page_for_posts', 0 );
}
}
unstick_post( $post->ID );
}
add_action( 'before_delete_post', '_reset_front_page_settings_for_post' );
add_action( 'wp_trash_post', '_reset_front_page_settings_for_post' );
/**
* Moves a post or page to the Trash
*
* If trash is disabled, the post or page is permanently deleted.
*
* @since 2.9.0
*
* @uses wp_delete_post() if trash is disabled
*
* @param int $post_id Post ID.
* @return mixed False on failure
*/
function wp_trash_post($post_id = 0) {
if ( !EMPTY_TRASH_DAYS )
return wp_delete_post($post_id, true);
if ( !$post = get_post($post_id, ARRAY_A) )
return $post;
if ( $post['post_status'] == 'trash' )
return false;
/**
* Fires before a post is sent to the trash.
*
* @since 3.3.0
*
* @param int $post_id Post ID.
*/
do_action( 'wp_trash_post', $post_id );
add_post_meta($post_id,'_wp_trash_meta_status', $post['post_status']);
add_post_meta($post_id,'_wp_trash_meta_time', time());
$post['post_status'] = 'trash';
wp_insert_post($post);
wp_trash_post_comments($post_id);
/**
* Fires after a post is sent to the trash.
*
* @since 2.9.0
*
* @param int $post_id Post ID.
*/
do_action( 'trashed_post', $post_id );
return $post;
}
/**
* Restores a post or page from the Trash
*
* @since 2.9.0
*
* @param int $post_id Post ID.
* @return mixed False on failure
*/
function wp_untrash_post($post_id = 0) {
if ( !$post = get_post($post_id, ARRAY_A) )
return $post;
if ( $post['post_status'] != 'trash' )
return false;
/**
* Fires before a post is restored from the trash.
*
* @since 2.9.0
*
* @param int $post_id Post ID.
*/
do_action( 'untrash_post', $post_id );
$post_status = get_post_meta($post_id, '_wp_trash_meta_status', true);
$post['post_status'] = $post_status;
delete_post_meta($post_id, '_wp_trash_meta_status');
delete_post_meta($post_id, '_wp_trash_meta_time');
wp_insert_post($post);
wp_untrash_post_comments($post_id);
/**
* Fires after a post is restored from the trash.
*
* @since 2.9.0
*
* @param int $post_id Post ID.
*/
do_action( 'untrashed_post', $post_id );
return $post;
}
/**
* Moves comments for a post to the trash
*
* @since 2.9.0
*
* @param int|WP_Post $post Optional. Post ID or post object.
* @return mixed False on failure
*/
function wp_trash_post_comments($post = null) {
global $wpdb;
$post = get_post($post);
if ( empty($post) )
return;
$post_id = $post->ID;
/**
* Fires before comments are sent to the trash.
*
* @since 2.9.0
*
* @param int $post_id Post ID.
*/
do_action( 'trash_post_comments', $post_id );
$comments = $wpdb->get_results( $wpdb->prepare("SELECT comment_ID, comment_approved FROM $wpdb->comments WHERE comment_post_ID = %d", $post_id) );
if ( empty($comments) )
return;
// Cache current status for each comment
$statuses = array();
foreach ( $comments as $comment )
$statuses[$comment->comment_ID] = $comment->comment_approved;
add_post_meta($post_id, '_wp_trash_meta_comments_status', $statuses);
// Set status for all comments to post-trashed
$result = $wpdb->update($wpdb->comments, array('comment_approved' => 'post-trashed'), array('comment_post_ID' => $post_id));
clean_comment_cache( array_keys($statuses) );
/**
* Fires after comments are sent to the trash.
*
* @since 2.9.0
*
* @param int $post_id Post ID.
* @param array $statuses Array of comment statuses.
*/
do_action( 'trashed_post_comments', $post_id, $statuses );
return $result;
}
/**
* Restore comments for a post from the trash
*
* @since 2.9.0
*
* @param int|WP_Post $post Optional. Post ID or post object.
* @return mixed False on failure
*/
function wp_untrash_post_comments($post = null) {
global $wpdb;
$post = get_post($post);
if ( empty($post) )
return;
$post_id = $post->ID;
$statuses = get_post_meta($post_id, '_wp_trash_meta_comments_status', true);
if ( empty($statuses) )
return true;
/**
* Fires before comments are restored for a post from the trash.
*
* @since 2.9.0
*
* @param int $post_id Post ID.
*/
do_action( 'untrash_post_comments', $post_id );
// Restore each comment to its original status
$group_by_status = array();
foreach ( $statuses as $comment_id => $comment_status )
$group_by_status[$comment_status][] = $comment_id;
foreach ( $group_by_status as $status => $comments ) {
// Sanity check. This shouldn't happen.
if ( 'post-trashed' == $status )
$status = '0';
$comments_in = implode( "', '", $comments );
$wpdb->query( "UPDATE $wpdb->comments SET comment_approved = '$status' WHERE comment_ID IN ('" . $comments_in . "')" );
}
clean_comment_cache( array_keys($statuses) );
delete_post_meta($post_id, '_wp_trash_meta_comments_status');
/**
* Fires after comments are restored for a post from the trash.
*
* @since 2.9.0
*
* @param int $post_id Post ID.
*/
do_action( 'untrashed_post_comments', $post_id );
}
/**
* Retrieve the list of categories for a post.
*
* Compatibility layer for themes and plugins. Also an easy layer of abstraction
* away from the complexity of the taxonomy layer.
*
* @since 2.1.0
*
* @uses wp_get_object_terms() Retrieves the categories. Args details can be found here.
*
* @param int $post_id Optional. The Post ID.
* @param array $args Optional. Overwrite the defaults.
* @return array
*/
function wp_get_post_categories( $post_id = 0, $args = array() ) {
$post_id = (int) $post_id;
$defaults = array('fields' => 'ids');
$args = wp_parse_args( $args, $defaults );
$cats = wp_get_object_terms($post_id, 'category', $args);
return $cats;
}
/**
* Retrieve the tags for a post.
*
* There is only one default for this function, called 'fields' and by default
* is set to 'all'. There are other defaults that can be overridden in
* {@link wp_get_object_terms()}.
*
* @since 2.3.0
*
* @uses wp_get_object_terms() Gets the tags for returning. Args can be found here
*
* @param int $post_id Optional. The Post ID
* @param array $args Optional. Overwrite the defaults
* @return array List of post tags.
*/
function wp_get_post_tags( $post_id = 0, $args = array() ) {
return wp_get_post_terms( $post_id, 'post_tag', $args);
}
/**
* Retrieve the terms for a post.
*
* There is only one default for this function, called 'fields' and by default
* is set to 'all'. There are other defaults that can be overridden in
* {@link wp_get_object_terms()}.
*
* @since 2.8.0
*
* @uses wp_get_object_terms() Gets the tags for returning. Args can be found here
*
* @param int $post_id Optional. The Post ID
* @param string $taxonomy The taxonomy for which to retrieve terms. Defaults to post_tag.
* @param array $args Optional. Overwrite the defaults
* @return array List of post tags.
*/
function wp_get_post_terms( $post_id = 0, $taxonomy = 'post_tag', $args = array() ) {
$post_id = (int) $post_id;
$defaults = array('fields' => 'all');
$args = wp_parse_args( $args, $defaults );
$tags = wp_get_object_terms($post_id, $taxonomy, $args);
return $tags;
}
/**
* Retrieve number of recent posts.
*
* @since 1.0.0
* @uses wp_parse_args()
* @uses get_posts()
*
* @param string $deprecated Deprecated.
* @param array $args Optional. Overrides defaults.
* @param string $output Optional.
* @return unknown.
*/
function wp_get_recent_posts( $args = array(), $output = ARRAY_A ) {
if ( is_numeric( $args ) ) {
_deprecated_argument( __FUNCTION__, '3.1', __( 'Passing an integer number of posts is deprecated. Pass an array of arguments instead.' ) );
$args = array( 'numberposts' => absint( $args ) );
}
// Set default arguments
$defaults = array(
'numberposts' => 10, 'offset' => 0,
'category' => 0, 'orderby' => 'post_date',
'order' => 'DESC', 'include' => '',
'exclude' => '', 'meta_key' => '',
'meta_value' =>'', 'post_type' => 'post', 'post_status' => 'draft, publish, future, pending, private',
'suppress_filters' => true
);
$r = wp_parse_args( $args, $defaults );
$results = get_posts( $r );
// Backward compatibility. Prior to 3.1 expected posts to be returned in array
if ( ARRAY_A == $output ){
foreach( $results as $key => $result ) {
$results[$key] = get_object_vars( $result );
}
return $results ? $results : array();
}
return $results ? $results : false;
}
/**
* Insert or update a post.
*
* If the $postarr parameter has 'ID' set to a value, then post will be updated.
*
* You can set the post date manually, by setting the values for 'post_date'
* and 'post_date_gmt' keys. You can close the comments or open the comments by
* setting the value for 'comment_status' key.
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @since 1.0.0
*
* @param array $postarr {
* An array of elements that make up a post to update or insert.
*
* @type int $ID The post ID. If equal to something other than 0, the post with that ID will
* be updated. Default 0.
* @type string $post_status The post status. Default 'draft'.
* @type string $post_type The post type. Default 'post'.
* @type int $post_author The ID of the user who added the post. Default the current user ID.
* @type bool $ping_status Whether the post can accept pings. Default value of 'default_ping_status' option.
* @type int $post_parent Set this for the post it belongs to, if any. Default 0.
* @type int $menu_order The order it is displayed. Default 0.
* @type string $to_ping Space or carriage return-separated list of URLs to ping. Default empty string.
* @type string $pinged Space or carriage return-separated list of URLs that have been pinged.
* Default empty string.
* @type string $post_password The password to access the post. Default empty string.
* @type string $guid' Global Unique ID for referencing the post.
* @type string $post_content_filtered The filtered post content. Default empty string.
* @type string $post_excerpt The post excerpt. Default empty string.
* }
* @param bool $wp_error Optional. Allow return of WP_Error on failure.
* @return int|WP_Error The post ID on success. The value 0 or WP_Error on failure.
*/
function wp_insert_post( $postarr, $wp_error = false ) {
global $wpdb;
$user_id = get_current_user_id();
$defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_id,
'ping_status' => get_option('default_ping_status'), 'post_parent' => 0,
'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '',
'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0,
'post_content' => '', 'post_title' => '');
$postarr = wp_parse_args($postarr, $defaults);
unset( $postarr[ 'filter' ] );
$postarr = sanitize_post($postarr, 'db');
// export array as variables
extract($postarr, EXTR_SKIP);
// Are we updating or creating?
$post_ID = 0;
$update = false;
if ( ! empty( $ID ) ) {
$update = true;
// Get the post ID and GUID
$post_ID = $ID;
$post_before = get_post( $post_ID );
if ( is_null( $post_before ) ) {
if ( $wp_error )
return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) );
return 0;
}
$guid = get_post_field( 'guid', $post_ID );
$previous_status = get_post_field('post_status', $ID);
} else {
$previous_status = 'new';
}
$maybe_empty = ! $post_content && ! $post_title && ! $post_excerpt && post_type_supports( $post_type, 'editor' )
&& post_type_supports( $post_type, 'title' ) && post_type_supports( $post_type, 'excerpt' );
/**
* Filter whether the post should be considered "empty".
*
* The post is considered "empty" if both:
* 1. The post type supports the title, editor, and excerpt fields
* 2. The title, editor, and excerpt fields are all empty
*
* Returning a truthy value to the filter will effectively short-circuit
* the new post being inserted, returning 0. If $wp_error is true, a WP_Error
* will be returned instead.
*
* @since 3.3.0
*
* @param bool $maybe_empty Whether the post should be considered "empty".
* @param array $postarr Array of post data.
*/
if ( apply_filters( 'wp_insert_post_empty_content', $maybe_empty, $postarr ) ) {
if ( $wp_error )
return new WP_Error( 'empty_content', __( 'Content, title, and excerpt are empty.' ) );
else
return 0;
}
if ( empty($post_type) )
$post_type = 'post';
if ( empty($post_status) )
$post_status = 'draft';
if ( !empty($post_category) )
$post_category = array_filter($post_category); // Filter out empty terms
// Make sure we set a valid category.
if ( empty($post_category) || 0 == count($post_category) || !is_array($post_category) ) {
// 'post' requires at least one category.
if ( 'post' == $post_type && 'auto-draft' != $post_status )
$post_category = array( get_option('default_category') );
else
$post_category = array();
}
if ( empty($post_author) )
$post_author = $user_id;
// Don't allow contributors to set the post slug for pending review posts
if ( 'pending' == $post_status && !current_user_can( 'publish_posts' ) )
$post_name = '';
// Create a valid post name. Drafts and pending posts are allowed to have an empty
// post name.
if ( empty($post_name) ) {
if ( !in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) )
$post_name = sanitize_title($post_title);
else
$post_name = '';
} else {
// On updates, we need to check to see if it's using the old, fixed sanitization context.
$check_name = sanitize_title( $post_name, '', 'old-save' );
if ( $update && strtolower( urlencode( $post_name ) ) == $check_name && get_post_field( 'post_name', $ID ) == $check_name )
$post_name = $check_name;
else // new post, or slug has changed.
$post_name = sanitize_title($post_name);
}
// If the post date is empty (due to having been new or a draft) and status is not 'draft' or 'pending', set date to now
if ( empty($post_date) || '0000-00-00 00:00:00' == $post_date )
$post_date = current_time('mysql');
// validate the date
$mm = substr( $post_date, 5, 2 );
$jj = substr( $post_date, 8, 2 );
$aa = substr( $post_date, 0, 4 );
$valid_date = wp_checkdate( $mm, $jj, $aa, $post_date );
if ( !$valid_date ) {
if ( $wp_error )
return new WP_Error( 'invalid_date', __( 'Whoops, the provided date is invalid.' ) );
else
return 0;
}
if ( empty($post_date_gmt) || '0000-00-00 00:00:00' == $post_date_gmt ) {
if ( !in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) )
$post_date_gmt = get_gmt_from_date($post_date);
else
$post_date_gmt = '0000-00-00 00:00:00';
}
if ( $update || '0000-00-00 00:00:00' == $post_date ) {
$post_modified = current_time( 'mysql' );
$post_modified_gmt = current_time( 'mysql', 1 );
} else {
$post_modified = $post_date;
$post_modified_gmt = $post_date_gmt;
}
if ( 'publish' == $post_status ) {
$now = gmdate('Y-m-d H:i:59');
if ( mysql2date('U', $post_date_gmt, false) > mysql2date('U', $now, false) )
$post_status = 'future';
} elseif( 'future' == $post_status ) {
$now = gmdate('Y-m-d H:i:59');
if ( mysql2date('U', $post_date_gmt, false) <= mysql2date('U', $now, false) )
$post_status = 'publish';
}
if ( empty($comment_status) ) {
if ( $update )
$comment_status = 'closed';
else
$comment_status = get_option('default_comment_status');
}
if ( empty($ping_status) )
$ping_status = get_option('default_ping_status');
if ( isset($to_ping) )
$to_ping = sanitize_trackback_urls( $to_ping );
else
$to_ping = '';
if ( ! isset($pinged) )
$pinged = '';
if ( isset($post_parent) )
$post_parent = (int) $post_parent;
else
$post_parent = 0;
/**
* Filter the post parent -- used to check for and prevent hierarchy loops.
*
* @since 3.1.0
*
* @param int $post_parent Post parent ID.
* @param int $post_ID Post ID.
* @param array $new_postarr Array of parsed post data.
* @param array $postarr Array of sanitized, but otherwise unmodified post data.
*/
$post_parent = apply_filters( 'wp_insert_post_parent', $post_parent, $post_ID, compact( array_keys( $postarr ) ), $postarr );
if ( isset($menu_order) )
$menu_order = (int) $menu_order;
else
$menu_order = 0;
if ( !isset($post_password) || 'private' == $post_status )
$post_password = '';
$post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent);
// expected_slashed (everything!)
$data = compact( array( 'post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_content_filtered', 'post_title', 'post_excerpt', 'post_status', 'post_type', 'comment_status', 'ping_status', 'post_password', 'post_name', 'to_ping', 'pinged', 'post_modified', 'post_modified_gmt', 'post_parent', 'menu_order', 'guid' ) );
/**
* Filter slashed post data just before it is inserted into the database.
*
* @since 2.7.0
*
* @param array $data Array of slashed post data.
* @param array $postarr Array of sanitized, but otherwise unmodified post data.
*/
$data = apply_filters( 'wp_insert_post_data', $data, $postarr );
$data = wp_unslash( $data );
$where = array( 'ID' => $post_ID );
if ( $update ) {
/**
* Fires immediately before an existing post is updated in the database.
*
* @since 2.5.0
*
* @param int $post_ID Post ID.
* @param array $data Array of unslashed post data.
*/
do_action( 'pre_post_update', $post_ID, $data );
if ( false === $wpdb->update( $wpdb->posts, $data, $where ) ) {
if ( $wp_error )
return new WP_Error('db_update_error', __('Could not update post in the database'), $wpdb->last_error);
else
return 0;
}
} else {
if ( isset($post_mime_type) )
$data['post_mime_type'] = wp_unslash( $post_mime_type ); // This isn't in the update
// If there is a suggested ID, use it if not already present
if ( !empty($import_id) ) {
$import_id = (int) $import_id;
if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) {
$data['ID'] = $import_id;
}
}
if ( false === $wpdb->insert( $wpdb->posts, $data ) ) {
if ( $wp_error )
return new WP_Error('db_insert_error', __('Could not insert post into the database'), $wpdb->last_error);
else
return 0;
}
$post_ID = (int) $wpdb->insert_id;
// use the newly generated $post_ID
$where = array( 'ID' => $post_ID );
}
if ( empty($data['post_name']) && !in_array( $data['post_status'], array( 'draft', 'pending', 'auto-draft' ) ) ) {
$data['post_name'] = sanitize_title($data['post_title'], $post_ID);
$wpdb->update( $wpdb->posts, array( 'post_name' => $data['post_name'] ), $where );
}
if ( is_object_in_taxonomy($post_type, 'category') )
wp_set_post_categories( $post_ID, $post_category );
if ( isset( $tags_input ) && is_object_in_taxonomy($post_type, 'post_tag') )
wp_set_post_tags( $post_ID, $tags_input );
// new-style support for all custom taxonomies
if ( !empty($tax_input) ) {
foreach ( $tax_input as $taxonomy => $tags ) {
$taxonomy_obj = get_taxonomy($taxonomy);
if ( is_array($tags) ) // array = hierarchical, string = non-hierarchical.
$tags = array_filter($tags);
if ( current_user_can($taxonomy_obj->cap->assign_terms) )
wp_set_post_terms( $post_ID, $tags, $taxonomy );
}
}
$current_guid = get_post_field( 'guid', $post_ID );
// Set GUID
if ( !$update && '' == $current_guid )
$wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post_ID ) ), $where );
clean_post_cache( $post_ID );
$post = get_post($post_ID);
if ( !empty($page_template) && 'page' == $data['post_type'] ) {
$post->page_template = $page_template;
$page_templates = wp_get_theme()->get_page_templates( $post );
if ( 'default' != $page_template && ! isset( $page_templates[ $page_template ] ) ) {
if ( $wp_error )
return new WP_Error('invalid_page_template', __('The page template is invalid.'));
else
return 0;
}
update_post_meta($post_ID, '_wp_page_template', $page_template);
}
wp_transition_post_status($data['post_status'], $previous_status, $post);
if ( $update ) {
/**
* Fires once an existing post has been updated.
*
* @since 1.2.0
*
* @param int $post_ID Post ID.
* @param WP_Post $post Post object.
*/
do_action( 'edit_post', $post_ID, $post );
$post_after = get_post($post_ID);
/**
* Fires once an existing post has been updated.
*
* @since 3.0.0
*
* @param int $post_ID Post ID.
* @param WP_Post $post_after Post object following the update.
* @param WP_Post $post_before Post object before the update.
*/
do_action( 'post_updated', $post_ID, $post_after, $post_before);
}
/**
* Fires once a post has been saved.
*
* The dynamic portion of the hook name, $post->post_type, refers to
* the post type slug.
*
* @since 3.7.0
*
* @param int $post_ID Post ID.
* @param WP_Post $post Post object.
* @param bool $update Whether this is an existing post being updated or not.
*/
do_action( "save_post_{$post->post_type}", $post_ID, $post, $update );
/**
* Fires once a post has been saved.
*
* @since 1.5.0
*
* @param int $post_ID Post ID.
* @param WP_Post $post Post object.
* @param bool $update Whether this is an existing post being updated or not.
*/
do_action( 'save_post', $post_ID, $post, $update );
/**
* Fires once a post has been saved.
*
* @since 2.0.0
*
* @param int $post_ID Post ID.
* @param WP_Post $post Post object.
* @param bool $update Whether this is an existing post being updated or not.
*/
do_action( 'wp_insert_post', $post_ID, $post, $update );
return $post_ID;
}
/**
* Update a post with new post data.
*
* The date does not have to be set for drafts. You can set the date and it will
* not be overridden.
*
* @since 1.0.0
*
* @param array|object $postarr Post data. Arrays are expected to be escaped, objects are not.
* @param bool $wp_error Optional. Allow return of WP_Error on failure.
* @return int|WP_Error The value 0 or WP_Error on failure. The post ID on success.
*/
function wp_update_post( $postarr = array(), $wp_error = false ) {
if ( is_object($postarr) ) {
// non-escaped post was passed
$postarr = get_object_vars($postarr);
$postarr = wp_slash($postarr);
}
// First, get all of the original fields
$post = get_post($postarr['ID'], ARRAY_A);
if ( is_null( $post ) ) {
if ( $wp_error )
return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) );
return 0;
}
// Escape data pulled from DB.
$post = wp_slash($post);
// Passed post category list overwrites existing category list if not empty.
if ( isset($postarr['post_category']) && is_array($postarr['post_category'])
&& 0 != count($postarr['post_category']) )
$post_cats = $postarr['post_category'];
else
$post_cats = $post['post_category'];
// Drafts shouldn't be assigned a date unless explicitly done so by the user
if ( isset( $post['post_status'] ) && in_array($post['post_status'], array('draft', 'pending', 'auto-draft')) && empty($postarr['edit_date']) &&
('0000-00-00 00:00:00' == $post['post_date_gmt']) )
$clear_date = true;
else
$clear_date = false;
// Merge old and new fields with new fields overwriting old ones.
$postarr = array_merge($post, $postarr);
$postarr['post_category'] = $post_cats;
if ( $clear_date ) {
$postarr['post_date'] = current_time('mysql');
$postarr['post_date_gmt'] = '';
}
if ($postarr['post_type'] == 'attachment')
return wp_insert_attachment($postarr);
return wp_insert_post( $postarr, $wp_error );
}
/**
* Publish a post by transitioning the post status.
*
* @since 2.1.0
* @uses $wpdb
*
* @param int|WP_Post $post Post ID or post object.
*/
function wp_publish_post( $post ) {
global $wpdb;
if ( ! $post = get_post( $post ) )
return;
if ( 'publish' == $post->post_status )
return;
$wpdb->update( $wpdb->posts, array( 'post_status' => 'publish' ), array( 'ID' => $post->ID ) );
clean_post_cache( $post->ID );
$old_status = $post->post_status;
$post->post_status = 'publish';
wp_transition_post_status( 'publish', $old_status, $post );
/** This action is documented in wp-includes/post.php */
do_action( 'edit_post', $post->ID, $post );
/** This action is documented in wp-includes/post.php */
do_action( "save_post_{$post->post_type}", $post->ID, $post, true );
/** This action is documented in wp-includes/post.php */
do_action( 'save_post', $post->ID, $post, true );
/** This action is documented in wp-includes/post.php */
do_action( 'wp_insert_post', $post->ID, $post, true );
}
/**
* Publish future post and make sure post ID has future post status.
*
* Invoked by cron 'publish_future_post' event. This safeguard prevents cron
* from publishing drafts, etc.
*
* @since 2.5.0
*
* @param int|WP_Post $post_id Post ID or post object.
* @return null Nothing is returned. Which can mean that no action is required or post was published.
*/
function check_and_publish_future_post($post_id) {
$post = get_post($post_id);
if ( empty($post) )
return;
if ( 'future' != $post->post_status )
return;
$time = strtotime( $post->post_date_gmt . ' GMT' );
if ( $time > time() ) { // Uh oh, someone jumped the gun!
wp_clear_scheduled_hook( 'publish_future_post', array( $post_id ) ); // clear anything else in the system
wp_schedule_single_event( $time, 'publish_future_post', array( $post_id ) );
return;
}
return wp_publish_post($post_id);
}
/**
* Computes a unique slug for the post, when given the desired slug and some post details.
*
* @since 2.8.0
*
* @global wpdb $wpdb
* @global WP_Rewrite $wp_rewrite
* @param string $slug the desired slug (post_name)
* @param integer $post_ID
* @param string $post_status no uniqueness checks are made if the post is still draft or pending
* @param string $post_type
* @param integer $post_parent
* @return string unique slug for the post, based on $post_name (with a -1, -2, etc. suffix)
*/
function wp_unique_post_slug( $slug, $post_ID, $post_status, $post_type, $post_parent ) {
if ( in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) || ( 'inherit' == $post_status && 'revision' == $post_type ) )
return $slug;
global $wpdb, $wp_rewrite;
$original_slug = $slug;
$feeds = $wp_rewrite->feeds;
if ( ! is_array( $feeds ) )
$feeds = array();
$hierarchical_post_types = get_post_types( array('hierarchical' => true) );
if ( 'attachment' == $post_type ) {
// Attachment slugs must be unique across all types.
$check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND ID != %d LIMIT 1";
$post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_ID ) );
/**
* Filter whether the post slug would make a bad attachment slug.
*
* @since 3.1.0
*
* @param bool $bad_slug Whether the slug would be bad as an attachment slug.
* @param string $slug The post slug.
*/
if ( $post_name_check || in_array( $slug, $feeds ) || apply_filters( 'wp_unique_post_slug_is_bad_attachment_slug', false, $slug ) ) {
$suffix = 2;
do {
$alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
$post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_ID ) );
$suffix++;
} while ( $post_name_check );
$slug = $alt_post_name;
}
} elseif ( in_array( $post_type, $hierarchical_post_types ) ) {
if ( 'nav_menu_item' == $post_type )
return $slug;
/*
* Page slugs must be unique within their own trees. Pages are in a separate
* namespace than posts so page slugs are allowed to overlap post slugs.
*/
$check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type IN ( '" . implode( "', '", esc_sql( $hierarchical_post_types ) ) . "' ) AND ID != %d AND post_parent = %d LIMIT 1";
$post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_ID, $post_parent ) );
/**
* Filter whether the post slug would make a bad hierarchical post slug.
*
* @since 3.1.0
*
* @param bool $bad_slug Whether the post slug would be bad in a hierarchical post context.
* @param string $slug The post slug.
* @param string $post_type Post type.
* @param int $post_parent Post parent ID.
*/
if ( $post_name_check || in_array( $slug, $feeds ) || preg_match( "@^($wp_rewrite->pagination_base)?\d+$@", $slug ) || apply_filters( 'wp_unique_post_slug_is_bad_hierarchical_slug', false, $slug, $post_type, $post_parent ) ) {
$suffix = 2;
do {
$alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
$post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_ID, $post_parent ) );
$suffix++;
} while ( $post_name_check );
$slug = $alt_post_name;
}
} else {
// Post slugs must be unique across all posts.
$check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type = %s AND ID != %d LIMIT 1";
$post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_type, $post_ID ) );
/**
* Filter whether the post slug would be bad as a flat slug.
*
* @since 3.1.0
*
* @param bool $bad_slug Whether the post slug would be bad as a flat slug.
* @param string $slug The post slug.
* @param string $post_type Post type.
*/
if ( $post_name_check || in_array( $slug, $feeds ) || apply_filters( 'wp_unique_post_slug_is_bad_flat_slug', false, $slug, $post_type ) ) {
$suffix = 2;
do {
$alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
$post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_type, $post_ID ) );
$suffix++;
} while ( $post_name_check );
$slug = $alt_post_name;
}
}
/**
* Filter the unique post slug.
*
* @since 3.3.0
*
* @param string $slug The post slug.
* @param int $post_ID Post ID.
* @param string $post_status The post status.
* @param string $post_type Post type.
* @param int $post_parent Post parent ID
* @param string $original_slug The original post slug.
*/
return apply_filters( 'wp_unique_post_slug', $slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug );
}
/**
* Truncates a post slug.
*
* @since 3.6.0
* @access private
* @uses utf8_uri_encode() Makes sure UTF-8 characters are properly cut and encoded.
*
* @param string $slug The slug to truncate.
* @param int $length Max length of the slug.
* @return string The truncated slug.
*/
function _truncate_post_slug( $slug, $length = 200 ) {
if ( strlen( $slug ) > $length ) {
$decoded_slug = urldecode( $slug );
if ( $decoded_slug === $slug )
$slug = substr( $slug, 0, $length );
else
$slug = utf8_uri_encode( $decoded_slug, $length );
}
return rtrim( $slug, '-' );
}
/**
* Adds tags to a post.
*
* @uses wp_set_post_tags() Same first two parameters, but the last parameter is always set to true.
*
* @since 2.3.0
*
* @param int $post_id Post ID
* @param string $tags The tags to set for the post, separated by commas.
* @return bool|null Will return false if $post_id is not an integer or is 0. Will return null otherwise
*/
function wp_add_post_tags($post_id = 0, $tags = '') {
return wp_set_post_tags($post_id, $tags, true);
}
/**
* Set the tags for a post.
*
* @since 2.3.0
* @uses wp_set_object_terms() Sets the tags for the post.
*
* @param int $post_id Post ID.
* @param string $tags The tags to set for the post, separated by commas.
* @param bool $append If true, don't delete existing tags, just add on. If false, replace the tags with the new tags.
* @return mixed Array of affected term IDs. WP_Error or false on failure.
*/
function wp_set_post_tags( $post_id = 0, $tags = '', $append = false ) {
return wp_set_post_terms( $post_id, $tags, 'post_tag', $append);
}
/**
* Set the terms for a post.
*
* @since 2.8.0
* @uses wp_set_object_terms() Sets the tags for the post.
*
* @param int $post_id Post ID.
* @param string $tags The tags to set for the post, separated by commas.
* @param string $taxonomy Taxonomy name. Defaults to 'post_tag'.
* @param bool $append If true, don't delete existing tags, just add on. If false, replace the tags with the new tags.
* @return mixed Array of affected term IDs. WP_Error or false on failure.
*/
function wp_set_post_terms( $post_id = 0, $tags = '', $taxonomy = 'post_tag', $append = false ) {
$post_id = (int) $post_id;
if ( !$post_id )
return false;
if ( empty($tags) )
$tags = array();
if ( ! is_array( $tags ) ) {
$comma = _x( ',', 'tag delimiter' );
if ( ',' !== $comma )
$tags = str_replace( $comma, ',', $tags );
$tags = explode( ',', trim( $tags, " \n\t\r\0\x0B," ) );
}
// Hierarchical taxonomies must always pass IDs rather than names so that children with the same
// names but different parents aren't confused.
if ( is_taxonomy_hierarchical( $taxonomy ) ) {
$tags = array_unique( array_map( 'intval', $tags ) );
}
return wp_set_object_terms( $post_id, $tags, $taxonomy, $append );
}
/**
* Set categories for a post.
*
* If the post categories parameter is not set, then the default category is
* going used.
*
* @since 2.1.0
*
* @param int $post_ID Post ID.
* @param array|int $post_categories Optional. List of categories or ID of category.
* @param bool $append If true, don't delete existing categories, just add on. If false, replace the categories with the new categories.
* @return bool|mixed
*/
function wp_set_post_categories( $post_ID = 0, $post_categories = array(), $append = false ) {
$post_ID = (int) $post_ID;
$post_type = get_post_type( $post_ID );
$post_status = get_post_status( $post_ID );
// If $post_categories isn't already an array, make it one:
$post_categories = (array) $post_categories;
if ( empty( $post_categories ) ) {
if ( 'post' == $post_type && 'auto-draft' != $post_status ) {
$post_categories = array( get_option('default_category') );
$append = false;
} else {
$post_categories = array();
}
} else if ( 1 == count($post_categories) && '' == reset($post_categories) ) {
return true;
}
return wp_set_post_terms( $post_ID, $post_categories, 'category', $append );
}
/**
* Transition the post status of a post.
*
* Calls hooks to transition post status.
*
* The first is 'transition_post_status' with new status, old status, and post data.
*
* The next action called is 'OLDSTATUS_to_NEWSTATUS' the 'NEWSTATUS' is the
* $new_status parameter and the 'OLDSTATUS' is $old_status parameter; it has the
* post data.
*
* The final action is named 'NEWSTATUS_POSTTYPE', 'NEWSTATUS' is from the $new_status
* parameter and POSTTYPE is post_type post data.
*
* @since 2.3.0
*
* @link http://codex.wordpress.org/Post_Status_Transitions
*
* @param string $new_status Transition to this post status.
* @param string $old_status Previous post status.
* @param object $post Post data.
*/
function wp_transition_post_status($new_status, $old_status, $post) {
/**
* Fires when a post is transitioned from one status to another.
*
* @since 2.3.0
*
* @param string $new_status New post status.
* @param string $old_status Old post status.
* @param WP_Post $post Post object.
*/
do_action( 'transition_post_status', $new_status, $old_status, $post );
/**
* Fires when a post is transitioned from one status to another.
*
* The dynamic portions of the hook name, $new_status and $old status,
* refer to the old and new post statuses, respectively.
*
* @since 2.3.0
*
* @param WP_Post $post Post object.
*/
do_action( "{$old_status}_to_{$new_status}", $post );
/**
* Fires when a post is transitioned from one status to another.
*
* The dynamic portions of the hook name, $new_status and $post->post_type,
* refer to the new post status and post type, respectively.
*
* @since 2.3.0
*
* @param int $post_id Post ID.
* @param WP_Post $post Post object.
*/
do_action( "{$new_status}_{$post->post_type}", $post->ID, $post );
}
//
// Trackback and ping functions
//
/**
* Add a URL to those already pung.
*
* @since 1.5.0
* @uses $wpdb
*
* @param int $post_id Post ID.
* @param string $uri Ping URI.
* @return int How many rows were updated.
*/
function add_ping($post_id, $uri) {
global $wpdb;
$pung = $wpdb->get_var( $wpdb->prepare( "SELECT pinged FROM $wpdb->posts WHERE ID = %d", $post_id ));
$pung = trim($pung);
$pung = preg_split('/\s/', $pung);
$pung[] = $uri;
$new = implode("\n", $pung);
/**
* Filter the new ping URL to add for the given post.
*
* @since 2.0.0
*
* @param string $new New ping URL to add.
*/
$new = apply_filters( 'add_ping', $new );
// expected_slashed ($new)
$new = wp_unslash($new);
return $wpdb->update( $wpdb->posts, array( 'pinged' => $new ), array( 'ID' => $post_id ) );
}
/**
* Retrieve enclosures already enclosed for a post.
*
* @since 1.5.0
*
* @param int $post_id Post ID.
* @return array List of enclosures
*/
function get_enclosed($post_id) {
$custom_fields = get_post_custom( $post_id );
$pung = array();
if ( !is_array( $custom_fields ) )
return $pung;
foreach ( $custom_fields as $key => $val ) {
if ( 'enclosure' != $key || !is_array( $val ) )
continue;
foreach( $val as $enc ) {
$enclosure = explode( "\n", $enc );
$pung[] = trim( $enclosure[ 0 ] );
}
}
/**
* Filter the list of enclosures already enclosed for the given post.
*
* @since 2.0.0
*
* @param array $pung Array of enclosures for the given post.
* @param int $post_id Post ID.
*/
$pung = apply_filters( 'get_enclosed', $pung, $post_id );
return $pung;
}
/**
* Retrieve URLs already pinged for a post.
*
* @since 1.5.0
* @uses $wpdb
*
* @param int $post_id Post ID.
* @return array
*/
function get_pung($post_id) {
global $wpdb;
$pung = $wpdb->get_var( $wpdb->prepare( "SELECT pinged FROM $wpdb->posts WHERE ID = %d", $post_id ));
$pung = trim($pung);
$pung = preg_split('/\s/', $pung);
/**
* Filter the list of already-pinged URLs for the given post.
*
* @since 2.0.0
*
* @param array $pung Array of URLs already pinged for the given post.
*/
$pung = apply_filters( 'get_pung', $pung );
return $pung;
}
/**
* Retrieve URLs that need to be pinged.
*
* @since 1.5.0
* @uses $wpdb
*
* @param int $post_id Post ID
* @return array
*/
function get_to_ping($post_id) {
global $wpdb;
$to_ping = $wpdb->get_var( $wpdb->prepare( "SELECT to_ping FROM $wpdb->posts WHERE ID = %d", $post_id ));
$to_ping = sanitize_trackback_urls( $to_ping );
$to_ping = preg_split('/\s/', $to_ping, -1, PREG_SPLIT_NO_EMPTY);
/**
* Filter the list of URLs yet to ping for the given post.
*
* @since 2.0.0
*
* @param array $to_ping List of URLs yet to ping.
*/
$to_ping = apply_filters( 'get_to_ping', $to_ping );
return $to_ping;
}
/**
* Do trackbacks for a list of URLs.
*
* @since 1.0.0
*
* @param string $tb_list Comma separated list of URLs
* @param int $post_id Post ID
*/
function trackback_url_list($tb_list, $post_id) {
if ( ! empty( $tb_list ) ) {
// get post data
$postdata = get_post($post_id, ARRAY_A);
// import postdata as variables
extract($postdata, EXTR_SKIP);
// form an excerpt
$excerpt = strip_tags($post_excerpt ? $post_excerpt : $post_content);
if (strlen($excerpt) > 255) {
$excerpt = substr($excerpt,0,252) . '…';
}
$trackback_urls = explode(',', $tb_list);
foreach( (array) $trackback_urls as $tb_url) {
$tb_url = trim($tb_url);
trackback($tb_url, wp_unslash($post_title), $excerpt, $post_id);
}
}
}
//
// Page functions
//
/**
* Get a list of page IDs.
*
* @since 2.0.0
* @uses $wpdb
*
* @return array List of page IDs.
*/
function get_all_page_ids() {
global $wpdb;
$page_ids = wp_cache_get('all_page_ids', 'posts');
if ( ! is_array( $page_ids ) ) {
$page_ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_type = 'page'");
wp_cache_add('all_page_ids', $page_ids, 'posts');
}
return $page_ids;
}
/**
* Retrieves page data given a page ID or page object.
*
* Use get_post() instead of get_page().
*
* @since 1.5.1
* @deprecated 3.5.0
*
* @param mixed $page Page object or page ID. Passed by reference.
* @param string $output What to output. OBJECT, ARRAY_A, or ARRAY_N.
* @param string $filter How the return value should be filtered.
* @return WP_Post|null WP_Post on success or null on failure
*/
function get_page( $page, $output = OBJECT, $filter = 'raw') {
return get_post( $page, $output, $filter );
}
/**
* Retrieves a page given its path.
*
* @since 2.1.0
* @uses $wpdb
*
* @param string $page_path Page path
* @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A. Default OBJECT.
* @param string|array $post_type Optional. Post type or array of post types. Default page.
* @return WP_Post|null WP_Post on success or null on failure
*/
function get_page_by_path( $page_path, $output = OBJECT, $post_type = 'page' ) {
global $wpdb;
$page_path = rawurlencode(urldecode($page_path));
$page_path = str_replace('%2F', '/', $page_path);
$page_path = str_replace('%20', ' ', $page_path);
$parts = explode( '/', trim( $page_path, '/' ) );
$parts = esc_sql( $parts );
$parts = array_map( 'sanitize_title_for_query', $parts );
$in_string = "'" . implode( "','", $parts ) . "'";
if ( is_array( $post_type ) ) {
$post_types = $post_type;
} else {
$post_types = array( $post_type, 'attachment' );
}
$post_types = esc_sql( $post_types );
$post_type_in_string = "'" . implode( "','", $post_types ) . "'";
$sql = "
SELECT ID, post_name, post_parent, post_type
FROM $wpdb->posts
WHERE post_name IN ($in_string)
AND post_type IN ($post_type_in_string)
";
$pages = $wpdb->get_results( $sql, OBJECT_K );
$revparts = array_reverse( $parts );
$foundid = 0;
foreach ( (array) $pages as $page ) {
if ( $page->post_name == $revparts[0] ) {
$count = 0;
$p = $page;
while ( $p->post_parent != 0 && isset( $pages[ $p->post_parent ] ) ) {
$count++;
$parent = $pages[ $p->post_parent ];
if ( ! isset( $revparts[ $count ] ) || $parent->post_name != $revparts[ $count ] )
break;
$p = $parent;
}
if ( $p->post_parent == 0 && $count+1 == count( $revparts ) && $p->post_name == $revparts[ $count ] ) {
$foundid = $page->ID;
if ( $page->post_type == $post_type )
break;
}
}
}
if ( $foundid )
return get_post( $foundid, $output );
return null;
}
/**
* Retrieve a page given its title.
*
* @since 2.1.0
* @uses $wpdb
*
* @param string $page_title Page title
* @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A. Default OBJECT.
* @param string|array $post_type Optional. Post type or array of post types. Default page.
* @return WP_Post|null WP_Post on success or null on failure
*/
function get_page_by_title( $page_title, $output = OBJECT, $post_type = 'page' ) {
global $wpdb;
if ( is_array( $post_type ) ) {
$post_type = esc_sql( $post_type );
$post_type_in_string = "'" . implode( "','", $post_type ) . "'";
$sql = $wpdb->prepare( "
SELECT ID
FROM $wpdb->posts
WHERE post_title = %s
AND post_type IN ($post_type_in_string)
", $page_title );
} else {
$sql = $wpdb->prepare( "
SELECT ID
FROM $wpdb->posts
WHERE post_title = %s
AND post_type = %s
", $page_title, $post_type );
}
$page = $wpdb->get_var( $sql );
if ( $page )
return get_post( $page, $output );
return null;
}
/**
* Retrieve child pages from list of pages matching page ID.
*
* Matches against the pages parameter against the page ID. Also matches all
* children for the same to retrieve all children of a page. Does not make any
* SQL queries to get the children.
*
* @since 1.5.1
*
* @param int $page_id Page ID.
* @param array $pages List of pages' objects.
* @return array
*/
function get_page_children($page_id, $pages) {
$page_list = array();
foreach ( (array) $pages as $page ) {
if ( $page->post_parent == $page_id ) {
$page_list[] = $page;
if ( $children = get_page_children($page->ID, $pages) )
$page_list = array_merge($page_list, $children);
}
}
return $page_list;
}
/**
* Order the pages with children under parents in a flat list.
*
* It uses auxiliary structure to hold parent-children relationships and
* runs in O(N) complexity
*
* @since 2.0.0
*
* @param array $pages Posts array.
* @param int $page_id Parent page ID.
* @return array A list arranged by hierarchy. Children immediately follow their parents.
*/
function get_page_hierarchy( &$pages, $page_id = 0 ) {
if ( empty( $pages ) ) {
$result = array();
return $result;
}
$children = array();
foreach ( (array) $pages as $p ) {
$parent_id = intval( $p->post_parent );
$children[ $parent_id ][] = $p;
}
$result = array();
_page_traverse_name( $page_id, $children, $result );
return $result;
}
/**
* function to traverse and return all the nested children post names of a root page.
* $children contains parent-children relations
*
* @since 2.9.0
*/
function _page_traverse_name( $page_id, &$children, &$result ){
if ( isset( $children[ $page_id ] ) ){
foreach( (array)$children[ $page_id ] as $child ) {
$result[ $child->ID ] = $child->post_name;
_page_traverse_name( $child->ID, $children, $result );
}
}
}
/**
* Builds URI for a page.
*
* Sub pages will be in the "directory" under the parent page post name.
*
* @since 1.5.0
*
* @param mixed $page Page object or page ID.
* @return string|false Page URI, false on error.
*/
function get_page_uri( $page ) {
$page = get_post( $page );
if ( ! $page )
return false;
$uri = $page->post_name;
foreach ( $page->ancestors as $parent ) {
$uri = get_post( $parent )->post_name . '/' . $uri;
}
return $uri;
}
/**
* Retrieve a list of pages.
*
* @global wpdb $wpdb WordPress database abstraction object
*
* @since 1.5.0
*
* @param mixed $args {
* Array or string of arguments. Optional.
*
* @type int 'child_of' Page ID to return child and grandchild pages of. Default 0, or no restriction.
* @type string 'sort_order' How to sort retrieved pages.
* Default 'ASC'. Accepts 'ASC', 'DESC'.
* @type string 'sort_column' What columns to sort pages by, comma-separated.
* Default 'post_title'. Accepts 'post_author', 'post_date', 'post_title', 'post_name',
* 'post_modified', 'post_modified_gmt', 'menu_order', 'post_parent', 'ID', 'rand',
* 'comment_count'. 'post_' can be omitted for any values that start with it.
* @type bool 'hierarchical' Whether to return pages hierarchically. Default true.
* @type array 'exclude' Array of page IDs to exclude.
* @type array 'include' Array of page IDs to include. Cannot be used with 'child_of', 'parent', 'exclude',
* 'meta_key', 'meta_value', or 'hierarchical'.
* @type string 'meta_key' Only include pages with this meta key.
* @type string 'meta_value' Only include pages with this meta value.
* @type string 'authors' A comma-separated list of author IDs.
* @type int 'parent' Page ID to return direct children of. 'hierarchical' must be false.
* Default -1, or no restriction.
* @type int 'exclude_tree' Remove all children of the given ID from returned pages.
* @type int 'number' The number of pages to return. Default 0, or all pages.
* @type int 'offset' The number of pages to skip before returning. Requires 'number'.
* Default 0.
* @type string 'post_type' The post type to query.
* Default 'page'.
* @type string 'post_status' A comma-separated list of post status types to include.
* Default 'publish'.
* }
* @return array List of pages matching defaults or $args.
*/
function get_pages( $args = array() ) {
global $wpdb;
$pages = false;
$defaults = array(
'child_of' => 0, 'sort_order' => 'ASC',
'sort_column' => 'post_title', 'hierarchical' => 1,
'exclude' => array(), 'include' => array(),
'meta_key' => '', 'meta_value' => '',
'authors' => '', 'parent' => -1, 'exclude_tree' => array(),
'number' => '', 'offset' => 0,
'post_type' => 'page', 'post_status' => 'publish',
);
$r = wp_parse_args( $args, $defaults );
extract( $r, EXTR_SKIP );
$number = (int) $number;
$offset = (int) $offset;
// Make sure the post type is hierarchical
$hierarchical_post_types = get_post_types( array( 'hierarchical' => true ) );
if ( !in_array( $post_type, $hierarchical_post_types ) )
return $pages;
if ( $parent > 0 && ! $child_of )
$hierarchical = false;
// Make sure we have a valid post status
if ( !is_array( $post_status ) )
$post_status = explode( ',', $post_status );
if ( array_diff( $post_status, get_post_stati() ) )
return $pages;
// $args can be whatever, only use the args defined in defaults to compute the key
$key = md5( serialize( compact(array_keys($defaults)) ) );
$last_changed = wp_cache_get( 'last_changed', 'posts' );
if ( ! $last_changed ) {
$last_changed = microtime();
wp_cache_set( 'last_changed', $last_changed, 'posts' );
}
$cache_key = "get_pages:$key:$last_changed";
if ( $cache = wp_cache_get( $cache_key, 'posts' ) ) {
// Convert to WP_Post instances
$pages = array_map( 'get_post', $cache );
/** This filter is documented in wp-includes/post.php */
$pages = apply_filters( 'get_pages', $pages, $r );
return $pages;
}
if ( !is_array($cache) )
$cache = array();
$inclusions = '';
if ( ! empty( $include ) ) {
$child_of = 0; //ignore child_of, parent, exclude, meta_key, and meta_value params if using include
$parent = -1;
$exclude = '';
$meta_key = '';
$meta_value = '';
$hierarchical = false;
$incpages = wp_parse_id_list( $include );
if ( ! empty( $incpages ) )
$inclusions = ' AND ID IN (' . implode( ',', $incpages ) . ')';
}
$exclusions = '';
if ( ! empty( $exclude ) ) {
$expages = wp_parse_id_list( $exclude );
if ( ! empty( $expages ) )
$exclusions = ' AND ID NOT IN (' . implode( ',', $expages ) . ')';
}
$author_query = '';
if (!empty($authors)) {
$post_authors = preg_split('/[\s,]+/',$authors);
if ( ! empty( $post_authors ) ) {
foreach ( $post_authors as $post_author ) {
//Do we have an author id or an author login?
if ( 0 == intval($post_author) ) {
$post_author = get_user_by('login', $post_author);
if ( empty($post_author) )
continue;
if ( empty($post_author->ID) )
continue;
$post_author = $post_author->ID;
}
if ( '' == $author_query )
$author_query = $wpdb->prepare(' post_author = %d ', $post_author);
else
$author_query .= $wpdb->prepare(' OR post_author = %d ', $post_author);
}
if ( '' != $author_query )
$author_query = " AND ($author_query)";
}
}
$join = '';
$where = "$exclusions $inclusions ";
if ( '' !== $meta_key || '' !== $meta_value ) {
$join = " LEFT JOIN $wpdb->postmeta ON ( $wpdb->posts.ID = $wpdb->postmeta.post_id )";
// meta_key and meta_value might be slashed
$meta_key = wp_unslash($meta_key);
$meta_value = wp_unslash($meta_value);
if ( '' !== $meta_key )
$where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_key = %s", $meta_key);
if ( '' !== $meta_value )
$where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_value = %s", $meta_value);
}
if ( is_array( $parent ) ) {
$post_parent__in = implode( ',', array_map( 'absint', (array) $parent ) );
if ( ! empty( $post_parent__in ) )
$where .= " AND post_parent IN ($post_parent__in)";
} elseif ( $parent >= 0 ) {
$where .= $wpdb->prepare(' AND post_parent = %d ', $parent);
}
if ( 1 == count( $post_status ) ) {
$where_post_type = $wpdb->prepare( "post_type = %s AND post_status = %s", $post_type, array_shift( $post_status ) );
} else {
$post_status = implode( "', '", $post_status );
$where_post_type = $wpdb->prepare( "post_type = %s AND post_status IN ('$post_status')", $post_type );
}
$orderby_array = array();
$allowed_keys = array('author', 'post_author', 'date', 'post_date', 'title', 'post_title', 'name', 'post_name', 'modified',
'post_modified', 'modified_gmt', 'post_modified_gmt', 'menu_order', 'parent', 'post_parent',
'ID', 'rand', 'comment_count');
foreach ( explode( ',', $sort_column ) as $orderby ) {
$orderby = trim( $orderby );
if ( !in_array( $orderby, $allowed_keys ) )
continue;
switch ( $orderby ) {
case 'menu_order':
break;
case 'ID':
$orderby = "$wpdb->posts.ID";
break;
case 'rand':
$orderby = 'RAND()';
break;
case 'comment_count':
$orderby = "$wpdb->posts.comment_count";
break;
default:
if ( 0 === strpos( $orderby, 'post_' ) )
$orderby = "$wpdb->posts." . $orderby;
else
$orderby = "$wpdb->posts.post_" . $orderby;
}
$orderby_array[] = $orderby;
}
$sort_column = ! empty( $orderby_array ) ? implode( ',', $orderby_array ) : "$wpdb->posts.post_title";
$sort_order = strtoupper( $sort_order );
if ( '' !== $sort_order && !in_array( $sort_order, array( 'ASC', 'DESC' ) ) )
$sort_order = 'ASC';
$query = "SELECT * FROM $wpdb->posts $join WHERE ($where_post_type) $where ";
$query .= $author_query;
$query .= " ORDER BY " . $sort_column . " " . $sort_order ;
if ( !empty($number) )
$query .= ' LIMIT ' . $offset . ',' . $number;
$pages = $wpdb->get_results($query);
if ( empty($pages) ) {
/** This filter is documented in wp-includes/post.php */
$pages = apply_filters( 'get_pages', array(), $r );
return $pages;
}
// Sanitize before caching so it'll only get done once
$num_pages = count($pages);
for ($i = 0; $i < $num_pages; $i++) {
$pages[$i] = sanitize_post($pages[$i], 'raw');
}
// Update cache.
update_post_cache( $pages );
if ( $child_of || $hierarchical )
$pages = get_page_children($child_of, $pages);
if ( ! empty( $exclude_tree ) ) {
$exclude = wp_parse_id_list( $exclude_tree );
foreach( $exclude as $id ) {
$children = get_page_children( $id, $pages );
foreach ( $children as $child ) {
$exclude[] = $child->ID;
}
}
$num_pages = count( $pages );
for ( $i = 0; $i < $num_pages; $i++ ) {
if ( in_array( $pages[$i]->ID, $exclude ) ) {
unset( $pages[$i] );
}
}
}
$page_structure = array();
foreach ( $pages as $page )
$page_structure[] = $page->ID;
wp_cache_set( $cache_key, $page_structure, 'posts' );
// Convert to WP_Post instances
$pages = array_map( 'get_post', $pages );
/**
* Filter the retrieved list of pages.
*
* @since 2.1.0
*
* @param array $pages List of pages to retrieve.
* @param array $r Array of get_pages() arguments.
*/
$pages = apply_filters( 'get_pages', $pages, $r );
return $pages;
}
//
// Attachment functions
//
/**
* Check if the attachment URI is local one and is really an attachment.
*
* @since 2.0.0
*
* @param string $url URL to check
* @return bool True on success, false on failure.
*/
function is_local_attachment($url) {
if (strpos($url, home_url()) === false)
return false;
if (strpos($url, home_url('/?attachment_id=')) !== false)
return true;
if ( $id = url_to_postid($url) ) {
$post = get_post($id);
if ( 'attachment' == $post->post_type )
return true;
}
return false;
}
/**
* Insert an attachment.
*
* If you set the 'ID' in the $object parameter, it will mean that you are
* updating and attempt to update the attachment. You can also set the
* attachment name or title by setting the key 'post_name' or 'post_title'.
*
* You can set the dates for the attachment manually by setting the 'post_date'
* and 'post_date_gmt' keys' values.
*
* By default, the comments will use the default settings for whether the
* comments are allowed. You can close them manually or keep them open by
* setting the value for the 'comment_status' key.
*
* The $object parameter can have the following:
* 'post_status' - Default is 'draft'. Can not be overridden, set the same as parent post.
* 'post_type' - Default is 'post', will be set to attachment. Can not override.
* 'post_author' - Default is current user ID. The ID of the user, who added the attachment.
* 'ping_status' - Default is the value in default ping status option. Whether the attachment
* can accept pings.
* 'post_parent' - Default is 0. Can use $parent parameter or set this for the post it belongs
* to, if any.
* 'menu_order' - Default is 0. The order it is displayed.
* 'to_ping' - Whether to ping.
* 'pinged' - Default is empty string.
* 'post_password' - Default is empty string. The password to access the attachment.
* 'guid' - Global Unique ID for referencing the attachment.
* 'post_content_filtered' - Attachment post content filtered.
* 'post_excerpt' - Attachment excerpt.
*
* @since 2.0.0
* @uses $wpdb
*
* @param string|array $object Arguments to override defaults.
* @param string $file Optional filename.
* @param int $parent Parent post ID.
* @return int Attachment ID.
*/
function wp_insert_attachment($object, $file = false, $parent = 0) {
global $wpdb;
$user_id = get_current_user_id();
$defaults = array('post_status' => 'inherit', 'post_type' => 'post', 'post_author' => $user_id,
'ping_status' => get_option('default_ping_status'), 'post_parent' => 0, 'post_title' => '',
'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '', 'post_content' => '',
'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0, 'context' => '');
$object = wp_parse_args($object, $defaults);
if ( !empty($parent) )
$object['post_parent'] = $parent;
unset( $object[ 'filter' ] );
$object = sanitize_post($object, 'db');
// export array as variables
extract($object, EXTR_SKIP);
if ( empty($post_author) )
$post_author = $user_id;
$post_type = 'attachment';
if ( ! in_array( $post_status, array( 'inherit', 'private' ) ) )
$post_status = 'inherit';
if ( !empty($post_category) )
$post_category = array_filter($post_category); // Filter out empty terms
// Make sure we set a valid category.
if ( empty($post_category) || 0 == count($post_category) || !is_array($post_category) ) {
$post_category = array();
}
// Are we updating or creating?
if ( !empty($ID) ) {
$update = true;
$post_ID = (int) $ID;
} else {
$update = false;
$post_ID = 0;
}
// Create a valid post name.
if ( empty($post_name) )
$post_name = sanitize_title($post_title);
else
$post_name = sanitize_title($post_name);
// expected_slashed ($post_name)
$post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent);
if ( empty($post_date) )
$post_date = current_time('mysql');
if ( empty($post_date_gmt) )
$post_date_gmt = current_time('mysql', 1);
if ( empty($post_modified) )
$post_modified = $post_date;
if ( empty($post_modified_gmt) )
$post_modified_gmt = $post_date_gmt;
if ( empty($comment_status) ) {
if ( $update )
$comment_status = 'closed';
else
$comment_status = get_option('default_comment_status');
}
if ( empty($ping_status) )
$ping_status = get_option('default_ping_status');
if ( isset($to_ping) )
$to_ping = preg_replace('|\s+|', "\n", $to_ping);
else
$to_ping = '';
if ( isset($post_parent) )
$post_parent = (int) $post_parent;
else
$post_parent = 0;
if ( isset($menu_order) )
$menu_order = (int) $menu_order;
else
$menu_order = 0;
if ( !isset($post_password) )
$post_password = '';
if ( ! isset($pinged) )
$pinged = '';
// expected_slashed (everything!)
$data = compact( array( 'post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_content_filtered', 'post_title', 'post_excerpt', 'post_status', 'post_type', 'comment_status', 'ping_status', 'post_password', 'post_name', 'to_ping', 'pinged', 'post_modified', 'post_modified_gmt', 'post_parent', 'menu_order', 'post_mime_type', 'guid' ) );
/**
* Filter attachment post data before it is updated in or added
* to the database.
*
* @since 3.9.0
*
* @param array $data Array of sanitized attachment post data.
* @param array $object Array of un-sanitized attachment post data.
*/
$data = apply_filters( 'wp_insert_attachment_data', $data, $object );
$data = wp_unslash( $data );
if ( $update ) {
$wpdb->update( $wpdb->posts, $data, array( 'ID' => $post_ID ) );
} else {
// If there is a suggested ID, use it if not already present
if ( !empty($import_id) ) {
$import_id = (int) $import_id;
if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) {
$data['ID'] = $import_id;
}
}
$wpdb->insert( $wpdb->posts, $data );
$post_ID = (int) $wpdb->insert_id;
}
if ( empty($post_name) ) {
$post_name = sanitize_title($post_title, $post_ID);
$wpdb->update( $wpdb->posts, compact("post_name"), array( 'ID' => $post_ID ) );
}
if ( is_object_in_taxonomy($post_type, 'category') )
wp_set_post_categories( $post_ID, $post_category );
if ( isset( $tags_input ) && is_object_in_taxonomy($post_type, 'post_tag') )
wp_set_post_tags( $post_ID, $tags_input );
// support for all custom taxonomies
if ( !empty($tax_input) ) {
foreach ( $tax_input as $taxonomy => $tags ) {
$taxonomy_obj = get_taxonomy($taxonomy);
if ( is_array($tags) ) // array = hierarchical, string = non-hierarchical.
$tags = array_filter($tags);
if ( current_user_can($taxonomy_obj->cap->assign_terms) )
wp_set_post_terms( $post_ID, $tags, $taxonomy );
}
}
if ( $file )
update_attached_file( $post_ID, $file );
clean_post_cache( $post_ID );
if ( ! empty( $context ) )
add_post_meta( $post_ID, '_wp_attachment_context', $context, true );
if ( $update) {
/**
* Fires once an existing attachment has been updated.
*
* @since 2.0.0
*
* @param int $post_ID Attachment ID.
*/
do_action( 'edit_attachment', $post_ID );
} else {
/**
* Fires once an attachment has been added.
*
* @since 2.0.0
*
* @param int $post_ID Attachment ID.
*/
do_action( 'add_attachment', $post_ID );
}
return $post_ID;
}
/**
* Trashes or deletes an attachment.
*
* When an attachment is permanently deleted, the file will also be removed.
* Deletion removes all post meta fields, taxonomy, comments, etc. associated
* with the attachment (except the main post).
*
* The attachment is moved to the trash instead of permanently deleted unless trash
* for media is disabled, item is already in the trash, or $force_delete is true.
*
* @since 2.0.0
* @uses $wpdb
*
* @param int $post_id Attachment ID.
* @param bool $force_delete Whether to bypass trash and force deletion. Defaults to false.
* @return mixed False on failure. Post data on success.
*/
function wp_delete_attachment( $post_id, $force_delete = false ) {
global $wpdb;
if ( !$post = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $post_id) ) )
return $post;
if ( 'attachment' != $post->post_type )
return false;
if ( !$force_delete && EMPTY_TRASH_DAYS && MEDIA_TRASH && 'trash' != $post->post_status )
return wp_trash_post( $post_id );
delete_post_meta($post_id, '_wp_trash_meta_status');
delete_post_meta($post_id, '_wp_trash_meta_time');
$meta = wp_get_attachment_metadata( $post_id );
$backup_sizes = get_post_meta( $post->ID, '_wp_attachment_backup_sizes', true );
$file = get_attached_file( $post_id );
$intermediate_sizes = array();
foreach ( get_intermediate_image_sizes() as $size ) {
if ( $intermediate = image_get_intermediate_size( $post_id, $size ) )
$intermediate_sizes[] = $intermediate;
}
if ( is_multisite() )
delete_transient( 'dirsize_cache' );
/**
* Fires before an attachment is deleted, at the start of wp_delete_attachment().
*
* @since 2.0.0
*
* @param int $post_id Attachment ID.
*/
do_action( 'delete_attachment', $post_id );
wp_delete_object_term_relationships($post_id, array('category', 'post_tag'));
wp_delete_object_term_relationships($post_id, get_object_taxonomies($post->post_type));
delete_metadata( 'post', null, '_thumbnail_id', $post_id, true ); // delete all for any posts.
$comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $post_id ));
foreach ( $comment_ids as $comment_id )
wp_delete_comment( $comment_id, true );
$post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $post_id ));
foreach ( $post_meta_ids as $mid )
delete_metadata_by_mid( 'post', $mid );
/** This action is documented in wp-includes/post.php */
do_action( 'delete_post', $post_id );
$result = $wpdb->delete( $wpdb->posts, array( 'ID' => $post_id ) );
if ( ! $result ) {
return false;
}
/** This action is documented in wp-includes/post.php */
do_action( 'deleted_post', $post_id );
$uploadpath = wp_upload_dir();
if ( ! empty($meta['thumb']) ) {
// Don't delete the thumb if another attachment uses it
if (! $wpdb->get_row( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attachment_metadata' AND meta_value LIKE %s AND post_id <> %d", '%' . $meta['thumb'] . '%', $post_id)) ) {
$thumbfile = str_replace(basename($file), $meta['thumb'], $file);
/** This filter is documented in wp-admin/custom-header.php */
$thumbfile = apply_filters( 'wp_delete_file', $thumbfile );
@ unlink( path_join($uploadpath['basedir'], $thumbfile) );
}
}
// remove intermediate and backup images if there are any
foreach ( $intermediate_sizes as $intermediate ) {
/** This filter is documented in wp-admin/custom-header.php */
$intermediate_file = apply_filters( 'wp_delete_file', $intermediate['path'] );
@ unlink( path_join($uploadpath['basedir'], $intermediate_file) );
}
if ( is_array($backup_sizes) ) {
foreach ( $backup_sizes as $size ) {
$del_file = path_join( dirname($meta['file']), $size['file'] );
/** This filter is documented in wp-admin/custom-header.php */
$del_file = apply_filters( 'wp_delete_file', $del_file );
@ unlink( path_join($uploadpath['basedir'], $del_file) );
}
}
/** This filter is documented in wp-admin/custom-header.php */
$file = apply_filters( 'wp_delete_file', $file );
if ( ! empty($file) )
@ unlink($file);
clean_post_cache( $post );
return $post;
}
/**
* Retrieve attachment meta field for attachment ID.
*
* @since 2.1.0
*
* @param int $post_id Attachment ID
* @param bool $unfiltered Optional, default is false. If true, filters are not run.
* @return string|bool Attachment meta field. False on failure.
*/
function wp_get_attachment_metadata( $post_id = 0, $unfiltered = false ) {
$post_id = (int) $post_id;
if ( !$post = get_post( $post_id ) )
return false;
$data = get_post_meta( $post->ID, '_wp_attachment_metadata', true );
if ( $unfiltered )
return $data;
/**
* Filter the attachment meta data.
*
* @since 2.1.0
*
* @param array|bool $data Array of meta data for the given attachment, or false
* if the object does not exist.
* @param int $post_id Attachment ID.
*/
return apply_filters( 'wp_get_attachment_metadata', $data, $post->ID );
}
/**
* Update metadata for an attachment.
*
* @since 2.1.0
*
* @param int $post_id Attachment ID.
* @param array $data Attachment data.
* @return int
*/
function wp_update_attachment_metadata( $post_id, $data ) {
$post_id = (int) $post_id;
if ( !$post = get_post( $post_id ) )
return false;
/**
* Filter the updated attachment meta data.
*
* @since 2.1.0
*
* @param array $data Array of updated attachment meta data.
* @param int $post_id Attachment ID.
*/
if ( $data = apply_filters( 'wp_update_attachment_metadata', $data, $post->ID ) )
return update_post_meta( $post->ID, '_wp_attachment_metadata', $data );
else
return delete_post_meta( $post->ID, '_wp_attachment_metadata' );
}
/**
* Retrieve the URL for an attachment.
*
* @since 2.1.0
*
* @param int $post_id Attachment ID.
* @return string
*/
function wp_get_attachment_url( $post_id = 0 ) {
$post_id = (int) $post_id;
if ( !$post = get_post( $post_id ) )
return false;
if ( 'attachment' != $post->post_type )
return false;
$url = '';
if ( $file = get_post_meta( $post->ID, '_wp_attached_file', true) ) { //Get attached file
if ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) { //Get upload directory
if ( 0 === strpos($file, $uploads['basedir']) ) //Check that the upload base exists in the file location
$url = str_replace($uploads['basedir'], $uploads['baseurl'], $file); //replace file location with url location
elseif ( false !== strpos($file, 'wp-content/uploads') )
$url = $uploads['baseurl'] . substr( $file, strpos($file, 'wp-content/uploads') + 18 );
else
$url = $uploads['baseurl'] . "/$file"; //Its a newly uploaded file, therefor $file is relative to the basedir.
}
}
if ( empty($url) ) //If any of the above options failed, Fallback on the GUID as used pre-2.7, not recommended to rely upon this.
$url = get_the_guid( $post->ID );
/**
* Filter the attachment URL.
*
* @since 2.1.0
*
* @param string $url URL for the given attachment.
* @param int $post_id Attachment ID.
*/
$url = apply_filters( 'wp_get_attachment_url', $url, $post->ID );
if ( empty( $url ) )
return false;
return $url;
}
/**
* Retrieve thumbnail for an attachment.
*
* @since 2.1.0
*
* @param int $post_id Attachment ID.
* @return mixed False on failure. Thumbnail file path on success.
*/
function wp_get_attachment_thumb_file( $post_id = 0 ) {
$post_id = (int) $post_id;
if ( !$post = get_post( $post_id ) )
return false;
if ( !is_array( $imagedata = wp_get_attachment_metadata( $post->ID ) ) )
return false;
$file = get_attached_file( $post->ID );
if ( !empty($imagedata['thumb']) && ($thumbfile = str_replace(basename($file), $imagedata['thumb'], $file)) && file_exists($thumbfile) ) {
/**
* Filter the attachment thumbnail file path.
*
* @since 2.1.0
*
* @param string $thumbfile File path to the attachment thumbnail.
* @param int $post_id Attachment ID.
*/
return apply_filters( 'wp_get_attachment_thumb_file', $thumbfile, $post->ID );
}
return false;
}
/**
* Retrieve URL for an attachment thumbnail.
*
* @since 2.1.0
*
* @param int $post_id Attachment ID
* @return string|bool False on failure. Thumbnail URL on success.
*/
function wp_get_attachment_thumb_url( $post_id = 0 ) {
$post_id = (int) $post_id;
if ( !$post = get_post( $post_id ) )
return false;
if ( !$url = wp_get_attachment_url( $post->ID ) )
return false;
$sized = image_downsize( $post_id, 'thumbnail' );
if ( $sized )
return $sized[0];
if ( !$thumb = wp_get_attachment_thumb_file( $post->ID ) )
return false;
$url = str_replace(basename($url), basename($thumb), $url);
/**
* Filter the attachment thumbnail URL.
*
* @since 2.1.0
*
* @param string $url URL for the attachment thumbnail.
* @param int $post_id Attachment ID.
*/
return apply_filters( 'wp_get_attachment_thumb_url', $url, $post->ID );
}
/**
* Check if the attachment is an image.
*
* @since 2.1.0
*
* @param int $post_id Attachment ID
* @return bool
*/
function wp_attachment_is_image( $post_id = 0 ) {
$post_id = (int) $post_id;
if ( !$post = get_post( $post_id ) )
return false;
if ( !$file = get_attached_file( $post->ID ) )
return false;
$ext = preg_match('/\.([^.]+)$/', $file, $matches) ? strtolower($matches[1]) : false;
$image_exts = array( 'jpg', 'jpeg', 'jpe', 'gif', 'png' );
if ( 'image/' == substr($post->post_mime_type, 0, 6) || $ext && 'import' == $post->post_mime_type && in_array($ext, $image_exts) )
return true;
return false;
}
/**
* Retrieve the icon for a MIME type.
*
* @since 2.1.0
*
* @param string|int $mime MIME type or attachment ID.
* @return string|bool
*/
function wp_mime_type_icon( $mime = 0 ) {
if ( !is_numeric($mime) )
$icon = wp_cache_get("mime_type_icon_$mime");
$post_id = 0;
if ( empty($icon) ) {
$post_mimes = array();
if ( is_numeric($mime) ) {
$mime = (int) $mime;
if ( $post = get_post( $mime ) ) {
$post_id = (int) $post->ID;
$ext = preg_replace('/^.+?\.([^.]+)$/', '$1', $post->guid);
if ( !empty($ext) ) {
$post_mimes[] = $ext;
if ( $ext_type = wp_ext2type( $ext ) )
$post_mimes[] = $ext_type;
}
$mime = $post->post_mime_type;
} else {
$mime = 0;
}
} else {
$post_mimes[] = $mime;
}
$icon_files = wp_cache_get('icon_files');
if ( !is_array($icon_files) ) {
/**
* Filter the icon directory path.
*
* @since 2.0.0
*
* @param string $path Icon directory absolute path.
*/
$icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/media' );
/**
* Filter the icon directory URI.
*
* @since 2.0.0
*
* @param string $uri Icon directory URI.
*/
$icon_dir_uri = apply_filters( 'icon_dir_uri', includes_url( 'images/media' ) );
/**
* Filter the list of icon directory URIs.
*
* @since 2.5.0
*
* @param array $uris List of icon directory URIs.
*/
$dirs = apply_filters( 'icon_dirs', array( $icon_dir => $icon_dir_uri ) );
$icon_files = array();
while ( $dirs ) {
$keys = array_keys( $dirs );
$dir = array_shift( $keys );
$uri = array_shift($dirs);
if ( $dh = opendir($dir) ) {
while ( false !== $file = readdir($dh) ) {
$file = basename($file);
if ( substr($file, 0, 1) == '.' )
continue;
if ( !in_array(strtolower(substr($file, -4)), array('.png', '.gif', '.jpg') ) ) {
if ( is_dir("$dir/$file") )
$dirs["$dir/$file"] = "$uri/$file";
continue;
}
$icon_files["$dir/$file"] = "$uri/$file";
}
closedir($dh);
}
}
wp_cache_add( 'icon_files', $icon_files, 'default', 600 );
}
// Icon basename - extension = MIME wildcard
foreach ( $icon_files as $file => $uri )
$types[ preg_replace('/^([^.]*).*$/', '$1', basename($file)) ] =& $icon_files[$file];
if ( ! empty($mime) ) {
$post_mimes[] = substr($mime, 0, strpos($mime, '/'));
$post_mimes[] = substr($mime, strpos($mime, '/') + 1);
$post_mimes[] = str_replace('/', '_', $mime);
}
$matches = wp_match_mime_types(array_keys($types), $post_mimes);
$matches['default'] = array('default');
foreach ( $matches as $match => $wilds ) {
if ( isset($types[$wilds[0]])) {
$icon = $types[$wilds[0]];
if ( !is_numeric($mime) )
wp_cache_add("mime_type_icon_$mime", $icon);
break;
}
}
}
/**
* Filter the mime type icon.
*
* @since 2.1.0
*
* @param string $icon Path to the mime type icon.
* @param string $mime Mime type.
* @param int $post_id Attachment ID. Will equal 0 if the function passed
* the mime type.
*/
return apply_filters( 'wp_mime_type_icon', $icon, $mime, $post_id );
}
/**
* Checked for changed slugs for published post objects and save the old slug.
*
* The function is used when a post object of any type is updated,
* by comparing the current and previous post objects.
*
* If the slug was changed and not already part of the old slugs then it will be
* added to the post meta field ('_wp_old_slug') for storing old slugs for that
* post.
*
* The most logically usage of this function is redirecting changed post objects, so
* that those that linked to an changed post will be redirected to the new post.
*
* @since 2.1.0
*
* @param int $post_id Post ID.
* @param object $post The Post Object
* @param object $post_before The Previous Post Object
* @return int Same as $post_id
*/
function wp_check_for_changed_slugs($post_id, $post, $post_before) {
// dont bother if it hasnt changed
if ( $post->post_name == $post_before->post_name )
return;
// we're only concerned with published, non-hierarchical objects
if ( $post->post_status != 'publish' || is_post_type_hierarchical( $post->post_type ) )
return;
$old_slugs = (array) get_post_meta($post_id, '_wp_old_slug');
// if we haven't added this old slug before, add it now
if ( !empty( $post_before->post_name ) && !in_array($post_before->post_name, $old_slugs) )
add_post_meta($post_id, '_wp_old_slug', $post_before->post_name);
// if the new slug was used previously, delete it from the list
if ( in_array($post->post_name, $old_slugs) )
delete_post_meta($post_id, '_wp_old_slug', $post->post_name);
}
/**
* Retrieve the private post SQL based on capability.
*
* This function provides a standardized way to appropriately select on the
* post_status of a post type. The function will return a piece of SQL code
* that can be added to a WHERE clause; this SQL is constructed to allow all
* published posts, and all private posts to which the user has access.
*
* @since 2.2.0
*
* @param string $post_type currently only supports 'post' or 'page'.
* @return string SQL code that can be added to a where clause.
*/
function get_private_posts_cap_sql( $post_type ) {
return get_posts_by_author_sql( $post_type, false );
}
/**
* Retrieve the post SQL based on capability, author, and type.
*
* @see get_private_posts_cap_sql() for full description.
*
* @since 3.0.0
* @param string $post_type Post type.
* @param bool $full Optional. Returns a full WHERE statement instead of just an 'andalso' term.
* @param int $post_author Optional. Query posts having a single author ID.
* @param bool $public_only Optional. Only return public posts. Skips cap checks for $current_user. Default is false.
* @return string SQL WHERE code that can be added to a query.
*/
function get_posts_by_author_sql( $post_type, $full = true, $post_author = null, $public_only = false ) {
global $wpdb;
// Private posts
$post_type_obj = get_post_type_object( $post_type );
if ( ! $post_type_obj )
return $full ? 'WHERE 1 = 0' : ' 1 = 0 ';
/**
* Filter the capability to read private posts for a custom post type
* when generating SQL for getting posts by author.
*
* @since 2.2.0
* @deprecated 3.2.0 The hook transitioned from "somewhat useless" to "totally useless".
*
* @param string $cap Capability.
*/
if ( ! $cap = apply_filters( 'pub_priv_sql_capability', '' ) ) {
$cap = $post_type_obj->cap->read_private_posts;
}
if ( $full ) {
if ( null === $post_author ) {
$sql = $wpdb->prepare( 'WHERE post_type = %s AND ', $post_type );
} else {
$sql = $wpdb->prepare( 'WHERE post_author = %d AND post_type = %s AND ', $post_author, $post_type );
}
} else {
$sql = '';
}
$sql .= "(post_status = 'publish'";
// Only need to check the cap if $public_only is false
if ( false === $public_only ) {
if ( current_user_can( $cap ) ) {
// Does the user have the capability to view private posts? Guess so.
$sql .= " OR post_status = 'private'";
} elseif ( is_user_logged_in() ) {
// Users can view their own private posts.
$id = get_current_user_id();
if ( null === $post_author || ! $full ) {
$sql .= " OR post_status = 'private' AND post_author = $id";
} elseif ( $id == (int) $post_author ) {
$sql .= " OR post_status = 'private'";
} // else none
} // else none
}
$sql .= ')';
return $sql;
}
/**
* Retrieve the date that the last post was published.
*
* The server timezone is the default and is the difference between GMT and
* server time. The 'blog' value is the date when the last post was posted. The
* 'gmt' is when the last post was posted in GMT formatted date.
*
* @since 0.71
*
* @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'.
* @return string The date of the last post.
*/
function get_lastpostdate($timezone = 'server') {
/**
* Filter the date the last post was published.
*
* @since 2.3.0
*
* @param string $date Date the last post was published. Likely values are 'gmt',
* 'blog', or 'server'.
* @param string $timezone Location to use for getting the post published date.
*/
return apply_filters( 'get_lastpostdate', _get_last_post_time( $timezone, 'date' ), $timezone );
}
/**
* Retrieve last post modified date depending on timezone.
*
* The server timezone is the default and is the difference between GMT and
* server time. The 'blog' value is just when the last post was modified. The
* 'gmt' is when the last post was modified in GMT time.
*
* @since 1.2.0
*
* @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'.
* @return string The date the post was last modified.
*/
function get_lastpostmodified($timezone = 'server') {
$lastpostmodified = _get_last_post_time( $timezone, 'modified' );
$lastpostdate = get_lastpostdate($timezone);
if ( $lastpostdate > $lastpostmodified )
$lastpostmodified = $lastpostdate;
/**
* Filter the date the last post was modified.
*
* @since 2.3.0
*
* @param string $lastpostmodified Date the last post was modified.
* @param string $timezone Location to use for getting the post modified date.
*/
return apply_filters( 'get_lastpostmodified', $lastpostmodified, $timezone );
}
/**
* Retrieve latest post date data based on timezone.
*
* @access private
* @since 3.1.0
*
* @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'.
* @param string $field Field to check. Can be 'date' or 'modified'.
* @return string The date.
*/
function _get_last_post_time( $timezone, $field ) {
global $wpdb;
if ( !in_array( $field, array( 'date', 'modified' ) ) )
return false;
$timezone = strtolower( $timezone );
$key = "lastpost{$field}:$timezone";
$date = wp_cache_get( $key, 'timeinfo' );
if ( !$date ) {
$add_seconds_server = date('Z');
$post_types = get_post_types( array( 'public' => true ) );
array_walk( $post_types, array( &$wpdb, 'escape_by_ref' ) );
$post_types = "'" . implode( "', '", $post_types ) . "'";
switch ( $timezone ) {
case 'gmt':
$date = $wpdb->get_var("SELECT post_{$field}_gmt FROM $wpdb->posts WHERE post_status = 'publish' AND post_type IN ({$post_types}) ORDER BY post_{$field}_gmt DESC LIMIT 1");
break;
case 'blog':
$date = $wpdb->get_var("SELECT post_{$field} FROM $wpdb->posts WHERE post_status = 'publish' AND post_type IN ({$post_types}) ORDER BY post_{$field}_gmt DESC LIMIT 1");
break;
case 'server':
$date = $wpdb->get_var("SELECT DATE_ADD(post_{$field}_gmt, INTERVAL '$add_seconds_server' SECOND) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type IN ({$post_types}) ORDER BY post_{$field}_gmt DESC LIMIT 1");
break;
}
if ( $date )
wp_cache_set( $key, $date, 'timeinfo' );
}
return $date;
}
/**
* Updates posts in cache.
*
* @since 1.5.1
*
* @param array $posts Array of post objects
*/
function update_post_cache( &$posts ) {
if ( ! $posts )
return;
foreach ( $posts as $post )
wp_cache_add( $post->ID, $post, 'posts' );
}
/**
* Will clean the post in the cache.
*
* Cleaning means delete from the cache of the post. Will call to clean the term
* object cache associated with the post ID.
*
* This function not run if $_wp_suspend_cache_invalidation is not empty. See
* wp_suspend_cache_invalidation().
*
* @since 2.0.0
*
* @param int|WP_Post $post Post ID or post object to remove from the cache.
*/
function clean_post_cache( $post ) {
global $_wp_suspend_cache_invalidation, $wpdb;
if ( ! empty( $_wp_suspend_cache_invalidation ) )
return;
$post = get_post( $post );
if ( empty( $post ) )
return;
wp_cache_delete( $post->ID, 'posts' );
wp_cache_delete( $post->ID, 'post_meta' );
clean_object_term_cache( $post->ID, $post->post_type );
wp_cache_delete( 'wp_get_archives', 'general' );
/**
* Fires immediately after the given post's cache is cleaned.
*
* @since 2.5.0
*
* @param int $post_id Post ID.
* @param WP_Post $post Post object.
*/
do_action( 'clean_post_cache', $post->ID, $post );
if ( is_post_type_hierarchical( $post->post_type ) )
wp_cache_delete( 'get_pages', 'posts' );
if ( 'page' == $post->post_type ) {
wp_cache_delete( 'all_page_ids', 'posts' );
/**
* Fires immediately after the given page's cache is cleaned.
*
* @since 2.5.0
*
* @param int $post_id Post ID.
*/
do_action( 'clean_page_cache', $post->ID );
}
wp_cache_set( 'last_changed', microtime(), 'posts' );
}
/**
* Call major cache updating functions for list of Post objects.
*
* @since 1.5.0
*
* @uses update_post_cache()
* @uses update_object_term_cache()
* @uses update_postmeta_cache()
*
* @param array $posts Array of Post objects
* @param string $post_type The post type of the posts in $posts. Default is 'post'.
* @param bool $update_term_cache Whether to update the term cache. Default is true.
* @param bool $update_meta_cache Whether to update the meta cache. Default is true.
*/
function update_post_caches(&$posts, $post_type = 'post', $update_term_cache = true, $update_meta_cache = true) {
// No point in doing all this work if we didn't match any posts.
if ( !$posts )
return;
update_post_cache($posts);
$post_ids = array();
foreach ( $posts as $post )
$post_ids[] = $post->ID;
if ( ! $post_type )
$post_type = 'any';
if ( $update_term_cache ) {
if ( is_array($post_type) ) {
$ptypes = $post_type;
} elseif ( 'any' == $post_type ) {
// Just use the post_types in the supplied posts.
foreach ( $posts as $post )
$ptypes[] = $post->post_type;
$ptypes = array_unique($ptypes);
} else {
$ptypes = array($post_type);
}
if ( ! empty($ptypes) )
update_object_term_cache($post_ids, $ptypes);
}
if ( $update_meta_cache )
update_postmeta_cache($post_ids);
}
/**
* Updates metadata cache for list of post IDs.
*
* Performs SQL query to retrieve the metadata for the post IDs and updates the
* metadata cache for the posts. Therefore, the functions, which call this
* function, do not need to perform SQL queries on their own.
*
* @since 2.1.0
*
* @param array $post_ids List of post IDs.
* @return bool|array Returns false if there is nothing to update or an array of metadata.
*/
function update_postmeta_cache($post_ids) {
return update_meta_cache('post', $post_ids);
}
/**
* Will clean the attachment in the cache.
*
* Cleaning means delete from the cache. Optionally will clean the term
* object cache associated with the attachment ID.
*
* This function will not run if $_wp_suspend_cache_invalidation is not empty. See
* wp_suspend_cache_invalidation().
*
* @since 3.0.0
*
* @param int $id The attachment ID in the cache to clean
* @param bool $clean_terms optional. Whether to clean terms cache
*/
function clean_attachment_cache($id, $clean_terms = false) {
global $_wp_suspend_cache_invalidation;
if ( !empty($_wp_suspend_cache_invalidation) )
return;
$id = (int) $id;
wp_cache_delete($id, 'posts');
wp_cache_delete($id, 'post_meta');
if ( $clean_terms )
clean_object_term_cache($id, 'attachment');
/**
* Fires after the given attachment's cache is cleaned.
*
* @since 3.0.0
*
* @param int $id Attachment ID.
*/
do_action( 'clean_attachment_cache', $id );
}
//
// Hooks
//
/**
* Hook for managing future post transitions to published.
*
* @since 2.3.0
* @access private
* @uses $wpdb
* @uses wp_clear_scheduled_hook() with 'publish_future_post' and post ID.
*
* @param string $new_status New post status
* @param string $old_status Previous post status
* @param object $post Object type containing the post information
*/
function _transition_post_status($new_status, $old_status, $post) {
global $wpdb;
if ( $old_status != 'publish' && $new_status == 'publish' ) {
// Reset GUID if transitioning to publish and it is empty
if ( '' == get_the_guid($post->ID) )
$wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post->ID ) ), array( 'ID' => $post->ID ) );
/**
* Fires when a post's status is transitioned from private to published.
*
* @since 1.5.0
* @deprecated 2.3.0 Use 'private_to_publish' instead.
*
* @param int $post_id Post ID.
*/
do_action('private_to_published', $post->ID);
}
// If published posts changed clear the lastpostmodified cache
if ( 'publish' == $new_status || 'publish' == $old_status) {
foreach ( array( 'server', 'gmt', 'blog' ) as $timezone ) {
wp_cache_delete( "lastpostmodified:$timezone", 'timeinfo' );
wp_cache_delete( "lastpostdate:$timezone", 'timeinfo' );
}
}
if ( $new_status !== $old_status ) {
wp_cache_delete( _count_posts_cache_key( $post->post_type ), 'counts' );
wp_cache_delete( _count_posts_cache_key( $post->post_type, 'readable' ), 'counts' );
}
// Always clears the hook in case the post status bounced from future to draft.
wp_clear_scheduled_hook('publish_future_post', array( $post->ID ) );
}
/**
* Hook used to schedule publication for a post marked for the future.
*
* The $post properties used and must exist are 'ID' and 'post_date_gmt'.
*
* @since 2.3.0
* @access private
*
* @param int $deprecated Not used. Can be set to null. Never implemented.
* Not marked as deprecated with _deprecated_argument() as it conflicts with
* wp_transition_post_status() and the default filter for _future_post_hook().
* @param object $post Object type containing the post information
*/
function _future_post_hook( $deprecated, $post ) {
wp_clear_scheduled_hook( 'publish_future_post', array( $post->ID ) );
wp_schedule_single_event( strtotime( get_gmt_from_date( $post->post_date ) . ' GMT') , 'publish_future_post', array( $post->ID ) );
}
/**
* Hook to schedule pings and enclosures when a post is published.
*
* @since 2.3.0
* @access private
* @uses XMLRPC_REQUEST and WP_IMPORTING constants.
*
* @param int $post_id The ID in the database table of the post being published
*/
function _publish_post_hook($post_id) {
if ( defined( 'XMLRPC_REQUEST' ) ) {
/**
* Fires when _publish_post_hook() is called during an XML-RPC request.
*
* @since 2.1.0
*
* @param int $post_id Post ID.
*/
do_action( 'xmlrpc_publish_post', $post_id );
}
if ( defined('WP_IMPORTING') )
return;
if ( get_option('default_pingback_flag') )
add_post_meta( $post_id, '_pingme', '1' );
add_post_meta( $post_id, '_encloseme', '1' );
wp_schedule_single_event(time(), 'do_pings');
}
/**
* Returns the post's parent's post_ID
*
* @since 3.1.0
*
* @param int $post_id
*
* @return int|bool false on error
*/
function wp_get_post_parent_id( $post_ID ) {
$post = get_post( $post_ID );
if ( !$post || is_wp_error( $post ) )
return false;
return (int) $post->post_parent;
}
/**
* Checks the given subset of the post hierarchy for hierarchy loops.
* Prevents loops from forming and breaks those that it finds.
*
* Attached to the wp_insert_post_parent filter.
*
* @since 3.1.0
* @uses wp_find_hierarchy_loop()
*
* @param int $post_parent ID of the parent for the post we're checking.
* @param int $post_ID ID of the post we're checking.
*
* @return int The new post_parent for the post.
*/
function wp_check_post_hierarchy_for_loops( $post_parent, $post_ID ) {
// Nothing fancy here - bail
if ( !$post_parent )
return 0;
// New post can't cause a loop
if ( empty( $post_ID ) )
return $post_parent;
// Can't be its own parent
if ( $post_parent == $post_ID )
return 0;
// Now look for larger loops
if ( !$loop = wp_find_hierarchy_loop( 'wp_get_post_parent_id', $post_ID, $post_parent ) )
return $post_parent; // No loop
// Setting $post_parent to the given value causes a loop
if ( isset( $loop[$post_ID] ) )
return 0;
// There's a loop, but it doesn't contain $post_ID. Break the loop.
foreach ( array_keys( $loop ) as $loop_member )
wp_update_post( array( 'ID' => $loop_member, 'post_parent' => 0 ) );
return $post_parent;
}
/**
* Sets a post thumbnail.
*
* @since 3.1.0
*
* @param int|WP_Post $post Post ID or post object where thumbnail should be attached.
* @param int $thumbnail_id Thumbnail to attach.
* @return bool True on success, false on failure.
*/
function set_post_thumbnail( $post, $thumbnail_id ) {
$post = get_post( $post );
$thumbnail_id = absint( $thumbnail_id );
if ( $post && $thumbnail_id && get_post( $thumbnail_id ) ) {
if ( $thumbnail_html = wp_get_attachment_image( $thumbnail_id, 'thumbnail' ) )
return update_post_meta( $post->ID, '_thumbnail_id', $thumbnail_id );
else
return delete_post_meta( $post->ID, '_thumbnail_id' );
}
return false;
}
/**
* Removes a post thumbnail.
*
* @since 3.3.0
*
* @param int|WP_Post $post Post ID or post object where thumbnail should be removed from.
* @return bool True on success, false on failure.
*/
function delete_post_thumbnail( $post ) {
$post = get_post( $post );
if ( $post )
return delete_post_meta( $post->ID, '_thumbnail_id' );
return false;
}
/**
* Deletes auto-drafts for new posts that are > 7 days old
*
* @since 3.4.0
*/
function wp_delete_auto_drafts() {
global $wpdb;
// Cleanup old auto-drafts more than 7 days old
$old_posts = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_status = 'auto-draft' AND DATE_SUB( NOW(), INTERVAL 7 DAY ) > post_date" );
foreach ( (array) $old_posts as $delete )
wp_delete_post( $delete, true ); // Force delete
}
/**
* Update the custom taxonomies' term counts when a post's status is changed. For example, default posts term counts (for custom taxonomies) don't include private / draft posts.
*
* @access private
* @param string $new_status
* @param string $old_status
* @param object $post
* @since 3.3.0
*/
function _update_term_count_on_transition_post_status( $new_status, $old_status, $post ) {
// Update counts for the post's terms.
foreach ( (array) get_object_taxonomies( $post->post_type ) as $taxonomy ) {
$tt_ids = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'tt_ids' ) );
wp_update_term_count( $tt_ids, $taxonomy );
}
}
/**
* Adds any posts from the given ids to the cache that do not already exist in cache
*
* @since 3.4.0
*
* @access private
*
* @param array $post_ids ID list
* @param bool $update_term_cache Whether to update the term cache. Default is true.
* @param bool $update_meta_cache Whether to update the meta cache. Default is true.
*/
function _prime_post_caches( $ids, $update_term_cache = true, $update_meta_cache = true ) {
global $wpdb;
$non_cached_ids = _get_non_cached_ids( $ids, 'posts' );
if ( !empty( $non_cached_ids ) ) {
$fresh_posts = $wpdb->get_results( sprintf( "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE ID IN (%s)", join( ",", $non_cached_ids ) ) );
update_post_caches( $fresh_posts, 'any', $update_term_cache, $update_meta_cache );
}
}
| PHP |
<?php
/**
* BackPress Scripts enqueue.
*
* These classes were refactored from the WordPress WP_Scripts and WordPress
* script enqueue API.
*
* @package BackPress
* @since r16
*/
/**
* BackPress Scripts enqueue class.
*
* @package BackPress
* @uses WP_Dependencies
* @since r16
*/
class WP_Scripts extends WP_Dependencies {
var $base_url; // Full URL with trailing slash
var $content_url;
var $default_version;
var $in_footer = array();
var $concat = '';
var $concat_version = '';
var $do_concat = false;
var $print_html = '';
var $print_code = '';
var $ext_handles = '';
var $ext_version = '';
var $default_dirs;
function __construct() {
$this->init();
add_action( 'init', array( $this, 'init' ), 0 );
}
function init() {
/**
* Fires when the WP_Scripts instance is initialized.
*
* @since 2.6.0
*
* @param WP_Scripts &$this WP_Scripts instance, passed by reference.
*/
do_action_ref_array( 'wp_default_scripts', array(&$this) );
}
/**
* Prints scripts
*
* Prints the scripts passed to it or the print queue. Also prints all necessary dependencies.
*
* @param mixed $handles (optional) Scripts to be printed. (void) prints queue, (string) prints that script, (array of strings) prints those scripts.
* @param int $group (optional) If scripts were queued in groups prints this group number.
* @return array Scripts that have been printed
*/
function print_scripts( $handles = false, $group = false ) {
return $this->do_items( $handles, $group );
}
// Deprecated since 3.3, see print_extra_script()
function print_scripts_l10n( $handle, $echo = true ) {
_deprecated_function( __FUNCTION__, '3.3', 'print_extra_script()' );
return $this->print_extra_script( $handle, $echo );
}
function print_extra_script( $handle, $echo = true ) {
if ( !$output = $this->get_data( $handle, 'data' ) )
return;
if ( !$echo )
return $output;
echo "<script type='text/javascript'>\n"; // CDATA and type='text/javascript' is not needed for HTML 5
echo "/* <![CDATA[ */\n";
echo "$output\n";
echo "/* ]]> */\n";
echo "</script>\n";
return true;
}
function do_item( $handle, $group = false ) {
if ( !parent::do_item($handle) )
return false;
if ( 0 === $group && $this->groups[$handle] > 0 ) {
$this->in_footer[] = $handle;
return false;
}
if ( false === $group && in_array($handle, $this->in_footer, true) )
$this->in_footer = array_diff( $this->in_footer, (array) $handle );
if ( null === $this->registered[$handle]->ver )
$ver = '';
else
$ver = $this->registered[$handle]->ver ? $this->registered[$handle]->ver : $this->default_version;
if ( isset($this->args[$handle]) )
$ver = $ver ? $ver . '&' . $this->args[$handle] : $this->args[$handle];
$src = $this->registered[$handle]->src;
if ( $this->do_concat ) {
/**
* Filter the script loader source.
*
* @since 2.2.0
*
* @param string $src Script loader source path.
* @param string $handle Script handle.
*/
$srce = apply_filters( 'script_loader_src', $src, $handle );
if ( $this->in_default_dir($srce) ) {
$this->print_code .= $this->print_extra_script( $handle, false );
$this->concat .= "$handle,";
$this->concat_version .= "$handle$ver";
return true;
} else {
$this->ext_handles .= "$handle,";
$this->ext_version .= "$handle$ver";
}
}
$this->print_extra_script( $handle );
if ( !preg_match('|^(https?:)?//|', $src) && ! ( $this->content_url && 0 === strpos($src, $this->content_url) ) ) {
$src = $this->base_url . $src;
}
if ( !empty($ver) )
$src = add_query_arg('ver', $ver, $src);
/** This filter is documented in wp-includes/class.wp-scripts.php */
$src = esc_url( apply_filters( 'script_loader_src', $src, $handle ) );
if ( ! $src )
return true;
if ( $this->do_concat )
$this->print_html .= "<script type='text/javascript' src='$src'></script>\n";
else
echo "<script type='text/javascript' src='$src'></script>\n";
return true;
}
/**
* Localizes a script
*
* Localizes only if the script has already been added
*/
function localize( $handle, $object_name, $l10n ) {
if ( $handle === 'jquery' )
$handle = 'jquery-core';
if ( is_array($l10n) && isset($l10n['l10n_print_after']) ) { // back compat, preserve the code in 'l10n_print_after' if present
$after = $l10n['l10n_print_after'];
unset($l10n['l10n_print_after']);
}
foreach ( (array) $l10n as $key => $value ) {
if ( !is_scalar($value) )
continue;
$l10n[$key] = html_entity_decode( (string) $value, ENT_QUOTES, 'UTF-8');
}
$script = "var $object_name = " . json_encode($l10n) . ';';
if ( !empty($after) )
$script .= "\n$after;";
$data = $this->get_data( $handle, 'data' );
if ( !empty( $data ) )
$script = "$data\n$script";
return $this->add_data( $handle, 'data', $script );
}
function set_group( $handle, $recursion, $group = false ) {
if ( $this->registered[$handle]->args === 1 )
$grp = 1;
else
$grp = (int) $this->get_data( $handle, 'group' );
if ( false !== $group && $grp > $group )
$grp = $group;
return parent::set_group( $handle, $recursion, $grp );
}
function all_deps( $handles, $recursion = false, $group = false ) {
$r = parent::all_deps( $handles, $recursion );
if ( ! $recursion ) {
/**
* Filter the list of script dependencies left to print.
*
* @since 2.3.0
*
* @param array $to_do An array of script dependencies.
*/
$this->to_do = apply_filters( 'print_scripts_array', $this->to_do );
}
return $r;
}
function do_head_items() {
$this->do_items(false, 0);
return $this->done;
}
function do_footer_items() {
$this->do_items(false, 1);
return $this->done;
}
function in_default_dir($src) {
if ( ! $this->default_dirs )
return true;
if ( 0 === strpos( $src, '/wp-includes/js/l10n' ) )
return false;
foreach ( (array) $this->default_dirs as $test ) {
if ( 0 === strpos($src, $test) )
return true;
}
return false;
}
function reset() {
$this->do_concat = false;
$this->print_code = '';
$this->concat = '';
$this->concat_version = '';
$this->print_html = '';
$this->ext_version = '';
$this->ext_handles = '';
}
}
| PHP |
<?php
/**
* Admin Bar
*
* This code handles the building and rendering of the press bar.
*/
/**
* Instantiate the admin bar object and set it up as a global for access elsewhere.
*
* UNHOOKING THIS FUNCTION WILL NOT PROPERLY REMOVE THE ADMIN BAR.
* For that, use show_admin_bar(false) or the 'show_admin_bar' filter.
*
* @since 3.1.0
* @access private
* @return bool Whether the admin bar was successfully initialized.
*/
function _wp_admin_bar_init() {
global $wp_admin_bar;
if ( ! is_admin_bar_showing() )
return false;
/* Load the admin bar class code ready for instantiation */
require( ABSPATH . WPINC . '/class-wp-admin-bar.php' );
/* Instantiate the admin bar */
/**
* Filter the admin bar class to instantiate.
*
* @since 3.1.0
*
* @param string $wp_admin_bar_class Admin bar class to use. Default 'WP_Admin_Bar'.
*/
$admin_bar_class = apply_filters( 'wp_admin_bar_class', 'WP_Admin_Bar' );
if ( class_exists( $admin_bar_class ) )
$wp_admin_bar = new $admin_bar_class;
else
return false;
$wp_admin_bar->initialize();
$wp_admin_bar->add_menus();
return true;
}
// Don't remove. Wrong way to disable.
add_action( 'template_redirect', '_wp_admin_bar_init', 0 );
add_action( 'admin_init', '_wp_admin_bar_init' );
/**
* Render the admin bar to the page based on the $wp_admin_bar->menu member var.
* This is called very late on the footer actions so that it will render after anything else being
* added to the footer.
*
* It includes the action "admin_bar_menu" which should be used to hook in and
* add new menus to the admin bar. That way you can be sure that you are adding at most optimal point,
* right before the admin bar is rendered. This also gives you access to the $post global, among others.
*
* @since 3.1.0
*/
function wp_admin_bar_render() {
global $wp_admin_bar;
if ( ! is_admin_bar_showing() || ! is_object( $wp_admin_bar ) )
return false;
/**
* Load all necessary admin bar items.
*
* This is the hook used to add, remove, or manipulate admin bar items.
*
* @since 3.1.0
*
* @param WP_Admin_Bar $wp_admin_bar WP_Admin_Bar instance, passed by reference
*/
do_action_ref_array( 'admin_bar_menu', array( &$wp_admin_bar ) );
/**
* Fires before the admin bar is rendered.
*
* @since 3.1.0
*/
do_action( 'wp_before_admin_bar_render' );
$wp_admin_bar->render();
/**
* Fires after the admin bar is rendered.
*
* @since 3.1.0
*/
do_action( 'wp_after_admin_bar_render' );
}
add_action( 'wp_footer', 'wp_admin_bar_render', 1000 );
add_action( 'in_admin_header', 'wp_admin_bar_render', 0 );
/**
* Add the WordPress logo menu.
*
* @since 3.3.0
*
* @param WP_Admin_Bar $wp_admin_bar
*/
function wp_admin_bar_wp_menu( $wp_admin_bar ) {
$wp_admin_bar->add_menu( array(
'id' => 'wp-logo',
'title' => '<span class="ab-icon"></span>',
'href' => self_admin_url( 'about.php' ),
'meta' => array(
'title' => __('About WordPress'),
),
) );
if ( is_user_logged_in() ) {
// Add "About WordPress" link
$wp_admin_bar->add_menu( array(
'parent' => 'wp-logo',
'id' => 'about',
'title' => __('About WordPress'),
'href' => self_admin_url( 'about.php' ),
) );
}
// Add WordPress.org link
$wp_admin_bar->add_menu( array(
'parent' => 'wp-logo-external',
'id' => 'wporg',
'title' => __('WordPress.org'),
'href' => __('https://wordpress.org/'),
) );
// Add codex link
$wp_admin_bar->add_menu( array(
'parent' => 'wp-logo-external',
'id' => 'documentation',
'title' => __('Documentation'),
'href' => __('http://codex.wordpress.org/'),
) );
// Add forums link
$wp_admin_bar->add_menu( array(
'parent' => 'wp-logo-external',
'id' => 'support-forums',
'title' => __('Support Forums'),
'href' => __('https://wordpress.org/support/'),
) );
// Add feedback link
$wp_admin_bar->add_menu( array(
'parent' => 'wp-logo-external',
'id' => 'feedback',
'title' => __('Feedback'),
'href' => __('https://wordpress.org/support/forum/requests-and-feedback'),
) );
}
/**
* Add the sidebar toggle button.
*
* @since 3.8.0
*
* @param WP_Admin_Bar $wp_admin_bar
*/
function wp_admin_bar_sidebar_toggle( $wp_admin_bar ) {
if ( is_admin() ) {
$wp_admin_bar->add_menu( array(
'id' => 'menu-toggle',
'title' => '<span class="ab-icon"></span><span class="screen-reader-text">' . __( 'Menu' ) . '</span>',
'href' => '#',
) );
}
}
/**
* Add the "My Account" item.
*
* @since 3.3.0
*
* @param WP_Admin_Bar $wp_admin_bar
*/
function wp_admin_bar_my_account_item( $wp_admin_bar ) {
$user_id = get_current_user_id();
$current_user = wp_get_current_user();
$profile_url = get_edit_profile_url( $user_id );
if ( ! $user_id )
return;
$avatar = get_avatar( $user_id, 26 );
$howdy = sprintf( __('Howdy, %1$s'), $current_user->display_name );
$class = empty( $avatar ) ? '' : 'with-avatar';
$wp_admin_bar->add_menu( array(
'id' => 'my-account',
'parent' => 'top-secondary',
'title' => $howdy . $avatar,
'href' => $profile_url,
'meta' => array(
'class' => $class,
'title' => __('My Account'),
),
) );
}
/**
* Add the "My Account" submenu items.
*
* @since 3.1.0
*
* @param WP_Admin_Bar $wp_admin_bar
*/
function wp_admin_bar_my_account_menu( $wp_admin_bar ) {
$user_id = get_current_user_id();
$current_user = wp_get_current_user();
$profile_url = get_edit_profile_url( $user_id );
if ( ! $user_id )
return;
$wp_admin_bar->add_group( array(
'parent' => 'my-account',
'id' => 'user-actions',
) );
$user_info = get_avatar( $user_id, 64 );
$user_info .= "<span class='display-name'>{$current_user->display_name}</span>";
if ( $current_user->display_name !== $current_user->user_login )
$user_info .= "<span class='username'>{$current_user->user_login}</span>";
$wp_admin_bar->add_menu( array(
'parent' => 'user-actions',
'id' => 'user-info',
'title' => $user_info,
'href' => $profile_url,
'meta' => array(
'tabindex' => -1,
),
) );
$wp_admin_bar->add_menu( array(
'parent' => 'user-actions',
'id' => 'edit-profile',
'title' => __( 'Edit My Profile' ),
'href' => $profile_url,
) );
$wp_admin_bar->add_menu( array(
'parent' => 'user-actions',
'id' => 'logout',
'title' => __( 'Log Out' ),
'href' => wp_logout_url(),
) );
}
/**
* Add the "Site Name" menu.
*
* @since 3.3.0
*
* @param WP_Admin_Bar $wp_admin_bar
*/
function wp_admin_bar_site_menu( $wp_admin_bar ) {
// Don't show for logged out users.
if ( ! is_user_logged_in() )
return;
// Show only when the user is a member of this site, or they're a super admin.
if ( ! is_user_member_of_blog() && ! is_super_admin() )
return;
$blogname = get_bloginfo('name');
if ( empty( $blogname ) )
$blogname = preg_replace( '#^(https?://)?(www.)?#', '', get_home_url() );
if ( is_network_admin() ) {
$blogname = sprintf( __('Network Admin: %s'), esc_html( get_current_site()->site_name ) );
} elseif ( is_user_admin() ) {
$blogname = sprintf( __('Global Dashboard: %s'), esc_html( get_current_site()->site_name ) );
}
$title = wp_html_excerpt( $blogname, 40, '…' );
$wp_admin_bar->add_menu( array(
'id' => 'site-name',
'title' => $title,
'href' => is_admin() ? home_url( '/' ) : admin_url(),
) );
// Create submenu items.
if ( is_admin() ) {
// Add an option to visit the site.
$wp_admin_bar->add_menu( array(
'parent' => 'site-name',
'id' => 'view-site',
'title' => __( 'Visit Site' ),
'href' => home_url( '/' ),
) );
if ( is_blog_admin() && is_multisite() && current_user_can( 'manage_sites' ) ) {
$wp_admin_bar->add_menu( array(
'parent' => 'site-name',
'id' => 'edit-site',
'title' => __( 'Edit Site' ),
'href' => network_admin_url( 'site-info.php?id=' . get_current_blog_id() ),
) );
}
} else {
// We're on the front end, link to the Dashboard.
$wp_admin_bar->add_menu( array(
'parent' => 'site-name',
'id' => 'dashboard',
'title' => __( 'Dashboard' ),
'href' => admin_url(),
) );
// Add the appearance submenu items.
wp_admin_bar_appearance_menu( $wp_admin_bar );
}
}
/**
* Add the "My Sites/[Site Name]" menu and all submenus.
*
* @since 3.1.0
*
* @param WP_Admin_Bar $wp_admin_bar
*/
function wp_admin_bar_my_sites_menu( $wp_admin_bar ) {
// Don't show for logged out users or single site mode.
if ( ! is_user_logged_in() || ! is_multisite() )
return;
// Show only when the user has at least one site, or they're a super admin.
if ( count( $wp_admin_bar->user->blogs ) < 1 && ! is_super_admin() )
return;
$wp_admin_bar->add_menu( array(
'id' => 'my-sites',
'title' => __( 'My Sites' ),
'href' => admin_url( 'my-sites.php' ),
) );
if ( is_super_admin() ) {
$wp_admin_bar->add_group( array(
'parent' => 'my-sites',
'id' => 'my-sites-super-admin',
) );
$wp_admin_bar->add_menu( array(
'parent' => 'my-sites-super-admin',
'id' => 'network-admin',
'title' => __('Network Admin'),
'href' => network_admin_url(),
) );
$wp_admin_bar->add_menu( array(
'parent' => 'network-admin',
'id' => 'network-admin-d',
'title' => __( 'Dashboard' ),
'href' => network_admin_url(),
) );
$wp_admin_bar->add_menu( array(
'parent' => 'network-admin',
'id' => 'network-admin-s',
'title' => __( 'Sites' ),
'href' => network_admin_url( 'sites.php' ),
) );
$wp_admin_bar->add_menu( array(
'parent' => 'network-admin',
'id' => 'network-admin-u',
'title' => __( 'Users' ),
'href' => network_admin_url( 'users.php' ),
) );
$wp_admin_bar->add_menu( array(
'parent' => 'network-admin',
'id' => 'network-admin-t',
'title' => __( 'Themes' ),
'href' => network_admin_url( 'themes.php' ),
) );
$wp_admin_bar->add_menu( array(
'parent' => 'network-admin',
'id' => 'network-admin-p',
'title' => __( 'Plugins' ),
'href' => network_admin_url( 'plugins.php' ),
) );
}
// Add site links
$wp_admin_bar->add_group( array(
'parent' => 'my-sites',
'id' => 'my-sites-list',
'meta' => array(
'class' => is_super_admin() ? 'ab-sub-secondary' : '',
),
) );
foreach ( (array) $wp_admin_bar->user->blogs as $blog ) {
switch_to_blog( $blog->userblog_id );
$blavatar = '<div class="blavatar"></div>';
$blogname = empty( $blog->blogname ) ? $blog->domain : $blog->blogname;
$menu_id = 'blog-' . $blog->userblog_id;
$wp_admin_bar->add_menu( array(
'parent' => 'my-sites-list',
'id' => $menu_id,
'title' => $blavatar . $blogname,
'href' => admin_url(),
) );
$wp_admin_bar->add_menu( array(
'parent' => $menu_id,
'id' => $menu_id . '-d',
'title' => __( 'Dashboard' ),
'href' => admin_url(),
) );
if ( current_user_can( get_post_type_object( 'post' )->cap->create_posts ) ) {
$wp_admin_bar->add_menu( array(
'parent' => $menu_id,
'id' => $menu_id . '-n',
'title' => __( 'New Post' ),
'href' => admin_url( 'post-new.php' ),
) );
}
if ( current_user_can( 'edit_posts' ) ) {
$wp_admin_bar->add_menu( array(
'parent' => $menu_id,
'id' => $menu_id . '-c',
'title' => __( 'Manage Comments' ),
'href' => admin_url( 'edit-comments.php' ),
) );
}
$wp_admin_bar->add_menu( array(
'parent' => $menu_id,
'id' => $menu_id . '-v',
'title' => __( 'Visit Site' ),
'href' => home_url( '/' ),
) );
restore_current_blog();
}
}
/**
* Provide a shortlink.
*
* @since 3.1.0
*
* @param WP_Admin_Bar $wp_admin_bar
*/
function wp_admin_bar_shortlink_menu( $wp_admin_bar ) {
$short = wp_get_shortlink( 0, 'query' );
$id = 'get-shortlink';
if ( empty( $short ) )
return;
$html = '<input class="shortlink-input" type="text" readonly="readonly" value="' . esc_attr( $short ) . '" />';
$wp_admin_bar->add_menu( array(
'id' => $id,
'title' => __( 'Shortlink' ),
'href' => $short,
'meta' => array( 'html' => $html ),
) );
}
/**
* Provide an edit link for posts and terms.
*
* @since 3.1.0
*
* @param WP_Admin_Bar $wp_admin_bar
*/
function wp_admin_bar_edit_menu( $wp_admin_bar ) {
global $tag, $wp_the_query;
if ( is_admin() ) {
$current_screen = get_current_screen();
$post = get_post();
if ( 'post' == $current_screen->base
&& 'add' != $current_screen->action
&& ( $post_type_object = get_post_type_object( $post->post_type ) )
&& current_user_can( 'read_post', $post->ID )
&& ( $post_type_object->public )
&& ( $post_type_object->show_in_admin_bar ) )
{
$wp_admin_bar->add_menu( array(
'id' => 'view',
'title' => $post_type_object->labels->view_item,
'href' => get_permalink( $post->ID )
) );
} elseif ( 'edit-tags' == $current_screen->base
&& isset( $tag ) && is_object( $tag )
&& ( $tax = get_taxonomy( $tag->taxonomy ) )
&& $tax->public )
{
$wp_admin_bar->add_menu( array(
'id' => 'view',
'title' => $tax->labels->view_item,
'href' => get_term_link( $tag )
) );
}
} else {
$current_object = $wp_the_query->get_queried_object();
if ( empty( $current_object ) )
return;
if ( ! empty( $current_object->post_type )
&& ( $post_type_object = get_post_type_object( $current_object->post_type ) )
&& current_user_can( 'edit_post', $current_object->ID )
&& $post_type_object->show_ui && $post_type_object->show_in_admin_bar )
{
$wp_admin_bar->add_menu( array(
'id' => 'edit',
'title' => $post_type_object->labels->edit_item,
'href' => get_edit_post_link( $current_object->ID )
) );
} elseif ( ! empty( $current_object->taxonomy )
&& ( $tax = get_taxonomy( $current_object->taxonomy ) )
&& current_user_can( $tax->cap->edit_terms )
&& $tax->show_ui )
{
$wp_admin_bar->add_menu( array(
'id' => 'edit',
'title' => $tax->labels->edit_item,
'href' => get_edit_term_link( $current_object->term_id, $current_object->taxonomy )
) );
}
}
}
/**
* Add "Add New" menu.
*
* @since 3.1.0
*
* @param WP_Admin_Bar $wp_admin_bar
*/
function wp_admin_bar_new_content_menu( $wp_admin_bar ) {
$actions = array();
$cpts = (array) get_post_types( array( 'show_in_admin_bar' => true ), 'objects' );
if ( isset( $cpts['post'] ) && current_user_can( $cpts['post']->cap->create_posts ) )
$actions[ 'post-new.php' ] = array( $cpts['post']->labels->name_admin_bar, 'new-post' );
if ( isset( $cpts['attachment'] ) && current_user_can( 'upload_files' ) )
$actions[ 'media-new.php' ] = array( $cpts['attachment']->labels->name_admin_bar, 'new-media' );
if ( current_user_can( 'manage_links' ) )
$actions[ 'link-add.php' ] = array( _x( 'Link', 'add new from admin bar' ), 'new-link' );
if ( isset( $cpts['page'] ) && current_user_can( $cpts['page']->cap->create_posts ) )
$actions[ 'post-new.php?post_type=page' ] = array( $cpts['page']->labels->name_admin_bar, 'new-page' );
unset( $cpts['post'], $cpts['page'], $cpts['attachment'] );
// Add any additional custom post types.
foreach ( $cpts as $cpt ) {
if ( ! current_user_can( $cpt->cap->create_posts ) )
continue;
$key = 'post-new.php?post_type=' . $cpt->name;
$actions[ $key ] = array( $cpt->labels->name_admin_bar, 'new-' . $cpt->name );
}
// Avoid clash with parent node and a 'content' post type.
if ( isset( $actions['post-new.php?post_type=content'] ) )
$actions['post-new.php?post_type=content'][1] = 'add-new-content';
if ( current_user_can( 'create_users' ) || current_user_can( 'promote_users' ) )
$actions[ 'user-new.php' ] = array( _x( 'User', 'add new from admin bar' ), 'new-user' );
if ( ! $actions )
return;
$title = '<span class="ab-icon"></span><span class="ab-label">' . _x( 'New', 'admin bar menu group label' ) . '</span>';
$wp_admin_bar->add_menu( array(
'id' => 'new-content',
'title' => $title,
'href' => admin_url( current( array_keys( $actions ) ) ),
'meta' => array(
'title' => _x( 'Add New', 'admin bar menu group label' ),
),
) );
foreach ( $actions as $link => $action ) {
list( $title, $id ) = $action;
$wp_admin_bar->add_menu( array(
'parent' => 'new-content',
'id' => $id,
'title' => $title,
'href' => admin_url( $link )
) );
}
}
/**
* Add edit comments link with awaiting moderation count bubble.
*
* @since 3.1.0
*
* @param WP_Admin_Bar $wp_admin_bar
*/
function wp_admin_bar_comments_menu( $wp_admin_bar ) {
if ( !current_user_can('edit_posts') )
return;
$awaiting_mod = wp_count_comments();
$awaiting_mod = $awaiting_mod->moderated;
$awaiting_title = esc_attr( sprintf( _n( '%s comment awaiting moderation', '%s comments awaiting moderation', $awaiting_mod ), number_format_i18n( $awaiting_mod ) ) );
$icon = '<span class="ab-icon"></span>';
$title = '<span id="ab-awaiting-mod" class="ab-label awaiting-mod pending-count count-' . $awaiting_mod . '">' . number_format_i18n( $awaiting_mod ) . '</span>';
$wp_admin_bar->add_menu( array(
'id' => 'comments',
'title' => $icon . $title,
'href' => admin_url('edit-comments.php'),
'meta' => array( 'title' => $awaiting_title ),
) );
}
/**
* Add appearance submenu items to the "Site Name" menu.
*
* @since 3.1.0
*
* @param WP_Admin_Bar $wp_admin_bar
*/
function wp_admin_bar_appearance_menu( $wp_admin_bar ) {
$wp_admin_bar->add_group( array( 'parent' => 'site-name', 'id' => 'appearance' ) );
if ( current_user_can( 'switch_themes' ) || current_user_can( 'edit_theme_options' ) )
$wp_admin_bar->add_menu( array( 'parent' => 'appearance', 'id' => 'themes', 'title' => __('Themes'), 'href' => admin_url('themes.php') ) );
if ( ! current_user_can( 'edit_theme_options' ) )
return;
$current_url = ( is_ssl() ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$wp_admin_bar->add_menu( array(
'parent' => 'appearance',
'id' => 'customize',
'title' => __('Customize'),
'href' => add_query_arg( 'url', urlencode( $current_url ), wp_customize_url() ),
'meta' => array(
'class' => 'hide-if-no-customize',
),
) );
add_action( 'wp_before_admin_bar_render', 'wp_customize_support_script' );
if ( current_theme_supports( 'widgets' ) )
$wp_admin_bar->add_menu( array( 'parent' => 'appearance', 'id' => 'widgets', 'title' => __('Widgets'), 'href' => admin_url('widgets.php') ) );
if ( current_theme_supports( 'menus' ) || current_theme_supports( 'widgets' ) )
$wp_admin_bar->add_menu( array( 'parent' => 'appearance', 'id' => 'menus', 'title' => __('Menus'), 'href' => admin_url('nav-menus.php') ) );
if ( current_theme_supports( 'custom-background' ) )
$wp_admin_bar->add_menu( array( 'parent' => 'appearance', 'id' => 'background', 'title' => __('Background'), 'href' => admin_url('themes.php?page=custom-background') ) );
if ( current_theme_supports( 'custom-header' ) )
$wp_admin_bar->add_menu( array( 'parent' => 'appearance', 'id' => 'header', 'title' => __('Header'), 'href' => admin_url('themes.php?page=custom-header') ) );
}
/**
* Provide an update link if theme/plugin/core updates are available.
*
* @since 3.1.0
*
* @param WP_Admin_Bar $wp_admin_bar
*/
function wp_admin_bar_updates_menu( $wp_admin_bar ) {
$update_data = wp_get_update_data();
if ( !$update_data['counts']['total'] )
return;
$title = '<span class="ab-icon"></span><span class="ab-label">' . number_format_i18n( $update_data['counts']['total'] ) . '</span>';
$title .= '<span class="screen-reader-text">' . $update_data['title'] . '</span>';
$wp_admin_bar->add_menu( array(
'id' => 'updates',
'title' => $title,
'href' => network_admin_url( 'update-core.php' ),
'meta' => array(
'title' => $update_data['title'],
),
) );
}
/**
* Add search form.
*
* @since 3.3.0
*
* @param WP_Admin_Bar $wp_admin_bar
*/
function wp_admin_bar_search_menu( $wp_admin_bar ) {
if ( is_admin() )
return;
$form = '<form action="' . esc_url( home_url( '/' ) ) . '" method="get" id="adminbarsearch">';
$form .= '<input class="adminbar-input" name="s" id="adminbar-search" type="text" value="" maxlength="150" />';
$form .= '<input type="submit" class="adminbar-button" value="' . __('Search') . '"/>';
$form .= '</form>';
$wp_admin_bar->add_menu( array(
'parent' => 'top-secondary',
'id' => 'search',
'title' => $form,
'meta' => array(
'class' => 'admin-bar-search',
'tabindex' => -1,
)
) );
}
/**
* Add secondary menus.
*
* @since 3.3.0
*
* @param WP_Admin_Bar $wp_admin_bar
*/
function wp_admin_bar_add_secondary_groups( $wp_admin_bar ) {
$wp_admin_bar->add_group( array(
'id' => 'top-secondary',
'meta' => array(
'class' => 'ab-top-secondary',
),
) );
$wp_admin_bar->add_group( array(
'parent' => 'wp-logo',
'id' => 'wp-logo-external',
'meta' => array(
'class' => 'ab-sub-secondary',
),
) );
}
/**
* Style and scripts for the admin bar.
*
* @since 3.1.0
*/
function wp_admin_bar_header() { ?>
<style type="text/css" media="print">#wpadminbar { display:none; }</style>
<?php
}
/**
* Default admin bar callback.
*
* @since 3.1.0
*/
function _admin_bar_bump_cb() { ?>
<style type="text/css" media="screen">
html { margin-top: 32px !important; }
* html body { margin-top: 32px !important; }
@media screen and ( max-width: 782px ) {
html { margin-top: 46px !important; }
* html body { margin-top: 46px !important; }
}
</style>
<?php
}
/**
* Set the display status of the admin bar.
*
* This can be called immediately upon plugin load. It does not need to be called from a function hooked to the init action.
*
* @since 3.1.0
*
* @param bool $show Whether to allow the admin bar to show.
* @return void
*/
function show_admin_bar( $show ) {
global $show_admin_bar;
$show_admin_bar = (bool) $show;
}
/**
* Determine whether the admin bar should be showing.
*
* @since 3.1.0
*
* @return bool Whether the admin bar should be showing.
*/
function is_admin_bar_showing() {
global $show_admin_bar, $pagenow;
// For all these types of requests, we never want an admin bar.
if ( defined('XMLRPC_REQUEST') || defined('DOING_AJAX') || defined('IFRAME_REQUEST') )
return false;
// Integrated into the admin.
if ( is_admin() )
return true;
if ( ! isset( $show_admin_bar ) ) {
if ( ! is_user_logged_in() || 'wp-login.php' == $pagenow ) {
$show_admin_bar = false;
} else {
$show_admin_bar = _get_admin_bar_pref();
}
}
/**
* Filter whether to show the admin bar.
*
* Returning false to this hook is the recommended way to hide the admin bar.
* The user's display preference is used for logged in users.
*
* @since 3.1.0
*
* @param bool $show_admin_bar Whether the admin bar should be shown. Default false.
*/
$show_admin_bar = apply_filters( 'show_admin_bar', $show_admin_bar );
return $show_admin_bar;
}
/**
* Retrieve the admin bar display preference of a user.
*
* @since 3.1.0
* @access private
*
* @param string $context Context of this preference check. Defaults to 'front'. The 'admin'
* preference is no longer used.
* @param int $user Optional. ID of the user to check, defaults to 0 for current user.
* @return bool Whether the admin bar should be showing for this user.
*/
function _get_admin_bar_pref( $context = 'front', $user = 0 ) {
$pref = get_user_option( "show_admin_bar_{$context}", $user );
if ( false === $pref )
return true;
return 'true' === $pref;
}
| PHP |
<?php
/**
* WordPress Category API
*
* @package WordPress
*/
/**
* Retrieves all category IDs.
*
* @since 2.0.0
* @link http://codex.wordpress.org/Function_Reference/get_all_category_ids
*
* @return object List of all of the category IDs.
*/
function get_all_category_ids() {
if ( ! $cat_ids = wp_cache_get( 'all_category_ids', 'category' ) ) {
$cat_ids = get_terms( 'category', array('fields' => 'ids', 'get' => 'all') );
wp_cache_add( 'all_category_ids', $cat_ids, 'category' );
}
return $cat_ids;
}
/**
* Retrieve list of category objects.
*
* If you change the type to 'link' in the arguments, then the link categories
* will be returned instead. Also all categories will be updated to be backwards
* compatible with pre-2.3 plugins and themes.
*
* @since 2.1.0
* @see get_terms() Type of arguments that can be changed.
* @link http://codex.wordpress.org/Function_Reference/get_categories
*
* @param string|array $args Optional. Change the defaults retrieving categories.
* @return array List of categories.
*/
function get_categories( $args = '' ) {
$defaults = array( 'taxonomy' => 'category' );
$args = wp_parse_args( $args, $defaults );
$taxonomy = $args['taxonomy'];
/**
* Filter the taxonomy used to retrieve terms when calling get_categories().
*
* @since 2.7.0
*
* @param string $taxonomy Taxonomy to retrieve terms from.
* @param array $args An array of arguments. @see get_terms()
*/
$taxonomy = apply_filters( 'get_categories_taxonomy', $taxonomy, $args );
// Back compat
if ( isset($args['type']) && 'link' == $args['type'] ) {
_deprecated_argument( __FUNCTION__, '3.0', '' );
$taxonomy = $args['taxonomy'] = 'link_category';
}
$categories = (array) get_terms( $taxonomy, $args );
foreach ( array_keys( $categories ) as $k )
_make_cat_compat( $categories[$k] );
return $categories;
}
/**
* Retrieves category data given a category ID or category object.
*
* If you pass the $category parameter an object, which is assumed to be the
* category row object retrieved the database. It will cache the category data.
*
* If you pass $category an integer of the category ID, then that category will
* be retrieved from the database, if it isn't already cached, and pass it back.
*
* If you look at get_term(), then both types will be passed through several
* filters and finally sanitized based on the $filter parameter value.
*
* The category will converted to maintain backwards compatibility.
*
* @since 1.5.1
* @uses get_term() Used to get the category data from the taxonomy.
*
* @param int|object $category Category ID or Category row object
* @param string $output Optional. Constant OBJECT, ARRAY_A, or ARRAY_N
* @param string $filter Optional. Default is raw or no WordPress defined filter will applied.
* @return object|array|WP_Error|null Category data in type defined by $output parameter. WP_Error if $category is empty, null if it does not exist.
*/
function get_category( $category, $output = OBJECT, $filter = 'raw' ) {
$category = get_term( $category, 'category', $output, $filter );
if ( is_wp_error( $category ) )
return $category;
_make_cat_compat( $category );
return $category;
}
/**
* Retrieve category based on URL containing the category slug.
*
* Breaks the $category_path parameter up to get the category slug.
*
* Tries to find the child path and will return it. If it doesn't find a
* match, then it will return the first category matching slug, if $full_match,
* is set to false. If it does not, then it will return null.
*
* It is also possible that it will return a WP_Error object on failure. Check
* for it when using this function.
*
* @since 2.1.0
*
* @param string $category_path URL containing category slugs.
* @param bool $full_match Optional. Whether full path should be matched.
* @param string $output Optional. Constant OBJECT, ARRAY_A, or ARRAY_N
* @return null|object|array Null on failure. Type is based on $output value.
*/
function get_category_by_path( $category_path, $full_match = true, $output = OBJECT ) {
$category_path = rawurlencode( urldecode( $category_path ) );
$category_path = str_replace( '%2F', '/', $category_path );
$category_path = str_replace( '%20', ' ', $category_path );
$category_paths = '/' . trim( $category_path, '/' );
$leaf_path = sanitize_title( basename( $category_paths ) );
$category_paths = explode( '/', $category_paths );
$full_path = '';
foreach ( (array) $category_paths as $pathdir )
$full_path .= ( $pathdir != '' ? '/' : '' ) . sanitize_title( $pathdir );
$categories = get_terms( 'category', array('get' => 'all', 'slug' => $leaf_path) );
if ( empty( $categories ) )
return null;
foreach ( $categories as $category ) {
$path = '/' . $leaf_path;
$curcategory = $category;
while ( ( $curcategory->parent != 0 ) && ( $curcategory->parent != $curcategory->term_id ) ) {
$curcategory = get_term( $curcategory->parent, 'category' );
if ( is_wp_error( $curcategory ) )
return $curcategory;
$path = '/' . $curcategory->slug . $path;
}
if ( $path == $full_path ) {
$category = get_term( $category->term_id, 'category', $output );
_make_cat_compat( $category );
return $category;
}
}
// If full matching is not required, return the first cat that matches the leaf.
if ( ! $full_match ) {
$category = get_term( reset( $categories )->term_id, 'category', $output );
_make_cat_compat( $category );
return $category;
}
return null;
}
/**
* Retrieve category object by category slug.
*
* @since 2.3.0
*
* @param string $slug The category slug.
* @return object Category data object
*/
function get_category_by_slug( $slug ) {
$category = get_term_by( 'slug', $slug, 'category' );
if ( $category )
_make_cat_compat( $category );
return $category;
}
/**
* Retrieve the ID of a category from its name.
*
* @since 1.0.0
*
* @param string $cat_name Category name.
* @return int 0, if failure and ID of category on success.
*/
function get_cat_ID( $cat_name ) {
$cat = get_term_by( 'name', $cat_name, 'category' );
if ( $cat )
return $cat->term_id;
return 0;
}
/**
* Retrieve the name of a category from its ID.
*
* @since 1.0.0
*
* @param int $cat_id Category ID
* @return string Category name, or an empty string if category doesn't exist.
*/
function get_cat_name( $cat_id ) {
$cat_id = (int) $cat_id;
$category = get_term( $cat_id, 'category' );
if ( ! $category || is_wp_error( $category ) )
return '';
return $category->name;
}
/**
* Check if a category is an ancestor of another category.
*
* You can use either an id or the category object for both parameters. If you
* use an integer the category will be retrieved.
*
* @since 2.1.0
*
* @param int|object $cat1 ID or object to check if this is the parent category.
* @param int|object $cat2 The child category.
* @return bool Whether $cat2 is child of $cat1
*/
function cat_is_ancestor_of( $cat1, $cat2 ) {
return term_is_ancestor_of( $cat1, $cat2, 'category' );
}
/**
* Sanitizes category data based on context.
*
* @since 2.3.0
* @uses sanitize_term() See this function for what context are supported.
*
* @param object|array $category Category data
* @param string $context Optional. Default is 'display'.
* @return object|array Same type as $category with sanitized data for safe use.
*/
function sanitize_category( $category, $context = 'display' ) {
return sanitize_term( $category, 'category', $context );
}
/**
* Sanitizes data in single category key field.
*
* @since 2.3.0
* @uses sanitize_term_field() See function for more details.
*
* @param string $field Category key to sanitize
* @param mixed $value Category value to sanitize
* @param int $cat_id Category ID
* @param string $context What filter to use, 'raw', 'display', etc.
* @return mixed Same type as $value after $value has been sanitized.
*/
function sanitize_category_field( $field, $value, $cat_id, $context ) {
return sanitize_term_field( $field, $value, $cat_id, 'category', $context );
}
/* Tags */
/**
* Retrieves all post tags.
*
* @since 2.3.0
* @see get_terms() For list of arguments to pass.
* @uses apply_filters() Calls 'get_tags' hook on array of tags and with $args.
*
* @param string|array $args Tag arguments to use when retrieving tags.
* @return array List of tags.
*/
function get_tags( $args = '' ) {
$tags = get_terms( 'post_tag', $args );
if ( empty( $tags ) ) {
$return = array();
return $return;
}
/**
* Filter the array of term objects returned for the 'post_tag' taxonomy.
*
* @since 2.3.0
*
* @param array $tags Array of 'post_tag' term objects.
* @param array $args An array of arguments. @see get_terms()
*/
$tags = apply_filters( 'get_tags', $tags, $args );
return $tags;
}
/**
* Retrieve post tag by tag ID or tag object.
*
* If you pass the $tag parameter an object, which is assumed to be the tag row
* object retrieved the database. It will cache the tag data.
*
* If you pass $tag an integer of the tag ID, then that tag will
* be retrieved from the database, if it isn't already cached, and pass it back.
*
* If you look at get_term(), then both types will be passed through several
* filters and finally sanitized based on the $filter parameter value.
*
* @since 2.3.0
*
* @param int|object $tag
* @param string $output Optional. Constant OBJECT, ARRAY_A, or ARRAY_N
* @param string $filter Optional. Default is raw or no WordPress defined filter will applied.
* @return object|array|WP_Error|null Tag data in type defined by $output parameter. WP_Error if $tag is empty, null if it does not exist.
*/
function get_tag( $tag, $output = OBJECT, $filter = 'raw' ) {
return get_term( $tag, 'post_tag', $output, $filter );
}
/* Cache */
/**
* Remove the category cache data based on ID.
*
* @since 2.1.0
* @uses clean_term_cache() Clears the cache for the category based on ID
*
* @param int $id Category ID
*/
function clean_category_cache( $id ) {
clean_term_cache( $id, 'category' );
}
/**
* Update category structure to old pre 2.3 from new taxonomy structure.
*
* This function was added for the taxonomy support to update the new category
* structure with the old category one. This will maintain compatibility with
* plugins and themes which depend on the old key or property names.
*
* The parameter should only be passed a variable and not create the array or
* object inline to the parameter. The reason for this is that parameter is
* passed by reference and PHP will fail unless it has the variable.
*
* There is no return value, because everything is updated on the variable you
* pass to it. This is one of the features with using pass by reference in PHP.
*
* @since 2.3.0
* @access private
*
* @param array|object $category Category Row object or array
*/
function _make_cat_compat( &$category ) {
if ( is_object( $category ) ) {
$category->cat_ID = &$category->term_id;
$category->category_count = &$category->count;
$category->category_description = &$category->description;
$category->cat_name = &$category->name;
$category->category_nicename = &$category->slug;
$category->category_parent = &$category->parent;
} elseif ( is_array( $category ) && isset( $category['term_id'] ) ) {
$category['cat_ID'] = &$category['term_id'];
$category['category_count'] = &$category['count'];
$category['category_description'] = &$category['description'];
$category['cat_name'] = &$category['name'];
$category['category_nicename'] = &$category['slug'];
$category['category_parent'] = &$category['parent'];
}
}
| PHP |
<?php
/**
* Simple and uniform HTTP request API.
*
* Standardizes the HTTP requests for WordPress. Handles cookies, gzip encoding and decoding, chunk
* decoding, if HTTP 1.1 and various other difficult HTTP protocol implementations.
*
* @link http://trac.wordpress.org/ticket/4779 HTTP API Proposal
*
* @package WordPress
* @subpackage HTTP
* @since 2.7.0
*/
/**
* WordPress HTTP Class for managing HTTP Transports and making HTTP requests.
*
* This class is used to consistently make outgoing HTTP requests easy for developers
* while still being compatible with the many PHP configurations under which
* WordPress runs.
*
* Debugging includes several actions, which pass different variables for debugging the HTTP API.
*
* @package WordPress
* @subpackage HTTP
* @since 2.7.0
*/
class WP_Http {
/**
* Send a HTTP request to a URI.
*
* The body and headers are part of the arguments. The 'body' argument is for the body and will
* accept either a string or an array. The 'headers' argument should be an array, but a string
* is acceptable. If the 'body' argument is an array, then it will automatically be escaped
* using http_build_query().
*
* The only URI that are supported in the HTTP Transport implementation are the HTTP and HTTPS
* protocols.
*
* The defaults are 'method', 'timeout', 'redirection', 'httpversion', 'blocking' and
* 'user-agent'.
*
* Accepted 'method' values are 'GET', 'POST', and 'HEAD', some transports technically allow
* others, but should not be assumed. The 'timeout' is used to sent how long the connection
* should stay open before failing when no response. 'redirection' is used to track how many
* redirects were taken and used to sent the amount for other transports, but not all transports
* accept setting that value.
*
* The 'httpversion' option is used to sent the HTTP version and accepted values are '1.0', and
* '1.1' and should be a string. The 'user-agent' option is the user-agent and is used to
* replace the default user-agent, which is 'WordPress/WP_Version', where WP_Version is the
* value from $wp_version.
*
* The 'blocking' parameter can be used to specify if the calling code requires the result of
* the HTTP request. If set to false, the request will be sent to the remote server, and
* processing returned to the calling code immediately, the caller will know if the request
* suceeded or failed, but will not receive any response from the remote server.
*
* @access public
* @since 2.7.0
*
* @param string $url URI resource.
* @param str|array $args Optional. Override the defaults.
* @return array|object Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
*/
function request( $url, $args = array() ) {
global $wp_version;
$defaults = array(
'method' => 'GET',
/**
* Filter the timeout value for an HTTP request.
*
* @since 2.7.0
*
* @param int $timeout_value Time in seconds until a request times out.
* Default 5.
*/
'timeout' => apply_filters( 'http_request_timeout', 5 ),
/**
* Filter the number of redirects allowed during an HTTP request.
*
* @since 2.7.0
*
* @param int $redirect_count Number of redirects allowed. Default 5.
*/
'redirection' => apply_filters( 'http_request_redirection_count', 5 ),
/**
* Filter the version of the HTTP protocol used in a request.
*
* @since 2.7.0
*
* @param string $version Version of HTTP used. Accepts '1.0' and '1.1'.
* Default '1.0'.
*/
'httpversion' => apply_filters( 'http_request_version', '1.0' ),
/**
* Filter the user agent value sent with an HTTP request.
*
* @since 2.7.0
*
* @param string $user_agent WordPress user agent string.
*/
'user-agent' => apply_filters( 'http_headers_useragent', 'WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' ) ),
/**
* Filter whether to pass URLs through wp_http_validate_url() in an HTTP request.
*
* @since 3.6.0
*
* @param bool $pass_url Whether to pass URLs through wp_http_validate_url().
* Default false.
*/
'reject_unsafe_urls' => apply_filters( 'http_request_reject_unsafe_urls', false ),
'blocking' => true,
'headers' => array(),
'cookies' => array(),
'body' => null,
'compress' => false,
'decompress' => true,
'sslverify' => true,
'sslcertificates' => ABSPATH . WPINC . '/certificates/ca-bundle.crt',
'stream' => false,
'filename' => null,
'limit_response_size' => null,
);
// Pre-parse for the HEAD checks.
$args = wp_parse_args( $args );
// By default, Head requests do not cause redirections.
if ( isset($args['method']) && 'HEAD' == $args['method'] )
$defaults['redirection'] = 0;
$r = wp_parse_args( $args, $defaults );
/**
* Filter the arguments used in an HTTP request.
*
* @since 2.7.0
*
* @param array $r An array of HTTP request arguments.
* @param string $url The request URI resource.
*/
$r = apply_filters( 'http_request_args', $r, $url );
// The transports decrement this, store a copy of the original value for loop purposes.
if ( ! isset( $r['_redirection'] ) )
$r['_redirection'] = $r['redirection'];
/**
* Filter whether to preempt an HTTP request's return.
*
* Returning a truthy value to the filter will short-circuit
* the HTTP request and return early with that value.
*
* @since 2.9.0
*
* @param bool $preempt Whether to preempt an HTTP request return. Default false.
* @param array $r HTTP request arguments.
* @param string $url The request URI resource.
*/
$pre = apply_filters( 'pre_http_request', false, $r, $url );
if ( false !== $pre )
return $pre;
if ( function_exists( 'wp_kses_bad_protocol' ) ) {
if ( $r['reject_unsafe_urls'] )
$url = wp_http_validate_url( $url );
$url = wp_kses_bad_protocol( $url, array( 'http', 'https', 'ssl' ) );
}
$arrURL = @parse_url( $url );
if ( empty( $url ) || empty( $arrURL['scheme'] ) )
return new WP_Error('http_request_failed', __('A valid URL was not provided.'));
if ( $this->block_request( $url ) )
return new WP_Error( 'http_request_failed', __( 'User has blocked requests through HTTP.' ) );
// Determine if this is a https call and pass that on to the transport functions
// so that we can blacklist the transports that do not support ssl verification
$r['ssl'] = $arrURL['scheme'] == 'https' || $arrURL['scheme'] == 'ssl';
// Determine if this request is to OUR install of WordPress
$homeURL = parse_url( get_bloginfo( 'url' ) );
$r['local'] = $homeURL['host'] == $arrURL['host'] || 'localhost' == $arrURL['host'];
unset( $homeURL );
// If we are streaming to a file but no filename was given drop it in the WP temp dir
// and pick its name using the basename of the $url
if ( $r['stream'] && empty( $r['filename'] ) )
$r['filename'] = get_temp_dir() . basename( $url );
// Force some settings if we are streaming to a file and check for existence and perms of destination directory
if ( $r['stream'] ) {
$r['blocking'] = true;
if ( ! wp_is_writable( dirname( $r['filename'] ) ) )
return new WP_Error( 'http_request_failed', __( 'Destination directory for file streaming does not exist or is not writable.' ) );
}
if ( is_null( $r['headers'] ) )
$r['headers'] = array();
if ( ! is_array( $r['headers'] ) ) {
$processedHeaders = WP_Http::processHeaders( $r['headers'], $url );
$r['headers'] = $processedHeaders['headers'];
}
if ( isset( $r['headers']['User-Agent'] ) ) {
$r['user-agent'] = $r['headers']['User-Agent'];
unset( $r['headers']['User-Agent'] );
}
if ( isset( $r['headers']['user-agent'] ) ) {
$r['user-agent'] = $r['headers']['user-agent'];
unset( $r['headers']['user-agent'] );
}
if ( '1.1' == $r['httpversion'] && !isset( $r['headers']['connection'] ) ) {
$r['headers']['connection'] = 'close';
}
// Construct Cookie: header if any cookies are set
WP_Http::buildCookieHeader( $r );
// Avoid issues where mbstring.func_overload is enabled
mbstring_binary_safe_encoding();
if ( ! isset( $r['headers']['Accept-Encoding'] ) ) {
if ( $encoding = WP_Http_Encoding::accept_encoding( $url, $r ) )
$r['headers']['Accept-Encoding'] = $encoding;
}
if ( ( ! is_null( $r['body'] ) && '' != $r['body'] ) || 'POST' == $r['method'] || 'PUT' == $r['method'] ) {
if ( is_array( $r['body'] ) || is_object( $r['body'] ) ) {
$r['body'] = http_build_query( $r['body'], null, '&' );
if ( ! isset( $r['headers']['Content-Type'] ) )
$r['headers']['Content-Type'] = 'application/x-www-form-urlencoded; charset=' . get_option( 'blog_charset' );
}
if ( '' === $r['body'] )
$r['body'] = null;
if ( ! isset( $r['headers']['Content-Length'] ) && ! isset( $r['headers']['content-length'] ) )
$r['headers']['Content-Length'] = strlen( $r['body'] );
}
$response = $this->_dispatch_request( $url, $r );
reset_mbstring_encoding();
if ( is_wp_error( $response ) )
return $response;
// Append cookies that were used in this request to the response
if ( ! empty( $r['cookies'] ) ) {
$cookies_set = wp_list_pluck( $response['cookies'], 'name' );
foreach ( $r['cookies'] as $cookie ) {
if ( ! in_array( $cookie->name, $cookies_set ) && $cookie->test( $url ) ) {
$response['cookies'][] = $cookie;
}
}
}
return $response;
}
/**
* Tests which transports are capable of supporting the request.
*
* @since 3.2.0
* @access private
*
* @param array $args Request arguments
* @param string $url URL to Request
*
* @return string|bool Class name for the first transport that claims to support the request. False if no transport claims to support the request.
*/
public function _get_first_available_transport( $args, $url = null ) {
/**
* Filter which HTTP transports are available and in what order.
*
* @since 3.7.0
*
* @param array $value Array of HTTP transports to check. Default array contains
* 'curl', and 'streams', in that order.
* @param array $args HTTP request arguments.
* @param string $url The URL to request.
*/
$request_order = apply_filters( 'http_api_transports', array( 'curl', 'streams' ), $args, $url );
// Loop over each transport on each HTTP request looking for one which will serve this request's needs
foreach ( $request_order as $transport ) {
$class = 'WP_HTTP_' . $transport;
// Check to see if this transport is a possibility, calls the transport statically
if ( !call_user_func( array( $class, 'test' ), $args, $url ) )
continue;
return $class;
}
return false;
}
/**
* Dispatches a HTTP request to a supporting transport.
*
* Tests each transport in order to find a transport which matches the request arguments.
* Also caches the transport instance to be used later.
*
* The order for requests is cURL, and then PHP Streams.
*
* @since 3.2.0
* @access private
*
* @param string $url URL to Request
* @param array $args Request arguments
* @return array|object Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
*/
private function _dispatch_request( $url, $args ) {
static $transports = array();
$class = $this->_get_first_available_transport( $args, $url );
if ( !$class )
return new WP_Error( 'http_failure', __( 'There are no HTTP transports available which can complete the requested request.' ) );
// Transport claims to support request, instantiate it and give it a whirl.
if ( empty( $transports[$class] ) )
$transports[$class] = new $class;
$response = $transports[$class]->request( $url, $args );
/**
* Fires after an HTTP API response is received and before the response is returned.
*
* @since 2.8.0
*
* @param mixed $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', $class, $args, $url );
if ( is_wp_error( $response ) )
return $response;
/**
* Filter the HTTP API response immediately before the response is returned.
*
* @since 2.9.0
*
* @param array|obj $response HTTP Response.
* @param array $args HTTP request arguments.
* @param string $url The request URL.
*/
return apply_filters( 'http_response', $response, $args, $url );
}
/**
* Uses the POST HTTP method.
*
* Used for sending data that is expected to be in the body.
*
* @access public
* @since 2.7.0
*
* @param string $url URI resource.
* @param string|array $args Optional. Override the defaults.
* @return array|object Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
*/
function post($url, $args = array()) {
$defaults = array('method' => 'POST');
$r = wp_parse_args( $args, $defaults );
return $this->request($url, $r);
}
/**
* Uses the GET HTTP method.
*
* Used for sending data that is expected to be in the body.
*
* @access public
* @since 2.7.0
*
* @param string $url URI resource.
* @param str|array $args Optional. Override the defaults.
* @return array|object Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
*/
function get($url, $args = array()) {
$defaults = array('method' => 'GET');
$r = wp_parse_args( $args, $defaults );
return $this->request($url, $r);
}
/**
* Uses the HEAD HTTP method.
*
* Used for sending data that is expected to be in the body.
*
* @access public
* @since 2.7.0
*
* @param string $url URI resource.
* @param str|array $args Optional. Override the defaults.
* @return array|object Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
*/
function head($url, $args = array()) {
$defaults = array('method' => 'HEAD');
$r = wp_parse_args( $args, $defaults );
return $this->request($url, $r);
}
/**
* Parses the responses and splits the parts into headers and body.
*
* @access public
* @static
* @since 2.7.0
*
* @param string $strResponse The full response string
* @return array Array with 'headers' and 'body' keys.
*/
public static function processResponse($strResponse) {
$res = explode("\r\n\r\n", $strResponse, 2);
return array('headers' => $res[0], 'body' => isset($res[1]) ? $res[1] : '');
}
/**
* Transform header string into an array.
*
* If an array is given then it is assumed to be raw header data with numeric keys with the
* headers as the values. No headers must be passed that were already processed.
*
* @access public
* @static
* @since 2.7.0
*
* @param string|array $headers
* @param string $url The URL that was requested
* @return array Processed string headers. If duplicate headers are encountered,
* Then a numbered array is returned as the value of that header-key.
*/
public static function processHeaders( $headers, $url = '' ) {
// split headers, one per array element
if ( is_string($headers) ) {
// tolerate line terminator: CRLF = LF (RFC 2616 19.3)
$headers = str_replace("\r\n", "\n", $headers);
// unfold folded header fields. LWS = [CRLF] 1*( SP | HT ) <US-ASCII SP, space (32)>, <US-ASCII HT, horizontal-tab (9)> (RFC 2616 2.2)
$headers = preg_replace('/\n[ \t]/', ' ', $headers);
// create the headers array
$headers = explode("\n", $headers);
}
$response = array('code' => 0, 'message' => '');
// If a redirection has taken place, The headers for each page request may have been passed.
// In this case, determine the final HTTP header and parse from there.
for ( $i = count($headers)-1; $i >= 0; $i-- ) {
if ( !empty($headers[$i]) && false === strpos($headers[$i], ':') ) {
$headers = array_splice($headers, $i);
break;
}
}
$cookies = array();
$newheaders = array();
foreach ( (array) $headers as $tempheader ) {
if ( empty($tempheader) )
continue;
if ( false === strpos($tempheader, ':') ) {
$stack = explode(' ', $tempheader, 3);
$stack[] = '';
list( , $response['code'], $response['message']) = $stack;
continue;
}
list($key, $value) = explode(':', $tempheader, 2);
$key = strtolower( $key );
$value = trim( $value );
if ( isset( $newheaders[ $key ] ) ) {
if ( ! is_array( $newheaders[ $key ] ) )
$newheaders[$key] = array( $newheaders[ $key ] );
$newheaders[ $key ][] = $value;
} else {
$newheaders[ $key ] = $value;
}
if ( 'set-cookie' == $key )
$cookies[] = new WP_Http_Cookie( $value, $url );
}
return array('response' => $response, 'headers' => $newheaders, 'cookies' => $cookies);
}
/**
* Takes the arguments for a ::request() and checks for the cookie array.
*
* If it's found, then it upgrades any basic name => value pairs to WP_Http_Cookie instances,
* which are each parsed into strings and added to the Cookie: header (within the arguments array).
* Edits the array by reference.
*
* @access public
* @version 2.8.0
* @static
*
* @param array $r Full array of args passed into ::request()
*/
public static function buildCookieHeader( &$r ) {
if ( ! empty($r['cookies']) ) {
// Upgrade any name => value cookie pairs to WP_HTTP_Cookie instances
foreach ( $r['cookies'] as $name => $value ) {
if ( ! is_object( $value ) )
$r['cookies'][ $name ] = new WP_HTTP_Cookie( array( 'name' => $name, 'value' => $value ) );
}
$cookies_header = '';
foreach ( (array) $r['cookies'] as $cookie ) {
$cookies_header .= $cookie->getHeaderValue() . '; ';
}
$cookies_header = substr( $cookies_header, 0, -2 );
$r['headers']['cookie'] = $cookies_header;
}
}
/**
* Decodes chunk transfer-encoding, based off the HTTP 1.1 specification.
*
* Based off the HTTP http_encoding_dechunk function.
*
* @link http://tools.ietf.org/html/rfc2616#section-19.4.6 Process for chunked decoding.
*
* @access public
* @since 2.7.0
* @static
*
* @param string $body Body content
* @return string Chunked decoded body on success or raw body on failure.
*/
public static function chunkTransferDecode( $body ) {
// The body is not chunked encoded or is malformed.
if ( ! preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', trim( $body ) ) )
return $body;
$parsed_body = '';
$body_original = $body; // We'll be altering $body, so need a backup in case of error
while ( true ) {
$has_chunk = (bool) preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', $body, $match );
if ( ! $has_chunk || empty( $match[1] ) )
return $body_original;
$length = hexdec( $match[1] );
$chunk_length = strlen( $match[0] );
// Parse out the chunk of data
$parsed_body .= substr( $body, $chunk_length, $length );
// Remove the chunk from the raw data
$body = substr( $body, $length + $chunk_length );
// End of document
if ( '0' === trim( $body ) )
return $parsed_body;
}
}
/**
* Block requests through the proxy.
*
* Those who are behind a proxy and want to prevent access to certain hosts may do so. This will
* prevent plugins from working and core functionality, if you don't include api.wordpress.org.
*
* You block external URL requests by defining WP_HTTP_BLOCK_EXTERNAL as true in your wp-config.php
* file and this will only allow localhost and your blog to make requests. The constant
* WP_ACCESSIBLE_HOSTS will allow additional hosts to go through for requests. The format of the
* WP_ACCESSIBLE_HOSTS constant is a comma separated list of hostnames to allow, wildcard domains
* are supported, eg *.wordpress.org will allow for all subdomains of wordpress.org to be contacted.
*
* @since 2.8.0
* @link http://core.trac.wordpress.org/ticket/8927 Allow preventing external requests.
* @link http://core.trac.wordpress.org/ticket/14636 Allow wildcard domains in WP_ACCESSIBLE_HOSTS
*
* @param string $uri URI of url.
* @return bool True to block, false to allow.
*/
function block_request($uri) {
// We don't need to block requests, because nothing is blocked.
if ( ! defined( 'WP_HTTP_BLOCK_EXTERNAL' ) || ! WP_HTTP_BLOCK_EXTERNAL )
return false;
$check = parse_url($uri);
if ( ! $check )
return true;
$home = parse_url( get_option('siteurl') );
// Don't block requests back to ourselves by default
if ( $check['host'] == 'localhost' || $check['host'] == $home['host'] ) {
/**
* Filter whether to block local requests through the proxy.
*
* @since 2.8.0
*
* @param bool $block Whether to block local requests through proxy.
* Default false.
*/
return apply_filters( 'block_local_requests', false );
}
if ( !defined('WP_ACCESSIBLE_HOSTS') )
return true;
static $accessible_hosts;
static $wildcard_regex = false;
if ( null == $accessible_hosts ) {
$accessible_hosts = preg_split('|,\s*|', WP_ACCESSIBLE_HOSTS);
if ( false !== strpos(WP_ACCESSIBLE_HOSTS, '*') ) {
$wildcard_regex = array();
foreach ( $accessible_hosts as $host )
$wildcard_regex[] = str_replace( '\*', '.+', preg_quote( $host, '/' ) );
$wildcard_regex = '/^(' . implode('|', $wildcard_regex) . ')$/i';
}
}
if ( !empty($wildcard_regex) )
return !preg_match($wildcard_regex, $check['host']);
else
return !in_array( $check['host'], $accessible_hosts ); //Inverse logic, If it's in the array, then we can't access it.
}
static function make_absolute_url( $maybe_relative_path, $url ) {
if ( empty( $url ) )
return $maybe_relative_path;
// Check for a scheme
if ( false !== strpos( $maybe_relative_path, '://' ) )
return $maybe_relative_path;
if ( ! $url_parts = @parse_url( $url ) )
return $maybe_relative_path;
if ( ! $relative_url_parts = @parse_url( $maybe_relative_path ) )
return $maybe_relative_path;
$absolute_path = $url_parts['scheme'] . '://' . $url_parts['host'];
if ( isset( $url_parts['port'] ) )
$absolute_path .= ':' . $url_parts['port'];
// Start off with the Absolute URL path
$path = ! empty( $url_parts['path'] ) ? $url_parts['path'] : '/';
// If it's a root-relative path, then great
if ( ! empty( $relative_url_parts['path'] ) && '/' == $relative_url_parts['path'][0] ) {
$path = $relative_url_parts['path'];
// Else it's a relative path
} elseif ( ! empty( $relative_url_parts['path'] ) ) {
// Strip off any file components from the absolute path
$path = substr( $path, 0, strrpos( $path, '/' ) + 1 );
// Build the new path
$path .= $relative_url_parts['path'];
// Strip all /path/../ out of the path
while ( strpos( $path, '../' ) > 1 ) {
$path = preg_replace( '![^/]+/\.\./!', '', $path );
}
// Strip any final leading ../ from the path
$path = preg_replace( '!^/(\.\./)+!', '', $path );
}
// Add the Query string
if ( ! empty( $relative_url_parts['query'] ) )
$path .= '?' . $relative_url_parts['query'];
return $absolute_path . '/' . ltrim( $path, '/' );
}
/**
* Handles HTTP Redirects and follows them if appropriate.
*
* @since 3.7.0
*
* @param string $url The URL which was requested.
* @param array $args The Arguements which were used to make the request.
* @param array $response The Response of the HTTP request.
* @return false|object False if no redirect is present, a WP_HTTP or WP_Error result otherwise.
*/
static function handle_redirects( $url, $args, $response ) {
// If no redirects are present, or, redirects were not requested, perform no action.
if ( ! isset( $response['headers']['location'] ) || 0 === $args['_redirection'] )
return false;
// Only perform redirections on redirection http codes
if ( $response['response']['code'] > 399 || $response['response']['code'] < 300 )
return false;
// Don't redirect if we've run out of redirects
if ( $args['redirection']-- <= 0 )
return new WP_Error( 'http_request_failed', __('Too many redirects.') );
$redirect_location = $response['headers']['location'];
// If there were multiple Location headers, use the last header specified
if ( is_array( $redirect_location ) )
$redirect_location = array_pop( $redirect_location );
$redirect_location = WP_HTTP::make_absolute_url( $redirect_location, $url );
// POST requests should not POST to a redirected location
if ( 'POST' == $args['method'] ) {
if ( in_array( $response['response']['code'], array( 302, 303 ) ) )
$args['method'] = 'GET';
}
// Include valid cookies in the redirect process
if ( ! empty( $response['cookies'] ) ) {
foreach ( $response['cookies'] as $cookie ) {
if ( $cookie->test( $redirect_location ) )
$args['cookies'][] = $cookie;
}
}
return wp_remote_request( $redirect_location, $args );
}
/**
* Determines if a specified string represents an IP address or not.
*
* This function also detects the type of the IP address, returning either
* '4' or '6' to represent a IPv4 and IPv6 address respectively.
* This does not verify if the IP is a valid IP, only that it appears to be
* an IP address.
*
* @see http://home.deds.nl/~aeron/regex/ for IPv6 regex
*
* @since 3.7.0
* @static
*
* @param string $maybe_ip A suspected IP address
* @return integer|bool Upon success, '4' or '6' to represent a IPv4 or IPv6 address, false upon failure
*/
static function is_ip_address( $maybe_ip ) {
if ( preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/', $maybe_ip ) )
return 4;
if ( false !== strpos( $maybe_ip, ':' ) && preg_match( '/^(((?=.*(::))(?!.*\3.+\3))\3?|([\dA-F]{1,4}(\3|:\b|$)|\2))(?4){5}((?4){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4})$/i', trim( $maybe_ip, ' []' ) ) )
return 6;
return false;
}
}
/**
* HTTP request method uses PHP Streams to retrieve the url.
*
* @since 2.7.0
* @since 3.7.0 Combined with the fsockopen transport and switched to stream_socket_client().
*/
class WP_Http_Streams {
/**
* Send a HTTP request to a URI using PHP Streams.
*
* @see WP_Http::request For default options descriptions.
*
* @since 2.7.0
* @since 3.7.0 Combined with the fsockopen transport and switched to stream_socket_client().
*
* @access public
* @param string $url URI resource.
* @param string|array $args Optional. Override the defaults.
* @return array 'headers', 'body', 'response', 'cookies' and 'filename' keys.
*/
function request($url, $args = array()) {
$defaults = array(
'method' => 'GET', 'timeout' => 5,
'redirection' => 5, 'httpversion' => '1.0',
'blocking' => true,
'headers' => array(), 'body' => null, 'cookies' => array()
);
$r = wp_parse_args( $args, $defaults );
if ( isset($r['headers']['User-Agent']) ) {
$r['user-agent'] = $r['headers']['User-Agent'];
unset($r['headers']['User-Agent']);
} else if ( isset($r['headers']['user-agent']) ) {
$r['user-agent'] = $r['headers']['user-agent'];
unset($r['headers']['user-agent']);
}
// Construct Cookie: header if any cookies are set
WP_Http::buildCookieHeader( $r );
$arrURL = parse_url($url);
$connect_host = $arrURL['host'];
$secure_transport = ( $arrURL['scheme'] == 'ssl' || $arrURL['scheme'] == 'https' );
if ( ! isset( $arrURL['port'] ) ) {
if ( $arrURL['scheme'] == 'ssl' || $arrURL['scheme'] == 'https' ) {
$arrURL['port'] = 443;
$secure_transport = true;
} else {
$arrURL['port'] = 80;
}
}
if ( isset( $r['headers']['Host'] ) || isset( $r['headers']['host'] ) ) {
if ( isset( $r['headers']['Host'] ) )
$arrURL['host'] = $r['headers']['Host'];
else
$arrURL['host'] = $r['headers']['host'];
unset( $r['headers']['Host'], $r['headers']['host'] );
}
// Certain versions of PHP have issues with 'localhost' and IPv6, It attempts to connect to ::1,
// which fails when the server is not set up for it. For compatibility, always connect to the IPv4 address.
if ( 'localhost' == strtolower( $connect_host ) )
$connect_host = '127.0.0.1';
$connect_host = $secure_transport ? 'ssl://' . $connect_host : 'tcp://' . $connect_host;
$is_local = isset( $r['local'] ) && $r['local'];
$ssl_verify = isset( $r['sslverify'] ) && $r['sslverify'];
if ( $is_local ) {
/**
* Filter whether SSL should be verified for local requests.
*
* @since 2.8.0
*
* @param bool $ssl_verify Whether to verify the SSL connection. Default true.
*/
$ssl_verify = apply_filters( 'https_local_ssl_verify', $ssl_verify );
} elseif ( ! $is_local ) {
/**
* Filter 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.
*/
$ssl_verify = apply_filters( 'https_ssl_verify', $ssl_verify );
}
$proxy = new WP_HTTP_Proxy();
$context = stream_context_create( array(
'ssl' => array(
'verify_peer' => $ssl_verify,
//'CN_match' => $arrURL['host'], // This is handled by self::verify_ssl_certificate()
'capture_peer_cert' => $ssl_verify,
'SNI_enabled' => true,
'cafile' => $r['sslcertificates'],
'allow_self_signed' => ! $ssl_verify,
)
) );
$timeout = (int) floor( $r['timeout'] );
$utimeout = $timeout == $r['timeout'] ? 0 : 1000000 * $r['timeout'] % 1000000;
$connect_timeout = max( $timeout, 1 );
$connection_error = null; // Store error number
$connection_error_str = null; // Store error string
if ( !WP_DEBUG ) {
// In the event that the SSL connection fails, silence the many PHP Warnings
if ( $secure_transport )
$error_reporting = error_reporting(0);
if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
$handle = @stream_socket_client( 'tcp://' . $proxy->host() . ':' . $proxy->port(), $connection_error, $connection_error_str, $connect_timeout, STREAM_CLIENT_CONNECT, $context );
else
$handle = @stream_socket_client( $connect_host . ':' . $arrURL['port'], $connection_error, $connection_error_str, $connect_timeout, STREAM_CLIENT_CONNECT, $context );
if ( $secure_transport )
error_reporting( $error_reporting );
} else {
if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
$handle = stream_socket_client( 'tcp://' . $proxy->host() . ':' . $proxy->port(), $connection_error, $connection_error_str, $connect_timeout, STREAM_CLIENT_CONNECT, $context );
else
$handle = stream_socket_client( $connect_host . ':' . $arrURL['port'], $connection_error, $connection_error_str, $connect_timeout, STREAM_CLIENT_CONNECT, $context );
}
if ( false === $handle ) {
// SSL connection failed due to expired/invalid cert, or, OpenSSL configuration is broken
if ( $secure_transport && 0 === $connection_error && '' === $connection_error_str )
return new WP_Error( 'http_request_failed', __( 'The SSL certificate for the host could not be verified.' ) );
return new WP_Error('http_request_failed', $connection_error . ': ' . $connection_error_str );
}
// Verify that the SSL certificate is valid for this request
if ( $secure_transport && $ssl_verify && ! $proxy->is_enabled() ) {
if ( ! self::verify_ssl_certificate( $handle, $arrURL['host'] ) )
return new WP_Error( 'http_request_failed', __( 'The SSL certificate for the host could not be verified.' ) );
}
stream_set_timeout( $handle, $timeout, $utimeout );
if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) //Some proxies require full URL in this field.
$requestPath = $url;
else
$requestPath = $arrURL['path'] . ( isset($arrURL['query']) ? '?' . $arrURL['query'] : '' );
if ( empty($requestPath) )
$requestPath .= '/';
$strHeaders = strtoupper($r['method']) . ' ' . $requestPath . ' HTTP/' . $r['httpversion'] . "\r\n";
if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
$strHeaders .= 'Host: ' . $arrURL['host'] . ':' . $arrURL['port'] . "\r\n";
else
$strHeaders .= 'Host: ' . $arrURL['host'] . "\r\n";
if ( isset($r['user-agent']) )
$strHeaders .= 'User-agent: ' . $r['user-agent'] . "\r\n";
if ( is_array($r['headers']) ) {
foreach ( (array) $r['headers'] as $header => $headerValue )
$strHeaders .= $header . ': ' . $headerValue . "\r\n";
} else {
$strHeaders .= $r['headers'];
}
if ( $proxy->use_authentication() )
$strHeaders .= $proxy->authentication_header() . "\r\n";
$strHeaders .= "\r\n";
if ( ! is_null($r['body']) )
$strHeaders .= $r['body'];
fwrite($handle, $strHeaders);
if ( ! $r['blocking'] ) {
stream_set_blocking( $handle, 0 );
fclose( $handle );
return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
}
$strResponse = '';
$bodyStarted = false;
$keep_reading = true;
$block_size = 4096;
if ( isset( $r['limit_response_size'] ) )
$block_size = min( $block_size, $r['limit_response_size'] );
// If streaming to a file setup the file handle
if ( $r['stream'] ) {
if ( ! WP_DEBUG )
$stream_handle = @fopen( $r['filename'], 'w+' );
else
$stream_handle = fopen( $r['filename'], 'w+' );
if ( ! $stream_handle )
return new WP_Error( 'http_request_failed', sprintf( __( 'Could not open handle for fopen() to %s' ), $r['filename'] ) );
$bytes_written = 0;
while ( ! feof($handle) && $keep_reading ) {
$block = fread( $handle, $block_size );
if ( ! $bodyStarted ) {
$strResponse .= $block;
if ( strpos( $strResponse, "\r\n\r\n" ) ) {
$process = WP_Http::processResponse( $strResponse );
$bodyStarted = true;
$block = $process['body'];
unset( $strResponse );
$process['body'] = '';
}
}
$this_block_size = strlen( $block );
if ( isset( $r['limit_response_size'] ) && ( $bytes_written + $this_block_size ) > $r['limit_response_size'] )
$block = substr( $block, 0, ( $r['limit_response_size'] - $bytes_written ) );
$bytes_written_to_file = fwrite( $stream_handle, $block );
if ( $bytes_written_to_file != $this_block_size ) {
fclose( $handle );
fclose( $stream_handle );
return new WP_Error( 'http_request_failed', __( 'Failed to write request to temporary file.' ) );
}
$bytes_written += $bytes_written_to_file;
$keep_reading = !isset( $r['limit_response_size'] ) || $bytes_written < $r['limit_response_size'];
}
fclose( $stream_handle );
} else {
$header_length = 0;
while ( ! feof( $handle ) && $keep_reading ) {
$block = fread( $handle, $block_size );
$strResponse .= $block;
if ( ! $bodyStarted && strpos( $strResponse, "\r\n\r\n" ) ) {
$header_length = strpos( $strResponse, "\r\n\r\n" ) + 4;
$bodyStarted = true;
}
$keep_reading = ( ! $bodyStarted || !isset( $r['limit_response_size'] ) || strlen( $strResponse ) < ( $header_length + $r['limit_response_size'] ) );
}
$process = WP_Http::processResponse( $strResponse );
unset( $strResponse );
}
fclose( $handle );
$arrHeaders = WP_Http::processHeaders( $process['headers'], $url );
$response = array(
'headers' => $arrHeaders['headers'],
'body' => null, // Not yet processed
'response' => $arrHeaders['response'],
'cookies' => $arrHeaders['cookies'],
'filename' => $r['filename']
);
// Handle redirects
if ( false !== ( $redirect_response = WP_HTTP::handle_redirects( $url, $r, $response ) ) )
return $redirect_response;
// If the body was chunk encoded, then decode it.
if ( ! empty( $process['body'] ) && isset( $arrHeaders['headers']['transfer-encoding'] ) && 'chunked' == $arrHeaders['headers']['transfer-encoding'] )
$process['body'] = WP_Http::chunkTransferDecode($process['body']);
if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($arrHeaders['headers']) )
$process['body'] = WP_Http_Encoding::decompress( $process['body'] );
if ( isset( $r['limit_response_size'] ) && strlen( $process['body'] ) > $r['limit_response_size'] )
$process['body'] = substr( $process['body'], 0, $r['limit_response_size'] );
$response['body'] = $process['body'];
return $response;
}
/**
* Verifies the received SSL certificate against it's Common Names and subjectAltName fields
*
* PHP's SSL verifications only verify that it's a valid Certificate, it doesn't verify if
* the certificate is valid for the hostname which was requested.
* This function verifies the requested hostname against certificate's subjectAltName field,
* if that is empty, or contains no DNS entries, a fallback to the Common Name field is used.
*
* IP Address support is included if the request is being made to an IP address.
*
* @since 3.7.0
* @static
*
* @param stream $stream The PHP Stream which the SSL request is being made over
* @param string $host The hostname being requested
* @return bool If the cerficiate presented in $stream is valid for $host
*/
static function verify_ssl_certificate( $stream, $host ) {
$context_options = stream_context_get_options( $stream );
if ( empty( $context_options['ssl']['peer_certificate'] ) )
return false;
$cert = openssl_x509_parse( $context_options['ssl']['peer_certificate'] );
if ( ! $cert )
return false;
// If the request is being made to an IP address, we'll validate against IP fields in the cert (if they exist)
$host_type = ( WP_HTTP::is_ip_address( $host ) ? 'ip' : 'dns' );
$certificate_hostnames = array();
if ( ! empty( $cert['extensions']['subjectAltName'] ) ) {
$match_against = preg_split( '/,\s*/', $cert['extensions']['subjectAltName'] );
foreach ( $match_against as $match ) {
list( $match_type, $match_host ) = explode( ':', $match );
if ( $host_type == strtolower( trim( $match_type ) ) ) // IP: or DNS:
$certificate_hostnames[] = strtolower( trim( $match_host ) );
}
} elseif ( !empty( $cert['subject']['CN'] ) ) {
// Only use the CN when the certificate includes no subjectAltName extension
$certificate_hostnames[] = strtolower( $cert['subject']['CN'] );
}
// Exact hostname/IP matches
if ( in_array( strtolower( $host ), $certificate_hostnames ) )
return true;
// IP's can't be wildcards, Stop processing
if ( 'ip' == $host_type )
return false;
// Test to see if the domain is at least 2 deep for wildcard support
if ( substr_count( $host, '.' ) < 2 )
return false;
// Wildcard subdomains certs (*.example.com) are valid for a.example.com but not a.b.example.com
$wildcard_host = preg_replace( '/^[^.]+\./', '*.', $host );
return in_array( strtolower( $wildcard_host ), $certificate_hostnames );
}
/**
* Whether this class can be used for retrieving a URL.
*
* @static
* @access public
* @since 2.7.0
* @since 3.7.0 Combined with the fsockopen transport and switched to stream_socket_client().
*
* @return boolean False means this class can not be used, true means it can.
*/
public static function test( $args = array() ) {
if ( ! function_exists( 'stream_socket_client' ) )
return false;
$is_ssl = isset( $args['ssl'] ) && $args['ssl'];
if ( $is_ssl ) {
if ( ! extension_loaded( 'openssl' ) )
return false;
if ( ! function_exists( 'openssl_x509_parse' ) )
return false;
}
/**
* Filter whether streams can be used as a transport for retrieving a URL.
*
* @since 2.7.0
*
* @param bool $use_class Whether the class can be used. Default true.
* @param array $args Request arguments.
*/
return apply_filters( 'use_streams_transport', true, $args );
}
}
/**
* Deprecated HTTP Transport method which used fsockopen.
*
* This class is not used, and is included for backwards compatibility only.
* All code should make use of WP_HTTP directly through it's API.
*
* @see WP_HTTP::request
*
* @since 2.7.0
* @deprecated 3.7.0 Please use WP_HTTP::request() directly
*/
class WP_HTTP_Fsockopen extends WP_HTTP_Streams {
// For backwards compatibility for users who are using the class directly
}
/**
* HTTP request method uses Curl extension to retrieve the url.
*
* Requires the Curl extension to be installed.
*
* @package WordPress
* @subpackage HTTP
* @since 2.7.0
*/
class WP_Http_Curl {
/**
* Temporary header storage for during requests.
*
* @since 3.2.0
* @access private
* @var string
*/
private $headers = '';
/**
* Temporary body storage for during requests.
*
* @since 3.6.0
* @access private
* @var string
*/
private $body = '';
/**
* The maximum amount of data to receive from the remote server.
*
* @since 3.6.0
* @access private
* @var int
*/
private $max_body_length = false;
/**
* The file resource used for streaming to file.
*
* @since 3.6.0
* @access private
* @var resource
*/
private $stream_handle = false;
/**
* Send a HTTP request to a URI using cURL extension.
*
* @access public
* @since 2.7.0
*
* @param string $url
* @param str|array $args Optional. Override the defaults.
* @return array 'headers', 'body', 'response', 'cookies' and 'filename' keys.
*/
function request($url, $args = array()) {
$defaults = array(
'method' => 'GET', 'timeout' => 5,
'redirection' => 5, 'httpversion' => '1.0',
'blocking' => true,
'headers' => array(), 'body' => null, 'cookies' => array()
);
$r = wp_parse_args( $args, $defaults );
if ( isset($r['headers']['User-Agent']) ) {
$r['user-agent'] = $r['headers']['User-Agent'];
unset($r['headers']['User-Agent']);
} else if ( isset($r['headers']['user-agent']) ) {
$r['user-agent'] = $r['headers']['user-agent'];
unset($r['headers']['user-agent']);
}
// Construct Cookie: header if any cookies are set.
WP_Http::buildCookieHeader( $r );
$handle = curl_init();
// cURL offers really easy proxy support.
$proxy = new WP_HTTP_Proxy();
if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
curl_setopt( $handle, CURLOPT_PROXYTYPE, CURLPROXY_HTTP );
curl_setopt( $handle, CURLOPT_PROXY, $proxy->host() );
curl_setopt( $handle, CURLOPT_PROXYPORT, $proxy->port() );
if ( $proxy->use_authentication() ) {
curl_setopt( $handle, CURLOPT_PROXYAUTH, CURLAUTH_ANY );
curl_setopt( $handle, CURLOPT_PROXYUSERPWD, $proxy->authentication() );
}
}
$is_local = isset($r['local']) && $r['local'];
$ssl_verify = isset($r['sslverify']) && $r['sslverify'];
if ( $is_local ) {
/** This filter is documented in wp-includes/class-http.php */
$ssl_verify = apply_filters( 'https_local_ssl_verify', $ssl_verify );
} elseif ( ! $is_local ) {
/** This filter is documented in wp-includes/class-http.php */
$ssl_verify = apply_filters( 'https_ssl_verify', $ssl_verify );
}
// CURLOPT_TIMEOUT and CURLOPT_CONNECTTIMEOUT expect integers. Have to use ceil since
// a value of 0 will allow an unlimited timeout.
$timeout = (int) ceil( $r['timeout'] );
curl_setopt( $handle, CURLOPT_CONNECTTIMEOUT, $timeout );
curl_setopt( $handle, CURLOPT_TIMEOUT, $timeout );
curl_setopt( $handle, CURLOPT_URL, $url);
curl_setopt( $handle, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $handle, CURLOPT_SSL_VERIFYHOST, ( $ssl_verify === true ) ? 2 : false );
curl_setopt( $handle, CURLOPT_SSL_VERIFYPEER, $ssl_verify );
curl_setopt( $handle, CURLOPT_CAINFO, $r['sslcertificates'] );
curl_setopt( $handle, CURLOPT_USERAGENT, $r['user-agent'] );
// The option doesn't work with safe mode or when open_basedir is set, and there's a
// bug #17490 with redirected POST requests, so handle redirections outside Curl.
curl_setopt( $handle, CURLOPT_FOLLOWLOCATION, false );
if ( defined( 'CURLOPT_PROTOCOLS' ) ) // PHP 5.2.10 / cURL 7.19.4
curl_setopt( $handle, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS );
switch ( $r['method'] ) {
case 'HEAD':
curl_setopt( $handle, CURLOPT_NOBODY, true );
break;
case 'POST':
curl_setopt( $handle, CURLOPT_POST, true );
curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] );
break;
case 'PUT':
curl_setopt( $handle, CURLOPT_CUSTOMREQUEST, 'PUT' );
curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] );
break;
default:
curl_setopt( $handle, CURLOPT_CUSTOMREQUEST, $r['method'] );
if ( ! is_null( $r['body'] ) )
curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] );
break;
}
if ( true === $r['blocking'] ) {
curl_setopt( $handle, CURLOPT_HEADERFUNCTION, array( $this, 'stream_headers' ) );
curl_setopt( $handle, CURLOPT_WRITEFUNCTION, array( $this, 'stream_body' ) );
}
curl_setopt( $handle, CURLOPT_HEADER, false );
if ( isset( $r['limit_response_size'] ) )
$this->max_body_length = intval( $r['limit_response_size'] );
else
$this->max_body_length = false;
// If streaming to a file open a file handle, and setup our curl streaming handler
if ( $r['stream'] ) {
if ( ! WP_DEBUG )
$this->stream_handle = @fopen( $r['filename'], 'w+' );
else
$this->stream_handle = fopen( $r['filename'], 'w+' );
if ( ! $this->stream_handle )
return new WP_Error( 'http_request_failed', sprintf( __( 'Could not open handle for fopen() to %s' ), $r['filename'] ) );
} else {
$this->stream_handle = false;
}
if ( !empty( $r['headers'] ) ) {
// cURL expects full header strings in each element
$headers = array();
foreach ( $r['headers'] as $name => $value ) {
$headers[] = "{$name}: $value";
}
curl_setopt( $handle, CURLOPT_HTTPHEADER, $headers );
}
if ( $r['httpversion'] == '1.0' )
curl_setopt( $handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0 );
else
curl_setopt( $handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 );
/**
* Fires before the cURL request is executed.
*
* Cookies are not currently handled by the HTTP API. This action allows
* plugins to handle cookies themselves.
*
* @since 2.8.0
*
* @param resource &$handle The cURL handle returned by curl_init().
* @param array $r The HTTP request arguments.
* @param string $url The destination URL.
*/
do_action_ref_array( 'http_api_curl', array( &$handle, $r, $url ) );
// We don't need to return the body, so don't. Just execute request and return.
if ( ! $r['blocking'] ) {
curl_exec( $handle );
if ( $curl_error = curl_error( $handle ) ) {
curl_close( $handle );
return new WP_Error( 'http_request_failed', $curl_error );
}
if ( in_array( curl_getinfo( $handle, CURLINFO_HTTP_CODE ), array( 301, 302 ) ) ) {
curl_close( $handle );
return new WP_Error( 'http_request_failed', __( 'Too many redirects.' ) );
}
curl_close( $handle );
return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() );
}
$theResponse = curl_exec( $handle );
$theHeaders = WP_Http::processHeaders( $this->headers, $url );
$theBody = $this->body;
$this->headers = '';
$this->body = '';
$curl_error = curl_errno( $handle );
// If an error occured, or, no response
if ( $curl_error || ( 0 == strlen( $theBody ) && empty( $theHeaders['headers'] ) ) ) {
if ( CURLE_WRITE_ERROR /* 23 */ == $curl_error && $r['stream'] ) {
fclose( $this->stream_handle );
return new WP_Error( 'http_request_failed', __( 'Failed to write request to temporary file.' ) );
}
if ( $curl_error = curl_error( $handle ) ) {
curl_close( $handle );
return new WP_Error( 'http_request_failed', $curl_error );
}
if ( in_array( curl_getinfo( $handle, CURLINFO_HTTP_CODE ), array( 301, 302 ) ) ) {
curl_close( $handle );
return new WP_Error( 'http_request_failed', __( 'Too many redirects.' ) );
}
}
$response = array();
$response['code'] = curl_getinfo( $handle, CURLINFO_HTTP_CODE );
$response['message'] = get_status_header_desc($response['code']);
curl_close( $handle );
if ( $r['stream'] )
fclose( $this->stream_handle );
$response = array(
'headers' => $theHeaders['headers'],
'body' => null,
'response' => $response,
'cookies' => $theHeaders['cookies'],
'filename' => $r['filename']
);
// Handle redirects
if ( false !== ( $redirect_response = WP_HTTP::handle_redirects( $url, $r, $response ) ) )
return $redirect_response;
if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($theHeaders['headers']) )
$theBody = WP_Http_Encoding::decompress( $theBody );
$response['body'] = $theBody;
return $response;
}
/**
* Grab the headers of the cURL request
*
* Each header is sent individually to this callback, so we append to the $header property for temporary storage
*
* @since 3.2.0
* @access private
* @return int
*/
private function stream_headers( $handle, $headers ) {
$this->headers .= $headers;
return strlen( $headers );
}
/**
* Grab the body of the cURL request
*
* The contents of the document are passed in chunks, so we append to the $body property for temporary storage.
* Returning a length shorter than the length of $data passed in will cause cURL to abort the request as "completed"
*
* @since 3.6.0
* @access private
* @return int
*/
private function stream_body( $handle, $data ) {
$data_length = strlen( $data );
if ( $this->max_body_length && ( strlen( $this->body ) + $data_length ) > $this->max_body_length )
$data = substr( $data, 0, ( $this->max_body_length - $data_length ) );
if ( $this->stream_handle ) {
$bytes_written = fwrite( $this->stream_handle, $data );
} else {
$this->body .= $data;
$bytes_written = $data_length;
}
// Upon event of this function returning less than strlen( $data ) curl will error with CURLE_WRITE_ERROR
return $bytes_written;
}
/**
* Whether this class can be used for retrieving an URL.
*
* @static
* @since 2.7.0
*
* @return boolean False means this class can not be used, true means it can.
*/
public static function test( $args = array() ) {
if ( ! function_exists( 'curl_init' ) || ! function_exists( 'curl_exec' ) )
return false;
$is_ssl = isset( $args['ssl'] ) && $args['ssl'];
if ( $is_ssl ) {
$curl_version = curl_version();
if ( ! (CURL_VERSION_SSL & $curl_version['features']) ) // Does this cURL version support SSL requests?
return false;
}
/**
* Filter whether cURL can be used as a transport for retrieving a URL.
*
* @since 2.7.0
*
* @param bool $use_class Whether the class can be used. Default true.
* @param array $args An array of request arguments.
*/
return apply_filters( 'use_curl_transport', true, $args );
}
}
/**
* Adds Proxy support to the WordPress HTTP API.
*
* There are caveats to proxy support. It requires that defines be made in the wp-config.php file to
* enable proxy support. There are also a few filters that plugins can hook into for some of the
* constants.
*
* Please note that only BASIC authentication is supported by most transports.
* cURL MAY support more methods (such as NTLM authentication) depending on your environment.
*
* The constants are as follows:
* <ol>
* <li>WP_PROXY_HOST - Enable proxy support and host for connecting.</li>
* <li>WP_PROXY_PORT - Proxy port for connection. No default, must be defined.</li>
* <li>WP_PROXY_USERNAME - Proxy username, if it requires authentication.</li>
* <li>WP_PROXY_PASSWORD - Proxy password, if it requires authentication.</li>
* <li>WP_PROXY_BYPASS_HOSTS - Will prevent the hosts in this list from going through the proxy.
* You do not need to have localhost and the blog host in this list, because they will not be passed
* through the proxy. The list should be presented in a comma separated list, wildcards using * are supported, eg. *.wordpress.org</li>
* </ol>
*
* An example can be as seen below.
* <code>
* define('WP_PROXY_HOST', '192.168.84.101');
* define('WP_PROXY_PORT', '8080');
* define('WP_PROXY_BYPASS_HOSTS', 'localhost, www.example.com, *.wordpress.org');
* </code>
*
* @link http://core.trac.wordpress.org/ticket/4011 Proxy support ticket in WordPress.
* @link http://core.trac.wordpress.org/ticket/14636 Allow wildcard domains in WP_PROXY_BYPASS_HOSTS
* @since 2.8.0
*/
class WP_HTTP_Proxy {
/**
* Whether proxy connection should be used.
*
* @since 2.8.0
*
* @use WP_PROXY_HOST
* @use WP_PROXY_PORT
*
* @return bool
*/
function is_enabled() {
return defined('WP_PROXY_HOST') && defined('WP_PROXY_PORT');
}
/**
* Whether authentication should be used.
*
* @since 2.8.0
*
* @use WP_PROXY_USERNAME
* @use WP_PROXY_PASSWORD
*
* @return bool
*/
function use_authentication() {
return defined('WP_PROXY_USERNAME') && defined('WP_PROXY_PASSWORD');
}
/**
* Retrieve the host for the proxy server.
*
* @since 2.8.0
*
* @return string
*/
function host() {
if ( defined('WP_PROXY_HOST') )
return WP_PROXY_HOST;
return '';
}
/**
* Retrieve the port for the proxy server.
*
* @since 2.8.0
*
* @return string
*/
function port() {
if ( defined('WP_PROXY_PORT') )
return WP_PROXY_PORT;
return '';
}
/**
* Retrieve the username for proxy authentication.
*
* @since 2.8.0
*
* @return string
*/
function username() {
if ( defined('WP_PROXY_USERNAME') )
return WP_PROXY_USERNAME;
return '';
}
/**
* Retrieve the password for proxy authentication.
*
* @since 2.8.0
*
* @return string
*/
function password() {
if ( defined('WP_PROXY_PASSWORD') )
return WP_PROXY_PASSWORD;
return '';
}
/**
* Retrieve authentication string for proxy authentication.
*
* @since 2.8.0
*
* @return string
*/
function authentication() {
return $this->username() . ':' . $this->password();
}
/**
* Retrieve header string for proxy authentication.
*
* @since 2.8.0
*
* @return string
*/
function authentication_header() {
return 'Proxy-Authorization: Basic ' . base64_encode( $this->authentication() );
}
/**
* Whether URL should be sent through the proxy server.
*
* We want to keep localhost and the blog URL from being sent through the proxy server, because
* some proxies can not handle this. We also have the constant available for defining other
* hosts that won't be sent through the proxy.
*
* @uses WP_PROXY_BYPASS_HOSTS
* @since 2.8.0
*
* @param string $uri URI to check.
* @return bool True, to send through the proxy and false if, the proxy should not be used.
*/
function send_through_proxy( $uri ) {
// parse_url() only handles http, https type URLs, and will emit E_WARNING on failure.
// This will be displayed on blogs, which is not reasonable.
$check = @parse_url($uri);
// Malformed URL, can not process, but this could mean ssl, so let through anyway.
if ( $check === false )
return true;
$home = parse_url( get_option('siteurl') );
/**
* Filter whether to preempt sending the request through the proxy server.
*
* Returning false will bypass the proxy; returning true will send
* the request through the proxy. Returning null bypasses the filter.
*
* @since 3.5.0
*
* @param null $override Whether to override the request result. Default null.
* @param string $uri URL to check.
* @param array $check Associative array result of parsing the URI.
* @param array $home Associative array result of parsing the site URL.
*/
$result = apply_filters( 'pre_http_send_through_proxy', null, $uri, $check, $home );
if ( ! is_null( $result ) )
return $result;
if ( $check['host'] == 'localhost' || $check['host'] == $home['host'] )
return false;
if ( !defined('WP_PROXY_BYPASS_HOSTS') )
return true;
static $bypass_hosts;
static $wildcard_regex = false;
if ( null == $bypass_hosts ) {
$bypass_hosts = preg_split('|,\s*|', WP_PROXY_BYPASS_HOSTS);
if ( false !== strpos(WP_PROXY_BYPASS_HOSTS, '*') ) {
$wildcard_regex = array();
foreach ( $bypass_hosts as $host )
$wildcard_regex[] = str_replace( '\*', '.+', preg_quote( $host, '/' ) );
$wildcard_regex = '/^(' . implode('|', $wildcard_regex) . ')$/i';
}
}
if ( !empty($wildcard_regex) )
return !preg_match($wildcard_regex, $check['host']);
else
return !in_array( $check['host'], $bypass_hosts );
}
}
/**
* Internal representation of a single cookie.
*
* Returned cookies are represented using this class, and when cookies are set, if they are not
* already a WP_Http_Cookie() object, then they are turned into one.
*
* @todo The WordPress convention is to use underscores instead of camelCase for function and method
* names. Need to switch to use underscores instead for the methods.
*
* @package WordPress
* @subpackage HTTP
* @since 2.8.0
*/
class WP_Http_Cookie {
/**
* Cookie name.
*
* @since 2.8.0
* @var string
*/
var $name;
/**
* Cookie value.
*
* @since 2.8.0
* @var string
*/
var $value;
/**
* When the cookie expires.
*
* @since 2.8.0
* @var string
*/
var $expires;
/**
* Cookie URL path.
*
* @since 2.8.0
* @var string
*/
var $path;
/**
* Cookie Domain.
*
* @since 2.8.0
* @var string
*/
var $domain;
/**
* Sets up this cookie object.
*
* The parameter $data should be either an associative array containing the indices names below
* or a header string detailing it.
*
* If it's an array, it should include the following elements:
* <ol>
* <li>Name</li>
* <li>Value - should NOT be urlencoded already.</li>
* <li>Expires - (optional) String or int (UNIX timestamp).</li>
* <li>Path (optional)</li>
* <li>Domain (optional)</li>
* <li>Port (optional)</li>
* </ol>
*
* @access public
* @since 2.8.0
*
* @param string|array $data Raw cookie data.
* @param string $requested_url The URL which the cookie was set on, used for default 'domain' and 'port' values
*/
function __construct( $data, $requested_url = '' ) {
if ( $requested_url )
$arrURL = @parse_url( $requested_url );
if ( isset( $arrURL['host'] ) )
$this->domain = $arrURL['host'];
$this->path = isset( $arrURL['path'] ) ? $arrURL['path'] : '/';
if ( '/' != substr( $this->path, -1 ) )
$this->path = dirname( $this->path ) . '/';
if ( is_string( $data ) ) {
// Assume it's a header string direct from a previous request
$pairs = explode( ';', $data );
// Special handling for first pair; name=value. Also be careful of "=" in value
$name = trim( substr( $pairs[0], 0, strpos( $pairs[0], '=' ) ) );
$value = substr( $pairs[0], strpos( $pairs[0], '=' ) + 1 );
$this->name = $name;
$this->value = urldecode( $value );
array_shift( $pairs ); //Removes name=value from items.
// Set everything else as a property
foreach ( $pairs as $pair ) {
$pair = rtrim($pair);
if ( empty($pair) ) //Handles the cookie ending in ; which results in a empty final pair
continue;
list( $key, $val ) = strpos( $pair, '=' ) ? explode( '=', $pair ) : array( $pair, '' );
$key = strtolower( trim( $key ) );
if ( 'expires' == $key )
$val = strtotime( $val );
$this->$key = $val;
}
} else {
if ( !isset( $data['name'] ) )
return false;
// Set properties based directly on parameters
foreach ( array( 'name', 'value', 'path', 'domain', 'port' ) as $field ) {
if ( isset( $data[ $field ] ) )
$this->$field = $data[ $field ];
}
if ( isset( $data['expires'] ) )
$this->expires = is_int( $data['expires'] ) ? $data['expires'] : strtotime( $data['expires'] );
else
$this->expires = null;
}
}
/**
* Confirms that it's OK to send this cookie to the URL checked against.
*
* Decision is based on RFC 2109/2965, so look there for details on validity.
*
* @access public
* @since 2.8.0
*
* @param string $url URL you intend to send this cookie to
* @return boolean true if allowed, false otherwise.
*/
function test( $url ) {
if ( is_null( $this->name ) )
return false;
// Expires - if expired then nothing else matters
if ( isset( $this->expires ) && time() > $this->expires )
return false;
// Get details on the URL we're thinking about sending to
$url = parse_url( $url );
$url['port'] = isset( $url['port'] ) ? $url['port'] : ( 'https' == $url['scheme'] ? 443 : 80 );
$url['path'] = isset( $url['path'] ) ? $url['path'] : '/';
// Values to use for comparison against the URL
$path = isset( $this->path ) ? $this->path : '/';
$port = isset( $this->port ) ? $this->port : null;
$domain = isset( $this->domain ) ? strtolower( $this->domain ) : strtolower( $url['host'] );
if ( false === stripos( $domain, '.' ) )
$domain .= '.local';
// Host - very basic check that the request URL ends with the domain restriction (minus leading dot)
$domain = substr( $domain, 0, 1 ) == '.' ? substr( $domain, 1 ) : $domain;
if ( substr( $url['host'], -strlen( $domain ) ) != $domain )
return false;
// Port - supports "port-lists" in the format: "80,8000,8080"
if ( !empty( $port ) && !in_array( $url['port'], explode( ',', $port) ) )
return false;
// Path - request path must start with path restriction
if ( substr( $url['path'], 0, strlen( $path ) ) != $path )
return false;
return true;
}
/**
* Convert cookie name and value back to header string.
*
* @access public
* @since 2.8.0
*
* @return string Header encoded cookie name and value.
*/
function getHeaderValue() {
if ( ! isset( $this->name ) || ! isset( $this->value ) )
return '';
/**
* Filter the header-encoded cookie value.
*
* @since 3.4.0
*
* @param string $value The cookie value.
* @param string $name The cookie name.
*/
return $this->name . '=' . apply_filters( 'wp_http_cookie_value', $this->value, $this->name );
}
/**
* Retrieve cookie header for usage in the rest of the WordPress HTTP API.
*
* @access public
* @since 2.8.0
*
* @return string
*/
function getFullHeader() {
return 'Cookie: ' . $this->getHeaderValue();
}
}
/**
* Implementation for deflate and gzip transfer encodings.
*
* Includes RFC 1950, RFC 1951, and RFC 1952.
*
* @since 2.8.0
* @package WordPress
* @subpackage HTTP
*/
class WP_Http_Encoding {
/**
* Compress raw string using the deflate format.
*
* Supports the RFC 1951 standard.
*
* @since 2.8.0
*
* @param string $raw String to compress.
* @param int $level Optional, default is 9. Compression level, 9 is highest.
* @param string $supports Optional, not used. When implemented it will choose the right compression based on what the server supports.
* @return string|bool False on failure.
*/
public static function compress( $raw, $level = 9, $supports = null ) {
return gzdeflate( $raw, $level );
}
/**
* Decompression of deflated string.
*
* Will attempt to decompress using the RFC 1950 standard, and if that fails
* then the RFC 1951 standard deflate will be attempted. Finally, the RFC
* 1952 standard gzip decode will be attempted. If all fail, then the
* original compressed string will be returned.
*
* @since 2.8.0
*
* @param string $compressed String to decompress.
* @param int $length The optional length of the compressed data.
* @return string|bool False on failure.
*/
public static function decompress( $compressed, $length = null ) {
if ( empty($compressed) )
return $compressed;
if ( false !== ( $decompressed = @gzinflate( $compressed ) ) )
return $decompressed;
if ( false !== ( $decompressed = WP_Http_Encoding::compatible_gzinflate( $compressed ) ) )
return $decompressed;
if ( false !== ( $decompressed = @gzuncompress( $compressed ) ) )
return $decompressed;
if ( function_exists('gzdecode') ) {
$decompressed = @gzdecode( $compressed );
if ( false !== $decompressed )
return $decompressed;
}
return $compressed;
}
/**
* Decompression of deflated string while staying compatible with the majority of servers.
*
* Certain Servers will return deflated data with headers which PHP's gzinflate()
* function cannot handle out of the box. The following function has been created from
* various snippets on the gzinflate() PHP documentation.
*
* Warning: Magic numbers within. Due to the potential different formats that the compressed
* data may be returned in, some "magic offsets" are needed to ensure proper decompression
* takes place. For a simple progmatic way to determine the magic offset in use, see:
* http://core.trac.wordpress.org/ticket/18273
*
* @since 2.8.1
* @link http://core.trac.wordpress.org/ticket/18273
* @link http://au2.php.net/manual/en/function.gzinflate.php#70875
* @link http://au2.php.net/manual/en/function.gzinflate.php#77336
*
* @param string $gzData String to decompress.
* @return string|bool False on failure.
*/
public static function compatible_gzinflate($gzData) {
// Compressed data might contain a full header, if so strip it for gzinflate()
if ( substr($gzData, 0, 3) == "\x1f\x8b\x08" ) {
$i = 10;
$flg = ord( substr($gzData, 3, 1) );
if ( $flg > 0 ) {
if ( $flg & 4 ) {
list($xlen) = unpack('v', substr($gzData, $i, 2) );
$i = $i + 2 + $xlen;
}
if ( $flg & 8 )
$i = strpos($gzData, "\0", $i) + 1;
if ( $flg & 16 )
$i = strpos($gzData, "\0", $i) + 1;
if ( $flg & 2 )
$i = $i + 2;
}
$decompressed = @gzinflate( substr($gzData, $i, -8) );
if ( false !== $decompressed )
return $decompressed;
}
// Compressed data from java.util.zip.Deflater amongst others.
$decompressed = @gzinflate( substr($gzData, 2) );
if ( false !== $decompressed )
return $decompressed;
return false;
}
/**
* What encoding types to accept and their priority values.
*
* @since 2.8.0
*
* @return string Types of encoding to accept.
*/
public static function accept_encoding( $url, $args ) {
$type = array();
$compression_enabled = WP_Http_Encoding::is_available();
if ( ! $args['decompress'] ) // decompression specifically disabled
$compression_enabled = false;
elseif ( $args['stream'] ) // disable when streaming to file
$compression_enabled = false;
elseif ( isset( $args['limit_response_size'] ) ) // If only partial content is being requested, we won't be able to decompress it
$compression_enabled = false;
if ( $compression_enabled ) {
if ( function_exists( 'gzinflate' ) )
$type[] = 'deflate;q=1.0';
if ( function_exists( 'gzuncompress' ) )
$type[] = 'compress;q=0.5';
if ( function_exists( 'gzdecode' ) )
$type[] = 'gzip;q=0.5';
}
/**
* Filter the allowed encoding types.
*
* @since 3.6.0
*
* @param array $type Encoding types allowed. Accepts 'gzinflate',
* 'gzuncompress', 'gzdecode'.
* @param string $url URL of the HTTP request.
* @param array $args HTTP request arguments.
*/
$type = apply_filters( 'wp_http_accept_encoding', $type, $url, $args );
return implode(', ', $type);
}
/**
* What encoding the content used when it was compressed to send in the headers.
*
* @since 2.8.0
*
* @return string Content-Encoding string to send in the header.
*/
public static function content_encoding() {
return 'deflate';
}
/**
* Whether the content be decoded based on the headers.
*
* @since 2.8.0
*
* @param array|string $headers All of the available headers.
* @return bool
*/
public static function should_decode($headers) {
if ( is_array( $headers ) ) {
if ( array_key_exists('content-encoding', $headers) && ! empty( $headers['content-encoding'] ) )
return true;
} else if ( is_string( $headers ) ) {
return ( stripos($headers, 'content-encoding:') !== false );
}
return false;
}
/**
* Whether decompression and compression are supported by the PHP version.
*
* Each function is tested instead of checking for the zlib extension, to
* ensure that the functions all exist in the PHP version and aren't
* disabled.
*
* @since 2.8.0
*
* @return bool
*/
public static function is_available() {
return ( function_exists('gzuncompress') || function_exists('gzdeflate') || function_exists('gzinflate') );
}
}
| PHP |
<?php
/**
* Sets up the default filters and actions for Multisite.
*
* If you need to remove a default hook, this file will give you the priority
* for which to use to remove the hook.
*
* Not all of the Multisite default hooks are found in ms-default-filters.php
*
* @package WordPress
* @subpackage Multisite
* @see default-filters.php
* @since 3.0.0
*/
// Users
add_filter( 'wpmu_validate_user_signup', 'signup_nonce_check' );
add_action( 'init', 'maybe_add_existing_user_to_blog' );
add_action( 'wpmu_new_user', 'newuser_notify_siteadmin' );
add_action( 'wpmu_activate_user', 'add_new_user_to_blog', 10, 3 );
add_filter( 'sanitize_user', 'strtolower' );
// Blogs
add_filter( 'wpmu_validate_blog_signup', 'signup_nonce_check' );
add_action( 'wpmu_new_blog', 'wpmu_log_new_registrations', 10, 2 );
add_action( 'wpmu_new_blog', 'newblog_notify_siteadmin', 10, 2 );
// Register Nonce
add_action( 'signup_hidden_fields', 'signup_nonce_fields' );
// Template
add_action( 'template_redirect', 'maybe_redirect_404' );
add_filter( 'allowed_redirect_hosts', 'redirect_this_site' );
// Administration
add_filter( 'term_id_filter', 'global_terms', 10, 2 );
add_action( 'publish_post', 'update_posts_count' );
add_action( 'delete_post', '_update_blog_date_on_post_delete' );
add_action( 'transition_post_status', '_update_blog_date_on_post_publish', 10, 3 );
// Counts
add_action( 'admin_init', 'wp_schedule_update_network_counts');
add_action( 'update_network_counts', 'wp_update_network_counts');
foreach ( array( 'user_register', 'deleted_user', 'wpmu_new_user', 'make_spam_user', 'make_ham_user' ) as $action )
add_action( $action, 'wp_maybe_update_network_user_counts' );
foreach ( array( 'make_spam_blog', 'make_ham_blog', 'archive_blog', 'unarchive_blog', 'make_delete_blog', 'make_undelete_blog' ) as $action )
add_action( $action, 'wp_maybe_update_network_site_counts' );
unset( $action );
// Files
add_filter( 'wp_upload_bits', 'upload_is_file_too_big' );
add_filter( 'import_upload_size_limit', 'fix_import_form_size' );
add_filter( 'upload_mimes', 'check_upload_mimes' );
add_filter( 'upload_size_limit', 'upload_size_limit_filter' );
add_action( 'upload_ui_over_quota', 'multisite_over_quota_message' );
// Mail
add_action( 'phpmailer_init', 'fix_phpmailer_messageid' );
// Disable somethings by default for multisite
add_filter( 'enable_update_services_configuration', '__return_false' );
if ( ! defined('POST_BY_EMAIL') || ! POST_BY_EMAIL ) // back compat constant.
add_filter( 'enable_post_by_email_configuration', '__return_false' );
if ( ! defined('EDIT_ANY_USER') || ! EDIT_ANY_USER ) // back compat constant.
add_filter( 'enable_edit_any_user_configuration', '__return_false' );
add_filter( 'force_filtered_html_on_import', '__return_true' );
// WP_HOME and WP_SITEURL should not have any effect in MS
remove_filter( 'option_siteurl', '_config_wp_siteurl' );
remove_filter( 'option_home', '_config_wp_home' );
// If the network upgrade hasn't run yet, assume ms-files.php rewriting is used.
add_filter( 'default_site_option_ms_files_rewriting', '__return_true' );
// Whitelist multisite domains for HTTP requests
add_filter( 'http_request_host_is_external', 'ms_allowed_http_request_hosts', 20, 2 );
| PHP |
<?php
/**
* These functions are needed to load WordPress.
*
* @internal This file must be parsable by PHP4.
*
* @package WordPress
*/
/**
* Turn register globals off.
*
* @access private
* @since 2.1.0
* @return null Will return null if register_globals PHP directive was disabled
*/
function wp_unregister_GLOBALS() {
if ( !ini_get( 'register_globals' ) )
return;
if ( isset( $_REQUEST['GLOBALS'] ) )
die( 'GLOBALS overwrite attempt detected' );
// Variables that shouldn't be unset
$no_unset = array( 'GLOBALS', '_GET', '_POST', '_COOKIE', '_REQUEST', '_SERVER', '_ENV', '_FILES', 'table_prefix' );
$input = array_merge( $_GET, $_POST, $_COOKIE, $_SERVER, $_ENV, $_FILES, isset( $_SESSION ) && is_array( $_SESSION ) ? $_SESSION : array() );
foreach ( $input as $k => $v )
if ( !in_array( $k, $no_unset ) && isset( $GLOBALS[$k] ) ) {
unset( $GLOBALS[$k] );
}
}
/**
* Fix $_SERVER variables for various setups.
*
* @access private
* @since 3.0.0
*/
function wp_fix_server_vars() {
global $PHP_SELF;
$default_server_values = array(
'SERVER_SOFTWARE' => '',
'REQUEST_URI' => '',
);
$_SERVER = array_merge( $default_server_values, $_SERVER );
// Fix for IIS when running with PHP ISAPI
if ( empty( $_SERVER['REQUEST_URI'] ) || ( php_sapi_name() != 'cgi-fcgi' && preg_match( '/^Microsoft-IIS\//', $_SERVER['SERVER_SOFTWARE'] ) ) ) {
// IIS Mod-Rewrite
if ( isset( $_SERVER['HTTP_X_ORIGINAL_URL'] ) ) {
$_SERVER['REQUEST_URI'] = $_SERVER['HTTP_X_ORIGINAL_URL'];
}
// IIS Isapi_Rewrite
else if ( isset( $_SERVER['HTTP_X_REWRITE_URL'] ) ) {
$_SERVER['REQUEST_URI'] = $_SERVER['HTTP_X_REWRITE_URL'];
} else {
// Use ORIG_PATH_INFO if there is no PATH_INFO
if ( !isset( $_SERVER['PATH_INFO'] ) && isset( $_SERVER['ORIG_PATH_INFO'] ) )
$_SERVER['PATH_INFO'] = $_SERVER['ORIG_PATH_INFO'];
// Some IIS + PHP configurations puts the script-name in the path-info (No need to append it twice)
if ( isset( $_SERVER['PATH_INFO'] ) ) {
if ( $_SERVER['PATH_INFO'] == $_SERVER['SCRIPT_NAME'] )
$_SERVER['REQUEST_URI'] = $_SERVER['PATH_INFO'];
else
$_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'] . $_SERVER['PATH_INFO'];
}
// Append the query string if it exists and isn't null
if ( ! empty( $_SERVER['QUERY_STRING'] ) ) {
$_SERVER['REQUEST_URI'] .= '?' . $_SERVER['QUERY_STRING'];
}
}
}
// Fix for PHP as CGI hosts that set SCRIPT_FILENAME to something ending in php.cgi for all requests
if ( isset( $_SERVER['SCRIPT_FILENAME'] ) && ( strpos( $_SERVER['SCRIPT_FILENAME'], 'php.cgi' ) == strlen( $_SERVER['SCRIPT_FILENAME'] ) - 7 ) )
$_SERVER['SCRIPT_FILENAME'] = $_SERVER['PATH_TRANSLATED'];
// Fix for Dreamhost and other PHP as CGI hosts
if ( strpos( $_SERVER['SCRIPT_NAME'], 'php.cgi' ) !== false )
unset( $_SERVER['PATH_INFO'] );
// Fix empty PHP_SELF
$PHP_SELF = $_SERVER['PHP_SELF'];
if ( empty( $PHP_SELF ) )
$_SERVER['PHP_SELF'] = $PHP_SELF = preg_replace( '/(\?.*)?$/', '', $_SERVER["REQUEST_URI"] );
}
/**
* Check for the required PHP version, and the MySQL extension or a database drop-in.
*
* Dies if requirements are not met.
*
* @access private
* @since 3.0.0
*/
function wp_check_php_mysql_versions() {
global $required_php_version, $wp_version;
$php_version = phpversion();
if ( version_compare( $required_php_version, $php_version, '>' ) ) {
wp_load_translations_early();
header( 'Content-Type: text/html; charset=utf-8' );
die( sprintf( __( 'Your server is running PHP version %1$s but WordPress %2$s requires at least %3$s.' ), $php_version, $wp_version, $required_php_version ) );
}
if ( ! extension_loaded( 'mysql' ) && ! extension_loaded( 'mysqli' ) && ! file_exists( WP_CONTENT_DIR . '/db.php' ) ) {
wp_load_translations_early();
header( 'Content-Type: text/html; charset=utf-8' );
die( __( 'Your PHP installation appears to be missing the MySQL extension which is required by WordPress.' ) );
}
}
/**
* Don't load all of WordPress when handling a favicon.ico request.
* Instead, send the headers for a zero-length favicon and bail.
*
* @since 3.0.0
*/
function wp_favicon_request() {
if ( '/favicon.ico' == $_SERVER['REQUEST_URI'] ) {
header('Content-Type: image/vnd.microsoft.icon');
header('Content-Length: 0');
exit;
}
}
/**
* Dies with a maintenance message when conditions are met.
*
* Checks for a file in the WordPress root directory named ".maintenance".
* This file will contain the variable $upgrading, set to the time the file
* was created. If the file was created less than 10 minutes ago, WordPress
* enters maintenance mode and displays a message.
*
* The default message can be replaced by using a drop-in (maintenance.php in
* the wp-content directory).
*
* @access private
* @since 3.0.0
*/
function wp_maintenance() {
if ( !file_exists( ABSPATH . '.maintenance' ) || defined( 'WP_INSTALLING' ) )
return;
global $upgrading;
include( ABSPATH . '.maintenance' );
// If the $upgrading timestamp is older than 10 minutes, don't die.
if ( ( time() - $upgrading ) >= 600 )
return;
if ( file_exists( WP_CONTENT_DIR . '/maintenance.php' ) ) {
require_once( WP_CONTENT_DIR . '/maintenance.php' );
die();
}
wp_load_translations_early();
$protocol = $_SERVER["SERVER_PROTOCOL"];
if ( 'HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol )
$protocol = 'HTTP/1.0';
header( "$protocol 503 Service Unavailable", true, 503 );
header( 'Content-Type: text/html; charset=utf-8' );
header( 'Retry-After: 600' );
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"<?php if ( is_rtl() ) echo ' dir="rtl"'; ?>>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><?php _e( 'Maintenance' ); ?></title>
</head>
<body>
<h1><?php _e( 'Briefly unavailable for scheduled maintenance. Check back in a minute.' ); ?></h1>
</body>
</html>
<?php
die();
}
/**
* PHP 5 standard microtime start capture.
*
* @access private
* @since 0.71
* @global float $timestart Seconds from when function is called.
* @return bool Always returns true.
*/
function timer_start() {
global $timestart;
$timestart = microtime( true );
return true;
}
/**
* Retrieve or display the time from the page start to when function is called.
*
* @since 0.71
*
* @global float $timestart Seconds from when timer_start() is called.
* @global float $timeend Seconds from when function is called.
*
* @param int $display Whether to echo or return the results. Accepts 0|false for return,
* 1|true for echo. Default 0|false.
* @param int $precision The number of digits from the right of the decimal to display.
* Default 3.
* @return string The "second.microsecond" finished time calculation. The number is formatted
* for human consumption, both localized and rounded.
*/
function timer_stop( $display = 0, $precision = 3 ) {
global $timestart, $timeend;
$timeend = microtime( true );
$timetotal = $timeend - $timestart;
$r = ( function_exists( 'number_format_i18n' ) ) ? number_format_i18n( $timetotal, $precision ) : number_format( $timetotal, $precision );
if ( $display )
echo $r;
return $r;
}
/**
* Sets PHP error handling and handles WordPress debug mode.
*
* Uses three constants: WP_DEBUG, WP_DEBUG_DISPLAY, and WP_DEBUG_LOG. All three can be
* defined in wp-config.php. Example: <code> define( 'WP_DEBUG', true ); </code>
*
* WP_DEBUG_DISPLAY and WP_DEBUG_LOG perform no function unless WP_DEBUG is true.
* WP_DEBUG defaults to false.
*
* When WP_DEBUG is true, all PHP notices are reported. WordPress will also display
* notices, including one when a deprecated WordPress function, function argument,
* or file is used. Deprecated code may be removed from a later version.
*
* It is strongly recommended that plugin and theme developers use WP_DEBUG in their
* development environments.
*
* When WP_DEBUG_DISPLAY is true, WordPress will force errors to be displayed.
* WP_DEBUG_DISPLAY defaults to true. Defining it as null prevents WordPress from
* changing the global configuration setting. Defining WP_DEBUG_DISPLAY as false
* will force errors to be hidden.
*
* When WP_DEBUG_LOG is true, errors will be logged to wp-content/debug.log.
* WP_DEBUG_LOG defaults to false.
*
* Errors are never displayed for XML-RPC requests.
*
* @access private
* @since 3.0.0
*/
function wp_debug_mode() {
if ( WP_DEBUG ) {
error_reporting( E_ALL );
if ( WP_DEBUG_DISPLAY )
ini_set( 'display_errors', 1 );
elseif ( null !== WP_DEBUG_DISPLAY )
ini_set( 'display_errors', 0 );
if ( WP_DEBUG_LOG ) {
ini_set( 'log_errors', 1 );
ini_set( 'error_log', WP_CONTENT_DIR . '/debug.log' );
}
} else {
error_reporting( E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_ERROR | E_WARNING | E_PARSE | E_USER_ERROR | E_USER_WARNING | E_RECOVERABLE_ERROR );
}
if ( defined( 'XMLRPC_REQUEST' ) )
ini_set( 'display_errors', 0 );
}
/**
* Sets the location of the language directory.
*
* To set directory manually, define <code>WP_LANG_DIR</code> in wp-config.php.
*
* If the language directory exists within WP_CONTENT_DIR, that is used.
* Otherwise if the language directory exists within WPINC, that's used.
* Finally, if neither of the preceding directories are found,
* WP_CONTENT_DIR/languages is used.
*
* The WP_LANG_DIR constant was introduced in 2.1.0.
*
* @access private
* @since 3.0.0
*/
function wp_set_lang_dir() {
if ( !defined( 'WP_LANG_DIR' ) ) {
if ( file_exists( WP_CONTENT_DIR . '/languages' ) && @is_dir( WP_CONTENT_DIR . '/languages' ) || !@is_dir(ABSPATH . WPINC . '/languages') ) {
define( 'WP_LANG_DIR', WP_CONTENT_DIR . '/languages' ); // no leading slash, no trailing slash, full path, not relative to ABSPATH
if ( !defined( 'LANGDIR' ) ) {
// Old static relative path maintained for limited backwards compatibility - won't work in some cases
define( 'LANGDIR', 'wp-content/languages' );
}
} else {
define( 'WP_LANG_DIR', ABSPATH . WPINC . '/languages' ); // no leading slash, no trailing slash, full path, not relative to ABSPATH
if ( !defined( 'LANGDIR' ) ) {
// Old relative path maintained for backwards compatibility
define( 'LANGDIR', WPINC . '/languages' );
}
}
}
}
/**
* Load the correct database class file.
*
* This function is used to load the database class file either at runtime or by
* wp-admin/setup-config.php. We must globalize $wpdb to ensure that it is
* defined globally by the inline code in wp-db.php.
*
* @since 2.5.0
* @global $wpdb WordPress Database Object
*/
function require_wp_db() {
global $wpdb;
require_once( ABSPATH . WPINC . '/wp-db.php' );
if ( file_exists( WP_CONTENT_DIR . '/db.php' ) )
require_once( WP_CONTENT_DIR . '/db.php' );
if ( isset( $wpdb ) )
return;
$wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST );
}
/**
* Sets the database table prefix and the format specifiers for database table columns.
*
* Columns not listed here default to %s.
*
* @see wpdb::$field_types Since 2.8.0
* @see wpdb::prepare()
* @see wpdb::insert()
* @see wpdb::update()
* @see wpdb::set_prefix()
*
* @access private
* @since 3.0.0
*/
function wp_set_wpdb_vars() {
global $wpdb, $table_prefix;
if ( !empty( $wpdb->error ) )
dead_db();
$wpdb->field_types = array( 'post_author' => '%d', 'post_parent' => '%d', 'menu_order' => '%d', 'term_id' => '%d', 'term_group' => '%d', 'term_taxonomy_id' => '%d',
'parent' => '%d', 'count' => '%d','object_id' => '%d', 'term_order' => '%d', 'ID' => '%d', 'comment_ID' => '%d', 'comment_post_ID' => '%d', 'comment_parent' => '%d',
'user_id' => '%d', 'link_id' => '%d', 'link_owner' => '%d', 'link_rating' => '%d', 'option_id' => '%d', 'blog_id' => '%d', 'meta_id' => '%d', 'post_id' => '%d',
'user_status' => '%d', 'umeta_id' => '%d', 'comment_karma' => '%d', 'comment_count' => '%d',
// multisite:
'active' => '%d', 'cat_id' => '%d', 'deleted' => '%d', 'lang_id' => '%d', 'mature' => '%d', 'public' => '%d', 'site_id' => '%d', 'spam' => '%d',
);
$prefix = $wpdb->set_prefix( $table_prefix );
if ( is_wp_error( $prefix ) ) {
wp_load_translations_early();
wp_die( __( '<strong>ERROR</strong>: <code>$table_prefix</code> in <code>wp-config.php</code> can only contain numbers, letters, and underscores.' ) );
}
}
/**
* Access/Modify private global variable $_wp_using_ext_object_cache
*
* Toggle $_wp_using_ext_object_cache on and off without directly touching global
*
* @since 3.7.0
*
* @param bool $using Whether external object cache is being used
* @return bool The current 'using' setting
*/
function wp_using_ext_object_cache( $using = null ) {
global $_wp_using_ext_object_cache;
$current_using = $_wp_using_ext_object_cache;
if ( null !== $using )
$_wp_using_ext_object_cache = $using;
return $current_using;
}
/**
* Starts the WordPress object cache.
*
* If an object-cache.php file exists in the wp-content directory,
* it uses that drop-in as an external object cache.
*
* @access private
* @since 3.0.0
*/
function wp_start_object_cache() {
global $blog_id;
$first_init = false;
if ( ! function_exists( 'wp_cache_init' ) ) {
if ( file_exists( WP_CONTENT_DIR . '/object-cache.php' ) ) {
require_once ( WP_CONTENT_DIR . '/object-cache.php' );
if ( function_exists( 'wp_cache_init' ) )
wp_using_ext_object_cache( true );
}
$first_init = true;
} else if ( ! wp_using_ext_object_cache() && file_exists( WP_CONTENT_DIR . '/object-cache.php' ) ) {
// Sometimes advanced-cache.php can load object-cache.php before it is loaded here.
// This breaks the function_exists check above and can result in $_wp_using_ext_object_cache
// being set incorrectly. Double check if an external cache exists.
wp_using_ext_object_cache( true );
}
if ( ! wp_using_ext_object_cache() )
require_once ( ABSPATH . WPINC . '/cache.php' );
// If cache supports reset, reset instead of init if already initialized.
// Reset signals to the cache that global IDs have changed and it may need to update keys
// and cleanup caches.
if ( ! $first_init && function_exists( 'wp_cache_switch_to_blog' ) )
wp_cache_switch_to_blog( $blog_id );
elseif ( function_exists( 'wp_cache_init' ) )
wp_cache_init();
if ( function_exists( 'wp_cache_add_global_groups' ) ) {
wp_cache_add_global_groups( array( 'users', 'userlogins', 'usermeta', 'user_meta', 'site-transient', 'site-options', 'site-lookup', 'blog-lookup', 'blog-details', 'rss', 'global-posts', 'blog-id-cache' ) );
wp_cache_add_non_persistent_groups( array( 'comment', 'counts', 'plugins' ) );
}
}
/**
* Redirects to the installer if WordPress is not installed.
*
* Dies with an error message when multisite is enabled.
*
* @access private
* @since 3.0.0
*/
function wp_not_installed() {
if ( is_multisite() ) {
if ( ! is_blog_installed() && ! defined( 'WP_INSTALLING' ) )
wp_die( __( 'The site you have requested is not installed properly. Please contact the system administrator.' ) );
} elseif ( ! is_blog_installed() && false === strpos( $_SERVER['PHP_SELF'], 'install.php' ) && !defined( 'WP_INSTALLING' ) ) {
require( ABSPATH . WPINC . '/kses.php' );
require( ABSPATH . WPINC . '/pluggable.php' );
require( ABSPATH . WPINC . '/formatting.php' );
$link = wp_guess_url() . '/wp-admin/install.php';
wp_redirect( $link );
die();
}
}
/**
* Returns array of must-use plugin files to be included in global scope.
*
* The default directory is wp-content/mu-plugins. To change the default directory
* manually, define <code>WPMU_PLUGIN_DIR</code> and <code>WPMU_PLUGIN_URL</code>
* in wp-config.php.
*
* @access private
* @since 3.0.0
* @return array Files to include
*/
function wp_get_mu_plugins() {
$mu_plugins = array();
if ( !is_dir( WPMU_PLUGIN_DIR ) )
return $mu_plugins;
if ( ! $dh = opendir( WPMU_PLUGIN_DIR ) )
return $mu_plugins;
while ( ( $plugin = readdir( $dh ) ) !== false ) {
if ( substr( $plugin, -4 ) == '.php' )
$mu_plugins[] = WPMU_PLUGIN_DIR . '/' . $plugin;
}
closedir( $dh );
sort( $mu_plugins );
return $mu_plugins;
}
/**
* Returns array of plugin files to be included in global scope.
*
* The default directory is wp-content/plugins. To change the default directory
* manually, define <code>WP_PLUGIN_DIR</code> and <code>WP_PLUGIN_URL</code>
* in wp-config.php.
*
* @access private
* @since 3.0.0
* @return array Files to include
*/
function wp_get_active_and_valid_plugins() {
$plugins = array();
$active_plugins = (array) get_option( 'active_plugins', array() );
// Check for hacks file if the option is enabled
if ( get_option( 'hack_file' ) && file_exists( ABSPATH . 'my-hacks.php' ) ) {
_deprecated_file( 'my-hacks.php', '1.5' );
array_unshift( $plugins, ABSPATH . 'my-hacks.php' );
}
if ( empty( $active_plugins ) || defined( 'WP_INSTALLING' ) )
return $plugins;
$network_plugins = is_multisite() ? wp_get_active_network_plugins() : false;
foreach ( $active_plugins as $plugin ) {
if ( ! validate_file( $plugin ) // $plugin must validate as file
&& '.php' == substr( $plugin, -4 ) // $plugin must end with '.php'
&& file_exists( WP_PLUGIN_DIR . '/' . $plugin ) // $plugin must exist
// not already included as a network plugin
&& ( ! $network_plugins || ! in_array( WP_PLUGIN_DIR . '/' . $plugin, $network_plugins ) )
)
$plugins[] = WP_PLUGIN_DIR . '/' . $plugin;
}
return $plugins;
}
/**
* Sets internal encoding using mb_internal_encoding().
*
* In most cases the default internal encoding is latin1, which is of no use,
* since we want to use the mb_ functions for utf-8 strings.
*
* @access private
* @since 3.0.0
*/
function wp_set_internal_encoding() {
if ( function_exists( 'mb_internal_encoding' ) ) {
$charset = get_option( 'blog_charset' );
if ( ! $charset || ! @mb_internal_encoding( $charset ) )
mb_internal_encoding( 'UTF-8' );
}
}
/**
* Add magic quotes to $_GET, $_POST, $_COOKIE, and $_SERVER.
*
* Also forces $_REQUEST to be $_GET + $_POST. If $_SERVER, $_COOKIE,
* or $_ENV are needed, use those superglobals directly.
*
* @access private
* @since 3.0.0
*/
function wp_magic_quotes() {
// If already slashed, strip.
if ( get_magic_quotes_gpc() ) {
$_GET = stripslashes_deep( $_GET );
$_POST = stripslashes_deep( $_POST );
$_COOKIE = stripslashes_deep( $_COOKIE );
}
// Escape with wpdb.
$_GET = add_magic_quotes( $_GET );
$_POST = add_magic_quotes( $_POST );
$_COOKIE = add_magic_quotes( $_COOKIE );
$_SERVER = add_magic_quotes( $_SERVER );
// Force REQUEST to be GET + POST.
$_REQUEST = array_merge( $_GET, $_POST );
}
/**
* Runs just before PHP shuts down execution.
*
* @access private
* @since 1.2.0
*/
function shutdown_action_hook() {
/**
* Fires just before PHP shuts down execution.
*
* @since 1.2.0
*/
do_action( 'shutdown' );
wp_cache_close();
}
/**
* Copy an object.
*
* @since 2.7.0
* @deprecated 3.2
*
* @param object $object The object to clone
* @return object The cloned object
*/
function wp_clone( $object ) {
// Use parens for clone to accommodate PHP 4. See #17880
return clone( $object );
}
/**
* Whether the current request is for a network or blog admin page
*
* Does not inform on whether the user is an admin! Use capability checks to
* tell if the user should be accessing a section or not.
*
* @since 1.5.1
*
* @return bool True if inside WordPress administration pages.
*/
function is_admin() {
if ( isset( $GLOBALS['current_screen'] ) )
return $GLOBALS['current_screen']->in_admin();
elseif ( defined( 'WP_ADMIN' ) )
return WP_ADMIN;
return false;
}
/**
* Whether the current request is for a blog admin screen /wp-admin/
*
* Does not inform on whether the user is a blog admin! Use capability checks to
* tell if the user should be accessing a section or not.
*
* @since 3.1.0
*
* @return bool True if inside WordPress network administration pages.
*/
function is_blog_admin() {
if ( isset( $GLOBALS['current_screen'] ) )
return $GLOBALS['current_screen']->in_admin( 'site' );
elseif ( defined( 'WP_BLOG_ADMIN' ) )
return WP_BLOG_ADMIN;
return false;
}
/**
* Whether the current request is for a network admin screen /wp-admin/network/
*
* Does not inform on whether the user is a network admin! Use capability checks to
* tell if the user should be accessing a section or not.
*
* @since 3.1.0
*
* @return bool True if inside WordPress network administration pages.
*/
function is_network_admin() {
if ( isset( $GLOBALS['current_screen'] ) )
return $GLOBALS['current_screen']->in_admin( 'network' );
elseif ( defined( 'WP_NETWORK_ADMIN' ) )
return WP_NETWORK_ADMIN;
return false;
}
/**
* Whether the current request is for a user admin screen /wp-admin/user/
*
* Does not inform on whether the user is an admin! Use capability checks to
* tell if the user should be accessing a section or not.
*
* @since 3.1.0
*
* @return bool True if inside WordPress user administration pages.
*/
function is_user_admin() {
if ( isset( $GLOBALS['current_screen'] ) )
return $GLOBALS['current_screen']->in_admin( 'user' );
elseif ( defined( 'WP_USER_ADMIN' ) )
return WP_USER_ADMIN;
return false;
}
/**
* Whether Multisite support is enabled
*
* @since 3.0.0
*
* @return bool True if multisite is enabled, false otherwise.
*/
function is_multisite() {
if ( defined( 'MULTISITE' ) )
return MULTISITE;
if ( defined( 'SUBDOMAIN_INSTALL' ) || defined( 'VHOST' ) || defined( 'SUNRISE' ) )
return true;
return false;
}
/**
* Retrieve the current blog id
*
* @since 3.1.0
*
* @return int Blog id
*/
function get_current_blog_id() {
global $blog_id;
return absint($blog_id);
}
/**
* Attempts an early load of translations.
*
* Used for errors encountered during the initial loading process, before the locale has been
* properly detected and loaded.
*
* Designed for unusual load sequences (like setup-config.php) or for when the script will then
* terminate with an error, otherwise there is a risk that a file can be double-included.
*
* @since 3.4.0
* @access private
*/
function wp_load_translations_early() {
global $text_direction, $wp_locale;
static $loaded = false;
if ( $loaded )
return;
$loaded = true;
if ( function_exists( 'did_action' ) && did_action( 'init' ) )
return;
// We need $wp_local_package
require ABSPATH . WPINC . '/version.php';
// Translation and localization
require_once ABSPATH . WPINC . '/pomo/mo.php';
require_once ABSPATH . WPINC . '/l10n.php';
require_once ABSPATH . WPINC . '/locale.php';
// General libraries
require_once ABSPATH . WPINC . '/plugin.php';
$locales = $locations = array();
while ( true ) {
if ( defined( 'WPLANG' ) ) {
if ( '' == WPLANG )
break;
$locales[] = WPLANG;
}
if ( isset( $wp_local_package ) )
$locales[] = $wp_local_package;
if ( ! $locales )
break;
if ( defined( 'WP_LANG_DIR' ) && @is_dir( WP_LANG_DIR ) )
$locations[] = WP_LANG_DIR;
if ( defined( 'WP_CONTENT_DIR' ) && @is_dir( WP_CONTENT_DIR . '/languages' ) )
$locations[] = WP_CONTENT_DIR . '/languages';
if ( @is_dir( ABSPATH . 'wp-content/languages' ) )
$locations[] = ABSPATH . 'wp-content/languages';
if ( @is_dir( ABSPATH . WPINC . '/languages' ) )
$locations[] = ABSPATH . WPINC . '/languages';
if ( ! $locations )
break;
$locations = array_unique( $locations );
foreach ( $locales as $locale ) {
foreach ( $locations as $location ) {
if ( file_exists( $location . '/' . $locale . '.mo' ) ) {
load_textdomain( 'default', $location . '/' . $locale . '.mo' );
if ( defined( 'WP_SETUP_CONFIG' ) && file_exists( $location . '/admin-' . $locale . '.mo' ) )
load_textdomain( 'default', $location . '/admin-' . $locale . '.mo' );
break 2;
}
}
}
break;
}
$wp_locale = new WP_Locale();
}
| PHP |
<?php
/**
* The plugin API is located in this file, which allows for creating actions
* and filters and hooking functions, and methods. The functions or methods will
* then be run when the action or filter is called.
*
* The API callback examples reference functions, but can be methods of classes.
* To hook methods, you'll need to pass an array one of two ways.
*
* Any of the syntaxes explained in the PHP documentation for the
* {@link http://us2.php.net/manual/en/language.pseudo-types.php#language.types.callback 'callback'}
* type are valid.
*
* Also see the {@link http://codex.wordpress.org/Plugin_API Plugin API} for
* more information and examples on how to use a lot of these functions.
*
* @package WordPress
* @subpackage Plugin
* @since 1.5.0
*/
// Initialize the filter globals.
global $wp_filter, $wp_actions, $merged_filters, $wp_current_filter;
if ( ! isset( $wp_filter ) )
$wp_filter = array();
if ( ! isset( $wp_actions ) )
$wp_actions = array();
if ( ! isset( $merged_filters ) )
$merged_filters = array();
if ( ! isset( $wp_current_filter ) )
$wp_current_filter = array();
/**
* Hooks a function or method to a specific filter action.
*
* WordPress offers filter hooks to allow plugins to modify
* various types of internal data at runtime.
*
* A plugin can modify data by binding a callback to a filter hook. When the filter
* is later applied, each bound callback is run in order of priority, and given
* the opportunity to modify a value by returning a new value.
*
* The following example shows how a callback function is bound to a filter hook.
* Note that $example is passed to the callback, (maybe) modified, then returned:
*
* <code>
* function example_callback( $example ) {
* // Maybe modify $example in some way
* return $example;
* }
* add_filter( 'example_filter', 'example_callback' );
* </code>
*
* Since WordPress 1.5.1, bound callbacks can take as many arguments as are
* passed as parameters in the corresponding apply_filters() call. The $accepted_args
* parameter allows for calling functions only when the number of args match.
*
* <strong>Note:</strong> the function will return true whether or not the callback
* is valid. It is up to you to take care. This is done for optimization purposes,
* so everything is as quick as possible.
*
* @global array $wp_filter A multidimensional array of all hooks and the callbacks hooked to them.
* @global array $merged_filters Tracks the tags that need to be merged for later. If the hook is added, it doesn't need to run through that process.
*
* @since 0.71
*
* @param string $tag The name of the filter to hook the $function_to_add callback to.
* @param callback $function_to_add The callback to be run when the filter is applied.
* @param int $priority (optional) The order in which the functions associated with a particular action are executed. Lower numbers correspond with earlier execution, and functions with the same priority are executed in the order in which they were added to the action.
* Default 10.
* @param int $accepted_args (optional) The number of arguments the function accepts.
* Default 1.
* @return boolean true
*/
function add_filter( $tag, $function_to_add, $priority = 10, $accepted_args = 1 ) {
global $wp_filter, $merged_filters;
$idx = _wp_filter_build_unique_id($tag, $function_to_add, $priority);
$wp_filter[$tag][$priority][$idx] = array('function' => $function_to_add, 'accepted_args' => $accepted_args);
unset( $merged_filters[ $tag ] );
return true;
}
/**
* Check if any filter has been registered for a hook.
*
* @since 2.5.0
*
* @global array $wp_filter Stores all of the filters
*
* @param string $tag The name of the filter hook.
* @param callback $function_to_check optional.
* @return mixed If $function_to_check is omitted, returns boolean for whether the hook has anything registered.
* When checking a specific function, the priority of that hook is returned, or false if the function is not attached.
* When using the $function_to_check argument, this function may return a non-boolean value that evaluates to false
* (e.g.) 0, so use the === operator for testing the return value.
*/
function has_filter($tag, $function_to_check = false) {
global $wp_filter;
$has = !empty($wp_filter[$tag]);
if ( false === $function_to_check || false == $has )
return $has;
if ( !$idx = _wp_filter_build_unique_id($tag, $function_to_check, false) )
return false;
foreach ( (array) array_keys($wp_filter[$tag]) as $priority ) {
if ( isset($wp_filter[$tag][$priority][$idx]) )
return $priority;
}
return false;
}
/**
* Call the functions added to a filter hook.
*
* The callback functions attached to filter hook $tag are invoked by calling
* this function. This function can be used to create a new filter hook by
* simply calling this function with the name of the new hook specified using
* the $tag parameter.
*
* The function allows for additional arguments to be added and passed to hooks.
* <code>
* // Our filter callback function
* function example_callback( $string, $arg1, $arg2 ) {
* // (maybe) modify $string
* return $string;
* }
* add_filter( 'example_filter', 'example_callback', 10, 3 );
*
* // Apply the filters by calling the 'example_callback' function we
* // "hooked" to 'example_filter' using the add_filter() function above.
* // - 'example_filter' is the filter hook $tag
* // - 'filter me' is the value being filtered
* // - $arg1 and $arg2 are the additional arguments passed to the callback.
* $value = apply_filters( 'example_filter', 'filter me', $arg1, $arg2 );
* </code>
*
* @global array $wp_filter Stores all of the filters
* @global array $merged_filters Merges the filter hooks using this function.
* @global array $wp_current_filter stores the list of current filters with the current one last
*
* @since 0.71
*
* @param string $tag The name of the filter hook.
* @param mixed $value The value on which the filters hooked to <tt>$tag</tt> are applied on.
* @param mixed $var Additional variables passed to the functions hooked to <tt>$tag</tt>.
* @return mixed The filtered value after all hooked functions are applied to it.
*/
function apply_filters( $tag, $value ) {
global $wp_filter, $merged_filters, $wp_current_filter;
$args = array();
// Do 'all' actions first
if ( isset($wp_filter['all']) ) {
$wp_current_filter[] = $tag;
$args = func_get_args();
_wp_call_all_hook($args);
}
if ( !isset($wp_filter[$tag]) ) {
if ( isset($wp_filter['all']) )
array_pop($wp_current_filter);
return $value;
}
if ( !isset($wp_filter['all']) )
$wp_current_filter[] = $tag;
// Sort
if ( !isset( $merged_filters[ $tag ] ) ) {
ksort($wp_filter[$tag]);
$merged_filters[ $tag ] = true;
}
reset( $wp_filter[ $tag ] );
if ( empty($args) )
$args = func_get_args();
do {
foreach( (array) current($wp_filter[$tag]) as $the_ )
if ( !is_null($the_['function']) ){
$args[1] = $value;
$value = call_user_func_array($the_['function'], array_slice($args, 1, (int) $the_['accepted_args']));
}
} while ( next($wp_filter[$tag]) !== false );
array_pop( $wp_current_filter );
return $value;
}
/**
* Execute functions hooked on a specific filter hook, specifying arguments in an array.
*
* @see apply_filters() This function is identical, but the arguments passed to the
* functions hooked to <tt>$tag</tt> are supplied using an array.
*
* @since 3.0.0
* @global array $wp_filter Stores all of the filters
* @global array $merged_filters Merges the filter hooks using this function.
* @global array $wp_current_filter stores the list of current filters with the current one last
*
* @param string $tag The name of the filter hook.
* @param array $args The arguments supplied to the functions hooked to <tt>$tag</tt>
* @return mixed The filtered value after all hooked functions are applied to it.
*/
function apply_filters_ref_array($tag, $args) {
global $wp_filter, $merged_filters, $wp_current_filter;
// Do 'all' actions first
if ( isset($wp_filter['all']) ) {
$wp_current_filter[] = $tag;
$all_args = func_get_args();
_wp_call_all_hook($all_args);
}
if ( !isset($wp_filter[$tag]) ) {
if ( isset($wp_filter['all']) )
array_pop($wp_current_filter);
return $args[0];
}
if ( !isset($wp_filter['all']) )
$wp_current_filter[] = $tag;
// Sort
if ( !isset( $merged_filters[ $tag ] ) ) {
ksort($wp_filter[$tag]);
$merged_filters[ $tag ] = true;
}
reset( $wp_filter[ $tag ] );
do {
foreach( (array) current($wp_filter[$tag]) as $the_ )
if ( !is_null($the_['function']) )
$args[0] = call_user_func_array($the_['function'], array_slice($args, 0, (int) $the_['accepted_args']));
} while ( next($wp_filter[$tag]) !== false );
array_pop( $wp_current_filter );
return $args[0];
}
/**
* Removes a function from a specified filter hook.
*
* This function removes a function attached to a specified filter hook. This
* method can be used to remove default functions attached to a specific filter
* hook and possibly replace them with a substitute.
*
* To remove a hook, the $function_to_remove and $priority arguments must match
* when the hook was added. This goes for both filters and actions. No warning
* will be given on removal failure.
*
* @since 1.2.0
*
* @param string $tag The filter hook to which the function to be removed is hooked.
* @param callback $function_to_remove The name of the function which should be removed.
* @param int $priority optional. The priority of the function (default: 10).
* @param int $accepted_args optional. The number of arguments the function accepts (default: 1).
* @return boolean Whether the function existed before it was removed.
*/
function remove_filter( $tag, $function_to_remove, $priority = 10 ) {
$function_to_remove = _wp_filter_build_unique_id($tag, $function_to_remove, $priority);
$r = isset($GLOBALS['wp_filter'][$tag][$priority][$function_to_remove]);
if ( true === $r) {
unset($GLOBALS['wp_filter'][$tag][$priority][$function_to_remove]);
if ( empty($GLOBALS['wp_filter'][$tag][$priority]) )
unset($GLOBALS['wp_filter'][$tag][$priority]);
unset($GLOBALS['merged_filters'][$tag]);
}
return $r;
}
/**
* Remove all of the hooks from a filter.
*
* @since 2.7.0
*
* @param string $tag The filter to remove hooks from.
* @param int $priority The priority number to remove.
* @return bool True when finished.
*/
function remove_all_filters($tag, $priority = false) {
global $wp_filter, $merged_filters;
if( isset($wp_filter[$tag]) ) {
if( false !== $priority && isset($wp_filter[$tag][$priority]) )
unset($wp_filter[$tag][$priority]);
else
unset($wp_filter[$tag]);
}
if( isset($merged_filters[$tag]) )
unset($merged_filters[$tag]);
return true;
}
/**
* Retrieve the name of the current filter or action.
*
* @since 2.5.0
*
* @return string Hook name of the current filter or action.
*/
function current_filter() {
global $wp_current_filter;
return end( $wp_current_filter );
}
/**
* Retrieve the name of the current action.
*
* @since 3.9.0
*
* @uses current_filter()
*
* @return string Hook name of the current action.
*/
function current_action() {
return current_filter();
}
/**
* Retrieve the name of a filter currently being processed.
*
* The function current_filter() only returns the most recent filter or action
* being executed. did_action() returns true once the action is initially
* processed. This function allows detection for any filter currently being
* executed (despite not being the most recent filter to fire, in the case of
* hooks called from hook callbacks) to be verified.
*
* @since 3.9.0
*
* @see current_filter()
* @see did_action()
* @global array $wp_current_filter Current filter.
*
* @param null|string $filter Optional. Filter to check. Defaults to null, which
* checks if any filter is currently being run.
* @return bool Whether the filter is currently in the stack
*/
function doing_filter( $filter = null ) {
global $wp_current_filter;
if ( null === $filter ) {
return ! empty( $wp_current_filter );
}
return in_array( $filter, $wp_current_filter );
}
/**
* Retrieve the name of an action currently being processed.
*
* @since 3.9.0
*
* @uses doing_filter()
*
* @param string|null $action Optional. Action to check. Defaults to null, which checks
* if any action is currently being run.
* @return bool Whether the action is currently in the stack.
*/
function doing_action( $action = null ) {
return doing_filter( $action );
}
/**
* Hooks a function on to a specific action.
*
* Actions are the hooks that the WordPress core launches at specific points
* during execution, or when specific events occur. Plugins can specify that
* one or more of its PHP functions are executed at these points, using the
* Action API.
*
* @uses add_filter() Adds an action. Parameter list and functionality are the same.
*
* @since 1.2.0
*
* @param string $tag The name of the action to which the $function_to_add is hooked.
* @param callback $function_to_add The name of the function you wish to be called.
* @param int $priority optional. Used to specify the order in which the functions associated with a particular action are executed (default: 10). Lower numbers correspond with earlier execution, and functions with the same priority are executed in the order in which they were added to the action.
* @param int $accepted_args optional. The number of arguments the function accept (default 1).
*/
function add_action($tag, $function_to_add, $priority = 10, $accepted_args = 1) {
return add_filter($tag, $function_to_add, $priority, $accepted_args);
}
/**
* Execute functions hooked on a specific action hook.
*
* This function invokes all functions attached to action hook $tag. It is
* possible to create new action hooks by simply calling this function,
* specifying the name of the new hook using the <tt>$tag</tt> parameter.
*
* You can pass extra arguments to the hooks, much like you can with
* apply_filters().
*
* @see apply_filters() This function works similar with the exception that
* nothing is returned and only the functions or methods are called.
*
* @since 1.2.0
*
* @global array $wp_filter Stores all of the filters
* @global array $wp_actions Increments the amount of times action was triggered.
*
* @param string $tag The name of the action to be executed.
* @param mixed $arg,... Optional additional arguments which are passed on to the functions hooked to the action.
* @return null Will return null if $tag does not exist in $wp_filter array
*/
function do_action($tag, $arg = '') {
global $wp_filter, $wp_actions, $merged_filters, $wp_current_filter;
if ( ! isset($wp_actions[$tag]) )
$wp_actions[$tag] = 1;
else
++$wp_actions[$tag];
// Do 'all' actions first
if ( isset($wp_filter['all']) ) {
$wp_current_filter[] = $tag;
$all_args = func_get_args();
_wp_call_all_hook($all_args);
}
if ( !isset($wp_filter[$tag]) ) {
if ( isset($wp_filter['all']) )
array_pop($wp_current_filter);
return;
}
if ( !isset($wp_filter['all']) )
$wp_current_filter[] = $tag;
$args = array();
if ( is_array($arg) && 1 == count($arg) && isset($arg[0]) && is_object($arg[0]) ) // array(&$this)
$args[] =& $arg[0];
else
$args[] = $arg;
for ( $a = 2; $a < func_num_args(); $a++ )
$args[] = func_get_arg($a);
// Sort
if ( !isset( $merged_filters[ $tag ] ) ) {
ksort($wp_filter[$tag]);
$merged_filters[ $tag ] = true;
}
reset( $wp_filter[ $tag ] );
do {
foreach ( (array) current($wp_filter[$tag]) as $the_ )
if ( !is_null($the_['function']) )
call_user_func_array($the_['function'], array_slice($args, 0, (int) $the_['accepted_args']));
} while ( next($wp_filter[$tag]) !== false );
array_pop($wp_current_filter);
}
/**
* Retrieve the number of times an action is fired.
*
* @since 2.1.0
*
* @global array $wp_actions Increments the amount of times action was triggered.
*
* @param string $tag The name of the action hook.
* @return int The number of times action hook <tt>$tag</tt> is fired
*/
function did_action($tag) {
global $wp_actions;
if ( ! isset( $wp_actions[ $tag ] ) )
return 0;
return $wp_actions[$tag];
}
/**
* Execute functions hooked on a specific action hook, specifying arguments in an array.
*
* @see do_action() This function is identical, but the arguments passed to the
* functions hooked to <tt>$tag</tt> are supplied using an array.
*
* @since 2.1.0
*
* @global array $wp_filter Stores all of the filters
* @global array $wp_actions Increments the amount of times action was triggered.
*
* @param string $tag The name of the action to be executed.
* @param array $args The arguments supplied to the functions hooked to <tt>$tag</tt>
* @return null Will return null if $tag does not exist in $wp_filter array
*/
function do_action_ref_array($tag, $args) {
global $wp_filter, $wp_actions, $merged_filters, $wp_current_filter;
if ( ! isset($wp_actions[$tag]) )
$wp_actions[$tag] = 1;
else
++$wp_actions[$tag];
// Do 'all' actions first
if ( isset($wp_filter['all']) ) {
$wp_current_filter[] = $tag;
$all_args = func_get_args();
_wp_call_all_hook($all_args);
}
if ( !isset($wp_filter[$tag]) ) {
if ( isset($wp_filter['all']) )
array_pop($wp_current_filter);
return;
}
if ( !isset($wp_filter['all']) )
$wp_current_filter[] = $tag;
// Sort
if ( !isset( $merged_filters[ $tag ] ) ) {
ksort($wp_filter[$tag]);
$merged_filters[ $tag ] = true;
}
reset( $wp_filter[ $tag ] );
do {
foreach( (array) current($wp_filter[$tag]) as $the_ )
if ( !is_null($the_['function']) )
call_user_func_array($the_['function'], array_slice($args, 0, (int) $the_['accepted_args']));
} while ( next($wp_filter[$tag]) !== false );
array_pop($wp_current_filter);
}
/**
* Check if any action has been registered for a hook.
*
* @since 2.5.0
*
* @see has_filter() has_action() is an alias of has_filter().
*
* @param string $tag The name of the action hook.
* @param callback $function_to_check optional.
* @return mixed If $function_to_check is omitted, returns boolean for whether the hook has anything registered.
* When checking a specific function, the priority of that hook is returned, or false if the function is not attached.
* When using the $function_to_check argument, this function may return a non-boolean value that evaluates to false
* (e.g.) 0, so use the === operator for testing the return value.
*/
function has_action($tag, $function_to_check = false) {
return has_filter($tag, $function_to_check);
}
/**
* Removes a function from a specified action hook.
*
* This function removes a function attached to a specified action hook. This
* method can be used to remove default functions attached to a specific filter
* hook and possibly replace them with a substitute.
*
* @since 1.2.0
*
* @param string $tag The action hook to which the function to be removed is hooked.
* @param callback $function_to_remove The name of the function which should be removed.
* @param int $priority optional The priority of the function (default: 10).
* @return boolean Whether the function is removed.
*/
function remove_action( $tag, $function_to_remove, $priority = 10 ) {
return remove_filter( $tag, $function_to_remove, $priority );
}
/**
* Remove all of the hooks from an action.
*
* @since 2.7.0
*
* @param string $tag The action to remove hooks from.
* @param int $priority The priority number to remove them from.
* @return bool True when finished.
*/
function remove_all_actions($tag, $priority = false) {
return remove_all_filters($tag, $priority);
}
//
// Functions for handling plugins.
//
/**
* Gets the basename of a plugin.
*
* This method extracts the name of a plugin from its filename.
*
* @since 1.5.0
*
* @access private
*
* @param string $file The filename of plugin.
* @return string The name of a plugin.
* @uses WP_PLUGIN_DIR
*/
function plugin_basename( $file ) {
global $wp_plugin_paths;
foreach ( $wp_plugin_paths as $dir => $realdir ) {
if ( strpos( $file, $realdir ) === 0 ) {
$file = $dir . substr( $file, strlen( $realdir ) );
}
}
$file = wp_normalize_path( $file );
$plugin_dir = wp_normalize_path( WP_PLUGIN_DIR );
$mu_plugin_dir = wp_normalize_path( WPMU_PLUGIN_DIR );
$file = preg_replace('#^' . preg_quote($plugin_dir, '#') . '/|^' . preg_quote($mu_plugin_dir, '#') . '/#','',$file); // get relative path from plugins dir
$file = trim($file, '/');
return $file;
}
/**
* Register a plugin's real path.
*
* This is used in plugin_basename() to resolve symlinked paths.
*
* @since 3.9.0
*
* @see plugin_basename()
*
* @param string $file Known path to the file.
* @return bool Whether the path was able to be registered.
*/
function wp_register_plugin_realpath( $file ) {
global $wp_plugin_paths;
// Normalize, but store as static to avoid recalculation of a constant value
static $wp_plugin_path, $wpmu_plugin_path;
if ( ! isset( $wp_plugin_path ) ) {
$wp_plugin_path = wp_normalize_path( WP_PLUGIN_DIR );
$wpmu_plugin_path = wp_normalize_path( WPMU_PLUGIN_DIR );
}
$plugin_path = wp_normalize_path( dirname( $file ) );
$plugin_realpath = wp_normalize_path( dirname( realpath( $file ) ) );
if ( $plugin_path === $wp_plugin_path || $plugin_path === $wpmu_plugin_path ) {
return false;
}
if ( $plugin_path !== $plugin_realpath ) {
$wp_plugin_paths[ $plugin_path ] = $plugin_realpath;
}
return true;
}
/**
* Gets the filesystem directory path (with trailing slash) for the plugin __FILE__ passed in
*
* @since 2.8.0
*
* @param string $file The filename of the plugin (__FILE__)
* @return string the filesystem path of the directory that contains the plugin
*/
function plugin_dir_path( $file ) {
return trailingslashit( dirname( $file ) );
}
/**
* Gets the URL directory path (with trailing slash) for the plugin __FILE__ passed in
*
* @since 2.8.0
*
* @param string $file The filename of the plugin (__FILE__)
* @return string the URL path of the directory that contains the plugin
*/
function plugin_dir_url( $file ) {
return trailingslashit( plugins_url( '', $file ) );
}
/**
* Set the activation hook for a plugin.
*
* When a plugin is activated, the action 'activate_PLUGINNAME' hook is
* called. In the name of this hook, PLUGINNAME is replaced with the name
* of the plugin, including the optional subdirectory. For example, when the
* plugin is located in wp-content/plugins/sampleplugin/sample.php, then
* the name of this hook will become 'activate_sampleplugin/sample.php'.
*
* When the plugin consists of only one file and is (as by default) located at
* wp-content/plugins/sample.php the name of this hook will be
* 'activate_sample.php'.
*
* @since 2.0.0
*
* @param string $file The filename of the plugin including the path.
* @param callback $function the function hooked to the 'activate_PLUGIN' action.
*/
function register_activation_hook($file, $function) {
$file = plugin_basename($file);
add_action('activate_' . $file, $function);
}
/**
* Set the deactivation hook for a plugin.
*
* When a plugin is deactivated, the action 'deactivate_PLUGINNAME' hook is
* called. In the name of this hook, PLUGINNAME is replaced with the name
* of the plugin, including the optional subdirectory. For example, when the
* plugin is located in wp-content/plugins/sampleplugin/sample.php, then
* the name of this hook will become 'deactivate_sampleplugin/sample.php'.
*
* When the plugin consists of only one file and is (as by default) located at
* wp-content/plugins/sample.php the name of this hook will be
* 'deactivate_sample.php'.
*
* @since 2.0.0
*
* @param string $file The filename of the plugin including the path.
* @param callback $function the function hooked to the 'deactivate_PLUGIN' action.
*/
function register_deactivation_hook($file, $function) {
$file = plugin_basename($file);
add_action('deactivate_' . $file, $function);
}
/**
* Set the uninstallation hook for a plugin.
*
* Registers the uninstall hook that will be called when the user clicks on the
* uninstall link that calls for the plugin to uninstall itself. The link won't
* be active unless the plugin hooks into the action.
*
* The plugin should not run arbitrary code outside of functions, when
* registering the uninstall hook. In order to run using the hook, the plugin
* will have to be included, which means that any code laying outside of a
* function will be run during the uninstall process. The plugin should not
* hinder the uninstall process.
*
* If the plugin can not be written without running code within the plugin, then
* the plugin should create a file named 'uninstall.php' in the base plugin
* folder. This file will be called, if it exists, during the uninstall process
* bypassing the uninstall hook. The plugin, when using the 'uninstall.php'
* should always check for the 'WP_UNINSTALL_PLUGIN' constant, before
* executing.
*
* @since 2.7.0
*
* @param string $file
* @param callback $callback The callback to run when the hook is called. Must be a static method or function.
*/
function register_uninstall_hook( $file, $callback ) {
if ( is_array( $callback ) && is_object( $callback[0] ) ) {
_doing_it_wrong( __FUNCTION__, __( 'Only a static class method or function can be used in an uninstall hook.' ), '3.1' );
return;
}
// The option should not be autoloaded, because it is not needed in most
// cases. Emphasis should be put on using the 'uninstall.php' way of
// uninstalling the plugin.
$uninstallable_plugins = (array) get_option('uninstall_plugins');
$uninstallable_plugins[plugin_basename($file)] = $callback;
update_option('uninstall_plugins', $uninstallable_plugins);
}
/**
* Calls the 'all' hook, which will process the functions hooked into it.
*
* The 'all' hook passes all of the arguments or parameters that were used for
* the hook, which this function was called for.
*
* This function is used internally for apply_filters(), do_action(), and
* do_action_ref_array() and is not meant to be used from outside those
* functions. This function does not check for the existence of the all hook, so
* it will fail unless the all hook exists prior to this function call.
*
* @since 2.5.0
* @access private
*
* @uses $wp_filter Used to process all of the functions in the 'all' hook
*
* @param array $args The collected parameters from the hook that was called.
*/
function _wp_call_all_hook($args) {
global $wp_filter;
reset( $wp_filter['all'] );
do {
foreach( (array) current($wp_filter['all']) as $the_ )
if ( !is_null($the_['function']) )
call_user_func_array($the_['function'], $args);
} while ( next($wp_filter['all']) !== false );
}
/**
* Build Unique ID for storage and retrieval.
*
* The old way to serialize the callback caused issues and this function is the
* solution. It works by checking for objects and creating an a new property in
* the class to keep track of the object and new objects of the same class that
* need to be added.
*
* It also allows for the removal of actions and filters for objects after they
* change class properties. It is possible to include the property $wp_filter_id
* in your class and set it to "null" or a number to bypass the workaround.
* However this will prevent you from adding new classes and any new classes
* will overwrite the previous hook by the same class.
*
* Functions and static method callbacks are just returned as strings and
* shouldn't have any speed penalty.
*
* @access private
* @since 2.2.3
* @link http://trac.wordpress.org/ticket/3875
*
* @global array $wp_filter Storage for all of the filters and actions
* @param string $tag Used in counting how many hooks were applied
* @param callback $function Used for creating unique id
* @param int|bool $priority Used in counting how many hooks were applied. If === false and $function is an object reference, we return the unique id only if it already has one, false otherwise.
* @return string|bool Unique ID for usage as array key or false if $priority === false and $function is an object reference, and it does not already have a unique id.
*/
function _wp_filter_build_unique_id($tag, $function, $priority) {
global $wp_filter;
static $filter_id_count = 0;
if ( is_string($function) )
return $function;
if ( is_object($function) ) {
// Closures are currently implemented as objects
$function = array( $function, '' );
} else {
$function = (array) $function;
}
if (is_object($function[0]) ) {
// Object Class Calling
if ( function_exists('spl_object_hash') ) {
return spl_object_hash($function[0]) . $function[1];
} else {
$obj_idx = get_class($function[0]).$function[1];
if ( !isset($function[0]->wp_filter_id) ) {
if ( false === $priority )
return false;
$obj_idx .= isset($wp_filter[$tag][$priority]) ? count((array)$wp_filter[$tag][$priority]) : $filter_id_count;
$function[0]->wp_filter_id = $filter_id_count;
++$filter_id_count;
} else {
$obj_idx .= $function[0]->wp_filter_id;
}
return $obj_idx;
}
} else if ( is_string($function[0]) ) {
// Static Calling
return $function[0] . '::' . $function[1];
}
}
| PHP |
<?php
/**
* Class for working with MO files
*
* @version $Id: mo.php 718 2012-10-31 00:32:02Z nbachiyski $
* @package pomo
* @subpackage mo
*/
require_once dirname(__FILE__) . '/translations.php';
require_once dirname(__FILE__) . '/streams.php';
if ( !class_exists( 'MO' ) ):
class MO extends Gettext_Translations {
var $_nplurals = 2;
/**
* Fills up with the entries from MO file $filename
*
* @param string $filename MO file to load
*/
function import_from_file($filename) {
$reader = new POMO_FileReader($filename);
if (!$reader->is_resource())
return false;
return $this->import_from_reader($reader);
}
function export_to_file($filename) {
$fh = fopen($filename, 'wb');
if ( !$fh ) return false;
$res = $this->export_to_file_handle( $fh );
fclose($fh);
return $res;
}
function export() {
$tmp_fh = fopen("php://temp", 'r+');
if ( !$tmp_fh ) return false;
$this->export_to_file_handle( $tmp_fh );
rewind( $tmp_fh );
return stream_get_contents( $tmp_fh );
}
function is_entry_good_for_export( $entry ) {
if ( empty( $entry->translations ) ) {
return false;
}
if ( !array_filter( $entry->translations ) ) {
return false;
}
return true;
}
function export_to_file_handle($fh) {
$entries = array_filter( $this->entries, array( $this, 'is_entry_good_for_export' ) );
ksort($entries);
$magic = 0x950412de;
$revision = 0;
$total = count($entries) + 1; // all the headers are one entry
$originals_lenghts_addr = 28;
$translations_lenghts_addr = $originals_lenghts_addr + 8 * $total;
$size_of_hash = 0;
$hash_addr = $translations_lenghts_addr + 8 * $total;
$current_addr = $hash_addr;
fwrite($fh, pack('V*', $magic, $revision, $total, $originals_lenghts_addr,
$translations_lenghts_addr, $size_of_hash, $hash_addr));
fseek($fh, $originals_lenghts_addr);
// headers' msgid is an empty string
fwrite($fh, pack('VV', 0, $current_addr));
$current_addr++;
$originals_table = chr(0);
foreach($entries as $entry) {
$originals_table .= $this->export_original($entry) . chr(0);
$length = strlen($this->export_original($entry));
fwrite($fh, pack('VV', $length, $current_addr));
$current_addr += $length + 1; // account for the NULL byte after
}
$exported_headers = $this->export_headers();
fwrite($fh, pack('VV', strlen($exported_headers), $current_addr));
$current_addr += strlen($exported_headers) + 1;
$translations_table = $exported_headers . chr(0);
foreach($entries as $entry) {
$translations_table .= $this->export_translations($entry) . chr(0);
$length = strlen($this->export_translations($entry));
fwrite($fh, pack('VV', $length, $current_addr));
$current_addr += $length + 1;
}
fwrite($fh, $originals_table);
fwrite($fh, $translations_table);
return true;
}
function export_original($entry) {
//TODO: warnings for control characters
$exported = $entry->singular;
if ($entry->is_plural) $exported .= chr(0).$entry->plural;
if (!is_null($entry->context)) $exported = $entry->context . chr(4) . $exported;
return $exported;
}
function export_translations($entry) {
//TODO: warnings for control characters
return implode(chr(0), $entry->translations);
}
function export_headers() {
$exported = '';
foreach($this->headers as $header => $value) {
$exported.= "$header: $value\n";
}
return $exported;
}
function get_byteorder($magic) {
// The magic is 0x950412de
// bug in PHP 5.0.2, see https://savannah.nongnu.org/bugs/?func=detailitem&item_id=10565
$magic_little = (int) - 1794895138;
$magic_little_64 = (int) 2500072158;
// 0xde120495
$magic_big = ((int) - 569244523) & 0xFFFFFFFF;
if ($magic_little == $magic || $magic_little_64 == $magic) {
return 'little';
} else if ($magic_big == $magic) {
return 'big';
} else {
return false;
}
}
function import_from_reader($reader) {
$endian_string = MO::get_byteorder($reader->readint32());
if (false === $endian_string) {
return false;
}
$reader->setEndian($endian_string);
$endian = ('big' == $endian_string)? 'N' : 'V';
$header = $reader->read(24);
if ($reader->strlen($header) != 24)
return false;
// parse header
$header = unpack("{$endian}revision/{$endian}total/{$endian}originals_lenghts_addr/{$endian}translations_lenghts_addr/{$endian}hash_length/{$endian}hash_addr", $header);
if (!is_array($header))
return false;
extract( $header );
// support revision 0 of MO format specs, only
if ($revision != 0)
return false;
// seek to data blocks
$reader->seekto($originals_lenghts_addr);
// read originals' indices
$originals_lengths_length = $translations_lenghts_addr - $originals_lenghts_addr;
if ( $originals_lengths_length != $total * 8 )
return false;
$originals = $reader->read($originals_lengths_length);
if ( $reader->strlen( $originals ) != $originals_lengths_length )
return false;
// read translations' indices
$translations_lenghts_length = $hash_addr - $translations_lenghts_addr;
if ( $translations_lenghts_length != $total * 8 )
return false;
$translations = $reader->read($translations_lenghts_length);
if ( $reader->strlen( $translations ) != $translations_lenghts_length )
return false;
// transform raw data into set of indices
$originals = $reader->str_split( $originals, 8 );
$translations = $reader->str_split( $translations, 8 );
// skip hash table
$strings_addr = $hash_addr + $hash_length * 4;
$reader->seekto($strings_addr);
$strings = $reader->read_all();
$reader->close();
for ( $i = 0; $i < $total; $i++ ) {
$o = unpack( "{$endian}length/{$endian}pos", $originals[$i] );
$t = unpack( "{$endian}length/{$endian}pos", $translations[$i] );
if ( !$o || !$t ) return false;
// adjust offset due to reading strings to separate space before
$o['pos'] -= $strings_addr;
$t['pos'] -= $strings_addr;
$original = $reader->substr( $strings, $o['pos'], $o['length'] );
$translation = $reader->substr( $strings, $t['pos'], $t['length'] );
if ('' === $original) {
$this->set_headers($this->make_headers($translation));
} else {
$entry = &$this->make_entry($original, $translation);
$this->entries[$entry->key()] = &$entry;
}
}
return true;
}
/**
* Build a Translation_Entry from original string and translation strings,
* found in a MO file
*
* @static
* @param string $original original string to translate from MO file. Might contain
* 0x04 as context separator or 0x00 as singular/plural separator
* @param string $translation translation string from MO file. Might contain
* 0x00 as a plural translations separator
*/
function &make_entry($original, $translation) {
$entry = new Translation_Entry();
// look for context
$parts = explode(chr(4), $original);
if (isset($parts[1])) {
$original = $parts[1];
$entry->context = $parts[0];
}
// look for plural original
$parts = explode(chr(0), $original);
$entry->singular = $parts[0];
if (isset($parts[1])) {
$entry->is_plural = true;
$entry->plural = $parts[1];
}
// plural translations are also separated by \0
$entry->translations = explode(chr(0), $translation);
return $entry;
}
function select_plural_form($count) {
return $this->gettext_select_plural_form($count);
}
function get_plural_forms_count() {
return $this->_nplurals;
}
}
endif; | PHP |
<?php
/**
* Contains Translation_Entry class
*
* @version $Id: entry.php 718 2012-10-31 00:32:02Z nbachiyski $
* @package pomo
* @subpackage entry
*/
if ( !class_exists( 'Translation_Entry' ) ):
/**
* Translation_Entry class encapsulates a translatable string
*/
class Translation_Entry {
/**
* Whether the entry contains a string and its plural form, default is false
*
* @var boolean
*/
var $is_plural = false;
var $context = null;
var $singular = null;
var $plural = null;
var $translations = array();
var $translator_comments = '';
var $extracted_comments = '';
var $references = array();
var $flags = array();
/**
* @param array $args associative array, support following keys:
* - singular (string) -- the string to translate, if omitted and empty entry will be created
* - plural (string) -- the plural form of the string, setting this will set {@link $is_plural} to true
* - translations (array) -- translations of the string and possibly -- its plural forms
* - context (string) -- a string differentiating two equal strings used in different contexts
* - translator_comments (string) -- comments left by translators
* - extracted_comments (string) -- comments left by developers
* - references (array) -- places in the code this strings is used, in relative_to_root_path/file.php:linenum form
* - flags (array) -- flags like php-format
*/
function Translation_Entry($args=array()) {
// if no singular -- empty object
if (!isset($args['singular'])) {
return;
}
// get member variable values from args hash
foreach ($args as $varname => $value) {
$this->$varname = $value;
}
if (isset($args['plural'])) $this->is_plural = true;
if (!is_array($this->translations)) $this->translations = array();
if (!is_array($this->references)) $this->references = array();
if (!is_array($this->flags)) $this->flags = array();
}
/**
* Generates a unique key for this entry
*
* @return string|bool the key or false if the entry is empty
*/
function key() {
if (is_null($this->singular)) return false;
// prepend context and EOT, like in MO files
return is_null($this->context)? $this->singular : $this->context.chr(4).$this->singular;
}
function merge_with(&$other) {
$this->flags = array_unique( array_merge( $this->flags, $other->flags ) );
$this->references = array_unique( array_merge( $this->references, $other->references ) );
if ( $this->extracted_comments != $other->extracted_comments ) {
$this->extracted_comments .= $other->extracted_comments;
}
}
}
endif; | PHP |
<?php
/**
* Classes, which help reading streams of data from files.
* Based on the classes from Danilo Segan <danilo@kvota.net>
*
* @version $Id: streams.php 718 2012-10-31 00:32:02Z nbachiyski $
* @package pomo
* @subpackage streams
*/
if ( !class_exists( 'POMO_Reader' ) ):
class POMO_Reader {
var $endian = 'little';
var $_post = '';
function POMO_Reader() {
$this->is_overloaded = ((ini_get("mbstring.func_overload") & 2) != 0) && function_exists('mb_substr');
$this->_pos = 0;
}
/**
* Sets the endianness of the file.
*
* @param $endian string 'big' or 'little'
*/
function setEndian($endian) {
$this->endian = $endian;
}
/**
* Reads a 32bit Integer from the Stream
*
* @return mixed The integer, corresponding to the next 32 bits from
* the stream of false if there are not enough bytes or on error
*/
function readint32() {
$bytes = $this->read(4);
if (4 != $this->strlen($bytes))
return false;
$endian_letter = ('big' == $this->endian)? 'N' : 'V';
$int = unpack($endian_letter, $bytes);
return array_shift($int);
}
/**
* Reads an array of 32-bit Integers from the Stream
*
* @param integer count How many elements should be read
* @return mixed Array of integers or false if there isn't
* enough data or on error
*/
function readint32array($count) {
$bytes = $this->read(4 * $count);
if (4*$count != $this->strlen($bytes))
return false;
$endian_letter = ('big' == $this->endian)? 'N' : 'V';
return unpack($endian_letter.$count, $bytes);
}
function substr($string, $start, $length) {
if ($this->is_overloaded) {
return mb_substr($string, $start, $length, 'ascii');
} else {
return substr($string, $start, $length);
}
}
function strlen($string) {
if ($this->is_overloaded) {
return mb_strlen($string, 'ascii');
} else {
return strlen($string);
}
}
function str_split($string, $chunk_size) {
if (!function_exists('str_split')) {
$length = $this->strlen($string);
$out = array();
for ($i = 0; $i < $length; $i += $chunk_size)
$out[] = $this->substr($string, $i, $chunk_size);
return $out;
} else {
return str_split( $string, $chunk_size );
}
}
function pos() {
return $this->_pos;
}
function is_resource() {
return true;
}
function close() {
return true;
}
}
endif;
if ( !class_exists( 'POMO_FileReader' ) ):
class POMO_FileReader extends POMO_Reader {
function POMO_FileReader($filename) {
parent::POMO_Reader();
$this->_f = fopen($filename, 'rb');
}
function read($bytes) {
return fread($this->_f, $bytes);
}
function seekto($pos) {
if ( -1 == fseek($this->_f, $pos, SEEK_SET)) {
return false;
}
$this->_pos = $pos;
return true;
}
function is_resource() {
return is_resource($this->_f);
}
function feof() {
return feof($this->_f);
}
function close() {
return fclose($this->_f);
}
function read_all() {
$all = '';
while ( !$this->feof() )
$all .= $this->read(4096);
return $all;
}
}
endif;
if ( !class_exists( 'POMO_StringReader' ) ):
/**
* Provides file-like methods for manipulating a string instead
* of a physical file.
*/
class POMO_StringReader extends POMO_Reader {
var $_str = '';
function POMO_StringReader($str = '') {
parent::POMO_Reader();
$this->_str = $str;
$this->_pos = 0;
}
function read($bytes) {
$data = $this->substr($this->_str, $this->_pos, $bytes);
$this->_pos += $bytes;
if ($this->strlen($this->_str) < $this->_pos) $this->_pos = $this->strlen($this->_str);
return $data;
}
function seekto($pos) {
$this->_pos = $pos;
if ($this->strlen($this->_str) < $this->_pos) $this->_pos = $this->strlen($this->_str);
return $this->_pos;
}
function length() {
return $this->strlen($this->_str);
}
function read_all() {
return $this->substr($this->_str, $this->_pos, $this->strlen($this->_str));
}
}
endif;
if ( !class_exists( 'POMO_CachedFileReader' ) ):
/**
* Reads the contents of the file in the beginning.
*/
class POMO_CachedFileReader extends POMO_StringReader {
function POMO_CachedFileReader($filename) {
parent::POMO_StringReader();
$this->_str = file_get_contents($filename);
if (false === $this->_str)
return false;
$this->_pos = 0;
}
}
endif;
if ( !class_exists( 'POMO_CachedIntFileReader' ) ):
/**
* Reads the contents of the file in the beginning.
*/
class POMO_CachedIntFileReader extends POMO_CachedFileReader {
function POMO_CachedIntFileReader($filename) {
parent::POMO_CachedFileReader($filename);
}
}
endif; | PHP |
<?php
/**
* Class for working with PO files
*
* @version $Id: po.php 718 2012-10-31 00:32:02Z nbachiyski $
* @package pomo
* @subpackage po
*/
require_once dirname(__FILE__) . '/translations.php';
define('PO_MAX_LINE_LEN', 79);
ini_set('auto_detect_line_endings', 1);
/**
* Routines for working with PO files
*/
if ( !class_exists( 'PO' ) ):
class PO extends Gettext_Translations {
var $comments_before_headers = '';
/**
* Exports headers to a PO entry
*
* @return string msgid/msgstr PO entry for this PO file headers, doesn't contain newline at the end
*/
function export_headers() {
$header_string = '';
foreach($this->headers as $header => $value) {
$header_string.= "$header: $value\n";
}
$poified = PO::poify($header_string);
if ($this->comments_before_headers)
$before_headers = $this->prepend_each_line(rtrim($this->comments_before_headers)."\n", '# ');
else
$before_headers = '';
return rtrim("{$before_headers}msgid \"\"\nmsgstr $poified");
}
/**
* Exports all entries to PO format
*
* @return string sequence of mgsgid/msgstr PO strings, doesn't containt newline at the end
*/
function export_entries() {
//TODO sorting
return implode("\n\n", array_map(array('PO', 'export_entry'), $this->entries));
}
/**
* Exports the whole PO file as a string
*
* @param bool $include_headers whether to include the headers in the export
* @return string ready for inclusion in PO file string for headers and all the enrtries
*/
function export($include_headers = true) {
$res = '';
if ($include_headers) {
$res .= $this->export_headers();
$res .= "\n\n";
}
$res .= $this->export_entries();
return $res;
}
/**
* Same as {@link export}, but writes the result to a file
*
* @param string $filename where to write the PO string
* @param bool $include_headers whether to include tje headers in the export
* @return bool true on success, false on error
*/
function export_to_file($filename, $include_headers = true) {
$fh = fopen($filename, 'w');
if (false === $fh) return false;
$export = $this->export($include_headers);
$res = fwrite($fh, $export);
if (false === $res) return false;
return fclose($fh);
}
/**
* Text to include as a comment before the start of the PO contents
*
* Doesn't need to include # in the beginning of lines, these are added automatically
*/
function set_comment_before_headers( $text ) {
$this->comments_before_headers = $text;
}
/**
* Formats a string in PO-style
*
* @static
* @param string $string the string to format
* @return string the poified string
*/
function poify($string) {
$quote = '"';
$slash = '\\';
$newline = "\n";
$replaces = array(
"$slash" => "$slash$slash",
"$quote" => "$slash$quote",
"\t" => '\t',
);
$string = str_replace(array_keys($replaces), array_values($replaces), $string);
$po = $quote.implode("${slash}n$quote$newline$quote", explode($newline, $string)).$quote;
// add empty string on first line for readbility
if (false !== strpos($string, $newline) &&
(substr_count($string, $newline) > 1 || !($newline === substr($string, -strlen($newline))))) {
$po = "$quote$quote$newline$po";
}
// remove empty strings
$po = str_replace("$newline$quote$quote", '', $po);
return $po;
}
/**
* Gives back the original string from a PO-formatted string
*
* @static
* @param string $string PO-formatted string
* @return string enascaped string
*/
function unpoify($string) {
$escapes = array('t' => "\t", 'n' => "\n", '\\' => '\\');
$lines = array_map('trim', explode("\n", $string));
$lines = array_map(array('PO', 'trim_quotes'), $lines);
$unpoified = '';
$previous_is_backslash = false;
foreach($lines as $line) {
preg_match_all('/./u', $line, $chars);
$chars = $chars[0];
foreach($chars as $char) {
if (!$previous_is_backslash) {
if ('\\' == $char)
$previous_is_backslash = true;
else
$unpoified .= $char;
} else {
$previous_is_backslash = false;
$unpoified .= isset($escapes[$char])? $escapes[$char] : $char;
}
}
}
return $unpoified;
}
/**
* Inserts $with in the beginning of every new line of $string and
* returns the modified string
*
* @static
* @param string $string prepend lines in this string
* @param string $with prepend lines with this string
*/
function prepend_each_line($string, $with) {
$php_with = var_export($with, true);
$lines = explode("\n", $string);
// do not prepend the string on the last empty line, artefact by explode
if ("\n" == substr($string, -1)) unset($lines[count($lines) - 1]);
$res = implode("\n", array_map(create_function('$x', "return $php_with.\$x;"), $lines));
// give back the empty line, we ignored above
if ("\n" == substr($string, -1)) $res .= "\n";
return $res;
}
/**
* Prepare a text as a comment -- wraps the lines and prepends #
* and a special character to each line
*
* @access private
* @param string $text the comment text
* @param string $char character to denote a special PO comment,
* like :, default is a space
*/
function comment_block($text, $char=' ') {
$text = wordwrap($text, PO_MAX_LINE_LEN - 3);
return PO::prepend_each_line($text, "#$char ");
}
/**
* Builds a string from the entry for inclusion in PO file
*
* @static
* @param object &$entry the entry to convert to po string
* @return string|bool PO-style formatted string for the entry or
* false if the entry is empty
*/
function export_entry(&$entry) {
if (is_null($entry->singular)) return false;
$po = array();
if (!empty($entry->translator_comments)) $po[] = PO::comment_block($entry->translator_comments);
if (!empty($entry->extracted_comments)) $po[] = PO::comment_block($entry->extracted_comments, '.');
if (!empty($entry->references)) $po[] = PO::comment_block(implode(' ', $entry->references), ':');
if (!empty($entry->flags)) $po[] = PO::comment_block(implode(", ", $entry->flags), ',');
if (!is_null($entry->context)) $po[] = 'msgctxt '.PO::poify($entry->context);
$po[] = 'msgid '.PO::poify($entry->singular);
if (!$entry->is_plural) {
$translation = empty($entry->translations)? '' : $entry->translations[0];
$po[] = 'msgstr '.PO::poify($translation);
} else {
$po[] = 'msgid_plural '.PO::poify($entry->plural);
$translations = empty($entry->translations)? array('', '') : $entry->translations;
foreach($translations as $i => $translation) {
$po[] = "msgstr[$i] ".PO::poify($translation);
}
}
return implode("\n", $po);
}
function import_from_file($filename) {
$f = fopen($filename, 'r');
if (!$f) return false;
$lineno = 0;
while (true) {
$res = $this->read_entry($f, $lineno);
if (!$res) break;
if ($res['entry']->singular == '') {
$this->set_headers($this->make_headers($res['entry']->translations[0]));
} else {
$this->add_entry($res['entry']);
}
}
PO::read_line($f, 'clear');
if ( false === $res ) {
return false;
}
if ( ! $this->headers && ! $this->entries ) {
return false;
}
return true;
}
function read_entry($f, $lineno = 0) {
$entry = new Translation_Entry();
// where were we in the last step
// can be: comment, msgctxt, msgid, msgid_plural, msgstr, msgstr_plural
$context = '';
$msgstr_index = 0;
$is_final = create_function('$context', 'return $context == "msgstr" || $context == "msgstr_plural";');
while (true) {
$lineno++;
$line = PO::read_line($f);
if (!$line) {
if (feof($f)) {
if ($is_final($context))
break;
elseif (!$context) // we haven't read a line and eof came
return null;
else
return false;
} else {
return false;
}
}
if ($line == "\n") continue;
$line = trim($line);
if (preg_match('/^#/', $line, $m)) {
// the comment is the start of a new entry
if ($is_final($context)) {
PO::read_line($f, 'put-back');
$lineno--;
break;
}
// comments have to be at the beginning
if ($context && $context != 'comment') {
return false;
}
// add comment
$this->add_comment_to_entry($entry, $line);
} elseif (preg_match('/^msgctxt\s+(".*")/', $line, $m)) {
if ($is_final($context)) {
PO::read_line($f, 'put-back');
$lineno--;
break;
}
if ($context && $context != 'comment') {
return false;
}
$context = 'msgctxt';
$entry->context .= PO::unpoify($m[1]);
} elseif (preg_match('/^msgid\s+(".*")/', $line, $m)) {
if ($is_final($context)) {
PO::read_line($f, 'put-back');
$lineno--;
break;
}
if ($context && $context != 'msgctxt' && $context != 'comment') {
return false;
}
$context = 'msgid';
$entry->singular .= PO::unpoify($m[1]);
} elseif (preg_match('/^msgid_plural\s+(".*")/', $line, $m)) {
if ($context != 'msgid') {
return false;
}
$context = 'msgid_plural';
$entry->is_plural = true;
$entry->plural .= PO::unpoify($m[1]);
} elseif (preg_match('/^msgstr\s+(".*")/', $line, $m)) {
if ($context != 'msgid') {
return false;
}
$context = 'msgstr';
$entry->translations = array(PO::unpoify($m[1]));
} elseif (preg_match('/^msgstr\[(\d+)\]\s+(".*")/', $line, $m)) {
if ($context != 'msgid_plural' && $context != 'msgstr_plural') {
return false;
}
$context = 'msgstr_plural';
$msgstr_index = $m[1];
$entry->translations[$m[1]] = PO::unpoify($m[2]);
} elseif (preg_match('/^".*"$/', $line)) {
$unpoified = PO::unpoify($line);
switch ($context) {
case 'msgid':
$entry->singular .= $unpoified; break;
case 'msgctxt':
$entry->context .= $unpoified; break;
case 'msgid_plural':
$entry->plural .= $unpoified; break;
case 'msgstr':
$entry->translations[0] .= $unpoified; break;
case 'msgstr_plural':
$entry->translations[$msgstr_index] .= $unpoified; break;
default:
return false;
}
} else {
return false;
}
}
if (array() == array_filter($entry->translations, create_function('$t', 'return $t || "0" === $t;'))) {
$entry->translations = array();
}
return array('entry' => $entry, 'lineno' => $lineno);
}
function read_line($f, $action = 'read') {
static $last_line = '';
static $use_last_line = false;
if ('clear' == $action) {
$last_line = '';
return true;
}
if ('put-back' == $action) {
$use_last_line = true;
return true;
}
$line = $use_last_line? $last_line : fgets($f);
$line = ( "\r\n" == substr( $line, -2 ) ) ? rtrim( $line, "\r\n" ) . "\n" : $line;
$last_line = $line;
$use_last_line = false;
return $line;
}
function add_comment_to_entry(&$entry, $po_comment_line) {
$first_two = substr($po_comment_line, 0, 2);
$comment = trim(substr($po_comment_line, 2));
if ('#:' == $first_two) {
$entry->references = array_merge($entry->references, preg_split('/\s+/', $comment));
} elseif ('#.' == $first_two) {
$entry->extracted_comments = trim($entry->extracted_comments . "\n" . $comment);
} elseif ('#,' == $first_two) {
$entry->flags = array_merge($entry->flags, preg_split('/,\s*/', $comment));
} else {
$entry->translator_comments = trim($entry->translator_comments . "\n" . $comment);
}
}
function trim_quotes($s) {
if ( substr($s, 0, 1) == '"') $s = substr($s, 1);
if ( substr($s, -1, 1) == '"') $s = substr($s, 0, -1);
return $s;
}
}
endif;
| PHP |
<?php
/**
* Class for a set of entries for translation and their associated headers
*
* @version $Id: translations.php 718 2012-10-31 00:32:02Z nbachiyski $
* @package pomo
* @subpackage translations
*/
require_once dirname(__FILE__) . '/entry.php';
if ( !class_exists( 'Translations' ) ):
class Translations {
var $entries = array();
var $headers = array();
/**
* Add entry to the PO structure
*
* @param object &$entry
* @return bool true on success, false if the entry doesn't have a key
*/
function add_entry($entry) {
if (is_array($entry)) {
$entry = new Translation_Entry($entry);
}
$key = $entry->key();
if (false === $key) return false;
$this->entries[$key] = &$entry;
return true;
}
function add_entry_or_merge($entry) {
if (is_array($entry)) {
$entry = new Translation_Entry($entry);
}
$key = $entry->key();
if (false === $key) return false;
if (isset($this->entries[$key]))
$this->entries[$key]->merge_with($entry);
else
$this->entries[$key] = &$entry;
return true;
}
/**
* Sets $header PO header to $value
*
* If the header already exists, it will be overwritten
*
* TODO: this should be out of this class, it is gettext specific
*
* @param string $header header name, without trailing :
* @param string $value header value, without trailing \n
*/
function set_header($header, $value) {
$this->headers[$header] = $value;
}
function set_headers($headers) {
foreach($headers as $header => $value) {
$this->set_header($header, $value);
}
}
function get_header($header) {
return isset($this->headers[$header])? $this->headers[$header] : false;
}
function translate_entry(&$entry) {
$key = $entry->key();
return isset($this->entries[$key])? $this->entries[$key] : false;
}
function translate($singular, $context=null) {
$entry = new Translation_Entry(array('singular' => $singular, 'context' => $context));
$translated = $this->translate_entry($entry);
return ($translated && !empty($translated->translations))? $translated->translations[0] : $singular;
}
/**
* Given the number of items, returns the 0-based index of the plural form to use
*
* Here, in the base Translations class, the common logic for English is implemented:
* 0 if there is one element, 1 otherwise
*
* This function should be overrided by the sub-classes. For example MO/PO can derive the logic
* from their headers.
*
* @param integer $count number of items
*/
function select_plural_form($count) {
return 1 == $count? 0 : 1;
}
function get_plural_forms_count() {
return 2;
}
function translate_plural($singular, $plural, $count, $context = null) {
$entry = new Translation_Entry(array('singular' => $singular, 'plural' => $plural, 'context' => $context));
$translated = $this->translate_entry($entry);
$index = $this->select_plural_form($count);
$total_plural_forms = $this->get_plural_forms_count();
if ($translated && 0 <= $index && $index < $total_plural_forms &&
is_array($translated->translations) &&
isset($translated->translations[$index]))
return $translated->translations[$index];
else
return 1 == $count? $singular : $plural;
}
/**
* Merge $other in the current object.
*
* @param Object &$other Another Translation object, whose translations will be merged in this one
* @return void
**/
function merge_with(&$other) {
foreach( $other->entries as $entry ) {
$this->entries[$entry->key()] = $entry;
}
}
function merge_originals_with(&$other) {
foreach( $other->entries as $entry ) {
if ( !isset( $this->entries[$entry->key()] ) )
$this->entries[$entry->key()] = $entry;
else
$this->entries[$entry->key()]->merge_with($entry);
}
}
}
class Gettext_Translations extends Translations {
/**
* The gettext implementation of select_plural_form.
*
* It lives in this class, because there are more than one descendand, which will use it and
* they can't share it effectively.
*
*/
function gettext_select_plural_form($count) {
if (!isset($this->_gettext_select_plural_form) || is_null($this->_gettext_select_plural_form)) {
list( $nplurals, $expression ) = $this->nplurals_and_expression_from_header($this->get_header('Plural-Forms'));
$this->_nplurals = $nplurals;
$this->_gettext_select_plural_form = $this->make_plural_form_function($nplurals, $expression);
}
return call_user_func($this->_gettext_select_plural_form, $count);
}
function nplurals_and_expression_from_header($header) {
if (preg_match('/^\s*nplurals\s*=\s*(\d+)\s*;\s+plural\s*=\s*(.+)$/', $header, $matches)) {
$nplurals = (int)$matches[1];
$expression = trim($this->parenthesize_plural_exression($matches[2]));
return array($nplurals, $expression);
} else {
return array(2, 'n != 1');
}
}
/**
* Makes a function, which will return the right translation index, according to the
* plural forms header
*/
function make_plural_form_function($nplurals, $expression) {
$expression = str_replace('n', '$n', $expression);
$func_body = "
\$index = (int)($expression);
return (\$index < $nplurals)? \$index : $nplurals - 1;";
return create_function('$n', $func_body);
}
/**
* Adds parantheses to the inner parts of ternary operators in
* plural expressions, because PHP evaluates ternary oerators from left to right
*
* @param string $expression the expression without parentheses
* @return string the expression with parentheses added
*/
function parenthesize_plural_exression($expression) {
$expression .= ';';
$res = '';
$depth = 0;
for ($i = 0; $i < strlen($expression); ++$i) {
$char = $expression[$i];
switch ($char) {
case '?':
$res .= ' ? (';
$depth++;
break;
case ':':
$res .= ') : (';
break;
case ';':
$res .= str_repeat(')', $depth) . ';';
$depth= 0;
break;
default:
$res .= $char;
}
}
return rtrim($res, ';');
}
function make_headers($translation) {
$headers = array();
// sometimes \ns are used instead of real new lines
$translation = str_replace('\n', "\n", $translation);
$lines = explode("\n", $translation);
foreach($lines as $line) {
$parts = explode(':', $line, 2);
if (!isset($parts[1])) continue;
$headers[trim($parts[0])] = trim($parts[1]);
}
return $headers;
}
function set_header($header, $value) {
parent::set_header($header, $value);
if ('Plural-Forms' == $header) {
list( $nplurals, $expression ) = $this->nplurals_and_expression_from_header($this->get_header('Plural-Forms'));
$this->_nplurals = $nplurals;
$this->_gettext_select_plural_form = $this->make_plural_form_function($nplurals, $expression);
}
}
}
endif;
if ( !class_exists( 'NOOP_Translations' ) ):
/**
* Provides the same interface as Translations, but doesn't do anything
*/
class NOOP_Translations {
var $entries = array();
var $headers = array();
function add_entry($entry) {
return true;
}
function set_header($header, $value) {
}
function set_headers($headers) {
}
function get_header($header) {
return false;
}
function translate_entry(&$entry) {
return false;
}
function translate($singular, $context=null) {
return $singular;
}
function select_plural_form($count) {
return 1 == $count? 0 : 1;
}
function get_plural_forms_count() {
return 2;
}
function translate_plural($singular, $plural, $count, $context = null) {
return 1 == $count? $singular : $plural;
}
function merge_with(&$other) {
}
}
endif;
| PHP |
<?php
/**
* MagpieRSS: a simple RSS integration tool
*
* A compiled file for RSS syndication
*
* @author Kellan Elliott-McCrea <kellan@protest.net>
* @version 0.51
* @license GPL
*
* @package External
* @subpackage MagpieRSS
* @deprecated 3.0.0 Use SimplePie instead.
*/
/**
* Deprecated. Use SimplePie (class-simplepie.php) instead.
*/
_deprecated_file( basename( __FILE__ ), '3.0', WPINC . '/class-simplepie.php' );
/**
* Fires before MagpieRSS is loaded, to optionally replace it.
*
* @since 2.3.0
* @deprecated 3.0.0
*/
do_action( 'load_feed_engine' );
/** RSS feed constant. */
define('RSS', 'RSS');
define('ATOM', 'Atom');
define('MAGPIE_USER_AGENT', 'WordPress/' . $GLOBALS['wp_version']);
class MagpieRSS {
var $parser;
var $current_item = array(); // item currently being parsed
var $items = array(); // collection of parsed items
var $channel = array(); // hash of channel fields
var $textinput = array();
var $image = array();
var $feed_type;
var $feed_version;
// parser variables
var $stack = array(); // parser stack
var $inchannel = false;
var $initem = false;
var $incontent = false; // if in Atom <content mode="xml"> field
var $intextinput = false;
var $inimage = false;
var $current_field = '';
var $current_namespace = false;
//var $ERROR = "";
var $_CONTENT_CONSTRUCTS = array('content', 'summary', 'info', 'title', 'tagline', 'copyright');
function MagpieRSS ($source) {
# if PHP xml isn't compiled in, die
#
if ( !function_exists('xml_parser_create') )
trigger_error( "Failed to load PHP's XML Extension. http://www.php.net/manual/en/ref.xml.php" );
$parser = @xml_parser_create();
if ( !is_resource($parser) )
trigger_error( "Failed to create an instance of PHP's XML parser. http://www.php.net/manual/en/ref.xml.php");
$this->parser = $parser;
# pass in parser, and a reference to this object
# set up handlers
#
xml_set_object( $this->parser, $this );
xml_set_element_handler($this->parser,
'feed_start_element', 'feed_end_element' );
xml_set_character_data_handler( $this->parser, 'feed_cdata' );
$status = xml_parse( $this->parser, $source );
if (! $status ) {
$errorcode = xml_get_error_code( $this->parser );
if ( $errorcode != XML_ERROR_NONE ) {
$xml_error = xml_error_string( $errorcode );
$error_line = xml_get_current_line_number($this->parser);
$error_col = xml_get_current_column_number($this->parser);
$errormsg = "$xml_error at line $error_line, column $error_col";
$this->error( $errormsg );
}
}
xml_parser_free( $this->parser );
$this->normalize();
}
function feed_start_element($p, $element, &$attrs) {
$el = $element = strtolower($element);
$attrs = array_change_key_case($attrs, CASE_LOWER);
// check for a namespace, and split if found
$ns = false;
if ( strpos( $element, ':' ) ) {
list($ns, $el) = split( ':', $element, 2);
}
if ( $ns and $ns != 'rdf' ) {
$this->current_namespace = $ns;
}
# if feed type isn't set, then this is first element of feed
# identify feed from root element
#
if (!isset($this->feed_type) ) {
if ( $el == 'rdf' ) {
$this->feed_type = RSS;
$this->feed_version = '1.0';
}
elseif ( $el == 'rss' ) {
$this->feed_type = RSS;
$this->feed_version = $attrs['version'];
}
elseif ( $el == 'feed' ) {
$this->feed_type = ATOM;
$this->feed_version = $attrs['version'];
$this->inchannel = true;
}
return;
}
if ( $el == 'channel' )
{
$this->inchannel = true;
}
elseif ($el == 'item' or $el == 'entry' )
{
$this->initem = true;
if ( isset($attrs['rdf:about']) ) {
$this->current_item['about'] = $attrs['rdf:about'];
}
}
// if we're in the default namespace of an RSS feed,
// record textinput or image fields
elseif (
$this->feed_type == RSS and
$this->current_namespace == '' and
$el == 'textinput' )
{
$this->intextinput = true;
}
elseif (
$this->feed_type == RSS and
$this->current_namespace == '' and
$el == 'image' )
{
$this->inimage = true;
}
# handle atom content constructs
elseif ( $this->feed_type == ATOM and in_array($el, $this->_CONTENT_CONSTRUCTS) )
{
// avoid clashing w/ RSS mod_content
if ($el == 'content' ) {
$el = 'atom_content';
}
$this->incontent = $el;
}
// if inside an Atom content construct (e.g. content or summary) field treat tags as text
elseif ($this->feed_type == ATOM and $this->incontent )
{
// if tags are inlined, then flatten
$attrs_str = join(' ',
array_map(array('MagpieRSS', 'map_attrs'),
array_keys($attrs),
array_values($attrs) ) );
$this->append_content( "<$element $attrs_str>" );
array_unshift( $this->stack, $el );
}
// Atom support many links per containging element.
// Magpie treats link elements of type rel='alternate'
// as being equivalent to RSS's simple link element.
//
elseif ($this->feed_type == ATOM and $el == 'link' )
{
if ( isset($attrs['rel']) and $attrs['rel'] == 'alternate' )
{
$link_el = 'link';
}
else {
$link_el = 'link_' . $attrs['rel'];
}
$this->append($link_el, $attrs['href']);
}
// set stack[0] to current element
else {
array_unshift($this->stack, $el);
}
}
function feed_cdata ($p, $text) {
if ($this->feed_type == ATOM and $this->incontent)
{
$this->append_content( $text );
}
else {
$current_el = join('_', array_reverse($this->stack));
$this->append($current_el, $text);
}
}
function feed_end_element ($p, $el) {
$el = strtolower($el);
if ( $el == 'item' or $el == 'entry' )
{
$this->items[] = $this->current_item;
$this->current_item = array();
$this->initem = false;
}
elseif ($this->feed_type == RSS and $this->current_namespace == '' and $el == 'textinput' )
{
$this->intextinput = false;
}
elseif ($this->feed_type == RSS and $this->current_namespace == '' and $el == 'image' )
{
$this->inimage = false;
}
elseif ($this->feed_type == ATOM and in_array($el, $this->_CONTENT_CONSTRUCTS) )
{
$this->incontent = false;
}
elseif ($el == 'channel' or $el == 'feed' )
{
$this->inchannel = false;
}
elseif ($this->feed_type == ATOM and $this->incontent ) {
// balance tags properly
// note: i don't think this is actually neccessary
if ( $this->stack[0] == $el )
{
$this->append_content("</$el>");
}
else {
$this->append_content("<$el />");
}
array_shift( $this->stack );
}
else {
array_shift( $this->stack );
}
$this->current_namespace = false;
}
function concat (&$str1, $str2="") {
if (!isset($str1) ) {
$str1="";
}
$str1 .= $str2;
}
function append_content($text) {
if ( $this->initem ) {
$this->concat( $this->current_item[ $this->incontent ], $text );
}
elseif ( $this->inchannel ) {
$this->concat( $this->channel[ $this->incontent ], $text );
}
}
// smart append - field and namespace aware
function append($el, $text) {
if (!$el) {
return;
}
if ( $this->current_namespace )
{
if ( $this->initem ) {
$this->concat(
$this->current_item[ $this->current_namespace ][ $el ], $text);
}
elseif ($this->inchannel) {
$this->concat(
$this->channel[ $this->current_namespace][ $el ], $text );
}
elseif ($this->intextinput) {
$this->concat(
$this->textinput[ $this->current_namespace][ $el ], $text );
}
elseif ($this->inimage) {
$this->concat(
$this->image[ $this->current_namespace ][ $el ], $text );
}
}
else {
if ( $this->initem ) {
$this->concat(
$this->current_item[ $el ], $text);
}
elseif ($this->intextinput) {
$this->concat(
$this->textinput[ $el ], $text );
}
elseif ($this->inimage) {
$this->concat(
$this->image[ $el ], $text );
}
elseif ($this->inchannel) {
$this->concat(
$this->channel[ $el ], $text );
}
}
}
function normalize () {
// if atom populate rss fields
if ( $this->is_atom() ) {
$this->channel['descripton'] = $this->channel['tagline'];
for ( $i = 0; $i < count($this->items); $i++) {
$item = $this->items[$i];
if ( isset($item['summary']) )
$item['description'] = $item['summary'];
if ( isset($item['atom_content']))
$item['content']['encoded'] = $item['atom_content'];
$this->items[$i] = $item;
}
}
elseif ( $this->is_rss() ) {
$this->channel['tagline'] = $this->channel['description'];
for ( $i = 0; $i < count($this->items); $i++) {
$item = $this->items[$i];
if ( isset($item['description']))
$item['summary'] = $item['description'];
if ( isset($item['content']['encoded'] ) )
$item['atom_content'] = $item['content']['encoded'];
$this->items[$i] = $item;
}
}
}
function is_rss () {
if ( $this->feed_type == RSS ) {
return $this->feed_version;
}
else {
return false;
}
}
function is_atom() {
if ( $this->feed_type == ATOM ) {
return $this->feed_version;
}
else {
return false;
}
}
function map_attrs($k, $v) {
return "$k=\"$v\"";
}
function error( $errormsg, $lvl = E_USER_WARNING ) {
// append PHP's error message if track_errors enabled
if ( isset($php_errormsg) ) {
$errormsg .= " ($php_errormsg)";
}
if ( MAGPIE_DEBUG ) {
trigger_error( $errormsg, $lvl);
} else {
error_log( $errormsg, 0);
}
}
}
if ( !function_exists('fetch_rss') ) :
/**
* Build Magpie object based on RSS from URL.
*
* @since 1.5.0
* @package External
* @subpackage MagpieRSS
*
* @param string $url URL to retrieve feed
* @return bool|MagpieRSS false on failure or MagpieRSS object on success.
*/
function fetch_rss ($url) {
// initialize constants
init();
if ( !isset($url) ) {
// error("fetch_rss called without a url");
return false;
}
// if cache is disabled
if ( !MAGPIE_CACHE_ON ) {
// fetch file, and parse it
$resp = _fetch_remote_file( $url );
if ( is_success( $resp->status ) ) {
return _response_to_rss( $resp );
}
else {
// error("Failed to fetch $url and cache is off");
return false;
}
}
// else cache is ON
else {
// Flow
// 1. check cache
// 2. if there is a hit, make sure it's fresh
// 3. if cached obj fails freshness check, fetch remote
// 4. if remote fails, return stale object, or error
$cache = new RSSCache( MAGPIE_CACHE_DIR, MAGPIE_CACHE_AGE );
if (MAGPIE_DEBUG and $cache->ERROR) {
debug($cache->ERROR, E_USER_WARNING);
}
$cache_status = 0; // response of check_cache
$request_headers = array(); // HTTP headers to send with fetch
$rss = 0; // parsed RSS object
$errormsg = 0; // errors, if any
if (!$cache->ERROR) {
// return cache HIT, MISS, or STALE
$cache_status = $cache->check_cache( $url );
}
// if object cached, and cache is fresh, return cached obj
if ( $cache_status == 'HIT' ) {
$rss = $cache->get( $url );
if ( isset($rss) and $rss ) {
$rss->from_cache = 1;
if ( MAGPIE_DEBUG > 1) {
debug("MagpieRSS: Cache HIT", E_USER_NOTICE);
}
return $rss;
}
}
// else attempt a conditional get
// set up headers
if ( $cache_status == 'STALE' ) {
$rss = $cache->get( $url );
if ( isset($rss->etag) and $rss->last_modified ) {
$request_headers['If-None-Match'] = $rss->etag;
$request_headers['If-Last-Modified'] = $rss->last_modified;
}
}
$resp = _fetch_remote_file( $url, $request_headers );
if (isset($resp) and $resp) {
if ($resp->status == '304' ) {
// we have the most current copy
if ( MAGPIE_DEBUG > 1) {
debug("Got 304 for $url");
}
// reset cache on 304 (at minutillo insistent prodding)
$cache->set($url, $rss);
return $rss;
}
elseif ( is_success( $resp->status ) ) {
$rss = _response_to_rss( $resp );
if ( $rss ) {
if (MAGPIE_DEBUG > 1) {
debug("Fetch successful");
}
// add object to cache
$cache->set( $url, $rss );
return $rss;
}
}
else {
$errormsg = "Failed to fetch $url. ";
if ( $resp->error ) {
# compensate for Snoopy's annoying habbit to tacking
# on '\n'
$http_error = substr($resp->error, 0, -2);
$errormsg .= "(HTTP Error: $http_error)";
}
else {
$errormsg .= "(HTTP Response: " . $resp->response_code .')';
}
}
}
else {
$errormsg = "Unable to retrieve RSS file for unknown reasons.";
}
// else fetch failed
// attempt to return cached object
if ($rss) {
if ( MAGPIE_DEBUG ) {
debug("Returning STALE object for $url");
}
return $rss;
}
// else we totally failed
// error( $errormsg );
return false;
} // end if ( !MAGPIE_CACHE_ON ) {
} // end fetch_rss()
endif;
/**
* Retrieve URL headers and content using WP HTTP Request API.
*
* @since 1.5.0
* @package External
* @subpackage MagpieRSS
*
* @param string $url URL to retrieve
* @param array $headers Optional. Headers to send to the URL.
* @return Snoopy style response
*/
function _fetch_remote_file($url, $headers = "" ) {
$resp = wp_safe_remote_request( $url, array( 'headers' => $headers, 'timeout' => MAGPIE_FETCH_TIME_OUT ) );
if ( is_wp_error($resp) ) {
$error = array_shift($resp->errors);
$resp = new stdClass;
$resp->status = 500;
$resp->response_code = 500;
$resp->error = $error[0] . "\n"; //\n = Snoopy compatibility
return $resp;
}
// Snoopy returns headers unprocessed.
// Also note, WP_HTTP lowercases all keys, Snoopy did not.
$return_headers = array();
foreach ( wp_remote_retrieve_headers( $resp ) as $key => $value ) {
if ( !is_array($value) ) {
$return_headers[] = "$key: $value";
} else {
foreach ( $value as $v )
$return_headers[] = "$key: $v";
}
}
$response = new stdClass;
$response->status = wp_remote_retrieve_response_code( $resp );
$response->response_code = wp_remote_retrieve_response_code( $resp );
$response->headers = $return_headers;
$response->results = wp_remote_retrieve_body( $resp );
return $response;
}
/**
* Retrieve
*
* @since 1.5.0
* @package External
* @subpackage MagpieRSS
*
* @param unknown_type $resp
* @return unknown
*/
function _response_to_rss ($resp) {
$rss = new MagpieRSS( $resp->results );
// if RSS parsed successfully
if ( $rss && (!isset($rss->ERROR) || !$rss->ERROR) ) {
// find Etag, and Last-Modified
foreach( (array) $resp->headers as $h) {
// 2003-03-02 - Nicola Asuni (www.tecnick.com) - fixed bug "Undefined offset: 1"
if (strpos($h, ": ")) {
list($field, $val) = explode(": ", $h, 2);
}
else {
$field = $h;
$val = "";
}
if ( $field == 'etag' ) {
$rss->etag = $val;
}
if ( $field == 'last-modified' ) {
$rss->last_modified = $val;
}
}
return $rss;
} // else construct error message
else {
$errormsg = "Failed to parse RSS file.";
if ($rss) {
$errormsg .= " (" . $rss->ERROR . ")";
}
// error($errormsg);
return false;
} // end if ($rss and !$rss->error)
}
/**
* Set up constants with default values, unless user overrides.
*
* @since 1.5.0
* @package External
* @subpackage MagpieRSS
*/
function init () {
if ( defined('MAGPIE_INITALIZED') ) {
return;
}
else {
define('MAGPIE_INITALIZED', 1);
}
if ( !defined('MAGPIE_CACHE_ON') ) {
define('MAGPIE_CACHE_ON', 1);
}
if ( !defined('MAGPIE_CACHE_DIR') ) {
define('MAGPIE_CACHE_DIR', './cache');
}
if ( !defined('MAGPIE_CACHE_AGE') ) {
define('MAGPIE_CACHE_AGE', 60*60); // one hour
}
if ( !defined('MAGPIE_CACHE_FRESH_ONLY') ) {
define('MAGPIE_CACHE_FRESH_ONLY', 0);
}
if ( !defined('MAGPIE_DEBUG') ) {
define('MAGPIE_DEBUG', 0);
}
if ( !defined('MAGPIE_USER_AGENT') ) {
$ua = 'WordPress/' . $GLOBALS['wp_version'];
if ( MAGPIE_CACHE_ON ) {
$ua = $ua . ')';
}
else {
$ua = $ua . '; No cache)';
}
define('MAGPIE_USER_AGENT', $ua);
}
if ( !defined('MAGPIE_FETCH_TIME_OUT') ) {
define('MAGPIE_FETCH_TIME_OUT', 2); // 2 second timeout
}
// use gzip encoding to fetch rss files if supported?
if ( !defined('MAGPIE_USE_GZIP') ) {
define('MAGPIE_USE_GZIP', true);
}
}
function is_info ($sc) {
return $sc >= 100 && $sc < 200;
}
function is_success ($sc) {
return $sc >= 200 && $sc < 300;
}
function is_redirect ($sc) {
return $sc >= 300 && $sc < 400;
}
function is_error ($sc) {
return $sc >= 400 && $sc < 600;
}
function is_client_error ($sc) {
return $sc >= 400 && $sc < 500;
}
function is_server_error ($sc) {
return $sc >= 500 && $sc < 600;
}
class RSSCache {
var $BASE_CACHE; // where the cache files are stored
var $MAX_AGE = 43200; // when are files stale, default twelve hours
var $ERROR = ''; // accumulate error messages
function RSSCache ($base='', $age='') {
$this->BASE_CACHE = WP_CONTENT_DIR . '/cache';
if ( $base ) {
$this->BASE_CACHE = $base;
}
if ( $age ) {
$this->MAX_AGE = $age;
}
}
/*=======================================================================*\
Function: set
Purpose: add an item to the cache, keyed on url
Input: url from wich the rss file was fetched
Output: true on sucess
\*=======================================================================*/
function set ($url, $rss) {
$cache_option = 'rss_' . $this->file_name( $url );
set_transient($cache_option, $rss, $this->MAX_AGE);
return $cache_option;
}
/*=======================================================================*\
Function: get
Purpose: fetch an item from the cache
Input: url from wich the rss file was fetched
Output: cached object on HIT, false on MISS
\*=======================================================================*/
function get ($url) {
$this->ERROR = "";
$cache_option = 'rss_' . $this->file_name( $url );
if ( ! $rss = get_transient( $cache_option ) ) {
$this->debug(
"Cache doesn't contain: $url (cache option: $cache_option)"
);
return 0;
}
return $rss;
}
/*=======================================================================*\
Function: check_cache
Purpose: check a url for membership in the cache
and whether the object is older then MAX_AGE (ie. STALE)
Input: url from wich the rss file was fetched
Output: cached object on HIT, false on MISS
\*=======================================================================*/
function check_cache ( $url ) {
$this->ERROR = "";
$cache_option = 'rss_' . $this->file_name( $url );
if ( get_transient($cache_option) ) {
// object exists and is current
return 'HIT';
} else {
// object does not exist
return 'MISS';
}
}
/*=======================================================================*\
Function: serialize
\*=======================================================================*/
function serialize ( $rss ) {
return serialize( $rss );
}
/*=======================================================================*\
Function: unserialize
\*=======================================================================*/
function unserialize ( $data ) {
return unserialize( $data );
}
/*=======================================================================*\
Function: file_name
Purpose: map url to location in cache
Input: url from wich the rss file was fetched
Output: a file name
\*=======================================================================*/
function file_name ($url) {
return md5( $url );
}
/*=======================================================================*\
Function: error
Purpose: register error
\*=======================================================================*/
function error ($errormsg, $lvl=E_USER_WARNING) {
// append PHP's error message if track_errors enabled
if ( isset($php_errormsg) ) {
$errormsg .= " ($php_errormsg)";
}
$this->ERROR = $errormsg;
if ( MAGPIE_DEBUG ) {
trigger_error( $errormsg, $lvl);
}
else {
error_log( $errormsg, 0);
}
}
function debug ($debugmsg, $lvl=E_USER_NOTICE) {
if ( MAGPIE_DEBUG ) {
$this->error("MagpieRSS [debug] $debugmsg", $lvl);
}
}
}
if ( !function_exists('parse_w3cdtf') ) :
function parse_w3cdtf ( $date_str ) {
# regex to match wc3dtf
$pat = "/(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(:(\d{2}))?(?:([-+])(\d{2}):?(\d{2})|(Z))?/";
if ( preg_match( $pat, $date_str, $match ) ) {
list( $year, $month, $day, $hours, $minutes, $seconds) =
array( $match[1], $match[2], $match[3], $match[4], $match[5], $match[7]);
# calc epoch for current date assuming GMT
$epoch = gmmktime( $hours, $minutes, $seconds, $month, $day, $year);
$offset = 0;
if ( $match[11] == 'Z' ) {
# zulu time, aka GMT
}
else {
list( $tz_mod, $tz_hour, $tz_min ) =
array( $match[8], $match[9], $match[10]);
# zero out the variables
if ( ! $tz_hour ) { $tz_hour = 0; }
if ( ! $tz_min ) { $tz_min = 0; }
$offset_secs = (($tz_hour*60)+$tz_min)*60;
# is timezone ahead of GMT? then subtract offset
#
if ( $tz_mod == '+' ) {
$offset_secs = $offset_secs * -1;
}
$offset = $offset_secs;
}
$epoch = $epoch + $offset;
return $epoch;
}
else {
return -1;
}
}
endif;
if ( !function_exists('wp_rss') ) :
/**
* Display all RSS items in a HTML ordered list.
*
* @since 1.5.0
* @package External
* @subpackage MagpieRSS
*
* @param string $url URL of feed to display. Will not auto sense feed URL.
* @param int $num_items Optional. Number of items to display, default is all.
*/
function wp_rss( $url, $num_items = -1 ) {
if ( $rss = fetch_rss( $url ) ) {
echo '<ul>';
if ( $num_items !== -1 ) {
$rss->items = array_slice( $rss->items, 0, $num_items );
}
foreach ( (array) $rss->items as $item ) {
printf(
'<li><a href="%1$s" title="%2$s">%3$s</a></li>',
esc_url( $item['link'] ),
esc_attr( strip_tags( $item['description'] ) ),
esc_html( $item['title'] )
);
}
echo '</ul>';
} else {
_e( 'An error has occurred, which probably means the feed is down. Try again later.' );
}
}
endif;
if ( !function_exists('get_rss') ) :
/**
* Display RSS items in HTML list items.
*
* You have to specify which HTML list you want, either ordered or unordered
* before using the function. You also have to specify how many items you wish
* to display. You can't display all of them like you can with wp_rss()
* function.
*
* @since 1.5.0
* @package External
* @subpackage MagpieRSS
*
* @param string $url URL of feed to display. Will not auto sense feed URL.
* @param int $num_items Optional. Number of items to display, default is all.
* @return bool False on failure.
*/
function get_rss ($url, $num_items = 5) { // Like get posts, but for RSS
$rss = fetch_rss($url);
if ( $rss ) {
$rss->items = array_slice($rss->items, 0, $num_items);
foreach ( (array) $rss->items as $item ) {
echo "<li>\n";
echo "<a href='$item[link]' title='$item[description]'>";
echo esc_html($item['title']);
echo "</a><br />\n";
echo "</li>\n";
}
} else {
return false;
}
}
endif;
| PHP |
<?php
/**
* Atom Feed Template for displaying Atom Comments feed.
*
* @package WordPress
*/
header('Content-Type: ' . feed_content_type('atom') . '; charset=' . get_option('blog_charset'), true);
echo '<?xml version="1.0" encoding="' . get_option('blog_charset') . '" ?' . '>';
?>
<feed
xmlns="http://www.w3.org/2005/Atom"
xml:lang="<?php bloginfo_rss( 'language' ); ?>"
xmlns:thr="http://purl.org/syndication/thread/1.0"
<?php
/** This action is documented in wp-includes/feed-atom.php */
do_action( 'atom_ns' );
/**
* Fires inside the feed tag in the Atom comment feed.
*
* @since 2.8.0
*/
do_action( 'atom_comments_ns' );
?>
>
<title type="text"><?php
if ( is_singular() )
printf( ent2ncr( __( 'Comments on %s' ) ), get_the_title_rss() );
elseif ( is_search() )
printf( ent2ncr( __( 'Comments for %1$s searching on %2$s' ) ), get_bloginfo_rss( 'name' ), get_search_query() );
else
printf( ent2ncr( __( 'Comments for %s' ) ), get_bloginfo_rss( 'name' ) . get_wp_title_rss() );
?></title>
<subtitle type="text"><?php bloginfo_rss('description'); ?></subtitle>
<updated><?php echo mysql2date('Y-m-d\TH:i:s\Z', get_lastcommentmodified('GMT'), false); ?></updated>
<?php if ( is_singular() ) { ?>
<link rel="alternate" type="<?php bloginfo_rss('html_type'); ?>" href="<?php comments_link_feed(); ?>" />
<link rel="self" type="application/atom+xml" href="<?php echo esc_url( get_post_comments_feed_link('', 'atom') ); ?>" />
<id><?php echo esc_url( get_post_comments_feed_link('', 'atom') ); ?></id>
<?php } elseif(is_search()) { ?>
<link rel="alternate" type="<?php bloginfo_rss('html_type'); ?>" href="<?php echo home_url() . '?s=' . get_search_query(); ?>" />
<link rel="self" type="application/atom+xml" href="<?php echo get_search_comments_feed_link('', 'atom'); ?>" />
<id><?php echo get_search_comments_feed_link('', 'atom'); ?></id>
<?php } else { ?>
<link rel="alternate" type="<?php bloginfo_rss('html_type'); ?>" href="<?php bloginfo_rss('url'); ?>" />
<link rel="self" type="application/atom+xml" href="<?php bloginfo_rss('comments_atom_url'); ?>" />
<id><?php bloginfo_rss('comments_atom_url'); ?></id>
<?php } ?>
<?php
/**
* Fires at the end of the Atom comment feed header.
*
* @since 2.8.0
*/
do_action( 'comments_atom_head' );
?>
<?php
if ( have_comments() ) : while ( have_comments() ) : the_comment();
$comment_post = $GLOBALS['post'] = get_post( $comment->comment_post_ID );
?>
<entry>
<title><?php
if ( !is_singular() ) {
$title = get_the_title($comment_post->ID);
/** This filter is documented in wp-includes/feed.php */
$title = apply_filters( 'the_title_rss', $title );
printf(ent2ncr(__('Comment on %1$s by %2$s')), $title, get_comment_author_rss());
} else {
printf(ent2ncr(__('By: %s')), get_comment_author_rss());
}
?></title>
<link rel="alternate" href="<?php comment_link(); ?>" type="<?php bloginfo_rss('html_type'); ?>" />
<author>
<name><?php comment_author_rss(); ?></name>
<?php if (get_comment_author_url()) echo '<uri>' . get_comment_author_url() . '</uri>'; ?>
</author>
<id><?php comment_guid(); ?></id>
<updated><?php echo mysql2date('Y-m-d\TH:i:s\Z', get_comment_time('Y-m-d H:i:s', true, false), false); ?></updated>
<published><?php echo mysql2date('Y-m-d\TH:i:s\Z', get_comment_time('Y-m-d H:i:s', true, false), false); ?></published>
<?php if ( post_password_required($comment_post) ) : ?>
<content type="html" xml:base="<?php comment_link(); ?>"><![CDATA[<?php echo get_the_password_form(); ?>]]></content>
<?php else : // post pass ?>
<content type="html" xml:base="<?php comment_link(); ?>"><![CDATA[<?php comment_text(); ?>]]></content>
<?php endif; // post pass
// Return comment threading information (http://www.ietf.org/rfc/rfc4685.txt)
if ( $comment->comment_parent == 0 ) : // This comment is top level ?>
<thr:in-reply-to ref="<?php the_guid(); ?>" href="<?php the_permalink_rss() ?>" type="<?php bloginfo_rss('html_type'); ?>" />
<?php else : // This comment is in reply to another comment
$parent_comment = get_comment($comment->comment_parent);
// The rel attribute below and the id tag above should be GUIDs, but WP doesn't create them for comments (unlike posts). Either way, it's more important that they both use the same system
?>
<thr:in-reply-to ref="<?php comment_guid($parent_comment) ?>" href="<?php echo get_comment_link($parent_comment) ?>" type="<?php bloginfo_rss('html_type'); ?>" />
<?php endif;
/**
* Fires at the end of each Atom comment feed item.
*
* @since 2.2.0
*
* @param int $comment_id ID of the current comment.
* @param int $comment_post_id ID of the post the current comment is connected to.
*/
do_action( 'comment_atom_entry', $comment->comment_ID, $comment_post->ID );
?>
</entry>
<?php endwhile; endif; ?>
</feed>
| PHP |
<?php
/**
* Gets the email message from the user's mailbox to add as
* a WordPress post. Mailbox connection information must be
* configured under Settings > Writing
*
* @package WordPress
*/
/** Make sure that the WordPress bootstrap has run before continuing. */
require(dirname(__FILE__) . '/wp-load.php');
/** This filter is documented in wp-admin/options.php */
if ( ! apply_filters( 'enable_post_by_email_configuration', true ) )
wp_die( __( 'This action has been disabled by the administrator.' ) );
/**
* Fires to allow a plugin to do a complete takeover of Post by Email.
*
* @since 2.9.0
*/
do_action( 'wp-mail.php' );
/** Get the POP3 class with which to access the mailbox. */
require_once( ABSPATH . WPINC . '/class-pop3.php' );
/** Only check at this interval for new messages. */
if ( !defined('WP_MAIL_INTERVAL') )
define('WP_MAIL_INTERVAL', 300); // 5 minutes
$last_checked = get_transient('mailserver_last_checked');
if ( $last_checked )
wp_die(__('Slow down cowboy, no need to check for new mails so often!'));
set_transient('mailserver_last_checked', true, WP_MAIL_INTERVAL);
$time_difference = get_option('gmt_offset') * HOUR_IN_SECONDS;
$phone_delim = '::';
$pop3 = new POP3();
if ( !$pop3->connect( get_option('mailserver_url'), get_option('mailserver_port') ) || !$pop3->user( get_option('mailserver_login') ) )
wp_die( esc_html( $pop3->ERROR ) );
$count = $pop3->pass( get_option('mailserver_pass') );
if( false === $count )
wp_die( esc_html( $pop3->ERROR ) );
if( 0 === $count ) {
$pop3->quit();
wp_die( __('There doesn’t seem to be any new mail.') );
}
for ( $i = 1; $i <= $count; $i++ ) {
$message = $pop3->get($i);
$bodysignal = false;
$boundary = '';
$charset = '';
$content = '';
$content_type = '';
$content_transfer_encoding = '';
$post_author = 1;
$author_found = false;
$dmonths = array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
foreach ($message as $line) {
// body signal
if ( strlen($line) < 3 )
$bodysignal = true;
if ( $bodysignal ) {
$content .= $line;
} else {
if ( preg_match('/Content-Type: /i', $line) ) {
$content_type = trim($line);
$content_type = substr($content_type, 14, strlen($content_type) - 14);
$content_type = explode(';', $content_type);
if ( ! empty( $content_type[1] ) ) {
$charset = explode('=', $content_type[1]);
$charset = ( ! empty( $charset[1] ) ) ? trim($charset[1]) : '';
}
$content_type = $content_type[0];
}
if ( preg_match('/Content-Transfer-Encoding: /i', $line) ) {
$content_transfer_encoding = trim($line);
$content_transfer_encoding = substr($content_transfer_encoding, 27, strlen($content_transfer_encoding) - 27);
$content_transfer_encoding = explode(';', $content_transfer_encoding);
$content_transfer_encoding = $content_transfer_encoding[0];
}
if ( ( $content_type == 'multipart/alternative' ) && ( false !== strpos($line, 'boundary="') ) && ( '' == $boundary ) ) {
$boundary = trim($line);
$boundary = explode('"', $boundary);
$boundary = $boundary[1];
}
if (preg_match('/Subject: /i', $line)) {
$subject = trim($line);
$subject = substr($subject, 9, strlen($subject) - 9);
// Captures any text in the subject before $phone_delim as the subject
if ( function_exists('iconv_mime_decode') ) {
$subject = iconv_mime_decode($subject, 2, get_option('blog_charset'));
} else {
$subject = wp_iso_descrambler($subject);
}
$subject = explode($phone_delim, $subject);
$subject = $subject[0];
}
// Set the author using the email address (From or Reply-To, the last used)
// otherwise use the site admin
if ( ! $author_found && preg_match( '/^(From|Reply-To): /', $line ) ) {
if ( preg_match('|[a-z0-9_.-]+@[a-z0-9_.-]+(?!.*<)|i', $line, $matches) )
$author = $matches[0];
else
$author = trim($line);
$author = sanitize_email($author);
if ( is_email($author) ) {
echo '<p>' . sprintf(__('Author is %s'), $author) . '</p>';
$userdata = get_user_by('email', $author);
if ( ! empty( $userdata ) ) {
$post_author = $userdata->ID;
$author_found = true;
}
}
}
if (preg_match('/Date: /i', $line)) { // of the form '20 Mar 2002 20:32:37'
$ddate = trim($line);
$ddate = str_replace('Date: ', '', $ddate);
if (strpos($ddate, ',')) {
$ddate = trim(substr($ddate, strpos($ddate, ',') + 1, strlen($ddate)));
}
$date_arr = explode(' ', $ddate);
$date_time = explode(':', $date_arr[3]);
$ddate_H = $date_time[0];
$ddate_i = $date_time[1];
$ddate_s = $date_time[2];
$ddate_m = $date_arr[1];
$ddate_d = $date_arr[0];
$ddate_Y = $date_arr[2];
for ( $j = 0; $j < 12; $j++ ) {
if ( $ddate_m == $dmonths[$j] ) {
$ddate_m = $j+1;
}
}
$time_zn = intval($date_arr[4]) * 36;
$ddate_U = gmmktime($ddate_H, $ddate_i, $ddate_s, $ddate_m, $ddate_d, $ddate_Y);
$ddate_U = $ddate_U - $time_zn;
$post_date = gmdate('Y-m-d H:i:s', $ddate_U + $time_difference);
$post_date_gmt = gmdate('Y-m-d H:i:s', $ddate_U);
}
}
}
// Set $post_status based on $author_found and on author's publish_posts capability
if ( $author_found ) {
$user = new WP_User($post_author);
$post_status = ( $user->has_cap('publish_posts') ) ? 'publish' : 'pending';
} else {
// Author not found in DB, set status to pending. Author already set to admin.
$post_status = 'pending';
}
$subject = trim($subject);
if ( $content_type == 'multipart/alternative' ) {
$content = explode('--'.$boundary, $content);
$content = $content[2];
// match case-insensitive content-transfer-encoding
if ( preg_match( '/Content-Transfer-Encoding: quoted-printable/i', $content, $delim) ) {
$content = explode($delim[0], $content);
$content = $content[1];
}
$content = strip_tags($content, '<img><p><br><i><b><u><em><strong><strike><font><span><div>');
}
$content = trim($content);
/**
* Filter the original content of the email.
*
* Give Post-By-Email extending plugins full access to the content, either
* the raw content, or the content of the last quoted-printable section.
*
* @since 2.8.0
*
* @param string $content The original email content.
*/
$content = apply_filters( 'wp_mail_original_content', $content );
if ( false !== stripos($content_transfer_encoding, "quoted-printable") ) {
$content = quoted_printable_decode($content);
}
if ( function_exists('iconv') && ! empty( $charset ) ) {
$content = iconv($charset, get_option('blog_charset'), $content);
}
// Captures any text in the body after $phone_delim as the body
$content = explode($phone_delim, $content);
$content = empty( $content[1] ) ? $content[0] : $content[1];
$content = trim($content);
/**
* Filter the content of the post submitted by email before saving.
*
* @since 1.2.0
*
* @param string $content The email content.
*/
$post_content = apply_filters( 'phone_content', $content );
$post_title = xmlrpc_getposttitle($content);
if ($post_title == '') $post_title = $subject;
$post_category = array(get_option('default_email_category'));
$post_data = compact('post_content','post_title','post_date','post_date_gmt','post_author','post_category', 'post_status');
$post_data = wp_slash($post_data);
$post_ID = wp_insert_post($post_data);
if ( is_wp_error( $post_ID ) )
echo "\n" . $post_ID->get_error_message();
// We couldn't post, for whatever reason. Better move forward to the next email.
if ( empty( $post_ID ) )
continue;
/**
* Fires after a post submitted by email is published.
*
* @since 1.2.0
*
* @param int $post_ID The post ID.
*/
do_action( 'publish_phone', $post_ID );
echo "\n<p>" . sprintf(__('<strong>Author:</strong> %s'), esc_html($post_author)) . '</p>';
echo "\n<p>" . sprintf(__('<strong>Posted title:</strong> %s'), esc_html($post_title)) . '</p>';
if(!$pop3->delete($i)) {
echo '<p>' . sprintf(__('Oops: %s'), esc_html($pop3->ERROR)) . '</p>';
$pop3->reset();
exit;
} else {
echo '<p>' . sprintf(__('Mission complete. Message <strong>%s</strong> deleted.'), $i) . '</p>';
}
}
$pop3->quit();
| PHP |
<?php
/**
* The base configurations of the WordPress.
*
* This file has the following configurations: MySQL settings, Table Prefix,
* Secret Keys, WordPress Language, and ABSPATH. You can find more information
* by visiting {@link http://codex.wordpress.org/Editing_wp-config.php Editing
* wp-config.php} Codex page. You can get the MySQL settings from your web host.
*
* This file is used by the wp-config.php creation script during the
* installation. You don't have to use the web site, you can just copy this file
* to "wp-config.php" and fill in the values.
*
* @package WordPress
*/
// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', 'asahikasei');
/** MySQL database username */
define('DB_USER', 'root');
/** MySQL database password */
define('DB_PASSWORD', '');
/** MySQL hostname */
define('DB_HOST', 'localhost');
/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8');
/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');
/** Asahi Kasei */
define('WP_ENV', 'development');
/**#@+
* Authentication Unique Keys and Salts.
*
* Change these to different unique phrases!
* You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service}
* You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again.
*
* @since 2.6.0
*/
define('AUTH_KEY', 'ynT&ia=d1]+^)}8?kjB?JrPSn&&#Cihcld|gk]n~_aG@F|)$sfg{^/K2_I(]Dm}E');
define('SECURE_AUTH_KEY', ' z{tBC0Qo }{_N0Ugu#+c-;<CT]gfQGuOc@1g;|4x-t/4(c>g{5l{$z& ZiE_)k');
define('LOGGED_IN_KEY', 'qDT!];<g^da7Hj1Hi9rp}:jgphXwr.uI:K_A;0TP{&4qm~@YB-B6b$f`==YTB {x');
define('NONCE_KEY', '-lv:mo7i2!=-Og~Dp3_ZB:-bXDw6e6%0u$e^iLzCGT5q<J|y^htcJMg fyJ0u9X-');
define('AUTH_SALT', 'x4s[M ^2Khl^+P8Q)?Z_akscNX&%4W/,t#&1{+zo7<h$}ua<P4(G-@23e&DGRJsK');
define('SECURE_AUTH_SALT', 'v<w8%FAxQ,w>|%7^0*=+N_wE:CJ^|4EEQl>3S>iXF?] TdYOr)MiXR|09ZU]yNW~');
define('LOGGED_IN_SALT', 'Gd3>xRe.m]Z[S_KtQ_J,pF[o>om?qv/-c/;ArzN7{J{-.U,pBn*uC/iqQ(tv*+/O');
define('NONCE_SALT', 'THM,}~ -d*]-uc|?dfr/y,T-wjt6&;;U%s(Vvpk-2[rV{FQ;w6Noz)nM:0aA_u0t');
/**#@-*/
/**
* WordPress Database Table prefix.
*
* You can have multiple installations in one database if you give each a unique
* prefix. Only numbers, letters, and underscores please!
*/
$table_prefix = 'wp_';
/**
* WordPress Localized Language, defaults to English.
*
* Change this to localize WordPress. A corresponding MO file for the chosen
* language must be installed to wp-content/languages. For example, install
* de_DE.mo to wp-content/languages and set WPLANG to 'de_DE' to enable German
* language support.
*/
define('WPLANG', '');
/**
* For developers: WordPress debugging mode.
*
* Change this to true to enable the display of notices during development.
* It is strongly recommended that plugin and theme developers use WP_DEBUG
* in their development environments.
*/
define('WP_DEBUG', false);
/* That's all, stop editing! Happy blogging. */
/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
/** Sets up WordPress vars and included files. */
require_once(ABSPATH . 'wp-settings.php');
| PHP |
<?php
/**
* XML-RPC protocol support for WordPress
*
* @package WordPress
*/
/**
* Whether this is an XML-RPC Request
*
* @var bool
*/
define('XMLRPC_REQUEST', true);
// Some browser-embedded clients send cookies. We don't want them.
$_COOKIE = array();
// A bug in PHP < 5.2.2 makes $HTTP_RAW_POST_DATA not set by default,
// but we can do it ourself.
if ( !isset( $HTTP_RAW_POST_DATA ) ) {
$HTTP_RAW_POST_DATA = file_get_contents( 'php://input' );
}
// fix for mozBlog and other cases where '<?xml' isn't on the very first line
if ( isset($HTTP_RAW_POST_DATA) )
$HTTP_RAW_POST_DATA = trim($HTTP_RAW_POST_DATA);
/** Include the bootstrap for setting up WordPress environment */
include('./wp-load.php');
if ( isset( $_GET['rsd'] ) ) { // http://cyber.law.harvard.edu/blogs/gems/tech/rsd.html
header('Content-Type: text/xml; charset=' . get_option('blog_charset'), true);
?>
<?php echo '<?xml version="1.0" encoding="'.get_option('blog_charset').'"?'.'>'; ?>
<rsd version="1.0" xmlns="http://archipelago.phrasewise.com/rsd">
<service>
<engineName>WordPress</engineName>
<engineLink>http://wordpress.org/</engineLink>
<homePageLink><?php bloginfo_rss('url') ?></homePageLink>
<apis>
<api name="WordPress" blogID="1" preferred="true" apiLink="<?php echo site_url('xmlrpc.php', 'rpc') ?>" />
<api name="Movable Type" blogID="1" preferred="false" apiLink="<?php echo site_url('xmlrpc.php', 'rpc') ?>" />
<api name="MetaWeblog" blogID="1" preferred="false" apiLink="<?php echo site_url('xmlrpc.php', 'rpc') ?>" />
<api name="Blogger" blogID="1" preferred="false" apiLink="<?php echo site_url('xmlrpc.php', 'rpc') ?>" />
<?php
/**
* Add additional APIs to the Really Simple Discovery (RSD) endpoint.
*
* @link http://cyber.law.harvard.edu/blogs/gems/tech/rsd.html
*
* @since 3.5.0
*/
do_action( 'xmlrpc_rsd_apis' );
?>
</apis>
</service>
</rsd>
<?php
exit;
}
include_once(ABSPATH . 'wp-admin/includes/admin.php');
include_once(ABSPATH . WPINC . '/class-IXR.php');
include_once(ABSPATH . WPINC . '/class-wp-xmlrpc-server.php');
/**
* Posts submitted via the XML-RPC interface get that title
* @name post_default_title
* @var string
*/
$post_default_title = "";
/**
* Filter the class used for handling XML-RPC requests.
*
* @since 3.1.0
*
* @param string $class The name of the XML-RPC server class.
*/
$wp_xmlrpc_server_class = apply_filters( 'wp_xmlrpc_server_class', 'wp_xmlrpc_server' );
$wp_xmlrpc_server = new $wp_xmlrpc_server_class;
// Fire off the request
$wp_xmlrpc_server->serve_request();
exit;
/**
* logIO() - Writes logging info to a file.
*
* @deprecated 3.4.0
* @deprecated Use error_log()
*
* @param string $io Whether input or output
* @param string $msg Information describing logging reason.
*/
function logIO( $io, $msg ) {
_deprecated_function( __FUNCTION__, '3.4', 'error_log()' );
if ( ! empty( $GLOBALS['xmlrpc_logging'] ) )
error_log( $io . ' - ' . $msg );
} | PHP |
<?php
// Silence is golden.
| PHP |
<?php
// Silence is golden.
?> | PHP |
<?php
/*
* Meta box - fields
*
* This template file is used when editing a field group and creates the interface for editing fields.
*
* @type template
* @date 26/01/13
*/
// global
global $post, $field_types;
// get fields
$fields = apply_filters('acf/field_group/get_fields', array(), $post->ID);
// add clone
$fields[] = apply_filters('acf/load_field_defaults', array(
'key' => 'field_clone',
'label' => __("New Field",'acf'),
'name' => 'new_field',
'type' => 'text',
));
// get name of all fields for use in field type drop down
$field_types = apply_filters('acf/registered_fields', array());
// helper function
function field_type_exists( $name )
{
global $field_types;
foreach( $field_types as $category )
{
if( isset( $category[ $name ] ) )
{
return $category[ $name ];
}
}
return false;
}
// conditional logic dummy data
$conditional_logic_rule = array(
'field' => '',
'operator' => '==',
'value' => ''
);
$error_field_type = '<b>' . __('Error', 'acf') . '</b> ' . __('Field type does not exist', 'acf');
?>
<!-- Hidden Fields -->
<div style="display:none;">
<input type="hidden" name="acf_nonce" value="<?php echo wp_create_nonce( 'field_group' ); ?>" />
</div>
<!-- / Hidden Fields -->
<!-- Fields Header -->
<div class="fields_header">
<table class="acf widefat">
<thead>
<tr>
<th class="field_order"><?php _e('Field Order','acf'); ?></th>
<th class="field_label"><?php _e('Field Label','acf'); ?></th>
<th class="field_name"><?php _e('Field Name','acf'); ?></th>
<th class="field_type"><?php _e('Field Type','acf'); ?></th>
<th class="field_key"><?php _e('Field Key','acf'); ?></th>
</tr>
</thead>
</table>
</div>
<!-- / Fields Header -->
<div class="fields">
<!-- No Fields Message -->
<div class="no_fields_message" <?php if(count($fields) > 1){ echo 'style="display:none;"'; } ?>>
<?php _e("No fields. Click the <strong>+ Add Field</strong> button to create your first field.",'acf'); ?>
</div>
<!-- / No Fields Message -->
<?php foreach($fields as $field):
$fake_name = $field['key'];
?>
<div class="field field_type-<?php echo $field['type']; ?> field_key-<?php echo $field['key']; ?>" data-type="<?php echo $field['type']; ?>" data-id="<?php echo $field['key']; ?>">
<input type="hidden" class="input-field_key" name="fields[<?php echo $field['key']; ?>][key]" value="<?php echo $field['key']; ?>" />
<div class="field_meta">
<table class="acf widefat">
<tr>
<td class="field_order"><span class="circle"><?php echo (int)$field['order_no'] + 1; ?></span></td>
<td class="field_label">
<strong>
<a class="acf_edit_field row-title" title="<?php _e("Edit this Field",'acf'); ?>" href="javascript:;"><?php echo $field['label']; ?></a>
</strong>
<div class="row_options">
<span><a class="acf_edit_field" title="<?php _e("Edit this Field",'acf'); ?>" href="javascript:;"><?php _e("Edit",'acf'); ?></a> | </span>
<span><a title="<?php _e("Read documentation for this field",'acf'); ?>" href="http://www.advancedcustomfields.com/resources/#field-types" target="_blank"><?php _e("Docs",'acf'); ?></a> | </span>
<span><a class="acf_duplicate_field" title="<?php _e("Duplicate this Field",'acf'); ?>" href="javascript:;"><?php _e("Duplicate",'acf'); ?></a> | </span>
<span><a class="acf_delete_field" title="<?php _e("Delete this Field",'acf'); ?>" href="javascript:;"><?php _e("Delete",'acf'); ?></a></span>
</div>
</td>
<td class="field_name"><?php echo $field['name']; ?></td>
<td class="field_type"><?php $l = field_type_exists( $field['type'] ); if( $l ){ echo $l; }else{ echo $error_field_type; } ?></td>
<td class="field_key"><?php echo $field['key']; ?></td>
</tr>
</table>
</div>
<div class="field_form_mask">
<div class="field_form">
<table class="acf_input widefat acf_field_form_table">
<tbody>
<tr class="field_label">
<td class="label">
<label><?php _e("Field Label",'acf'); ?><span class="required">*</span></label>
<p class="description"><?php _e("This is the name which will appear on the EDIT page",'acf'); ?></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'text',
'name' => 'fields[' .$fake_name . '][label]',
'value' => $field['label'],
'class' => 'label',
));
?>
</td>
</tr>
<tr class="field_name">
<td class="label">
<label><?php _e("Field Name",'acf'); ?><span class="required">*</span></label>
<p class="description"><?php _e("Single word, no spaces. Underscores and dashes allowed",'acf'); ?></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'text',
'name' => 'fields[' .$fake_name . '][name]',
'value' => $field['name'],
'class' => 'name',
));
?>
</td>
</tr>
<tr class="field_type">
<td class="label">
<label><?php _e("Field Type",'acf'); ?><span class="required">*</span></label>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'select',
'name' => 'fields[' .$fake_name . '][type]',
'value' => $field['type'],
'choices' => $field_types,
));
?>
</td>
</tr>
<tr class="field_instructions">
<td class="label"><label><?php _e("Field Instructions",'acf'); ?></label>
<p class="description"><?php _e("Instructions for authors. Shown when submitting data",'acf'); ?></p></td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'textarea',
'name' => 'fields[' .$fake_name . '][instructions]',
'value' => $field['instructions'],
'rows' => 6
));
?>
</td>
</tr>
<tr class="required">
<td class="label"><label><?php _e("Required?",'acf'); ?></label></td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'radio',
'name' => 'fields[' .$fake_name . '][required]',
'value' => $field['required'],
'choices' => array(
1 => __("Yes",'acf'),
0 => __("No",'acf'),
),
'layout' => 'horizontal',
));
?>
</td>
</tr>
<?php
$field['name'] = $fake_name;
do_action('acf/create_field_options', $field );
?>
<tr class="conditional-logic" data-field_name="<?php echo $field['key']; ?>">
<td class="label"><label><?php _e("Conditional Logic",'acf'); ?></label></td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'radio',
'name' => 'fields['.$field['key'].'][conditional_logic][status]',
'value' => $field['conditional_logic']['status'],
'choices' => array(
1 => __("Yes",'acf'),
0 => __("No",'acf'),
),
'layout' => 'horizontal',
));
// no rules?
if( ! $field['conditional_logic']['rules'] )
{
$field['conditional_logic']['rules'] = array(
array() // this will get merged with $conditional_logic_rule
);
}
?>
<div class="contional-logic-rules-wrapper" <?php if( ! $field['conditional_logic']['status'] ) echo 'style="display:none"'; ?>>
<table class="conditional-logic-rules widefat acf-rules <?php if( count($field['conditional_logic']['rules']) == 1) echo 'remove-disabled'; ?>">
<tbody>
<?php foreach( $field['conditional_logic']['rules'] as $rule_i => $rule ):
// validate
$rule = array_merge($conditional_logic_rule, $rule);
// fix PHP error in 3.5.4.1
if( strpos($rule['value'],'Undefined index: value in') !== false )
{
$rule['value'] = '';
}
?>
<tr data-i="<?php echo $rule_i; ?>">
<td>
<input class="conditional-logic-field" type="hidden" name="fields[<?php echo $field['key']; ?>][conditional_logic][rules][<?php echo $rule_i; ?>][field]" value="<?php echo $rule['field']; ?>" />
</td>
<td width="25%">
<?php
do_action('acf/create_field', array(
'type' => 'select',
'name' => 'fields['.$field['key'].'][conditional_logic][rules][' . $rule_i . '][operator]',
'value' => $rule['operator'],
'choices' => array(
'==' => __("is equal to",'acf'),
'!=' => __("is not equal to",'acf'),
),
));
?>
</td>
<td><input class="conditional-logic-value" type="hidden" name="fields[<?php echo $field['key']; ?>][conditional_logic][rules][<?php echo $rule_i; ?>][value]" value="<?php echo $rule['value']; ?>" /></td>
<td class="buttons">
<ul class="hl clearfix">
<li><a class="acf-button-remove" href="javascript:;"></a></li>
<li><a class="acf-button-add" href="javascript:;"></a></li>
</ul>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<ul class="hl clearfix">
<li style="padding:4px 4px 0 0;"><?php _e("Show this field when",'acf'); ?></li>
<li><?php do_action('acf/create_field', array(
'type' => 'select',
'name' => 'fields['.$field['key'].'][conditional_logic][allorany]',
'value' => $field['conditional_logic']['allorany'],
'choices' => array(
'all' => __("all",'acf'),
'any' => __("any",'acf'),
),
)); ?></li>
<li style="padding:4px 0 0 4px;"><?php _e("these rules are met",'acf'); ?></li>
</ul>
</div>
</td>
</tr>
<tr class="field_save">
<td class="label"></td>
<td>
<ul class="hl clearfix">
<li>
<a class="acf_edit_field acf-button grey" title="<?php _e("Close Field",'acf'); ?>" href="javascript:;"><?php _e("Close Field",'acf'); ?></a>
</li>
</ul>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<?php endforeach; ?>
</div>
<div class="table_footer">
<div class="order_message"><?php _e('Drag and drop to reorder','acf'); ?></div>
<a href="javascript:;" id="add_field" class="acf-button"><?php _e('+ Add Field','acf'); ?></a>
</div> | PHP |
<?php
/*
* Meta box - locations
*
* This template file is used when editing a field group and creates the interface for editing location rules.
*
* @type template
* @date 23/06/12
*/
// global
global $post;
// vars
$groups = apply_filters('acf/field_group/get_location', array(), $post->ID);
// at lease 1 location rule
if( empty($groups) )
{
$groups = array(
// group_0
array(
// rule_0
array(
'param' => 'post_type',
'operator' => '==',
'value' => 'post',
'order_no' => 0,
'group_no' => 0
)
)
);
}
?>
<table class="acf_input widefat" id="acf_location">
<tbody>
<tr>
<td class="label">
<label for="post_type"><?php _e("Rules",'acf'); ?></label>
<p class="description"><?php _e("Create a set of rules to determine which edit screens will use these advanced custom fields",'acf'); ?></p>
</td>
<td>
<div class="location-groups">
<?php if( is_array($groups) ): ?>
<?php foreach( $groups as $group_id => $group ):
$group_id = 'group_' . $group_id;
?>
<div class="location-group" data-id="<?php echo $group_id; ?>">
<?php if( $group_id == 'group_0' ): ?>
<h4><?php _e("Show this field group if",'acf'); ?></h4>
<?php else: ?>
<h4><?php _e("or",'acf'); ?></h4>
<?php endif; ?>
<?php if( is_array($group) ): ?>
<table class="acf_input widefat">
<tbody>
<?php foreach( $group as $rule_id => $rule ):
$rule_id = 'rule_' . $rule_id;
?>
<tr data-id="<?php echo $rule_id; ?>">
<td class="param"><?php
$choices = array(
__("Basic",'acf') => array(
'post_type' => __("Post Type",'acf'),
'user_type' => __("Logged in User Type",'acf'),
),
__("Post",'acf') => array(
'post' => __("Post",'acf'),
'post_category' => __("Post Category",'acf'),
'post_format' => __("Post Format",'acf'),
'post_status' => __("Post Status",'acf'),
'taxonomy' => __("Post Taxonomy",'acf'),
),
__("Page",'acf') => array(
'page' => __("Page",'acf'),
'page_type' => __("Page Type",'acf'),
'page_parent' => __("Page Parent",'acf'),
'page_template' => __("Page Template",'acf'),
),
__("Other",'acf') => array(
'ef_media' => __("Attachment",'acf'),
'ef_taxonomy' => __("Taxonomy Term",'acf'),
'ef_user' => __("User",'acf'),
)
);
// allow custom location rules
$choices = apply_filters( 'acf/location/rule_types', $choices );
// create field
$args = array(
'type' => 'select',
'name' => 'location[' . $group_id . '][' . $rule_id . '][param]',
'value' => $rule['param'],
'choices' => $choices,
);
do_action('acf/create_field', $args);
?></td>
<td class="operator"><?php
$choices = array(
'==' => __("is equal to",'acf'),
'!=' => __("is not equal to",'acf'),
);
// allow custom location rules
$choices = apply_filters( 'acf/location/rule_operators', $choices );
// create field
do_action('acf/create_field', array(
'type' => 'select',
'name' => 'location[' . $group_id . '][' . $rule_id . '][operator]',
'value' => $rule['operator'],
'choices' => $choices
));
?></td>
<td class="value"><?php
$this->ajax_render_location(array(
'group_id' => $group_id,
'rule_id' => $rule_id,
'value' => $rule['value'],
'param' => $rule['param'],
));
?></td>
<td class="add">
<a href="#" class="location-add-rule button"><?php _e("and",'acf'); ?></a>
</td>
<td class="remove">
<a href="#" class="location-remove-rule acf-button-remove"></a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
</div>
<?php endforeach; ?>
<h4><?php _e("or",'acf'); ?></h4>
<a class="button location-add-group" href="#"><?php _e("Add rule group",'acf'); ?></a>
<?php endif; ?>
</div>
</td>
</tr>
</tbody>
</table> | PHP |
<?php
/*
* Meta box - options
*
* This template file is used when editing a field group and creates the interface for editing options.
*
* @type template
* @date 23/06/12
*/
// global
global $post;
// vars
$options = apply_filters('acf/field_group/get_options', array(), $post->ID);
?>
<table class="acf_input widefat" id="acf_options">
<tr>
<td class="label">
<label for=""><?php _e("Order No.",'acf'); ?></label>
<p class="description"><?php _e("Field groups are created in order <br />from lowest to highest",'acf'); ?></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'number',
'name' => 'menu_order',
'value' => $post->menu_order,
));
?>
</td>
</tr>
<tr>
<td class="label">
<label for=""><?php _e("Position",'acf'); ?></label>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'select',
'name' => 'options[position]',
'value' => $options['position'],
'choices' => array(
'acf_after_title' => __("High (after title)",'acf'),
'normal' => __("Normal (after content)",'acf'),
'side' => __("Side",'acf'),
),
'default_value' => 'normal'
));
?>
</td>
</tr>
<tr>
<td class="label">
<label for="post_type"><?php _e("Style",'acf'); ?></label>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'select',
'name' => 'options[layout]',
'value' => $options['layout'],
'choices' => array(
'no_box' => __("Seamless (no metabox)",'acf'),
'default' => __("Standard (WP metabox)",'acf'),
)
));
?>
</td>
</tr>
<tr id="hide-on-screen">
<td class="label">
<label for="post_type"><?php _e("Hide on screen",'acf'); ?></label>
<p class="description"><?php _e("<b>Select</b> items to <b>hide</b> them from the edit screen",'acf'); ?></p>
<p class="description"><?php _e("If multiple field groups appear on an edit screen, the first field group's options will be used. (the one with the lowest order number)",'acf'); ?></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'checkbox',
'name' => 'options[hide_on_screen]',
'value' => $options['hide_on_screen'],
'choices' => array(
'permalink' => __("Permalink", 'acf'),
'the_content' => __("Content Editor",'acf'),
'excerpt' => __("Excerpt", 'acf'),
'custom_fields' => __("Custom Fields", 'acf'),
'discussion' => __("Discussion", 'acf'),
'comments' => __("Comments", 'acf'),
'revisions' => __("Revisions", 'acf'),
'slug' => __("Slug", 'acf'),
'author' => __("Author", 'acf'),
'format' => __("Format", 'acf'),
'featured_image' => __("Featured Image", 'acf'),
'categories' => __("Categories", 'acf'),
'tags' => __("Tags", 'acf'),
'send-trackbacks' => __("Send Trackbacks", 'acf'),
)
));
?>
</td>
</tr>
</table> | PHP |
<?php
/*
* Export
*
* @description:
* @since: 3.6
* @created: 25/01/13
*/
// Exit if accessed directly
if ( !defined( 'ABSPATH' ) ) exit;
// vars
$defaults = array(
'acf_posts' => array(),
'nonce' => ''
);
$my_options = array_merge( $defaults, $_POST );
// validate nonce
if( !wp_verify_nonce($my_options['nonce'], 'export') )
{
wp_die(__("Error",'acf'));
}
// check for posts
if( empty($my_options['acf_posts']) )
{
wp_die(__("No ACF groups selected",'acf'));
}
/**
* Version number for the export format.
*
* Bump this when something changes that might affect compatibility.
*
* @since 2.5.0
*/
define( 'WXR_VERSION', '1.1' );
/*
* fix_line_breaks
*
* This function will loop through all array pieces and correct double line breaks from DB to XML
*
* @type function
* @date 2/12/2013
* @since 5.0.0
*
* @param $v (mixed)
* @return $v (mixed)
*/
function fix_line_breaks( $v )
{
if( is_array($v) )
{
foreach( array_keys($v) as $k )
{
$v[ $k ] = fix_line_breaks( $v[ $k ] );
}
}
elseif( is_string($v) )
{
$v = str_replace("\r\n", "\r", $v);
}
return $v;
}
/**
* Wrap given string in XML CDATA tag.
*
* @since 2.1.0
*
* @param string $str String to wrap in XML CDATA tag.
*/
function wxr_cdata( $str ) {
if ( seems_utf8( $str ) == false )
$str = utf8_encode( $str );
// $str = ent2ncr(esc_html($str));
$str = "<![CDATA[$str" . ( ( substr( $str, -1 ) == ']' ) ? ' ' : '' ) . ']]>';
return $str;
}
/**
* Return the URL of the site
*
* @since 2.5.0
*
* @return string Site URL.
*/
function wxr_site_url() {
// ms: the base url
if ( is_multisite() )
return network_home_url();
// wp: the blog url
else
return get_site_url();
}
/**
* Output a tag_description XML tag from a given tag object
*
* @since 2.3.0
*
* @param object $tag Tag Object
*/
function wxr_tag_description( $tag ) {
if ( empty( $tag->description ) )
return;
echo '<wp:tag_description>' . wxr_cdata( $tag->description ) . '</wp:tag_description>';
}
/**
* Output a term_name XML tag from a given term object
*
* @since 2.9.0
*
* @param object $term Term Object
*/
function wxr_term_name( $term ) {
if ( empty( $term->name ) )
return;
echo '<wp:term_name>' . wxr_cdata( $term->name ) . '</wp:term_name>';
}
/**
* Output a term_description XML tag from a given term object
*
* @since 2.9.0
*
* @param object $term Term Object
*/
function wxr_term_description( $term ) {
if ( empty( $term->description ) )
return;
echo '<wp:term_description>' . wxr_cdata( $term->description ) . '</wp:term_description>';
}
/**
* Output list of authors with posts
*
* @since 3.1.0
*/
function wxr_authors_list() {
global $wpdb;
$authors = array();
$results = $wpdb->get_results( "SELECT DISTINCT post_author FROM $wpdb->posts" );
foreach ( (array) $results as $result )
$authors[] = get_userdata( $result->post_author );
$authors = array_filter( $authors );
foreach( $authors as $author ) {
echo "\t<wp:author>";
echo '<wp:author_id>' . $author->ID . '</wp:author_id>';
echo '<wp:author_login>' . $author->user_login . '</wp:author_login>';
echo '<wp:author_email>' . $author->user_email . '</wp:author_email>';
echo '<wp:author_display_name>' . wxr_cdata( $author->display_name ) . '</wp:author_display_name>';
echo '<wp:author_first_name>' . wxr_cdata( $author->user_firstname ) . '</wp:author_first_name>';
echo '<wp:author_last_name>' . wxr_cdata( $author->user_lastname ) . '</wp:author_last_name>';
echo "</wp:author>\n";
}
}
header( 'Content-Description: File Transfer' );
header( 'Content-Disposition: attachment; filename=advanced-custom-field-export.xml' );
header( 'Content-Type: text/xml; charset=' . get_option( 'blog_charset' ), true );
echo '<?xml version="1.0" encoding="' . get_bloginfo('charset') . "\" ?>\n";
?>
<!-- This is a WordPress eXtended RSS file generated by WordPress as an export of your site. -->
<!-- It contains information about your site's posts, pages, comments, categories, and other content. -->
<!-- You may use this file to transfer that content from one site to another. -->
<!-- This file is not intended to serve as a complete backup of your site. -->
<!-- To import this information into a WordPress site follow these steps: -->
<!-- 1. Log in to that site as an administrator. -->
<!-- 2. Go to Tools: Import in the WordPress admin panel. -->
<!-- 3. Install the "WordPress" importer from the list. -->
<!-- 4. Activate & Run Importer. -->
<!-- 5. Upload this file using the form provided on that page. -->
<!-- 6. You will first be asked to map the authors in this export file to users -->
<!-- on the site. For each author, you may choose to map to an -->
<!-- existing user on the site or to create a new user. -->
<!-- 7. WordPress will then import each of the posts, pages, comments, categories, etc. -->
<!-- contained in this file into your site. -->
<?php the_generator( 'export' ); ?>
<rss version="2.0"
xmlns:excerpt="http://wordpress.org/export/<?php echo WXR_VERSION; ?>/excerpt/"
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:wfw="http://wellformedweb.org/CommentAPI/"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:wp="http://wordpress.org/export/<?php echo WXR_VERSION; ?>/"
>
<channel>
<title><?php bloginfo_rss( 'name' ); ?></title>
<link><?php bloginfo_rss( 'url' ); ?></link>
<description><?php bloginfo_rss( 'description' ); ?></description>
<pubDate><?php echo date( 'D, d M Y H:i:s +0000' ); ?></pubDate>
<language><?php echo get_option( 'rss_language' ); ?></language>
<wp:wxr_version><?php echo WXR_VERSION; ?></wp:wxr_version>
<wp:base_site_url><?php echo wxr_site_url(); ?></wp:base_site_url>
<wp:base_blog_url><?php bloginfo_rss( 'url' ); ?></wp:base_blog_url>
<?php wxr_authors_list(); ?>
<?php if ( $my_options['acf_posts'] ) {
global $wp_query, $wpdb, $post;
$wp_query->in_the_loop = true; // Fake being in the loop.
// create SQL with %d placeholders
$where = 'WHERE ID IN (' . substr(str_repeat('%d,', count($my_options['acf_posts'])), 0, -1) . ')';
// now prepare the SQL based on the %d + $_POST data
$posts = $wpdb->get_results( $wpdb->prepare("SELECT * FROM {$wpdb->posts} $where", $my_options['acf_posts']));
// Begin Loop
foreach ( $posts as $post ) {
setup_postdata( $post );
?>
<item>
<title><?php echo apply_filters( 'the_title_rss', $post->post_title ); ?></title>
<link><?php the_permalink_rss() ?></link>
<pubDate><?php echo mysql2date( 'D, d M Y H:i:s +0000', get_post_time( 'Y-m-d H:i:s', true ), false ); ?></pubDate>
<dc:creator><?php echo get_the_author_meta( 'login' ); ?></dc:creator>
<guid isPermaLink="false"><?php esc_url( the_guid() ); ?></guid>
<wp:post_id><?php echo $post->ID; ?></wp:post_id>
<wp:post_date><?php echo $post->post_date; ?></wp:post_date>
<wp:post_date_gmt><?php echo $post->post_date_gmt; ?></wp:post_date_gmt>
<wp:comment_status><?php echo $post->comment_status; ?></wp:comment_status>
<wp:ping_status><?php echo $post->ping_status; ?></wp:ping_status>
<wp:post_name><?php echo $post->post_name; ?></wp:post_name>
<wp:status><?php echo $post->post_status; ?></wp:status>
<wp:post_parent><?php echo $post->post_parent; ?></wp:post_parent>
<wp:menu_order><?php echo $post->menu_order; ?></wp:menu_order>
<wp:post_type><?php echo $post->post_type; ?></wp:post_type>
<wp:post_password><?php echo $post->post_password; ?></wp:post_password>
<?php $postmeta = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->postmeta WHERE post_id = %d", $post->ID ) );
foreach( $postmeta as $meta ) : if ( $meta->meta_key != '_edit_lock' ) :
$meta->meta_value = maybe_unserialize( $meta->meta_value );
$meta->meta_value = fix_line_breaks( $meta->meta_value );
$meta->meta_value = maybe_serialize( $meta->meta_value );
?>
<wp:postmeta>
<wp:meta_key><?php echo $meta->meta_key; ?></wp:meta_key>
<wp:meta_value><?php echo wxr_cdata( $meta->meta_value ); ?></wp:meta_value>
</wp:postmeta>
<?php endif; endforeach; ?>
</item>
<?php
}
}
?>
</channel>
</rss>
| PHP |
<?php
class acf_field_taxonomy extends acf_field
{
/*
* __construct
*
* Set name / label needed for actions / filters
*
* @since 3.6
* @date 23/01/13
*/
function __construct()
{
// vars
$this->name = 'taxonomy';
$this->label = __("Taxonomy",'acf');
$this->category = __("Relational",'acf');
$this->defaults = array(
'taxonomy' => 'category',
'field_type' => 'checkbox',
'allow_null' => 0,
'load_save_terms' => 0,
'multiple' => 0,
'return_format' => 'id'
);
// do not delete!
parent::__construct();
}
/*
* load_value()
*
* This filter is appied to the $value after it is loaded from the db
*
* @type filter
* @since 3.6
* @date 23/01/13
*
* @param $value - the value found in the database
* @param $post_id - the $post_id from which the value was loaded from
* @param $field - the field array holding all the field options
*
* @return $value - the value to be saved in te database
*/
function load_value( $value, $post_id, $field )
{
if( $field['load_save_terms'] )
{
$value = array();
$terms = get_the_terms( $post_id, $field['taxonomy'] );
if( is_array($terms) ){ foreach( $terms as $term ){
$value[] = $term->term_id;
}}
}
return $value;
}
/*
* update_value()
*
* This filter is appied to the $value before it is updated in the db
*
* @type filter
* @since 3.6
* @date 23/01/13
*
* @param $value - the value which will be saved in the database
* @param $field - the field array holding all the field options
* @param $post_id - the $post_id of which the value will be saved
*
* @return $value - the modified value
*/
function update_value( $value, $post_id, $field )
{
// vars
if( is_array($value) )
{
$value = array_filter($value);
}
if( $field['load_save_terms'] )
{
// Parse values
$value = apply_filters( 'acf/parse_types', $value );
wp_set_object_terms( $post_id, $value, $field['taxonomy'], false );
}
return $value;
}
/*
* format_value_for_api()
*
* This filter is appied to the $value after it is loaded from the db and before it is passed back to the api functions such as the_field
*
* @type filter
* @since 3.6
* @date 23/01/13
*
* @param $value - the value which was loaded from the database
* @param $post_id - the $post_id from which the value was loaded
* @param $field - the field array holding all the field options
*
* @return $value - the modified value
*/
function format_value_for_api( $value, $post_id, $field )
{
// no value?
if( !$value )
{
return $value;
}
// temp convert to array
$is_array = true;
if( !is_array($value) )
{
$is_array = false;
$value = array( $value );
}
// format
if( $field['return_format'] == 'object' )
{
foreach( $value as $k => $v )
{
$value[ $k ] = get_term( $v, $field['taxonomy'] );
}
}
// de-convert from array
if( !$is_array && isset($value[0]) )
{
$value = $value[0];
}
// Note: This function can be removed if not used
return $value;
}
/*
* create_field()
*
* Create the HTML interface for your field
*
* @type action
* @since 3.6
* @date 23/01/13
*
* @param $field - an array holding all the field's data
*/
function create_field( $field )
{
// vars
$single_name = $field['name'];
// multi select?
if( $field['field_type'] == 'multi_select' )
{
$field['multiple'] = 1;
$field['field_type'] = 'select';
$field['name'] .= '[]';
}
elseif( $field['field_type'] == 'checkbox' )
{
$field['name'] .= '[]';
}
// value must be array!
if( !is_array($field['value']) )
{
$field['value'] = array( $field['value'] );
}
// vars
$args = array(
'taxonomy' => $field['taxonomy'],
'hide_empty' => false,
'style' => 'none',
'walker' => new acf_taxonomy_field_walker( $field ),
);
$args = apply_filters('acf/fields/taxonomy/wp_list_categories', $args, $field );
?>
<div class="acf-taxonomy-field" data-load_save="<?php echo $field['load_save_terms']; ?>">
<input type="hidden" name="<?php echo $single_name; ?>" value="" />
<?php if( $field['field_type'] == 'select' ): ?>
<select id="<?php echo $field['id']; ?>" name="<?php echo $field['name']; ?>" <?php if( $field['multiple'] ): ?>multiple="multiple" size="5"<?php endif; ?>>
<?php if( $field['allow_null'] ): ?>
<option value=""><?php _e("None", 'acf'); ?></option>
<?php endif; ?>
<?php else: ?>
<div class="categorychecklist-holder">
<ul class="acf-checkbox-list">
<?php if( $field['allow_null'] ): ?>
<li>
<label class="selectit">
<input type="<?php echo $field['field_type']; ?>" name="<?php echo $field['name']; ?>" value="" /> <?php _e("None", 'acf'); ?>
</label>
</li>
<?php endif; ?>
<?php endif; ?>
<?php wp_list_categories( $args ); ?>
<?php if( $field['field_type'] == 'select' ): ?>
</select>
<?php else: ?>
</ul>
</div>
<?php endif; ?>
</div>
<?php
}
/*
* create_options()
*
* Create extra options for your field. This is rendered when editing a field.
* The value of $field['name'] can be used (like bellow) to save extra data to the $field
*
* @type action
* @since 3.6
* @date 23/01/13
*
* @param $field - an array holding all the field's data
*/
function create_options( $field )
{
// vars
$key = $field['name'];
?>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Taxonomy",'acf'); ?></label>
</td>
<td>
<?php
// vars
$choices = array();
$taxonomies = get_taxonomies( array(), 'objects' );
$ignore = array( 'post_format', 'nav_menu', 'link_category' );
foreach( $taxonomies as $taxonomy )
{
if( in_array($taxonomy->name, $ignore) )
{
continue;
}
$choices[ $taxonomy->name ] = $taxonomy->name;
}
do_action('acf/create_field', array(
'type' => 'select',
'name' => 'fields['.$key.'][taxonomy]',
'value' => $field['taxonomy'],
'choices' => $choices,
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Field Type",'acf'); ?></label>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'select',
'name' => 'fields['.$key.'][field_type]',
'value' => $field['field_type'],
'optgroup' => true,
'choices' => array(
__("Multiple Values",'acf') => array(
'checkbox' => __('Checkbox', 'acf'),
'multi_select' => __('Multi Select', 'acf')
),
__("Single Value",'acf') => array(
'radio' => __('Radio Buttons', 'acf'),
'select' => __('Select', 'acf')
)
)
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Allow Null?",'acf'); ?></label>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'radio',
'name' => 'fields['.$key.'][allow_null]',
'value' => $field['allow_null'],
'choices' => array(
1 => __("Yes",'acf'),
0 => __("No",'acf'),
),
'layout' => 'horizontal',
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Load & Save Terms to Post",'acf'); ?></label>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'true_false',
'name' => 'fields['.$key.'][load_save_terms]',
'value' => $field['load_save_terms'],
'message' => __("Load value based on the post's terms and update the post's terms on save",'acf')
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Return Value",'acf'); ?></label>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'radio',
'name' => 'fields['.$key.'][return_format]',
'value' => $field['return_format'],
'layout' => 'horizontal',
'choices' => array(
'object' => __("Term Object",'acf'),
'id' => __("Term ID",'acf')
)
));
?>
</td>
</tr>
<?php
}
}
new acf_field_taxonomy();
class acf_taxonomy_field_walker extends Walker
{
// vars
var $field = null,
$tree_type = 'category',
$db_fields = array ( 'parent' => 'parent', 'id' => 'term_id' );
// construct
function __construct( $field )
{
$this->field = $field;
}
// start_el
function start_el( &$output, $term, $depth = 0, $args = array(), $current_object_id = 0)
{
// vars
$selected = in_array( $term->term_id, $this->field['value'] );
if( $this->field['field_type'] == 'checkbox' )
{
$output .= '<li><label class="selectit"><input type="checkbox" name="' . $this->field['name'] . '" value="' . $term->term_id . '" ' . ($selected ? 'checked="checked"' : '') . ' /> ' . $term->name . '</label>';
}
elseif( $this->field['field_type'] == 'radio' )
{
$output .= '<li><label class="selectit"><input type="radio" name="' . $this->field['name'] . '" value="' . $term->term_id . '" ' . ($selected ? 'checked="checkbox"' : '') . ' /> ' . $term->name . '</label>';
}
elseif( $this->field['field_type'] == 'select' )
{
$indent = str_repeat("— ", $depth);
$output .= '<option value="' . $term->term_id . '" ' . ($selected ? 'selected="selected"' : '') . '>' . $indent . $term->name . '</option>';
}
}
//end_el
function end_el( &$output, $term, $depth = 0, $args = array() )
{
if( in_array($this->field['field_type'], array('checkbox', 'radio')) )
{
$output .= '</li>';
}
$output .= "\n";
}
// start_lvl
function start_lvl( &$output, $depth = 0, $args = array() )
{
// indent
//$output .= str_repeat( "\t", $depth);
// wrap element
if( in_array($this->field['field_type'], array('checkbox', 'radio')) )
{
$output .= '<ul class="children">' . "\n";
}
}
// end_lvl
function end_lvl( &$output, $depth = 0, $args = array() )
{
// indent
//$output .= str_repeat( "\t", $depth);
// wrap element
if( in_array($this->field['field_type'], array('checkbox', 'radio')) )
{
$output .= '</ul>' . "\n";
}
}
}
?> | PHP |
<?php
/*
* acf_field
*
* @description: This is the base class for all fields.
* @since: 3.6
* @created: 30/01/13
*/
class acf_field
{
/*
* Vars
*
* @description:
* @since: 3.6
* @created: 30/01/13
*/
var $name,
$title,
$category,
$defaults,
$l10n;
/*
* __construct()
*
* Adds neccessary Actions / Filters
*
* @since 3.6
* @date 30/01/13
*/
function __construct()
{
// register field
add_filter('acf/registered_fields', array($this, 'registered_fields'), 10, 1);
add_filter('acf/load_field_defaults/type=' . $this->name, array($this, 'load_field_defaults'), 10, 1);
// value
$this->add_filter('acf/load_value/type=' . $this->name, array($this, 'load_value'), 10, 3);
$this->add_filter('acf/update_value/type=' . $this->name, array($this, 'update_value'), 10, 3);
$this->add_filter('acf/format_value/type=' . $this->name, array($this, 'format_value'), 10, 3);
$this->add_filter('acf/format_value_for_api/type=' . $this->name, array($this, 'format_value_for_api'), 10, 3);
// field
$this->add_filter('acf/load_field/type=' . $this->name, array($this, 'load_field'), 10, 3);
$this->add_filter('acf/update_field/type=' . $this->name, array($this, 'update_field'), 10, 2);
$this->add_action('acf/create_field/type=' . $this->name, array($this, 'create_field'), 10, 1);
$this->add_action('acf/create_field_options/type=' . $this->name, array($this, 'create_options'), 10, 1);
// input actions
$this->add_action('acf/input/admin_enqueue_scripts', array($this, 'input_admin_enqueue_scripts'), 10, 0);
$this->add_action('acf/input/admin_head', array($this, 'input_admin_head'), 10, 0);
$this->add_filter('acf/input/admin_l10n', array($this, 'input_admin_l10n'), 10, 1);
// field group actions
$this->add_action('acf/field_group/admin_enqueue_scripts', array($this, 'field_group_admin_enqueue_scripts'), 10, 0);
$this->add_action('acf/field_group/admin_head', array($this, 'field_group_admin_head'), 10, 0);
}
/*
* add_filter
*
* @description: checks if the function is_callable before adding the filter
* @since: 3.6
* @created: 30/01/13
*/
function add_filter($tag, $function_to_add, $priority = 10, $accepted_args = 1)
{
if( is_callable($function_to_add) )
{
add_filter($tag, $function_to_add, $priority, $accepted_args);
}
}
/*
* add_action
*
* @description: checks if the function is_callable before adding the action
* @since: 3.6
* @created: 30/01/13
*/
function add_action($tag, $function_to_add, $priority = 10, $accepted_args = 1)
{
if( is_callable($function_to_add) )
{
add_action($tag, $function_to_add, $priority, $accepted_args);
}
}
/*
* registered_fields()
*
* Adds this field to the select list when creating a new field
*
* @type filter
* @since 3.6
* @date 23/01/13
*
* @param $fields - the array of all registered fields
*
* @return $fields - the array of all registered fields
*/
function registered_fields( $fields )
{
// defaults
if( !$this->category )
{
$this->category = __('Basic', 'acf');
}
// add to array
$fields[ $this->category ][ $this->name ] = $this->label;
// return array
return $fields;
}
/*
* load_field_defaults
*
* action called when rendering the head of an admin screen. Used primarily for passing PHP to JS
*
* @type filer
* @date 1/06/13
*
* @param $field {array}
* @return $field {array}
*/
function load_field_defaults( $field )
{
if( !empty($this->defaults) )
{
foreach( $this->defaults as $k => $v )
{
if( !isset($field[ $k ]) )
{
$field[ $k ] = $v;
}
}
}
return $field;
}
/*
* admin_l10n
*
* filter is called to load all l10n text translations into the admin head script tag
*
* @type filer
* @date 1/06/13
*
* @param $field {array}
* @return $field {array}
*/
function input_admin_l10n( $l10n )
{
if( !empty($this->l10n) )
{
$l10n[ $this->name ] = $this->l10n;
}
return $l10n;
}
}
?> | PHP |
<?php
class acf_field_checkbox extends acf_field
{
/*
* __construct
*
* Set name / label needed for actions / filters
*
* @since 3.6
* @date 23/01/13
*/
function __construct()
{
// vars
$this->name = 'checkbox';
$this->label = __("Checkbox",'acf');
$this->category = __("Choice",'acf');
$this->defaults = array(
'layout' => 'vertical',
'choices' => array(),
'default_value' => '',
);
// do not delete!
parent::__construct();
}
/*
* create_field()
*
* Create the HTML interface for your field
*
* @param $field - an array holding all the field's data
*
* @type action
* @since 3.6
* @date 23/01/13
*/
function create_field( $field )
{
// value must be array
if( !is_array($field['value']) )
{
// perhaps this is a default value with new lines in it?
if( strpos($field['value'], "\n") !== false )
{
// found multiple lines, explode it
$field['value'] = explode("\n", $field['value']);
}
else
{
$field['value'] = array( $field['value'] );
}
}
// trim value
$field['value'] = array_map('trim', $field['value']);
// vars
$i = 0;
$e = '<input type="hidden" name="' . esc_attr($field['name']) . '" value="" />';
$e .= '<ul class="acf-checkbox-list ' . esc_attr($field['class']) . ' ' . esc_attr($field['layout']) . '">';
// checkbox saves an array
$field['name'] .= '[]';
// foreach choices
foreach( $field['choices'] as $key => $value )
{
// vars
$i++;
$atts = '';
if( in_array($key, $field['value']) )
{
$atts = 'checked="yes"';
}
if( isset($field['disabled']) && in_array($key, $field['disabled']) )
{
$atts .= ' disabled="true"';
}
// each checkbox ID is generated with the $key, however, the first checkbox must not use $key so that it matches the field's label for attribute
$id = $field['id'];
if( $i > 1 )
{
$id .= '-' . $key;
}
$e .= '<li><label><input id="' . esc_attr($id) . '" type="checkbox" class="' . esc_attr($field['class']) . '" name="' . esc_attr($field['name']) . '" value="' . esc_attr($key) . '" ' . $atts . ' />' . $value . '</label></li>';
}
$e .= '</ul>';
// return
echo $e;
}
/*
* create_options()
*
* Create extra options for your field. This is rendered when editing a field.
* The value of $field['name'] can be used (like bellow) to save extra data to the $field
*
* @type action
* @since 3.6
* @date 23/01/13
*
* @param $field - an array holding all the field's data
*/
function create_options( $field )
{
// vars
$key = $field['name'];
// implode checkboxes so they work in a textarea
if( is_array($field['choices']) )
{
foreach( $field['choices'] as $k => $v )
{
$field['choices'][ $k ] = $k . ' : ' . $v;
}
$field['choices'] = implode("\n", $field['choices']);
}
?>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label for=""><?php _e("Choices",'acf'); ?></label>
<p><?php _e("Enter each choice on a new line.",'acf'); ?></p>
<p><?php _e("For more control, you may specify both a value and label like this:",'acf'); ?></p>
<p><?php _e("red : Red",'acf'); ?><br /><?php _e("blue : Blue",'acf'); ?></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'textarea',
'class' => 'textarea field_option-choices',
'name' => 'fields['.$key.'][choices]',
'value' => $field['choices'],
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Default Value",'acf'); ?></label>
<p class="description"><?php _e("Enter each default value on a new line",'acf'); ?></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'textarea',
'name' => 'fields['.$key.'][default_value]',
'value' => $field['default_value'],
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label for=""><?php _e("Layout",'acf'); ?></label>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'radio',
'name' => 'fields['.$key.'][layout]',
'value' => $field['layout'],
'layout' => 'horizontal',
'choices' => array(
'vertical' => __("Vertical",'acf'),
'horizontal' => __("Horizontal",'acf')
)
));
?>
</td>
</tr>
<?php
}
}
new acf_field_checkbox();
?> | PHP |
<?php
class acf_field_radio extends acf_field
{
/*
* __construct
*
* Set name / label needed for actions / filters
*
* @since 3.6
* @date 23/01/13
*/
function __construct()
{
// vars
$this->name = 'radio';
$this->label = __("Radio Button",'acf');
$this->category = __("Choice",'acf');
$this->defaults = array(
'layout' => 'vertical',
'choices' => array(),
'default_value' => '',
'other_choice' => 0,
'save_other_choice' => 0,
);
// do not delete!
parent::__construct();
}
/*
* create_field()
*
* Create the HTML interface for your field
*
* @param $field - an array holding all the field's data
*
* @type action
* @since 3.6
* @date 23/01/13
*/
function create_field( $field )
{
// vars
$i = 0;
$e = '<ul class="acf-radio-list ' . esc_attr($field['class']) . ' ' . esc_attr($field['layout']) . '">';
// add choices
if( is_array($field['choices']) )
{
foreach( $field['choices'] as $key => $value )
{
// vars
$i++;
$atts = '';
// if there is no value and this is the first of the choices, select this on by default
if( $field['value'] === false )
{
if( $i === 1 )
{
$atts = 'checked="checked" data-checked="checked"';
}
}
else
{
if( strval($key) === strval($field['value']) )
{
$atts = 'checked="checked" data-checked="checked"';
}
}
// HTML
$e .= '<li><label><input id="' . esc_attr($field['id']) . '-' . esc_attr($key) . '" type="radio" name="' . esc_attr($field['name']) . '" value="' . esc_attr($key) . '" ' . esc_attr( $atts ) . ' />' . $value . '</label></li>';
}
}
// other choice
if( $field['other_choice'] )
{
// vars
$atts = '';
$atts2 = 'name="" value="" style="display:none"';
if( $field['value'] !== false )
{
if( !isset($field['choices'][ $field['value'] ]) )
{
$atts = 'checked="checked" data-checked="checked"';
$atts2 = 'name="' . esc_attr($field['name']) . '" value="' . esc_attr($field['value']) . '"' ;
}
}
$e .= '<li><label><input id="' . esc_attr($field['id']) . '-other" type="radio" name="' . esc_attr($field['name']) . '" value="other" ' . $atts . ' />' . __("Other", 'acf') . '</label> <input type="text" ' . $atts2 . ' /></li>';
}
$e .= '</ul>';
echo $e;
}
/*
* create_options()
*
* Create extra options for your field. This is rendered when editing a field.
* The value of $field['name'] can be used (like bellow) to save extra data to the $field
*
* @type action
* @since 3.6
* @date 23/01/13
*
* @param $field - an array holding all the field's data
*/
function create_options( $field )
{
// vars
$key = $field['name'];
// implode checkboxes so they work in a textarea
if( is_array($field['choices']) )
{
foreach( $field['choices'] as $k => $v )
{
$field['choices'][ $k ] = $k . ' : ' . $v;
}
$field['choices'] = implode("\n", $field['choices']);
}
?>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label for=""><?php _e("Choices",'acf'); ?></label>
<p class="description"><?php _e("Enter your choices one per line",'acf'); ?><br />
<br />
<?php _e("Red",'acf'); ?><br />
<?php _e("Blue",'acf'); ?><br />
<br />
<?php _e("red : Red",'acf'); ?><br />
<?php _e("blue : Blue",'acf'); ?><br />
</p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'textarea',
'class' => 'textarea field_option-choices',
'name' => 'fields['.$key.'][choices]',
'value' => $field['choices'],
));
?>
<div class="radio-option-other_choice">
<?php
do_action('acf/create_field', array(
'type' => 'true_false',
'name' => 'fields['.$key.'][other_choice]',
'value' => $field['other_choice'],
'message' => __("Add 'other' choice to allow for custom values", 'acf')
));
?>
</div>
<div class="radio-option-save_other_choice" <?php if( !$field['other_choice'] ): ?>style="display:none"<?php endif; ?>>
<?php
do_action('acf/create_field', array(
'type' => 'true_false',
'name' => 'fields['.$key.'][save_other_choice]',
'value' => $field['save_other_choice'],
'message' => __("Save 'other' values to the field's choices", 'acf')
));
?>
</div>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Default Value",'acf'); ?></label>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'text',
'name' => 'fields['.$key.'][default_value]',
'value' => $field['default_value'],
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label for=""><?php _e("Layout",'acf'); ?></label>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'radio',
'name' => 'fields['.$key.'][layout]',
'value' => $field['layout'],
'layout' => 'horizontal',
'choices' => array(
'vertical' => __("Vertical",'acf'),
'horizontal' => __("Horizontal",'acf')
)
));
?>
</td>
</tr>
<?php
}
/*
* update_value()
*
* This filter is appied to the $value before it is updated in the db
*
* @type filter
* @since 3.6
* @date 23/01/13
*
* @param $value - the value which will be saved in the database
* @param $post_id - the $post_id of which the value will be saved
* @param $field - the field array holding all the field options
*
* @return $value - the modified value
*/
function update_value( $value, $post_id, $field )
{
// validate
if( $field['save_other_choice'] )
{
// value isn't in choices yet
if( !isset($field['choices'][ $value ]) )
{
// update $field
$field['choices'][ $value ] = $value;
// can save
if( isset($field['field_group']) )
{
do_action('acf/update_field', $field, $field['field_group']);
}
}
}
return $value;
}
}
new acf_field_radio();
?> | PHP |
<?php
class acf_field_file extends acf_field
{
/*
* __construct
*
* Set name / label needed for actions / filters
*
* @since 3.6
* @date 23/01/13
*/
function __construct()
{
// vars
$this->name = 'file';
$this->label = __("File",'acf');
$this->category = __("Content",'acf');
$this->defaults = array(
'save_format' => 'object',
'library' => 'all'
);
$this->l10n = array(
'select' => __("Select File",'acf'),
'edit' => __("Edit File",'acf'),
'update' => __("Update File",'acf'),
'uploadedTo' => __("uploaded to this post",'acf'),
);
// do not delete!
parent::__construct();
// filters
add_filter('get_media_item_args', array($this, 'get_media_item_args'));
add_filter('wp_prepare_attachment_for_js', array($this, 'wp_prepare_attachment_for_js'), 10, 3);
// JSON
add_action('wp_ajax_acf/fields/file/get_files', array($this, 'ajax_get_files'));
add_action('wp_ajax_nopriv_acf/fields/file/get_files', array($this, 'ajax_get_files'), 10, 1);
}
/*
* create_field()
*
* Create the HTML interface for your field
*
* @param $field - an array holding all the field's data
*
* @type action
* @since 3.6
* @date 23/01/13
*/
function create_field( $field )
{
// vars
$o = array(
'class' => '',
'icon' => '',
'title' => '',
'size' => '',
'url' => '',
'name' => '',
);
if( $field['value'] && is_numeric($field['value']) )
{
$file = get_post( $field['value'] );
if( $file )
{
$o['class'] = 'active';
$o['icon'] = wp_mime_type_icon( $file->ID );
$o['title'] = $file->post_title;
$o['size'] = size_format(filesize( get_attached_file( $file->ID ) ));
$o['url'] = wp_get_attachment_url( $file->ID );
$explode = explode('/', $o['url']);
$o['name'] = end( $explode );
}
}
?>
<div class="acf-file-uploader clearfix <?php echo $o['class']; ?>" data-library="<?php echo $field['library']; ?>">
<input class="acf-file-value" type="hidden" name="<?php echo $field['name']; ?>" value="<?php echo $field['value']; ?>" />
<div class="has-file">
<ul class="hl clearfix">
<li>
<img class="acf-file-icon" src="<?php echo $o['icon']; ?>" alt=""/>
<div class="hover">
<ul class="bl">
<li><a href="#" class="acf-button-delete ir">Remove</a></li>
<li><a href="#" class="acf-button-edit ir">Edit</a></li>
</ul>
</div>
</li>
<li>
<p>
<strong class="acf-file-title"><?php echo $o['title']; ?></strong>
</p>
<p>
<strong><?php _e('Name', 'acf'); ?>:</strong>
<a class="acf-file-name" href="<?php echo $o['url']; ?>" target="_blank"><?php echo $o['name']; ?></a>
</p>
<p>
<strong><?php _e('Size', 'acf'); ?>:</strong>
<span class="acf-file-size"><?php echo $o['size']; ?></span>
</p>
</li>
</ul>
</div>
<div class="no-file">
<ul class="hl clearfix">
<li>
<span><?php _e('No File Selected','acf'); ?></span>. <a href="#" class="button add-file"><?php _e('Add File','acf'); ?></a>
</li>
</ul>
</div>
</div>
<?php
}
/*
* create_options()
*
* Create extra options for your field. This is rendered when editing a field.
* The value of $field['name'] can be used (like bellow) to save extra data to the $field
*
* @type action
* @since 3.6
* @date 23/01/13
*
* @param $field - an array holding all the field's data
*/
function create_options( $field )
{
// vars
$key = $field['name'];
?>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Return Value",'acf'); ?></label>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'radio',
'name' => 'fields['.$key.'][save_format]',
'value' => $field['save_format'],
'layout' => 'horizontal',
'choices' => array(
'object' => __("File Object",'acf'),
'url' => __("File URL",'acf'),
'id' => __("File ID",'acf')
)
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Library",'acf'); ?></label>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'radio',
'name' => 'fields['.$key.'][library]',
'value' => $field['library'],
'layout' => 'horizontal',
'choices' => array(
'all' => __('All', 'acf'),
'uploadedTo' => __('Uploaded to post', 'acf')
)
));
?>
</td>
</tr>
<?php
}
/*
* format_value_for_api()
*
* This filter is appied to the $value after it is loaded from the db and before it is passed back to the api functions such as the_field
*
* @type filter
* @since 3.6
* @date 23/01/13
*
* @param $value - the value which was loaded from the database
* @param $post_id - the $post_id from which the value was loaded
* @param $field - the field array holding all the field options
*
* @return $value - the modified value
*/
function format_value_for_api( $value, $post_id, $field )
{
// validate
if( !$value )
{
return false;
}
// format
if( $field['save_format'] == 'url' )
{
$value = wp_get_attachment_url($value);
}
elseif( $field['save_format'] == 'object' )
{
$attachment = get_post( $value );
// validate
if( !$attachment )
{
return false;
}
// create array to hold value data
$value = array(
'id' => $attachment->ID,
'alt' => get_post_meta($attachment->ID, '_wp_attachment_image_alt', true),
'title' => $attachment->post_title,
'caption' => $attachment->post_excerpt,
'description' => $attachment->post_content,
'mime_type' => $attachment->post_mime_type,
'url' => wp_get_attachment_url( $attachment->ID ),
);
}
return $value;
}
/*
* get_media_item_args
*
* @description:
* @since: 3.6
* @created: 27/01/13
*/
function get_media_item_args( $vars )
{
$vars['send'] = true;
return($vars);
}
/*
* ajax_get_files
*
* @description:
* @since: 3.5.7
* @created: 13/01/13
*/
function ajax_get_files()
{
// vars
$options = array(
'nonce' => '',
'files' => array()
);
$return = array();
// load post options
$options = array_merge($options, $_POST);
// verify nonce
if( ! wp_verify_nonce($options['nonce'], 'acf_nonce') )
{
die(0);
}
if( $options['files'] )
{
foreach( $options['files'] as $id )
{
$o = array();
$file = get_post( $id );
$o['id'] = $file->ID;
$o['icon'] = wp_mime_type_icon( $file->ID );
$o['title'] = $file->post_title;
$o['size'] = size_format(filesize( get_attached_file( $file->ID ) ));
$o['url'] = wp_get_attachment_url( $file->ID );
$o['name'] = end(explode('/', $o['url']));
$return[] = $o;
}
}
// return json
echo json_encode( $return );
die;
}
/*
* update_value()
*
* This filter is appied to the $value before it is updated in the db
*
* @type filter
* @since 3.6
* @date 23/01/13
*
* @param $value - the value which will be saved in the database
* @param $post_id - the $post_id of which the value will be saved
* @param $field - the field array holding all the field options
*
* @return $value - the modified value
*/
function update_value( $value, $post_id, $field )
{
// array?
if( is_array($value) && isset($value['id']) )
{
$value = $value['id'];
}
// object?
if( is_object($value) && isset($value->ID) )
{
$value = $value->ID;
}
return $value;
}
/*
* wp_prepare_attachment_for_js
*
* this filter allows ACF to add in extra data to an attachment JS object
*
* @type function
* @date 1/06/13
*
* @param {int} $post_id
* @return {int} $post_id
*/
function wp_prepare_attachment_for_js( $response, $attachment, $meta )
{
// default
$fs = '0 kb';
// supress PHP warnings caused by corrupt images
if( $i = @filesize( get_attached_file( $attachment->ID ) ) )
{
$fs = size_format( $i );
}
// update JSON
$response['filesize'] = $fs;
// return
return $response;
}
}
new acf_field_file();
?> | PHP |
<?php
class acf_field_password extends acf_field
{
/*
* __construct
*
* Set name / label needed for actions / filters
*
* @since 3.6
* @date 23/01/13
*/
function __construct()
{
// vars
$this->name = 'password';
$this->label = __("Password",'acf');
$this->defaults = array(
'placeholder' => '',
'prepend' => '',
'append' => ''
);
// do not delete!
parent::__construct();
}
/*
* create_field()
*
* Create the HTML interface for your field
*
* @param $field - an array holding all the field's data
*
* @type action
* @since 3.6
* @date 23/01/13
*/
function create_field( $field )
{
// vars
$o = array( 'id', 'class', 'name', 'value', 'placeholder' );
$e = '';
// prepend
if( $field['prepend'] !== "" )
{
$field['class'] .= ' acf-is-prepended';
$e .= '<div class="acf-input-prepend">' . $field['prepend'] . '</div>';
}
// append
if( $field['append'] !== "" )
{
$field['class'] .= ' acf-is-appended';
$e .= '<div class="acf-input-append">' . $field['append'] . '</div>';
}
$e .= '<div class="acf-input-wrap">';
$e .= '<input type="password"';
foreach( $o as $k )
{
$e .= ' ' . $k . '="' . esc_attr( $field[ $k ] ) . '"';
}
$e .= ' />';
$e .= '</div>';
// return
echo $e;
}
/*
* create_options()
*
* Create extra options for your field. This is rendered when editing a field.
* The value of $field['name'] can be used (like bellow) to save extra data to the $field
*
* @type action
* @since 3.6
* @date 23/01/13
*
* @param $field - an array holding all the field's data
*/
function create_options( $field )
{
// vars
$key = $field['name'];
?>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Placeholder Text",'acf'); ?></label>
<p><?php _e("Appears within the input",'acf') ?></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'text',
'name' => 'fields[' .$key.'][placeholder]',
'value' => $field['placeholder'],
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Prepend",'acf'); ?></label>
<p><?php _e("Appears before the input",'acf') ?></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'text',
'name' => 'fields[' .$key.'][prepend]',
'value' => $field['prepend'],
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Append",'acf'); ?></label>
<p><?php _e("Appears after the input",'acf') ?></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'text',
'name' => 'fields[' .$key.'][append]',
'value' => $field['append'],
));
?>
</td>
</tr>
<?php
}
}
new acf_field_password();
?> | PHP |
<?php
class acf_field_select extends acf_field
{
/*
* __construct
*
* Set name / label needed for actions / filters
*
* @since 3.6
* @date 23/01/13
*/
function __construct()
{
// vars
$this->name = 'select';
$this->label = __("Select",'acf');
$this->category = __("Choice",'acf');
$this->defaults = array(
'multiple' => 0,
'allow_null' => 0,
'choices' => array(),
'default_value' => ''
);
// do not delete!
parent::__construct();
// extra
//add_filter('acf/update_field/type=select', array($this, 'update_field'), 5, 2);
add_filter('acf/update_field/type=checkbox', array($this, 'update_field'), 5, 2);
add_filter('acf/update_field/type=radio', array($this, 'update_field'), 5, 2);
}
/*
* create_field()
*
* Create the HTML interface for your field
*
* @param $field - an array holding all the field's data
*
* @type action
* @since 3.6
* @date 23/01/13
*/
function create_field( $field )
{
// vars
$optgroup = false;
// determin if choices are grouped (2 levels of array)
if( is_array($field['choices']) )
{
foreach( $field['choices'] as $k => $v )
{
if( is_array($v) )
{
$optgroup = true;
}
}
}
// value must be array
if( !is_array($field['value']) )
{
// perhaps this is a default value with new lines in it?
if( strpos($field['value'], "\n") !== false )
{
// found multiple lines, explode it
$field['value'] = explode("\n", $field['value']);
}
else
{
$field['value'] = array( $field['value'] );
}
}
// trim value
$field['value'] = array_map('trim', $field['value']);
// multiple select
$multiple = '';
if( $field['multiple'] )
{
// create a hidden field to allow for no selections
echo '<input type="hidden" name="' . $field['name'] . '" />';
$multiple = ' multiple="multiple" size="5" ';
$field['name'] .= '[]';
}
// html
echo '<select id="' . $field['id'] . '" class="' . $field['class'] . '" name="' . $field['name'] . '" ' . $multiple . ' >';
// null
if( $field['allow_null'] )
{
echo '<option value="null">- ' . __("Select",'acf') . ' -</option>';
}
// loop through values and add them as options
if( is_array($field['choices']) )
{
foreach( $field['choices'] as $key => $value )
{
if( $optgroup )
{
// this select is grouped with optgroup
if($key != '') echo '<optgroup label="'.$key.'">';
if( is_array($value) )
{
foreach($value as $id => $label)
{
$selected = in_array($id, $field['value']) ? 'selected="selected"' : '';
echo '<option value="'.$id.'" '.$selected.'>'.$label.'</option>';
}
}
if($key != '') echo '</optgroup>';
}
else
{
$selected = in_array($key, $field['value']) ? 'selected="selected"' : '';
echo '<option value="'.$key.'" '.$selected.'>'.$value.'</option>';
}
}
}
echo '</select>';
}
/*
* create_options()
*
* Create extra options for your field. This is rendered when editing a field.
* The value of $field['name'] can be used (like bellow) to save extra data to the $field
*
* @type action
* @since 3.6
* @date 23/01/13
*
* @param $field - an array holding all the field's data
*/
function create_options( $field )
{
$key = $field['name'];
// implode choices so they work in a textarea
if( is_array($field['choices']) )
{
foreach( $field['choices'] as $k => $v )
{
$field['choices'][ $k ] = $k . ' : ' . $v;
}
$field['choices'] = implode("\n", $field['choices']);
}
?>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label for=""><?php _e("Choices",'acf'); ?></label>
<p><?php _e("Enter each choice on a new line.",'acf'); ?></p>
<p><?php _e("For more control, you may specify both a value and label like this:",'acf'); ?></p>
<p><?php _e("red : Red",'acf'); ?><br /><?php _e("blue : Blue",'acf'); ?></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'textarea',
'class' => 'textarea field_option-choices',
'name' => 'fields['.$key.'][choices]',
'value' => $field['choices'],
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Default Value",'acf'); ?></label>
<p class="description"><?php _e("Enter each default value on a new line",'acf'); ?></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'textarea',
'name' => 'fields['.$key.'][default_value]',
'value' => $field['default_value'],
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Allow Null?",'acf'); ?></label>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'radio',
'name' => 'fields['.$key.'][allow_null]',
'value' => $field['allow_null'],
'choices' => array(
1 => __("Yes",'acf'),
0 => __("No",'acf'),
),
'layout' => 'horizontal',
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Select multiple values?",'acf'); ?></label>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'radio',
'name' => 'fields['.$key.'][multiple]',
'value' => $field['multiple'],
'choices' => array(
1 => __("Yes",'acf'),
0 => __("No",'acf'),
),
'layout' => 'horizontal',
));
?>
</td>
</tr>
<?php
}
/*
* format_value_for_api()
*
* This filter is appied to the $value after it is loaded from the db and before it is passed back to the api functions such as the_field
*
* @type filter
* @since 3.6
* @date 23/01/13
*
* @param $value - the value which was loaded from the database
* @param $post_id - the $post_id from which the value was loaded
* @param $field - the field array holding all the field options
*
* @return $value - the modified value
*/
function format_value_for_api( $value, $post_id, $field )
{
if( $value == 'null' )
{
$value = false;
}
return $value;
}
/*
* update_field()
*
* This filter is appied to the $field before it is saved to the database
*
* @type filter
* @since 3.6
* @date 23/01/13
*
* @param $field - the field array holding all the field options
* @param $post_id - the field group ID (post_type = acf)
*
* @return $field - the modified field
*/
function update_field( $field, $post_id )
{
// check if is array. Normal back end edit posts a textarea, but a user might use update_field from the front end
if( is_array( $field['choices'] ))
{
return $field;
}
// vars
$new_choices = array();
// explode choices from each line
if( $field['choices'] )
{
// stripslashes ("")
$field['choices'] = stripslashes_deep($field['choices']);
if(strpos($field['choices'], "\n") !== false)
{
// found multiple lines, explode it
$field['choices'] = explode("\n", $field['choices']);
}
else
{
// no multiple lines!
$field['choices'] = array($field['choices']);
}
// key => value
foreach($field['choices'] as $choice)
{
if(strpos($choice, ' : ') !== false)
{
$choice = explode(' : ', $choice);
$new_choices[ trim($choice[0]) ] = trim($choice[1]);
}
else
{
$new_choices[ trim($choice) ] = trim($choice);
}
}
}
// update choices
$field['choices'] = $new_choices;
return $field;
}
}
new acf_field_select();
?>
| PHP |
<?php
class acf_field_true_false extends acf_field
{
/*
* __construct
*
* Set name / label needed for actions / filters
*
* @since 3.6
* @date 23/01/13
*/
function __construct()
{
// vars
$this->name = 'true_false';
$this->label = __("True / False",'acf');
$this->category = __("Choice",'acf');
$this->defaults = array(
'default_value' => 0,
'message' => '',
);
// do not delete!
parent::__construct();
}
/*
* create_field()
*
* Create the HTML interface for your field
*
* @param $field - an array holding all the field's data
*
* @type action
* @since 3.6
* @date 23/01/13
*/
function create_field( $field )
{
// html
echo '<ul class="acf-checkbox-list ' . $field['class'] . '">';
echo '<input type="hidden" name="'.$field['name'].'" value="0" />';
$selected = ($field['value'] == 1) ? 'checked="yes"' : '';
echo '<li><label><input id="' . $field['id'] . '-1" type="checkbox" name="'.$field['name'].'" value="1" ' . $selected . ' />' . $field['message'] . '</label></li>';
echo '</ul>';
}
/*
* create_options()
*
* Create extra options for your field. This is rendered when editing a field.
* The value of $field['name'] can be used (like bellow) to save extra data to the $field
*
* @type action
* @since 3.6
* @date 23/01/13
*
* @param $field - an array holding all the field's data
*/
function create_options( $field )
{
// vars
$key = $field['name'];
?>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Message",'acf'); ?></label>
<p class="description"><?php _e("eg. Show extra content",'acf'); ?></a></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'text',
'name' => 'fields['.$key.'][message]',
'value' => $field['message'],
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Default Value",'acf'); ?></label>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'true_false',
'name' => 'fields['.$key.'][default_value]',
'value' => $field['default_value'],
));
?>
</td>
</tr>
<?php
}
/*
* format_value_for_api()
*
* This filter is appied to the $value after it is loaded from the db and before it is passed back to the api functions such as the_field
*
* @type filter
* @since 3.6
* @date 23/01/13
*
* @param $value - the value which was loaded from the database
* @param $post_id - the $post_id from which the value was loaded
* @param $field - the field array holding all the field options
*
* @return $value - the modified value
*/
function format_value_for_api( $value, $post_id, $field )
{
$value = ($value == 1) ? true : false;
return $value;
}
}
new acf_field_true_false();
?> | PHP |
<?php
// Create an acf version of the_content filter (acf_the_content)
if( isset($GLOBALS['wp_embed']) )
{
add_filter( 'acf_the_content', array( $GLOBALS['wp_embed'], 'run_shortcode' ), 8 );
add_filter( 'acf_the_content', array( $GLOBALS['wp_embed'], 'autoembed' ), 8 );
}
add_filter( 'acf_the_content', 'capital_P_dangit', 11 );
add_filter( 'acf_the_content', 'wptexturize' );
add_filter( 'acf_the_content', 'convert_smilies' );
add_filter( 'acf_the_content', 'convert_chars' );
add_filter( 'acf_the_content', 'wpautop' );
add_filter( 'acf_the_content', 'shortcode_unautop' );
add_filter( 'acf_the_content', 'prepend_attachment' );
add_filter( 'acf_the_content', 'do_shortcode', 11);
class acf_field_wysiwyg extends acf_field
{
/*
* __construct
*
* Set name / label needed for actions / filters
*
* @since 3.6
* @date 23/01/13
*/
function __construct()
{
// vars
$this->name = 'wysiwyg';
$this->label = __("Wysiwyg Editor",'acf');
$this->category = __("Content",'acf');
$this->defaults = array(
'toolbar' => 'full',
'media_upload' => 'yes',
'default_value' => '',
);
// do not delete!
parent::__construct();
// filters
add_filter( 'acf/fields/wysiwyg/toolbars', array( $this, 'toolbars'), 1, 1 );
add_filter( 'mce_external_plugins', array( $this, 'mce_external_plugins'), 20, 1 );
}
/*
* mce_external_plugins
*
* This filter will add in the tinyMCE 'code' plugin which is missing in WP 3.9
*
* @type function
* @date 18/04/2014
* @since 5.0.0
*
* @param $post_id (int)
* @return $post_id (int)
*/
function mce_external_plugins( $plugins ){
// global
global $wp_version;
// WP 3.9 an above
if( version_compare($wp_version, '3.9', '>=' ) ) {
// add code
$plugins['code'] = apply_filters('acf/get_info', 'dir') . 'js/tinymce.code.min.js';
}
// return
return $plugins;
}
/*
* toolbars()
*
* This filter allowsyou to customize the WYSIWYG toolbars
*
* @param $toolbars - an array of toolbars
*
* @return $toolbars - the modified $toolbars
*
* @type filter
* @since 3.6
* @date 23/01/13
*/
function toolbars( $toolbars ) {
// global
global $wp_version;
// vars
$editor_id = 'acf_settings';
if( version_compare($wp_version, '3.9', '>=' ) ) {
// Full
$toolbars['Full'] = array(
1 => apply_filters( 'mce_buttons', array('bold', 'italic', 'strikethrough', 'bullist', 'numlist', 'blockquote', 'hr', 'alignleft', 'aligncenter', 'alignright', 'link', 'unlink', 'wp_more', 'spellchecker', 'fullscreen', 'wp_adv' ), $editor_id ),
2 => apply_filters( 'mce_buttons_2', array( 'formatselect', 'underline', 'alignjustify', 'forecolor', 'pastetext', 'removeformat', 'charmap', 'outdent', 'indent', 'undo', 'redo', 'wp_help', 'code' ), $editor_id ),
3 => apply_filters('mce_buttons_3', array(), $editor_id),
4 => apply_filters('mce_buttons_4', array(), $editor_id),
);
// Basic
$toolbars['Basic'] = array(
1 => apply_filters( 'teeny_mce_buttons', array('bold', 'italic', 'underline', 'blockquote', 'strikethrough', 'bullist', 'numlist', 'alignleft', 'aligncenter', 'alignright', 'undo', 'redo', 'link', 'unlink', 'fullscreen'), $editor_id ),
);
} else {
// Full
$toolbars['Full'] = array(
1 => apply_filters( 'mce_buttons', array('bold', 'italic', 'strikethrough', 'bullist', 'numlist', 'blockquote', 'justifyleft', 'justifycenter', 'justifyright', 'link', 'unlink', 'wp_more', 'spellchecker', 'fullscreen', 'wp_adv' ), $editor_id ),
2 => apply_filters( 'mce_buttons_2', array( 'formatselect', 'underline', 'justifyfull', 'forecolor', 'pastetext', 'pasteword', 'removeformat', 'charmap', 'outdent', 'indent', 'undo', 'redo', 'wp_help', 'code' ), $editor_id ),
3 => apply_filters('mce_buttons_3', array(), $editor_id),
4 => apply_filters('mce_buttons_4', array(), $editor_id),
);
// Basic
$toolbars['Basic'] = array(
1 => apply_filters( 'teeny_mce_buttons', array('bold', 'italic', 'underline', 'blockquote', 'strikethrough', 'bullist', 'numlist', 'justifyleft', 'justifycenter', 'justifyright', 'undo', 'redo', 'link', 'unlink', 'fullscreen'), $editor_id ),
);
}
// Custom - can be added with acf/fields/wysiwyg/toolbars filter
return $toolbars;
}
/*
* input_admin_head()
*
* This action is called in the admin_head action on the edit screen where your field is created.
* Use this action to add css and javascript to assist your create_field() action.
*
* @info http://codex.wordpress.org/Plugin_API/Action_Reference/admin_head
* @type action
* @since 3.6
* @date 23/01/13
*/
function input_admin_head()
{
add_action( 'admin_footer', array( $this, 'admin_footer') );
}
function admin_footer()
{
?>
<div style="display:none;">
<?php wp_editor( '', 'acf_settings' ); ?>
</div>
<?php
}
/*
* create_field()
*
* Create the HTML interface for your field
*
* @param $field - an array holding all the field's data
*
* @type action
* @since 3.6
* @date 23/01/13
*/
function create_field( $field )
{
global $wp_version;
// vars
$id = 'wysiwyg-' . $field['id'] . '-' . uniqid();
?>
<div id="wp-<?php echo $id; ?>-wrap" class="acf_wysiwyg wp-editor-wrap" data-toolbar="<?php echo $field['toolbar']; ?>" data-upload="<?php echo $field['media_upload']; ?>">
<?php if( user_can_richedit() && $field['media_upload'] == 'yes' ): ?>
<?php if( version_compare($wp_version, '3.3', '<') ): ?>
<div id="editor-toolbar">
<div id="media-buttons" class="hide-if-no-js">
<?php do_action( 'media_buttons' ); ?>
</div>
</div>
<?php else: ?>
<div id="wp-<?php echo $id; ?>-editor-tools" class="wp-editor-tools">
<div id="wp-<?php echo $id; ?>-media-buttons" class="hide-if-no-js wp-media-buttons">
<?php do_action( 'media_buttons' ); ?>
</div>
</div>
<?php endif; ?>
<?php endif; ?>
<div id="wp-<?php echo $id; ?>-editor-container" class="wp-editor-container">
<textarea id="<?php echo $id; ?>" class="wp-editor-area" name="<?php echo $field['name']; ?>" ><?php
if( user_can_richedit() )
{
echo wp_richedit_pre( $field['value'] );
}
else
{
echo wp_htmledit_pre( $field['value'] );
}
?></textarea>
</div>
</div>
<?php
}
/*
* create_options()
*
* Create extra options for your field. This is rendered when editing a field.
* The value of $field['name'] can be used (like bellow) to save extra data to the $field
*
* @type action
* @since 3.6
* @date 23/01/13
*
* @param $field - an array holding all the field's data
*/
function create_options( $field )
{
// vars
$key = $field['name'];
?>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Default Value",'acf'); ?></label>
<p><?php _e("Appears when creating a new post",'acf') ?></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'textarea',
'name' => 'fields['.$key.'][default_value]',
'value' => $field['default_value'],
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Toolbar",'acf'); ?></label>
</td>
<td>
<?php
$toolbars = apply_filters( 'acf/fields/wysiwyg/toolbars', array() );
$choices = array();
if( is_array($toolbars) )
{
foreach( $toolbars as $k => $v )
{
$label = $k;
$name = sanitize_title( $label );
$name = str_replace('-', '_', $name);
$choices[ $name ] = $label;
}
}
do_action('acf/create_field', array(
'type' => 'radio',
'name' => 'fields['.$key.'][toolbar]',
'value' => $field['toolbar'],
'layout' => 'horizontal',
'choices' => $choices
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Show Media Upload Buttons?",'acf'); ?></label>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'radio',
'name' => 'fields['.$key.'][media_upload]',
'value' => $field['media_upload'],
'layout' => 'horizontal',
'choices' => array(
'yes' => __("Yes",'acf'),
'no' => __("No",'acf'),
)
));
?>
</td>
</tr>
<?php
}
/*
* format_value_for_api()
*
* This filter is appied to the $value after it is loaded from the db and before it is passed back to the api functions such as the_field
*
* @type filter
* @since 3.6
* @date 23/01/13
*
* @param $value - the value which was loaded from the database
* @param $post_id - the $post_id from which the value was loaded
* @param $field - the field array holding all the field options
*
* @return $value - the modified value
*/
function format_value_for_api( $value, $post_id, $field )
{
// apply filters
$value = apply_filters( 'acf_the_content', $value );
// follow the_content function in /wp-includes/post-template.php
$value = str_replace(']]>', ']]>', $value);
return $value;
}
}
new acf_field_wysiwyg();
?> | PHP |
<?php
class acf_field_page_link extends acf_field
{
/*
* __construct
*
* Set name / label needed for actions / filters
*
* @since 3.6
* @date 23/01/13
*/
function __construct()
{
// vars
$this->name = 'page_link';
$this->label = __("Page Link",'acf');
$this->category = __("Relational",'acf');
$this->defaults = array(
'post_type' => array('all'),
'multiple' => 0,
'allow_null' => 0,
);
// do not delete!
parent::__construct();
}
/*
* load_field()
*
* This filter is appied to the $field after it is loaded from the database
*
* @type filter
* @since 3.6
* @date 23/01/13
*
* @param $field - the field array holding all the field options
*
* @return $field - the field array holding all the field options
*/
function load_field( $field )
{
// validate post_type
if( !$field['post_type'] || !is_array($field['post_type']) || in_array('', $field['post_type']) )
{
$field['post_type'] = array( 'all' );
}
// return
return $field;
}
/*
* create_field()
*
* Create the HTML interface for your field
*
* @param $field - an array holding all the field's data
*
* @type action
* @since 3.6
* @date 23/01/13
*/
function create_field( $field )
{
// let post_object create the field
$field['type'] = 'post_object';
do_action('acf/create_field', $field );
}
/*
* create_options()
*
* Create extra options for your field. This is rendered when editing a field.
* The value of $field['name'] can be used (like bellow) to save extra data to the $field
*
* @type action
* @since 3.6
* @date 23/01/13
*
* @param $field - an array holding all the field's data
*/
function create_options( $field )
{
$key = $field['name'];
?>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label for=""><?php _e("Post Type",'acf'); ?></label>
</td>
<td>
<?php
$choices = array(
'all' => __("All",'acf')
);
$choices = apply_filters('acf/get_post_types', $choices);
do_action('acf/create_field', array(
'type' => 'select',
'name' => 'fields['.$key.'][post_type]',
'value' => $field['post_type'],
'choices' => $choices,
'multiple' => 1,
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Allow Null?",'acf'); ?></label>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'radio',
'name' => 'fields['.$key.'][allow_null]',
'value' => $field['allow_null'],
'choices' => array(
1 => __("Yes",'acf'),
0 => __("No",'acf'),
),
'layout' => 'horizontal',
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Select multiple values?",'acf'); ?></label>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'radio',
'name' => 'fields['.$key.'][multiple]',
'value' => $field['multiple'],
'choices' => array(
1 => __("Yes",'acf'),
0 => __("No",'acf'),
),
'layout' => 'horizontal',
));
?>
</td>
</tr>
<?php
}
/*
* format_value_for_api()
*
* This filter is appied to the $value after it is loaded from the db and before it is passed back to the api functions such as the_field
*
* @type filter
* @since 3.6
* @date 23/01/13
*
* @param $value - the value which was loaded from the database
* @param $post_id - the $post_id from which the value was loaded
* @param $field - the field array holding all the field options
*
* @return $value - the modified value
*/
function format_value_for_api( $value, $post_id, $field )
{
if( !$value )
{
return false;
}
if( $value == 'null' )
{
return false;
}
if( is_array($value) )
{
foreach( $value as $k => $v )
{
$value[ $k ] = get_permalink($v);
}
}
else
{
$value = get_permalink($value);
}
return $value;
}
}
new acf_field_page_link();
?> | PHP |
<?php
class acf_field_message extends acf_field
{
/*
* __construct
*
* Set name / label needed for actions / filters
*
* @since 3.6
* @date 23/01/13
*/
function __construct()
{
// vars
$this->name = 'message';
$this->label = __("Message",'acf');
$this->category = __("Layout",'acf');
$this->defaults = array(
'message' => '',
);
// do not delete!
parent::__construct();
}
/*
* create_field()
*
* Create the HTML interface for your field
*
* @param $field - an array holding all the field's data
*
* @type action
* @since 3.6
* @date 23/01/13
*/
function create_field( $field )
{
echo wpautop( $field['message'] );
}
/*
* create_options()
*
* Create extra options for your field. This is rendered when editing a field.
* The value of $field['name'] can be used (like bellow) to save extra data to the $field
*
* @param $field - an array holding all the field's data
*
* @type action
* @since 3.6
* @date 23/01/13
*/
function create_options( $field )
{
// vars
$key = $field['name'];
?>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label for=""><?php _e("Message",'acf'); ?></label>
<p class="description"><?php _e("Text & HTML entered here will appear inline with the fields",'acf'); ?><br /><br />
<?php _e("Please note that all text will first be passed through the wp function ",'acf'); ?><a href="http://codex.wordpress.org/Function_Reference/wpautop" target="_blank">wpautop</a></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'textarea',
'class' => 'textarea',
'name' => 'fields['.$key.'][message]',
'value' => $field['message'],
));
?>
</td>
</tr>
<?php
}
}
new acf_field_message();
?> | PHP |
<?php
class acf_field_email extends acf_field
{
/*
* __construct
*
* Set name / label needed for actions / filters
*
* @since 3.6
* @date 23/01/13
*/
function __construct()
{
// vars
$this->name = 'email';
$this->label = __("Email",'acf');
$this->defaults = array(
'default_value' => '',
'placeholder' => '',
'prepend' => '',
'append' => ''
);
// do not delete!
parent::__construct();
}
/*
* create_field()
*
* Create the HTML interface for your field
*
* @param $field - an array holding all the field's data
*
* @type action
* @since 3.6
* @date 23/01/13
*/
function create_field( $field )
{
// vars
$o = array( 'id', 'class', 'name', 'value', 'placeholder' );
$e = '';
// prepend
if( $field['prepend'] !== "" )
{
$field['class'] .= ' acf-is-prepended';
$e .= '<div class="acf-input-prepend">' . $field['prepend'] . '</div>';
}
// append
if( $field['append'] !== "" )
{
$field['class'] .= ' acf-is-appended';
$e .= '<div class="acf-input-append">' . $field['append'] . '</div>';
}
$e .= '<div class="acf-input-wrap">';
$e .= '<input type="email"';
foreach( $o as $k )
{
$e .= ' ' . $k . '="' . esc_attr( $field[ $k ] ) . '"';
}
$e .= ' />';
$e .= '</div>';
// return
echo $e;
}
/*
* create_options()
*
* Create extra options for your field. This is rendered when editing a field.
* The value of $field['name'] can be used (like bellow) to save extra data to the $field
*
* @type action
* @since 3.6
* @date 23/01/13
*
* @param $field - an array holding all the field's data
*/
function create_options( $field )
{
// vars
$key = $field['name'];
?>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Default Value",'acf'); ?></label>
<p><?php _e("Appears when creating a new post",'acf') ?></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'text',
'name' => 'fields['.$key.'][default_value]',
'value' => $field['default_value'],
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Placeholder Text",'acf'); ?></label>
<p><?php _e("Appears within the input",'acf') ?></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'text',
'name' => 'fields[' .$key.'][placeholder]',
'value' => $field['placeholder'],
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Prepend",'acf'); ?></label>
<p><?php _e("Appears before the input",'acf') ?></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'text',
'name' => 'fields[' .$key.'][prepend]',
'value' => $field['prepend'],
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Append",'acf'); ?></label>
<p><?php _e("Appears after the input",'acf') ?></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'text',
'name' => 'fields[' .$key.'][append]',
'value' => $field['append'],
));
?>
</td>
</tr>
<?php
}
}
new acf_field_email();
?> | PHP |
<?php
class acf_field_tab extends acf_field
{
/*
* __construct
*
* Set name / label needed for actions / filters
*
* @since 3.6
* @date 23/01/13
*/
function __construct()
{
// vars
$this->name = 'tab';
$this->label = __("Tab",'acf');
$this->category = __("Layout",'acf');
// do not delete!
parent::__construct();
}
/*
* create_field()
*
* Create the HTML interface for your field
*
* @param $field - an array holding all the field's data
*
* @type action
* @since 3.6
* @date 23/01/13
*/
function create_field( $field )
{
echo '<div class="acf-tab">' . $field['label'] . '</div>';
}
/*
* create_options()
*
* Create extra options for your field. This is rendered when editing a field.
* The value of $field['name'] can be used (like bellow) to save extra data to the $field
*
* @param $field - an array holding all the field's data
*
* @type action
* @since 3.6
* @date 23/01/13
*/
function create_options( $field )
{
?>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Instructions",'acf'); ?></label>
</td>
<td>
<p><?php _e("Use \"Tab Fields\" to better organize your edit screen by grouping your fields together under separate tab headings.",'acf'); ?></p>
<p><?php _e("All the fields following this \"tab field\" (or until another \"tab field\" is defined) will be grouped together.",'acf'); ?></p>
<p><?php _e("Use multiple tabs to divide your fields into sections.",'acf'); ?></p>
</td>
</tr>
<?php
}
}
new acf_field_tab();
?> | PHP |
<?php
class acf_field_dummy extends acf_field
{
/*
* __construct
*
* Set name / label needed for actions / filters
*
* @since 3.6
* @date 23/01/13
*/
function __construct()
{
// vars
$this->name = 'dummy';
$this->label = __('Dummy');
// do not delete!
parent::__construct();
}
/*
* load_value()
*
* This filter is appied to the $value after it is loaded from the db
*
* @type filter
* @since 3.6
* @date 23/01/13
*
* @param $value - the value found in the database
* @param $post_id - the $post_id from which the value was loaded from
* @param $field - the field array holding all the field options
*
* @return $value - the value to be saved in te database
*/
function load_value( $value, $post_id, $field )
{
return $value;
}
/*
* format_value()
*
* This filter is appied to the $value after it is loaded from the db and before it is passed to the create_field action
*
* @type filter
* @since 3.6
* @date 23/01/13
*
* @param $value - the value which was loaded from the database
* @param $post_id - the $post_id from which the value was loaded
* @param $field - the field array holding all the field options
*
* @return $value - the modified value
*/
function format_value( $value, $post_id, $field )
{
return $value;
}
/*
* format_value_for_api()
*
* This filter is appied to the $value after it is loaded from the db and before it is passed back to the api functions such as the_field
*
* @type filter
* @since 3.6
* @date 23/01/13
*
* @param $value - the value which was loaded from the database
* @param $post_id - the $post_id from which the value was loaded
* @param $field - the field array holding all the field options
*
* @return $value - the modified value
*/
function format_value_for_api( $value, $post_id, $field )
{
return $value;
}
/*
* update_value()
*
* This filter is appied to the $value before it is updated in the db
*
* @type filter
* @since 3.6
* @date 23/01/13
*
* @param $value - the value which will be saved in the database
* @param $field - the field array holding all the field options
* @param $post_id - the $post_id of which the value will be saved
*
* @return $value - the modified value
*/
function update_value( $value, $post_id, $field )
{
return $value;
}
/*
* load_field()
*
* This filter is appied to the $field after it is loaded from the database
*
* @type filter
* @since 3.6
* @date 23/01/13
*
* @param $field - the field array holding all the field options
*
* @return $field - the field array holding all the field options
*/
function load_field( $field )
{
return $field;
}
/*
* update_field()
*
* This filter is appied to the $field before it is saved to the database
*
* @type filter
* @since 3.6
* @date 23/01/13
*
* @param $field - the field array holding all the field options
* @param $post_id - the field group ID (post_type = acf)
*
* @return $field - the modified field
*/
function update_field( $field, $post_id )
{
return $field;
}
/*
* create_field()
*
* Create the HTML interface for your field
*
* @type action
* @since 3.6
* @date 23/01/13
*
* @param $field - an array holding all the field's data
*/
function create_field( $field )
{
}
/*
* create_options()
*
* Create extra options for your field. This is rendered when editing a field.
* The value of $field['name'] can be used (like bellow) to save extra data to the $field
*
* @type action
* @since 3.6
* @date 23/01/13
*
* @param $field - an array holding all the field's data
*/
function create_options( $field )
{
}
/*
* input_admin_enqueue_scripts()
*
* This action is called in the admin_enqueue_scripts action on the edit screen where your field is created.
* Use this action to add css + javascript to assist your create_field() action.
*
* $info http://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts
* @type action
* @since 3.6
* @date 23/01/13
*/
function input_admin_enqueue_scripts()
{
}
/*
* input_admin_head()
*
* This action is called in the admin_head action on the edit screen where your field is created.
* Use this action to add css and javascript to assist your create_field() action.
*
* @info http://codex.wordpress.org/Plugin_API/Action_Reference/admin_head
* @type action
* @since 3.6
* @date 23/01/13
*/
function input_admin_head()
{
}
/*
* field_group_admin_enqueue_scripts()
*
* This action is called in the admin_enqueue_scripts action on the edit screen where your field is edited.
* Use this action to add css + javascript to assist your create_field_options() action.
*
* $info http://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts
* @type action
* @since 3.6
* @date 23/01/13
*/
function field_group_admin_enqueue_scripts()
{
}
/*
* field_group_admin_head()
*
* This action is called in the admin_head action on the edit screen where your field is edited.
* Use this action to add css and javascript to assist your create_field_options() action.
*
* @info http://codex.wordpress.org/Plugin_API/Action_Reference/admin_head
* @type action
* @since 3.6
* @date 23/01/13
*/
function field_group_admin_head()
{
}
}
// create field
new acf_field_dummy();
/*--------------------------------------- fuctions.php ----------------------------------------------------*/
add_action('acf/register_fields', 'my_register_fields');
function my_register_fields()
{
include_once('fields/dummy.php');
}
?> | PHP |
<?php
class acf_field_user extends acf_field
{
/*
* __construct
*
* Set name / label needed for actions / filters
*
* @since 3.6
* @date 23/01/13
*/
function __construct()
{
// vars
$this->name = 'user';
$this->label = __("User",'acf');
$this->category = __("Relational",'acf');
$this->defaults = array(
'role' => 'all',
'field_type' => 'select',
'allow_null' => 0,
);
// do not delete!
parent::__construct();
}
/*
* format_value_for_api()
*
* This filter is appied to the $value after it is loaded from the db and before it is passed back to the api functions such as the_field
*
* @type filter
* @since 3.6
* @date 23/01/13
*
* @param $value - the value which was loaded from the database
* @param $field - the field array holding all the field options
*
* @return $value - the modified value
*/
function format_value_for_api( $value, $post_id, $field )
{
// format value
if( !$value || $value == 'null' )
{
return false;
}
// temp convert to array
$is_array = true;
if( !is_array($value) )
{
$is_array = false;
$value = array( $value );
}
foreach( $value as $k => $v )
{
$user_data = get_userdata( $v );
//cope with deleted users by @adampope
if( !is_object($user_data) )
{
unset( $value[$k] );
continue;
}
$value[ $k ] = array();
$value[ $k ]['ID'] = $v;
$value[ $k ]['user_firstname'] = $user_data->user_firstname;
$value[ $k ]['user_lastname'] = $user_data->user_lastname;
$value[ $k ]['nickname'] = $user_data->nickname;
$value[ $k ]['user_nicename'] = $user_data->user_nicename;
$value[ $k ]['display_name'] = $user_data->display_name;
$value[ $k ]['user_email'] = $user_data->user_email;
$value[ $k ]['user_url'] = $user_data->user_url;
$value[ $k ]['user_registered'] = $user_data->user_registered;
$value[ $k ]['user_description'] = $user_data->user_description;
$value[ $k ]['user_avatar'] = get_avatar( $v );
}
// de-convert from array
if( !$is_array && isset($value[0]) )
{
$value = $value[0];
}
// return value
return $value;
}
/*
* input_admin_head()
*
* This action is called in the admin_head action on the edit screen where your field is created.
* Use this action to add css and javascript to assist your create_field() action.
*
* @info http://codex.wordpress.org/Plugin_API/Action_Reference/admin_head
* @type action
* @since 3.6
* @date 23/01/13
*/
function input_admin_head()
{
if( ! function_exists( 'get_editable_roles' ) )
{
// if using front-end forms then we need to add this core file
require_once( ABSPATH . '/wp-admin/includes/user.php' );
}
}
/*
* create_field()
*
* Create the HTML interface for your field
*
* @type action
* @since 3.6
* @date 23/01/13
*
* @param $field - an array holding all the field's data
*/
function create_field( $field )
{
if( ! function_exists( 'get_editable_roles' ) )
{
// if using front-end forms then we need to add this core file
require_once( ABSPATH . '/wp-admin/includes/user.php' );
}
// options
$options = array(
'post_id' => get_the_ID(),
);
// vars
$args = array();
// editable roles
$editable_roles = get_editable_roles();
if( !empty($field['role']) )
{
if( ! in_array('all', $field['role']) )
{
foreach( $editable_roles as $role => $role_info )
{
if( !in_array($role, $field['role']) )
{
unset( $editable_roles[ $role ] );
}
}
}
}
// filters
$args = apply_filters('acf/fields/user/query', $args, $field, $options['post_id']);
$args = apply_filters('acf/fields/user/query/name=' . $field['_name'], $args, $field, $options['post_id'] );
$args = apply_filters('acf/fields/user/query/key=' . $field['key'], $args, $field, $options['post_id'] );
// get users
$users = get_users( $args );
if( !empty($users) && !empty($editable_roles) )
{
$field['choices'] = array();
foreach( $editable_roles as $role => $role_info )
{
// vars
$this_users = array();
$this_json = array();
// loop over users
$keys = array_keys($users);
foreach( $keys as $key )
{
if( in_array($role, $users[ $key ]->roles) )
{
$this_users[] = $users[ $key ];
unset( $users[ $key ] );
}
}
// bail early if no users for this role
if( empty($this_users) )
{
continue;
}
// label
$label = translate_user_role( $role_info['name'] );
// append to choices
$field['choices'][ $label ] = array();
foreach( $this_users as $user )
{
$field['choices'][ $label ][ $user->ID ] = ucfirst( $user->display_name );
}
}
}
// modify field
if( $field['field_type'] == 'multi_select' )
{
$field['multiple'] = 1;
}
$field['type'] = 'select';
do_action('acf/create_field', $field);
}
/*
* create_options()
*
* Create extra options for your field. This is rendered when editing a field.
* The value of $field['name'] can be used (like bellow) to save extra data to the $field
*
* @type action
* @since 3.6
* @date 23/01/13
*
* @param $field - an array holding all the field's data
*/
function create_options( $field )
{
// vars
$key = $field['name'];
?>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e( "Filter by role", 'acf' ); ?></label>
</td>
<td>
<?php
$choices = array('all' => __('All', 'acf'));
$editable_roles = get_editable_roles();
foreach( $editable_roles as $role => $details )
{
// only translate the output not the value
$choices[$role] = translate_user_role( $details['name'] );
}
do_action('acf/create_field', array(
'type' => 'select',
'name' => 'fields[' . $key . '][role]',
'value' => $field['role'],
'choices' => $choices,
'multiple' => '1',
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Field Type",'acf'); ?></label>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'select',
'name' => 'fields['.$key.'][field_type]',
'value' => $field['field_type'],
'choices' => array(
__("Multiple Values",'acf') => array(
//'checkbox' => __('Checkbox', 'acf'),
'multi_select' => __('Multi Select', 'acf')
),
__("Single Value",'acf') => array(
//'radio' => __('Radio Buttons', 'acf'),
'select' => __('Select', 'acf')
)
)
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Allow Null?",'acf'); ?></label>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'radio',
'name' => 'fields['.$key.'][allow_null]',
'value' => $field['allow_null'],
'choices' => array(
1 => __("Yes",'acf'),
0 => __("No",'acf'),
),
'layout' => 'horizontal',
));
?>
</td>
</tr>
<?php
}
/*
* update_value()
*
* This filter is appied to the $value before it is updated in the db
*
* @type filter
* @since 3.6
* @date 23/01/13
*
* @param $value - the value which will be saved in the database
* @param $post_id - the $post_id of which the value will be saved
* @param $field - the field array holding all the field options
*
* @return $value - the modified value
*/
function update_value( $value, $post_id, $field )
{
// array?
if( is_array($value) && isset($value['ID']) )
{
$value = $value['ID'];
}
// object?
if( is_object($value) && isset($value->ID) )
{
$value = $value->ID;
}
return $value;
}
}
new acf_field_user();
?> | PHP |
<?php
class acf_field_textarea extends acf_field
{
/*
* __construct
*
* Set name / label needed for actions / filters
*
* @since 3.6
* @date 23/01/13
*/
function __construct()
{
// vars
$this->name = 'textarea';
$this->label = __("Text Area",'acf');
$this->defaults = array(
'default_value' => '',
'formatting' => 'br',
'maxlength' => '',
'placeholder' => '',
'rows' => ''
);
// do not delete!
parent::__construct();
}
/*
* create_field()
*
* Create the HTML interface for your field
*
* @param $field - an array holding all the field's data
*
* @type action
* @since 3.6
* @date 23/01/13
*/
function create_field( $field )
{
// vars
$o = array( 'id', 'class', 'name', 'placeholder', 'rows' );
$e = '';
// maxlength
if( $field['maxlength'] !== "" )
{
$o[] = 'maxlength';
}
// rows
if( empty($field['rows']) )
{
$field['rows'] = 8;
}
$e .= '<textarea';
foreach( $o as $k )
{
$e .= ' ' . $k . '="' . esc_attr( $field[ $k ] ) . '"';
}
$e .= '>';
$e .= esc_textarea($field['value']);
$e .= '</textarea>';
// return
echo $e;
}
/*
* create_options()
*
* Create extra options for your field. This is rendered when editing a field.
* The value of $field['name'] can be used (like bellow) to save extra data to the $field
*
* @param $field - an array holding all the field's data
*
* @type action
* @since 3.6
* @date 23/01/13
*/
function create_options( $field )
{
// vars
$key = $field['name'];
?>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Default Value",'acf'); ?></label>
<p><?php _e("Appears when creating a new post",'acf') ?></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'textarea',
'name' => 'fields['.$key.'][default_value]',
'value' => $field['default_value'],
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Placeholder Text",'acf'); ?></label>
<p><?php _e("Appears within the input",'acf') ?></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'text',
'name' => 'fields[' .$key.'][placeholder]',
'value' => $field['placeholder'],
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Character Limit",'acf'); ?></label>
<p><?php _e("Leave blank for no limit",'acf') ?></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'number',
'name' => 'fields[' .$key.'][maxlength]',
'value' => $field['maxlength'],
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Rows",'acf'); ?></label>
<p><?php _e("Sets the textarea height",'acf') ?></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'number',
'name' => 'fields[' .$key.'][rows]',
'value' => $field['rows'],
'placeholder' => 8
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Formatting",'acf'); ?></label>
<p><?php _e("Effects value on front end",'acf') ?></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'select',
'name' => 'fields['.$key.'][formatting]',
'value' => $field['formatting'],
'choices' => array(
'none' => __("No formatting",'acf'),
'br' => __("Convert new lines into <br /> tags",'acf'),
'html' => __("Convert HTML into tags",'acf')
)
));
?>
</td>
</tr>
<?php
}
/*
* format_value_for_api()
*
* This filter is appied to the $value after it is loaded from the db and before it is passed back to the api functions such as the_field
*
* @type filter
* @since 3.6
* @date 23/01/13
*
* @param $value - the value which was loaded from the database
* @param $post_id - the $post_id from which the value was loaded
* @param $field - the field array holding all the field options
*
* @return $value - the modified value
*/
function format_value_for_api( $value, $post_id, $field )
{
// validate type
if( !is_string($value) )
{
return $value;
}
if( $field['formatting'] == 'none' )
{
$value = htmlspecialchars($value, ENT_QUOTES);
}
elseif( $field['formatting'] == 'html' )
{
//$value = html_entity_decode($value);
//$value = nl2br($value);
}
elseif( $field['formatting'] == 'br' )
{
$value = htmlspecialchars($value, ENT_QUOTES);
$value = nl2br($value);
}
return $value;
}
}
new acf_field_textarea();
?> | PHP |
<?php
class acf_field_number extends acf_field
{
/*
* __construct
*
* Set name / label needed for actions / filters
*
* @since 3.6
* @date 23/01/13
*/
function __construct()
{
// vars
$this->name = 'number';
$this->label = __("Number",'acf');
$this->defaults = array(
'default_value' => '',
'min' => '',
'max' => '',
'step' => '',
'placeholder' => '',
'prepend' => '',
'append' => ''
);
// do not delete!
parent::__construct();
}
/*
* create_field()
*
* Create the HTML interface for your field
*
* @param $field - an array holding all the field's data
*
* @type action
* @since 3.6
* @date 23/01/13
*/
function create_field( $field )
{
// vars
$o = array( 'id', 'class', 'min', 'max', 'step', 'name', 'value', 'placeholder' );
$e = '';
// step
if( !$field['step'] )
{
$field['step'] = 'any';
}
// prepend
if( $field['prepend'] !== "" )
{
$field['class'] .= ' acf-is-prepended';
$e .= '<div class="acf-input-prepend">' . $field['prepend'] . '</div>';
}
// append
if( $field['append'] !== "" )
{
$field['class'] .= ' acf-is-appended';
$e .= '<div class="acf-input-append">' . $field['append'] . '</div>';
}
$e .= '<div class="acf-input-wrap">';
$e .= '<input type="number"';
foreach( $o as $k )
{
$e .= ' ' . $k . '="' . esc_attr( $field[ $k ] ) . '"';
}
$e .= ' />';
$e .= '</div>';
// return
echo $e;
}
/*
* create_options()
*
* Create extra options for your field. This is rendered when editing a field.
* The value of $field['name'] can be used (like bellow) to save extra data to the $field
*
* @type action
* @since 3.6
* @date 23/01/13
*
* @param $field - an array holding all the field's data
*/
function create_options( $field )
{
// vars
$key = $field['name'];
?>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Default Value",'acf'); ?></label>
<p><?php _e("Appears when creating a new post",'acf') ?></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'number',
'name' => 'fields['.$key.'][default_value]',
'value' => $field['default_value'],
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Placeholder Text",'acf'); ?></label>
<p><?php _e("Appears within the input",'acf') ?></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'text',
'name' => 'fields[' .$key.'][placeholder]',
'value' => $field['placeholder'],
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Prepend",'acf'); ?></label>
<p><?php _e("Appears before the input",'acf') ?></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'text',
'name' => 'fields[' .$key.'][prepend]',
'value' => $field['prepend'],
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Append",'acf'); ?></label>
<p><?php _e("Appears after the input",'acf') ?></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'text',
'name' => 'fields[' .$key.'][append]',
'value' => $field['append'],
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Minimum Value",'acf'); ?></label>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'number',
'name' => 'fields['.$key.'][min]',
'value' => $field['min'],
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Maximum Value",'acf'); ?></label>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'number',
'name' => 'fields['.$key.'][max]',
'value' => $field['max'],
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Step Size",'acf'); ?></label>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'number',
'name' => 'fields['.$key.'][step]',
'value' => $field['step'],
));
?>
</td>
</tr>
<?php
}
/*
* update_value()
*
* This filter is appied to the $value before it is updated in the db
*
* @type filter
* @since 3.6
* @date 23/01/13
*
* @param $value - the value which will be saved in the database
* @param $field - the field array holding all the field options
* @param $post_id - the $post_id of which the value will be saved
*
* @return $value - the modified value
*/
function update_value( $value, $post_id, $field )
{
// no formatting needed for empty value
if( empty($value) ) {
return $value;
}
// remove ','
$value = str_replace(',', '', $value);
// convert to float. This removes any chars
$value = floatval( $value );
// convert back to string. This alows decimals to save
$value = (string) $value;
return $value;
}
}
new acf_field_number();
?> | PHP |
<?php
/*
* Field Functions
*
* @description: The API for all fields
* @since: 3.6
* @created: 23/01/13
*/
class acf_field_functions
{
/*
* __construct
*
* @description:
* @since 3.1.8
* @created: 23/06/12
*/
function __construct()
{
//value
add_filter('acf/load_value', array($this, 'load_value'), 5, 3);
add_action('acf/update_value', array($this, 'update_value'), 5, 3);
add_action('acf/delete_value', array($this, 'delete_value'), 5, 2);
add_action('acf/format_value', array($this, 'format_value'), 5, 3);
add_action('acf/format_value_for_api', array($this, 'format_value_for_api'), 5, 3);
// field
add_filter('acf/load_field', array($this, 'load_field'), 5, 3);
add_action('acf/update_field', array($this, 'update_field'), 5, 2);
add_action('acf/delete_field', array($this, 'delete_field'), 5, 2);
add_action('acf/create_field', array($this, 'create_field'), 5, 1);
add_action('acf/create_field_options', array($this, 'create_field_options'), 5, 1);
// extra
add_filter('acf/load_field_defaults', array($this, 'load_field_defaults'), 5, 1);
}
/*
* load_value
*
* @description: loads basic value from the db
* @since: 3.6
* @created: 23/01/13
*/
function load_value($value, $post_id, $field)
{
$found = false;
$cache = wp_cache_get( 'load_value/post_id=' . $post_id . '/name=' . $field['name'], 'acf', false, $found );
if( $found )
{
return $cache;
}
// set default value
$value = false;
// if $post_id is a string, then it is used in the everything fields and can be found in the options table
if( is_numeric($post_id) )
{
$v = get_post_meta( $post_id, $field['name'], false );
// value is an array
if( isset($v[0]) )
{
$value = $v[0];
}
}
elseif( strpos($post_id, 'user_') !== false )
{
$post_id = str_replace('user_', '', $post_id);
$v = get_user_meta( $post_id, $field['name'], false );
// value is an array
if( isset($v[0]) )
{
$value = $v[0];
}
}
else
{
$v = get_option( $post_id . '_' . $field['name'], false );
if( !is_null($value) )
{
$value = $v;
}
}
// no value?
if( $value === false )
{
if( isset($field['default_value']) && $field['default_value'] !== "" )
{
$value = $field['default_value'];
}
}
// if value was duplicated, it may now be a serialized string!
$value = maybe_unserialize($value);
// apply filters
foreach( array('type', 'name', 'key') as $key )
{
// run filters
$value = apply_filters('acf/load_value/' . $key . '=' . $field[ $key ], $value, $post_id, $field); // new filter
}
//update cache
wp_cache_set( 'load_value/post_id=' . $post_id . '/name=' . $field['name'], $value, 'acf' );
return $value;
}
/*
* format_value
*
* @description: uses the basic value and allows the field type to format it
* @since: 3.6
* @created: 26/01/13
*/
function format_value( $value, $post_id, $field )
{
$value = apply_filters('acf/format_value/type=' . $field['type'], $value, $post_id, $field);
return $value;
}
/*
* format_value_for_api
*
* @description: uses the basic value and allows the field type to format it or the api functions
* @since: 3.6
* @created: 26/01/13
*/
function format_value_for_api( $value, $post_id, $field )
{
$value = apply_filters('acf/format_value_for_api/type=' . $field['type'], $value, $post_id, $field);
return $value;
}
/*
* update_value
*
* updates a value into the db
*
* @type action
* @date 23/01/13
*
* @param {mixed} $value the value to be saved
* @param {int} $post_id the post ID to save the value to
* @param {array} $field the field array
* @param {boolean} $exact allows the update_value filter to be skipped
* @return N/A
*/
function update_value( $value, $post_id, $field )
{
// strip slashes
// - not needed? http://support.advancedcustomfields.com/discussion/3168/backslashes-stripped-in-wysiwyg-filed
//if( get_magic_quotes_gpc() )
//{
$value = stripslashes_deep($value);
//}
// apply filters
foreach( array('key', 'name', 'type') as $key )
{
// run filters
$value = apply_filters('acf/update_value/' . $key . '=' . $field[ $key ], $value, $post_id, $field); // new filter
}
// if $post_id is a string, then it is used in the everything fields and can be found in the options table
if( is_numeric($post_id) )
{
// allow ACF to save to revision!
update_metadata('post', $post_id, $field['name'], $value );
update_metadata('post', $post_id, '_' . $field['name'], $field['key']);
}
elseif( strpos($post_id, 'user_') !== false )
{
$user_id = str_replace('user_', '', $post_id);
update_metadata('user', $user_id, $field['name'], $value);
update_metadata('user', $user_id, '_' . $field['name'], $field['key']);
}
else
{
// for some reason, update_option does not use stripslashes_deep.
// update_metadata -> http://core.trac.wordpress.org/browser/tags/3.4.2/wp-includes/meta.php#L82: line 101 (does use stripslashes_deep)
// update_option -> http://core.trac.wordpress.org/browser/tags/3.5.1/wp-includes/option.php#L0: line 215 (does not use stripslashes_deep)
$value = stripslashes_deep($value);
$this->update_option( $post_id . '_' . $field['name'], $value );
$this->update_option( '_' . $post_id . '_' . $field['name'], $field['key'] );
}
// update the cache
wp_cache_set( 'load_value/post_id=' . $post_id . '/name=' . $field['name'], $value, 'acf' );
}
/*
* update_option
*
* This function is a wrapper for the WP update_option but provides logic for a 'no' autoload
*
* @type function
* @date 4/01/2014
* @since 5.0.0
*
* @param $option (string)
* @param $value (mixed)
* @return (boolean)
*/
function update_option( $option = '', $value = false, $autoload = 'no' ) {
// vars
$deprecated = '';
$return = false;
if( get_option($option) !== false )
{
$return = update_option( $option, $value );
}
else
{
$return = add_option( $option, $value, $deprecated, $autoload );
}
// return
return $return;
}
/*
* delete_value
*
* @description: deletes a value from the database
* @since: 3.6
* @created: 23/01/13
*/
function delete_value( $post_id, $key )
{
// if $post_id is a string, then it is used in the everything fields and can be found in the options table
if( is_numeric($post_id) )
{
delete_post_meta( $post_id, $key );
delete_post_meta( $post_id, '_' . $key );
}
elseif( strpos($post_id, 'user_') !== false )
{
$post_id = str_replace('user_', '', $post_id);
delete_user_meta( $post_id, $key );
delete_user_meta( $post_id, '_' . $key );
}
else
{
delete_option( $post_id . '_' . $key );
delete_option( '_' . $post_id . '_' . $key );
}
wp_cache_delete( 'load_value/post_id=' . $post_id . '/name=' . $key, 'acf' );
}
/*
* load_field
*
* @description: loads a field from the database
* @since 3.5.1
* @created: 14/10/12
*/
function load_field( $field, $field_key, $post_id = false )
{
// load cache
if( !$field )
{
$field = wp_cache_get( 'load_field/key=' . $field_key, 'acf' );
}
// load from DB
if( !$field )
{
// vars
global $wpdb;
// get field from postmeta
$sql = $wpdb->prepare("SELECT post_id, meta_value FROM $wpdb->postmeta WHERE meta_key = %s", $field_key);
if( $post_id )
{
$sql .= $wpdb->prepare("AND post_id = %d", $post_id);
}
$rows = $wpdb->get_results( $sql, ARRAY_A );
// nothing found?
if( !empty($rows) )
{
$row = $rows[0];
/*
* WPML compatibility
*
* If WPML is active, and the $post_id (Field group ID) was not defined,
* it is assumed that the load_field functio has been called from the API (front end).
* In this case, the field group ID is never known and we can check for the correct translated field group
*/
if( defined('ICL_LANGUAGE_CODE') && !$post_id )
{
$wpml_post_id = icl_object_id($row['post_id'], 'acf', true, ICL_LANGUAGE_CODE);
foreach( $rows as $r )
{
if( $r['post_id'] == $wpml_post_id )
{
// this row is a field from the translated field group
$row = $r;
}
}
}
// return field if it is not in a trashed field group
if( get_post_status( $row['post_id'] ) != "trash" )
{
$field = $row['meta_value'];
$field = maybe_unserialize( $field );
$field = maybe_unserialize( $field ); // run again for WPML
// add field_group ID
$field['field_group'] = $row['post_id'];
}
}
}
// apply filters
$field = apply_filters('acf/load_field_defaults', $field);
// apply filters
foreach( array('type', 'name', 'key') as $key )
{
// run filters
$field = apply_filters('acf/load_field/' . $key . '=' . $field[ $key ], $field); // new filter
}
// set cache
wp_cache_set( 'load_field/key=' . $field_key, $field, 'acf' );
return $field;
}
/*
* load_field_defaults
*
* @description: applies default values to the field after it has been loaded
* @since 3.5.1
* @created: 14/10/12
*/
function load_field_defaults( $field )
{
// validate $field
if( !is_array($field) )
{
$field = array();
}
// defaults
$defaults = array(
'key' => '',
'label' => '',
'name' => '',
'_name' => '',
'type' => 'text',
'order_no' => 1,
'instructions' => '',
'required' => 0,
'id' => '',
'class' => '',
'conditional_logic' => array(
'status' => 0,
'allorany' => 'all',
'rules' => 0
),
);
$field = array_merge($defaults, $field);
// Parse Values
$field = apply_filters( 'acf/parse_types', $field );
// field specific defaults
$field = apply_filters('acf/load_field_defaults/type=' . $field['type'] , $field);
// class
if( !$field['class'] )
{
$field['class'] = $field['type'];
}
// id
if( !$field['id'] )
{
$id = $field['name'];
$id = str_replace('][', '_', $id);
$id = str_replace('fields[', '', $id);
$id = str_replace('[', '-', $id); // location rules (select) does'nt have "fields[" in it
$id = str_replace(']', '', $id);
$field['id'] = 'acf-field-' . $id;
}
// _name
if( !$field['_name'] )
{
$field['_name'] = $field['name'];
}
// clean up conditional logic keys
if( !empty($field['conditional_logic']['rules']) )
{
$field['conditional_logic']['rules'] = array_values($field['conditional_logic']['rules']);
}
// return
return $field;
}
/*
* update_field
*
* @description: updates a field in the database
* @since: 3.6
* @created: 24/01/13
*/
function update_field( $field, $post_id )
{
// sanitize field name
// - http://support.advancedcustomfields.com/discussion/5262/sanitize_title-on-field-name
// - issue with camel case! Replaced with JS
//$field['name'] = sanitize_title( $field['name'] );
// filters
$field = apply_filters('acf/update_field/type=' . $field['type'], $field, $post_id ); // new filter
// clear cache
wp_cache_delete( 'load_field/key=' . $field['key'], 'acf' );
// save
update_post_meta( $post_id, $field['key'], $field );
}
/*
* delete_field
*
* @description: deletes a field in the database
* @since: 3.6
* @created: 24/01/13
*/
function delete_field( $post_id, $field_key )
{
// clear cache
wp_cache_delete( 'load_field/key=' . $field['key'], 'acf' );
// delete
delete_post_meta($post_id, $field_key);
}
/*
* create_field
*
* @description: renders a field into a HTML interface
* @since: 3.6
* @created: 23/01/13
*/
function create_field( $field )
{
// load defaults
// if field was loaded from db, these default will already be appield
// if field was written by hand, it may be missing keys
$field = apply_filters('acf/load_field_defaults', $field);
// create field specific html
do_action('acf/create_field/type=' . $field['type'], $field);
// conditional logic
if( $field['conditional_logic']['status'] )
{
$field['conditional_logic']['field'] = $field['key'];
?>
<script type="text/javascript">
(function($) {
if( typeof acf !== 'undefined' )
{
acf.conditional_logic.items.push(<?php echo json_encode($field['conditional_logic']); ?>);
}
})(jQuery);
</script>
<?php
}
}
/*
* create_field_options
*
* @description: renders a field into a HTML interface
* @since: 3.6
* @created: 23/01/13
*/
function create_field_options($field)
{
// load standard + field specific defaults
$field = apply_filters('acf/load_field_defaults', $field);
// render HTML
do_action('acf/create_field_options/type=' . $field['type'], $field);
}
}
new acf_field_functions();
?> | PHP |
<?php
class acf_field_text extends acf_field
{
/*
* __construct
*
* Set name / label needed for actions / filters
*
* @since 3.6
* @date 23/01/13
*/
function __construct()
{
// vars
$this->name = 'text';
$this->label = __("Text",'acf');
$this->defaults = array(
'default_value' => '',
'formatting' => 'html',
'maxlength' => '',
'placeholder' => '',
'prepend' => '',
'append' => ''
);
// do not delete!
parent::__construct();
}
/*
* create_field()
*
* Create the HTML interface for your field
*
* @param $field - an array holding all the field's data
*
* @type action
* @since 3.6
* @date 23/01/13
*/
function create_field( $field )
{
// vars
$o = array( 'id', 'class', 'name', 'value', 'placeholder' );
$e = '';
// maxlength
if( $field['maxlength'] !== "" )
{
$o[] = 'maxlength';
}
// prepend
if( $field['prepend'] !== "" )
{
$field['class'] .= ' acf-is-prepended';
$e .= '<div class="acf-input-prepend">' . $field['prepend'] . '</div>';
}
// append
if( $field['append'] !== "" )
{
$field['class'] .= ' acf-is-appended';
$e .= '<div class="acf-input-append">' . $field['append'] . '</div>';
}
$e .= '<div class="acf-input-wrap">';
$e .= '<input type="text"';
foreach( $o as $k )
{
$e .= ' ' . $k . '="' . esc_attr( $field[ $k ] ) . '"';
}
$e .= ' />';
$e .= '</div>';
// return
echo $e;
}
/*
* create_options()
*
* Create extra options for your field. This is rendered when editing a field.
* The value of $field['name'] can be used (like bellow) to save extra data to the $field
*
* @param $field - an array holding all the field's data
*
* @type action
* @since 3.6
* @date 23/01/13
*/
function create_options( $field )
{
// vars
$key = $field['name'];
?>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Default Value",'acf'); ?></label>
<p><?php _e("Appears when creating a new post",'acf') ?></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'text',
'name' => 'fields[' .$key.'][default_value]',
'value' => $field['default_value'],
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Placeholder Text",'acf'); ?></label>
<p><?php _e("Appears within the input",'acf') ?></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'text',
'name' => 'fields[' .$key.'][placeholder]',
'value' => $field['placeholder'],
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Prepend",'acf'); ?></label>
<p><?php _e("Appears before the input",'acf') ?></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'text',
'name' => 'fields[' .$key.'][prepend]',
'value' => $field['prepend'],
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Append",'acf'); ?></label>
<p><?php _e("Appears after the input",'acf') ?></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'text',
'name' => 'fields[' .$key.'][append]',
'value' => $field['append'],
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Formatting",'acf'); ?></label>
<p><?php _e("Effects value on front end",'acf') ?></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'select',
'name' => 'fields['.$key.'][formatting]',
'value' => $field['formatting'],
'choices' => array(
'none' => __("No formatting",'acf'),
'html' => __("Convert HTML into tags",'acf')
)
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Character Limit",'acf'); ?></label>
<p><?php _e("Leave blank for no limit",'acf') ?></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'number',
'name' => 'fields[' .$key.'][maxlength]',
'value' => $field['maxlength'],
));
?>
</td>
</tr>
<?php
}
/*
* format_value()
*
* This filter is appied to the $value after it is loaded from the db and before it is passed to the create_field action
*
* @type filter
* @since 3.6
* @date 23/01/13
*
* @param $value - the value which was loaded from the database
* @param $post_id - the $post_id from which the value was loaded
* @param $field - the field array holding all the field options
*
* @return $value - the modified value
*/
function format_value( $value, $post_id, $field )
{
$value = htmlspecialchars($value, ENT_QUOTES);
return $value;
}
/*
* format_value_for_api()
*
* This filter is appied to the $value after it is loaded from the db and before it is passed back to the api functions such as the_field
*
* @type filter
* @since 3.6
* @date 23/01/13
*
* @param $value - the value which was loaded from the database
* @param $post_id - the $post_id from which the value was loaded
* @param $field - the field array holding all the field options
*
* @return $value - the modified value
*/
function format_value_for_api( $value, $post_id, $field )
{
// validate type
if( !is_string($value) )
{
return $value;
}
if( $field['formatting'] == 'none' )
{
$value = htmlspecialchars($value, ENT_QUOTES);
}
elseif( $field['formatting'] == 'html' )
{
$value = nl2br($value);
}
return $value;
}
}
new acf_field_text();
?> | PHP |
<?php
class acf_field_relationship extends acf_field
{
/*
* __construct
*
* Set name / label needed for actions / filters
*
* @since 3.6
* @date 23/01/13
*/
function __construct()
{
// vars
$this->name = 'relationship';
$this->label = __("Relationship",'acf');
$this->category = __("Relational",'acf');
$this->defaults = array(
'post_type' => array('all'),
'max' => '',
'taxonomy' => array('all'),
'filters' => array('search'),
'result_elements' => array('post_title', 'post_type'),
'return_format' => 'object'
);
$this->l10n = array(
'max' => __("Maximum values reached ( {max} values )",'acf'),
'tmpl_li' => '
<li>
<a href="#" data-post_id="<%= post_id %>"><%= title %><span class="acf-button-remove"></span></a>
<input type="hidden" name="<%= name %>[]" value="<%= post_id %>" />
</li>
'
);
// do not delete!
parent::__construct();
// extra
add_action('wp_ajax_acf/fields/relationship/query_posts', array($this, 'query_posts'));
add_action('wp_ajax_nopriv_acf/fields/relationship/query_posts', array($this, 'query_posts'));
}
/*
* load_field()
*
* This filter is appied to the $field after it is loaded from the database
*
* @type filter
* @since 3.6
* @date 23/01/13
*
* @param $field - the field array holding all the field options
*
* @return $field - the field array holding all the field options
*/
function load_field( $field )
{
// validate post_type
if( !$field['post_type'] || !is_array($field['post_type']) || in_array('', $field['post_type']) )
{
$field['post_type'] = array( 'all' );
}
// validate taxonomy
if( !$field['taxonomy'] || !is_array($field['taxonomy']) || in_array('', $field['taxonomy']) )
{
$field['taxonomy'] = array( 'all' );
}
// validate result_elements
if( !is_array( $field['result_elements'] ) )
{
$field['result_elements'] = array();
}
if( !in_array('post_title', $field['result_elements']) )
{
$field['result_elements'][] = 'post_title';
}
// filters
if( !is_array( $field['filters'] ) )
{
$field['filters'] = array();
}
// return
return $field;
}
/*
* posts_where
*
* @description:
* @created: 3/09/12
*/
function posts_where( $where, &$wp_query )
{
global $wpdb;
if ( $title = $wp_query->get('like_title') )
{
$where .= " AND " . $wpdb->posts . ".post_title LIKE '%" . esc_sql( like_escape( $title ) ) . "%'";
}
return $where;
}
/*
* query_posts
*
* @description:
* @since: 3.6
* @created: 27/01/13
*/
function query_posts()
{
// vars
$r = array(
'next_page_exists' => 1,
'html' => ''
);
// options
$options = array(
'post_type' => 'all',
'taxonomy' => 'all',
'posts_per_page' => 10,
'paged' => 1,
'orderby' => 'title',
'order' => 'ASC',
'post_status' => 'any',
'suppress_filters' => false,
's' => '',
'lang' => false,
'update_post_meta_cache' => false,
'field_key' => '',
'nonce' => '',
'ancestor' => false,
);
$options = array_merge( $options, $_POST );
// validate
if( ! wp_verify_nonce($options['nonce'], 'acf_nonce') )
{
die();
}
// WPML
if( $options['lang'] )
{
global $sitepress;
if( !empty($sitepress) )
{
$sitepress->switch_lang( $options['lang'] );
}
}
// convert types
$options['post_type'] = explode(',', $options['post_type']);
$options['taxonomy'] = explode(',', $options['taxonomy']);
// load all post types by default
if( in_array('all', $options['post_type']) )
{
$options['post_type'] = apply_filters('acf/get_post_types', array());
}
// attachment doesn't work if it is the only item in an array???
if( is_array($options['post_type']) && count($options['post_type']) == 1 )
{
$options['post_type'] = $options['post_type'][0];
}
// create tax queries
if( ! in_array('all', $options['taxonomy']) )
{
// vars
$taxonomies = array();
$options['tax_query'] = array();
foreach( $options['taxonomy'] as $v )
{
// find term (find taxonomy!)
// $term = array( 0 => $taxonomy, 1 => $term_id )
$term = explode(':', $v);
// validate
if( !is_array($term) || !isset($term[1]) )
{
continue;
}
// add to tax array
$taxonomies[ $term[0] ][] = $term[1];
}
// now create the tax queries
foreach( $taxonomies as $k => $v )
{
$options['tax_query'][] = array(
'taxonomy' => $k,
'field' => 'id',
'terms' => $v,
);
}
}
unset( $options['taxonomy'] );
// search
if( $options['s'] )
{
$options['like_title'] = $options['s'];
add_filter( 'posts_where', array($this, 'posts_where'), 10, 2 );
}
unset( $options['s'] );
// load field
$field = array();
if( $options['ancestor'] )
{
$ancestor = apply_filters('acf/load_field', array(), $options['ancestor'] );
$field = acf_get_child_field_from_parent_field( $options['field_key'], $ancestor );
}
else
{
$field = apply_filters('acf/load_field', array(), $options['field_key'] );
}
// get the post from which this field is rendered on
$the_post = get_post( $options['post_id'] );
// filters
$options = apply_filters('acf/fields/relationship/query', $options, $field, $the_post);
$options = apply_filters('acf/fields/relationship/query/name=' . $field['_name'], $options, $field, $the_post );
$options = apply_filters('acf/fields/relationship/query/key=' . $field['key'], $options, $field, $the_post );
// query
$wp_query = new WP_Query( $options );
// global
global $post;
// loop
while( $wp_query->have_posts() )
{
$wp_query->the_post();
// right aligned info
$title = '<span class="relationship-item-info">';
if( in_array('post_type', $field['result_elements']) )
{
$post_type_object = get_post_type_object( get_post_type() );
$title .= $post_type_object->labels->singular_name;
}
// WPML
if( $options['lang'] )
{
$title .= ' (' . $options['lang'] . ')';
}
$title .= '</span>';
// featured_image
if( in_array('featured_image', $field['result_elements']) )
{
$image = get_the_post_thumbnail( get_the_ID(), array(21, 21) );
$title .= '<div class="result-thumbnail">' . $image . '</div>';
}
// title
$title .= get_the_title();
// status
if( get_post_status() != "publish" )
{
$title .= ' (' . get_post_status() . ')';
}
// filters
$title = apply_filters('acf/fields/relationship/result', $title, $post, $field, $the_post);
$title = apply_filters('acf/fields/relationship/result/name=' . $field['_name'] , $title, $post, $field, $the_post);
$title = apply_filters('acf/fields/relationship/result/key=' . $field['key'], $title, $post, $field, $the_post);
// update html
$r['html'] .= '<li><a href="' . get_permalink() . '" data-post_id="' . get_the_ID() . '">' . $title . '<span class="acf-button-add"></span></a></li>';
}
if( (int)$options['paged'] >= $wp_query->max_num_pages )
{
$r['next_page_exists'] = 0;
}
wp_reset_postdata();
// return JSON
echo json_encode( $r );
die();
}
/*
* create_field()
*
* Create the HTML interface for your field
*
* @param $field - an array holding all the field's data
*
* @type action
* @since 3.6
* @date 23/01/13
*/
function create_field( $field )
{
// global
global $post;
// no row limit?
if( !$field['max'] || $field['max'] < 1 )
{
$field['max'] = 9999;
}
// class
$class = '';
if( $field['filters'] )
{
foreach( $field['filters'] as $filter )
{
$class .= ' has-' . $filter;
}
}
$attributes = array(
'max' => $field['max'],
's' => '',
'paged' => 1,
'post_type' => implode(',', $field['post_type']),
'taxonomy' => implode(',', $field['taxonomy']),
'field_key' => $field['key']
);
// Lang
if( defined('ICL_LANGUAGE_CODE') )
{
$attributes['lang'] = ICL_LANGUAGE_CODE;
}
// parent
preg_match('/\[(field_.*?)\]/', $field['name'], $ancestor);
if( isset($ancestor[1]) && $ancestor[1] != $field['key'])
{
$attributes['ancestor'] = $ancestor[1];
}
?>
<div class="acf_relationship<?php echo $class; ?>"<?php foreach( $attributes as $k => $v ): ?> data-<?php echo $k; ?>="<?php echo $v; ?>"<?php endforeach; ?>>
<!-- Hidden Blank default value -->
<input type="hidden" name="<?php echo $field['name']; ?>" value="" />
<!-- Left List -->
<div class="relationship_left">
<table class="widefat">
<thead>
<?php if(in_array( 'search', $field['filters']) ): ?>
<tr>
<th>
<input class="relationship_search" placeholder="<?php _e("Search...",'acf'); ?>" type="text" id="relationship_<?php echo $field['name']; ?>" />
</th>
</tr>
<?php endif; ?>
<?php if(in_array( 'post_type', $field['filters']) ): ?>
<tr>
<th>
<?php
// vars
$choices = array(
'all' => __("Filter by post type",'acf')
);
if( in_array('all', $field['post_type']) )
{
$post_types = apply_filters( 'acf/get_post_types', array() );
$choices = array_merge( $choices, $post_types);
}
else
{
foreach( $field['post_type'] as $post_type )
{
$choices[ $post_type ] = $post_type;
}
}
// create field
do_action('acf/create_field', array(
'type' => 'select',
'name' => '',
'class' => 'select-post_type',
'value' => '',
'choices' => $choices,
));
?>
</th>
</tr>
<?php endif; ?>
</thead>
</table>
<ul class="bl relationship_list">
<li class="load-more">
<div class="acf-loading"></div>
</li>
</ul>
</div>
<!-- /Left List -->
<!-- Right List -->
<div class="relationship_right">
<ul class="bl relationship_list">
<?php
if( $field['value'] )
{
foreach( $field['value'] as $p )
{
// right aligned info
$title = '<span class="relationship-item-info">';
if( in_array('post_type', $field['result_elements']) )
{
$post_type_object = get_post_type_object( get_post_type() );
$title .= $post_type_object->labels->singular_name;
}
// WPML
if( defined('ICL_LANGUAGE_CODE') )
{
$title .= ' (' . ICL_LANGUAGE_CODE . ')';
}
$title .= '</span>';
// featured_image
if( in_array('featured_image', $field['result_elements']) )
{
$image = get_the_post_thumbnail( $p->ID, array(21, 21) );
$title .= '<div class="result-thumbnail">' . $image . '</div>';
}
// find title. Could use get_the_title, but that uses get_post(), so I think this uses less Memory
$title .= apply_filters( 'the_title', $p->post_title, $p->ID );
// status
if($p->post_status != "publish")
{
$title .= " ($p->post_status)";
}
// filters
$title = apply_filters('acf/fields/relationship/result', $title, $p, $field, $post);
$title = apply_filters('acf/fields/relationship/result/name=' . $field['_name'] , $title, $p, $field, $post);
$title = apply_filters('acf/fields/relationship/result/key=' . $field['key'], $title, $p, $field, $post);
echo '<li>
<a href="' . get_permalink($p->ID) . '" class="" data-post_id="' . $p->ID . '">' . $title . '<span class="acf-button-remove"></span></a>
<input type="hidden" name="' . $field['name'] . '[]" value="' . $p->ID . '" />
</li>';
}
}
?>
</ul>
</div>
<!-- / Right List -->
</div>
<?php
}
/*
* create_options()
*
* Create extra options for your field. This is rendered when editing a field.
* The value of $field['name'] can be used (like bellow) to save extra data to the $field
*
* @type action
* @since 3.6
* @date 23/01/13
*
* @param $field - an array holding all the field's data
*/
function create_options( $field )
{
// vars
$key = $field['name'];
?>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Return Format",'acf'); ?></label>
<p><?php _e("Specify the returned value on front end",'acf') ?></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'radio',
'name' => 'fields['.$key.'][return_format]',
'value' => $field['return_format'],
'layout' => 'horizontal',
'choices' => array(
'object' => __("Post Objects",'acf'),
'id' => __("Post IDs",'acf')
)
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label for=""><?php _e("Post Type",'acf'); ?></label>
</td>
<td>
<?php
$choices = array(
'all' => __("All",'acf')
);
$choices = apply_filters('acf/get_post_types', $choices);
do_action('acf/create_field', array(
'type' => 'select',
'name' => 'fields['.$key.'][post_type]',
'value' => $field['post_type'],
'choices' => $choices,
'multiple' => 1,
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Filter from Taxonomy",'acf'); ?></label>
</td>
<td>
<?php
$choices = array(
'' => array(
'all' => __("All",'acf')
)
);
$simple_value = false;
$choices = apply_filters('acf/get_taxonomies_for_select', $choices, $simple_value);
do_action('acf/create_field', array(
'type' => 'select',
'name' => 'fields['.$key.'][taxonomy]',
'value' => $field['taxonomy'],
'choices' => $choices,
'multiple' => 1,
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Filters",'acf'); ?></label>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'checkbox',
'name' => 'fields['.$key.'][filters]',
'value' => $field['filters'],
'choices' => array(
'search' => __("Search",'acf'),
'post_type' => __("Post Type Select",'acf'),
)
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Elements",'acf'); ?></label>
<p><?php _e("Selected elements will be displayed in each result",'acf') ?></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'checkbox',
'name' => 'fields['.$key.'][result_elements]',
'value' => $field['result_elements'],
'choices' => array(
'featured_image' => __("Featured Image",'acf'),
'post_title' => __("Post Title",'acf'),
'post_type' => __("Post Type",'acf'),
),
'disabled' => array(
'post_title'
)
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Maximum posts",'acf'); ?></label>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'number',
'name' => 'fields['.$key.'][max]',
'value' => $field['max'],
));
?>
</td>
</tr>
<?php
}
/*
* format_value()
*
* This filter is appied to the $value after it is loaded from the db and before it is passed to the create_field action
*
* @type filter
* @since 3.6
* @date 23/01/13
*
* @param $value - the value which was loaded from the database
* @param $post_id - the $post_id from which the value was loaded
* @param $field - the field array holding all the field options
*
* @return $value - the modified value
*/
function format_value( $value, $post_id, $field )
{
// empty?
if( !empty($value) )
{
// Pre 3.3.3, the value is a string coma seperated
if( is_string($value) )
{
$value = explode(',', $value);
}
// convert to integers
if( is_array($value) )
{
$value = array_map('intval', $value);
// convert into post objects
$value = $this->get_posts( $value );
}
}
// return value
return $value;
}
/*
* format_value_for_api()
*
* This filter is appied to the $value after it is loaded from the db and before it is passed back to the api functions such as the_field
*
* @type filter
* @since 3.6
* @date 23/01/13
*
* @param $value - the value which was loaded from the database
* @param $post_id - the $post_id from which the value was loaded
* @param $field - the field array holding all the field options
*
* @return $value - the modified value
*/
function format_value_for_api( $value, $post_id, $field )
{
// empty?
if( !$value )
{
return $value;
}
// Pre 3.3.3, the value is a string coma seperated
if( is_string($value) )
{
$value = explode(',', $value);
}
// empty?
if( !is_array($value) || empty($value) )
{
return $value;
}
// convert to integers
$value = array_map('intval', $value);
// return format
if( $field['return_format'] == 'object' )
{
$value = $this->get_posts( $value );
}
// return
return $value;
}
/*
* get_posts
*
* This function will take an array of post_id's ($value) and return an array of post_objects
*
* @type function
* @date 7/08/13
*
* @param $post_ids (array) the array of post ID's
* @return (array) an array of post objects
*/
function get_posts( $post_ids )
{
// validate
if( empty($post_ids) )
{
return $post_ids;
}
// vars
$r = array();
// find posts (DISTINCT POSTS)
$posts = get_posts(array(
'numberposts' => -1,
'post__in' => $post_ids,
'post_type' => apply_filters('acf/get_post_types', array()),
'post_status' => 'any',
));
$ordered_posts = array();
foreach( $posts as $p )
{
// create array to hold value data
$ordered_posts[ $p->ID ] = $p;
}
// override value array with attachments
foreach( $post_ids as $k => $v)
{
// check that post exists (my have been trashed)
if( isset($ordered_posts[ $v ]) )
{
$r[] = $ordered_posts[ $v ];
}
}
// return
return $r;
}
/*
* update_value()
*
* This filter is appied to the $value before it is updated in the db
*
* @type filter
* @since 3.6
* @date 23/01/13
*
* @param $value - the value which will be saved in the database
* @param $post_id - the $post_id of which the value will be saved
* @param $field - the field array holding all the field options
*
* @return $value - the modified value
*/
function update_value( $value, $post_id, $field )
{
// validate
if( empty($value) )
{
return $value;
}
if( is_string($value) )
{
// string
$value = explode(',', $value);
}
elseif( is_object($value) && isset($value->ID) )
{
// object
$value = array( $value->ID );
}
elseif( is_array($value) )
{
// array
foreach( $value as $k => $v ){
// object?
if( is_object($v) && isset($v->ID) )
{
$value[ $k ] = $v->ID;
}
}
}
// save value as strings, so we can clearly search for them in SQL LIKE statements
$value = array_map('strval', $value);
return $value;
}
}
new acf_field_relationship();
?> | PHP |
<?php
class acf_field_image extends acf_field
{
/*
* __construct
*
* Set name / label needed for actions / filters
*
* @since 3.6
* @date 23/01/13
*/
function __construct()
{
// vars
$this->name = 'image';
$this->label = __("Image",'acf');
$this->category = __("Content",'acf');
$this->defaults = array(
'save_format' => 'object',
'preview_size' => 'thumbnail',
'library' => 'all'
);
$this->l10n = array(
'select' => __("Select Image",'acf'),
'edit' => __("Edit Image",'acf'),
'update' => __("Update Image",'acf'),
'uploadedTo' => __("uploaded to this post",'acf'),
);
// do not delete!
parent::__construct();
// filters
add_filter('get_media_item_args', array($this, 'get_media_item_args'));
add_filter('wp_prepare_attachment_for_js', array($this, 'wp_prepare_attachment_for_js'), 10, 3);
// JSON
add_action('wp_ajax_acf/fields/image/get_images', array($this, 'ajax_get_images'), 10, 1);
add_action('wp_ajax_nopriv_acf/fields/image/get_images', array($this, 'ajax_get_images'), 10, 1);
}
/*
* create_field()
*
* Create the HTML interface for your field
*
* @param $field - an array holding all the field's data
*
* @type action
* @since 3.6
* @date 23/01/13
*/
function create_field( $field )
{
// vars
$o = array(
'class' => '',
'url' => '',
);
if( $field['value'] && is_numeric($field['value']) )
{
$url = wp_get_attachment_image_src($field['value'], $field['preview_size']);
$o['class'] = 'active';
$o['url'] = $url[0];
}
?>
<div class="acf-image-uploader clearfix <?php echo $o['class']; ?>" data-preview_size="<?php echo $field['preview_size']; ?>" data-library="<?php echo $field['library']; ?>" >
<input class="acf-image-value" type="hidden" name="<?php echo $field['name']; ?>" value="<?php echo $field['value']; ?>" />
<div class="has-image">
<div class="hover">
<ul class="bl">
<li><a class="acf-button-delete ir" href="#"><?php _e("Remove",'acf'); ?></a></li>
<li><a class="acf-button-edit ir" href="#"><?php _e("Edit",'acf'); ?></a></li>
</ul>
</div>
<img class="acf-image-image" src="<?php echo $o['url']; ?>" alt=""/>
</div>
<div class="no-image">
<p><?php _e('No image selected','acf'); ?> <input type="button" class="button add-image" value="<?php _e('Add Image','acf'); ?>" />
</div>
</div>
<?php
}
/*
* create_options()
*
* Create extra options for your field. This is rendered when editing a field.
* The value of $field['name'] can be used (like bellow) to save extra data to the $field
*
* @type action
* @since 3.6
* @date 23/01/13
*
* @param $field - an array holding all the field's data
*/
function create_options( $field )
{
// vars
$key = $field['name'];
?>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Return Value",'acf'); ?></label>
<p><?php _e("Specify the returned value on front end",'acf') ?></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'radio',
'name' => 'fields['.$key.'][save_format]',
'value' => $field['save_format'],
'layout' => 'horizontal',
'choices' => array(
'object' => __("Image Object",'acf'),
'url' => __("Image URL",'acf'),
'id' => __("Image ID",'acf')
)
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Preview Size",'acf'); ?></label>
<p><?php _e("Shown when entering data",'acf') ?></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'radio',
'name' => 'fields['.$key.'][preview_size]',
'value' => $field['preview_size'],
'layout' => 'horizontal',
'choices' => apply_filters('acf/get_image_sizes', array())
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Library",'acf'); ?></label>
<p><?php _e("Limit the media library choice",'acf') ?></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'radio',
'name' => 'fields['.$key.'][library]',
'value' => $field['library'],
'layout' => 'horizontal',
'choices' => array(
'all' => __('All', 'acf'),
'uploadedTo' => __('Uploaded to post', 'acf')
)
));
?>
</td>
</tr>
<?php
}
/*
* format_value_for_api()
*
* This filter is appied to the $value after it is loaded from the db and before it is passed back to the api functions such as the_field
*
* @type filter
* @since 3.6
* @date 23/01/13
*
* @param $value - the value which was loaded from the database
* @param $post_id - the $post_id from which the value was loaded
* @param $field - the field array holding all the field options
*
* @return $value - the modified value
*/
function format_value_for_api( $value, $post_id, $field )
{
// validate
if( !$value )
{
return false;
}
// format
if( $field['save_format'] == 'url' )
{
$value = wp_get_attachment_url( $value );
}
elseif( $field['save_format'] == 'object' )
{
$attachment = get_post( $value );
// validate
if( !$attachment )
{
return false;
}
// create array to hold value data
$src = wp_get_attachment_image_src( $attachment->ID, 'full' );
$value = array(
'id' => $attachment->ID,
'alt' => get_post_meta($attachment->ID, '_wp_attachment_image_alt', true),
'title' => $attachment->post_title,
'caption' => $attachment->post_excerpt,
'description' => $attachment->post_content,
'mime_type' => $attachment->post_mime_type,
'url' => $src[0],
'width' => $src[1],
'height' => $src[2],
'sizes' => array(),
);
// find all image sizes
$image_sizes = get_intermediate_image_sizes();
if( $image_sizes )
{
foreach( $image_sizes as $image_size )
{
// find src
$src = wp_get_attachment_image_src( $attachment->ID, $image_size );
// add src
$value[ 'sizes' ][ $image_size ] = $src[0];
$value[ 'sizes' ][ $image_size . '-width' ] = $src[1];
$value[ 'sizes' ][ $image_size . '-height' ] = $src[2];
}
// foreach( $image_sizes as $image_size )
}
// if( $image_sizes )
}
return $value;
}
/*
* get_media_item_args
*
* @description:
* @since: 3.6
* @created: 27/01/13
*/
function get_media_item_args( $vars )
{
$vars['send'] = true;
return($vars);
}
/*
* ajax_get_images
*
* @description:
* @since: 3.5.7
* @created: 13/01/13
*/
function ajax_get_images()
{
// vars
$options = array(
'nonce' => '',
'images' => array(),
'preview_size' => 'thumbnail'
);
$return = array();
// load post options
$options = array_merge($options, $_POST);
// verify nonce
if( ! wp_verify_nonce($options['nonce'], 'acf_nonce') )
{
die(0);
}
if( $options['images'] )
{
foreach( $options['images'] as $id )
{
$url = wp_get_attachment_image_src( $id, $options['preview_size'] );
$return[] = array(
'id' => $id,
'url' => $url[0],
);
}
}
// return json
echo json_encode( $return );
die;
}
/*
* image_size_names_choose
*
* @description:
* @since: 3.5.7
* @created: 13/01/13
*/
function image_size_names_choose( $sizes )
{
global $_wp_additional_image_sizes;
if( $_wp_additional_image_sizes )
{
foreach( $_wp_additional_image_sizes as $k => $v )
{
$title = $k;
$title = str_replace('-', ' ', $title);
$title = str_replace('_', ' ', $title);
$title = ucwords( $title );
$sizes[ $k ] = $title;
}
// foreach( $image_sizes as $image_size )
}
return $sizes;
}
/*
* wp_prepare_attachment_for_js
*
* @description: This sneaky hook adds the missing sizes to each attachment in the 3.5 uploader. It would be a lot easier to add all the sizes to the 'image_size_names_choose' filter but then it will show up on the normal the_content editor
* @since: 3.5.7
* @created: 13/01/13
*/
function wp_prepare_attachment_for_js( $response, $attachment, $meta )
{
// only for image
if( $response['type'] != 'image' )
{
return $response;
}
// make sure sizes exist. Perhaps they dont?
if( !isset($meta['sizes']) )
{
return $response;
}
$attachment_url = $response['url'];
$base_url = str_replace( wp_basename( $attachment_url ), '', $attachment_url );
if( isset($meta['sizes']) && is_array($meta['sizes']) )
{
foreach( $meta['sizes'] as $k => $v )
{
if( !isset($response['sizes'][ $k ]) )
{
$response['sizes'][ $k ] = array(
'height' => $v['height'],
'width' => $v['width'],
'url' => $base_url . $v['file'],
'orientation' => $v['height'] > $v['width'] ? 'portrait' : 'landscape',
);
}
}
}
return $response;
}
/*
* update_value()
*
* This filter is appied to the $value before it is updated in the db
*
* @type filter
* @since 3.6
* @date 23/01/13
*
* @param $value - the value which will be saved in the database
* @param $post_id - the $post_id of which the value will be saved
* @param $field - the field array holding all the field options
*
* @return $value - the modified value
*/
function update_value( $value, $post_id, $field )
{
// array?
if( is_array($value) && isset($value['id']) )
{
$value = $value['id'];
}
// object?
if( is_object($value) && isset($value->ID) )
{
$value = $value->ID;
}
return $value;
}
}
new acf_field_image();
?> | PHP |
<?php
class acf_field_post_object extends acf_field
{
/*
* __construct
*
* Set name / label needed for actions / filters
*
* @since 3.6
* @date 23/01/13
*/
function __construct()
{
// vars
$this->name = 'post_object';
$this->label = __("Post Object",'acf');
$this->category = __("Relational",'acf');
$this->defaults = array(
'post_type' => array('all'),
'taxonomy' => array('all'),
'multiple' => 0,
'allow_null' => 0,
);
// do not delete!
parent::__construct();
}
/*
* load_field()
*
* This filter is appied to the $field after it is loaded from the database
*
* @type filter
* @since 3.6
* @date 23/01/13
*
* @param $field - the field array holding all the field options
*
* @return $field - the field array holding all the field options
*/
function load_field( $field )
{
// validate post_type
if( !$field['post_type'] || !is_array($field['post_type']) || in_array('', $field['post_type']) )
{
$field['post_type'] = array( 'all' );
}
// validate taxonomy
if( !$field['taxonomy'] || !is_array($field['taxonomy']) || in_array('', $field['taxonomy']) )
{
$field['taxonomy'] = array( 'all' );
}
// return
return $field;
}
/*
* create_field()
*
* Create the HTML interface for your field
*
* @param $field - an array holding all the field's data
*
* @type action
* @since 3.6
* @date 23/01/13
*/
function create_field( $field )
{
// global
global $post;
// vars
$args = array(
'numberposts' => -1,
'post_type' => null,
'orderby' => 'title',
'order' => 'ASC',
'post_status' => array('publish', 'private', 'draft', 'inherit', 'future'),
'suppress_filters' => false,
);
// load all post types by default
if( in_array('all', $field['post_type']) )
{
$field['post_type'] = apply_filters('acf/get_post_types', array());
}
// create tax queries
if( ! in_array('all', $field['taxonomy']) )
{
// vars
$taxonomies = array();
$args['tax_query'] = array();
foreach( $field['taxonomy'] as $v )
{
// find term (find taxonomy!)
// $term = array( 0 => $taxonomy, 1 => $term_id )
$term = explode(':', $v);
// validate
if( !is_array($term) || !isset($term[1]) )
{
continue;
}
// add to tax array
$taxonomies[ $term[0] ][] = $term[1];
}
// now create the tax queries
foreach( $taxonomies as $k => $v )
{
$args['tax_query'][] = array(
'taxonomy' => $k,
'field' => 'id',
'terms' => $v,
);
}
}
// Change Field into a select
$field['type'] = 'select';
$field['choices'] = array();
foreach( $field['post_type'] as $post_type )
{
// set post_type
$args['post_type'] = $post_type;
// set order
$get_pages = false;
if( is_post_type_hierarchical($post_type) && !isset($args['tax_query']) )
{
$args['sort_column'] = 'menu_order, post_title';
$args['sort_order'] = 'ASC';
$get_pages = true;
}
// filters
$args = apply_filters('acf/fields/post_object/query', $args, $field, $post);
$args = apply_filters('acf/fields/post_object/query/name=' . $field['_name'], $args, $field, $post );
$args = apply_filters('acf/fields/post_object/query/key=' . $field['key'], $args, $field, $post );
if( $get_pages )
{
$posts = get_pages( $args );
}
else
{
$posts = get_posts( $args );
}
if($posts)
{
foreach( $posts as $p )
{
// find title. Could use get_the_title, but that uses get_post(), so I think this uses less Memory
$title = '';
$ancestors = get_ancestors( $p->ID, $p->post_type );
if($ancestors)
{
foreach($ancestors as $a)
{
$title .= '–';
}
}
$title .= ' ' . apply_filters( 'the_title', $p->post_title, $p->ID );
// status
if( $p->post_status != "publish" )
{
$title .= " ($p->post_status)";
}
// WPML
if( defined('ICL_LANGUAGE_CODE') )
{
$title .= ' (' . ICL_LANGUAGE_CODE . ')';
}
// filters
$title = apply_filters('acf/fields/post_object/result', $title, $p, $field, $post);
$title = apply_filters('acf/fields/post_object/result/name=' . $field['_name'] , $title, $p, $field, $post);
$title = apply_filters('acf/fields/post_object/result/key=' . $field['key'], $title, $p, $field, $post);
// add to choices
if( count($field['post_type']) == 1 )
{
$field['choices'][ $p->ID ] = $title;
}
else
{
// group by post type
$post_type_object = get_post_type_object( $p->post_type );
$post_type_name = $post_type_object->labels->name;
$field['choices'][ $post_type_name ][ $p->ID ] = $title;
}
}
// foreach( $posts as $post )
}
// if($posts)
}
// foreach( $field['post_type'] as $post_type )
// create field
do_action('acf/create_field', $field );
}
/*
* create_options()
*
* Create extra options for your field. This is rendered when editing a field.
* The value of $field['name'] can be used (like bellow) to save extra data to the $field
*
* @type action
* @since 3.6
* @date 23/01/13
*
* @param $field - an array holding all the field's data
*/
function create_options( $field )
{
// vars
$key = $field['name'];
?>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label for=""><?php _e("Post Type",'acf'); ?></label>
</td>
<td>
<?php
$choices = array(
'all' => __("All",'acf')
);
$choices = apply_filters('acf/get_post_types', $choices);
do_action('acf/create_field', array(
'type' => 'select',
'name' => 'fields['.$key.'][post_type]',
'value' => $field['post_type'],
'choices' => $choices,
'multiple' => 1,
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Filter from Taxonomy",'acf'); ?></label>
</td>
<td>
<?php
$choices = array(
'' => array(
'all' => __("All",'acf')
)
);
$simple_value = false;
$choices = apply_filters('acf/get_taxonomies_for_select', $choices, $simple_value);
do_action('acf/create_field', array(
'type' => 'select',
'name' => 'fields['.$key.'][taxonomy]',
'value' => $field['taxonomy'],
'choices' => $choices,
'multiple' => 1,
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Allow Null?",'acf'); ?></label>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'radio',
'name' => 'fields['.$key.'][allow_null]',
'value' => $field['allow_null'],
'choices' => array(
1 => __("Yes",'acf'),
0 => __("No",'acf'),
),
'layout' => 'horizontal',
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Select multiple values?",'acf'); ?></label>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'radio',
'name' => 'fields['.$key.'][multiple]',
'value' => $field['multiple'],
'choices' => array(
1 => __("Yes",'acf'),
0 => __("No",'acf'),
),
'layout' => 'horizontal',
));
?>
</td>
</tr>
<?php
}
/*
* format_value()
*
* This filter is appied to the $value after it is loaded from the db and before it is passed to the create_field action
*
* @type filter
* @since 3.6
* @date 23/01/13
*
* @param $value - the value which was loaded from the database
* @param $post_id - the $post_id from which the value was loaded
* @param $field - the field array holding all the field options
*
* @return $value - the modified value
*/
function format_value( $value, $post_id, $field )
{
// empty?
if( !empty($value) )
{
// convert to integers
if( is_array($value) )
{
$value = array_map('intval', $value);
}
else
{
$value = intval($value);
}
}
// return value
return $value;
}
/*
* format_value_for_api()
*
* This filter is appied to the $value after it is loaded from the db and before it is passed back to the api functions such as the_field
*
* @type filter
* @since 3.6
* @date 23/01/13
*
* @param $value - the value which was loaded from the database
* @param $post_id - the $post_id from which the value was loaded
* @param $field - the field array holding all the field options
*
* @return $value - the modified value
*/
function format_value_for_api( $value, $post_id, $field )
{
// no value?
if( !$value )
{
return false;
}
// null?
if( $value == 'null' )
{
return false;
}
// multiple / single
if( is_array($value) )
{
// find posts (DISTINCT POSTS)
$posts = get_posts(array(
'numberposts' => -1,
'post__in' => $value,
'post_type' => apply_filters('acf/get_post_types', array()),
'post_status' => array('publish', 'private', 'draft', 'inherit', 'future'),
));
$ordered_posts = array();
foreach( $posts as $post )
{
// create array to hold value data
$ordered_posts[ $post->ID ] = $post;
}
// override value array with attachments
foreach( $value as $k => $v)
{
// check that post exists (my have been trashed)
if( !isset($ordered_posts[ $v ]) )
{
unset( $value[ $k ] );
}
else
{
$value[ $k ] = $ordered_posts[ $v ];
}
}
}
else
{
$value = get_post($value);
}
// return the value
return $value;
}
/*
* update_value()
*
* This filter is appied to the $value before it is updated in the db
*
* @type filter
* @since 3.6
* @date 23/01/13
*
* @param $value - the value which will be saved in the database
* @param $post_id - the $post_id of which the value will be saved
* @param $field - the field array holding all the field options
*
* @return $value - the modified value
*/
function update_value( $value, $post_id, $field )
{
// validate
if( empty($value) )
{
return $value;
}
if( is_object($value) && isset($value->ID) )
{
// object
$value = $value->ID;
}
elseif( is_array($value) )
{
// array
foreach( $value as $k => $v ){
// object?
if( is_object($v) && isset($v->ID) )
{
$value[ $k ] = $v->ID;
}
}
// save value as strings, so we can clearly search for them in SQL LIKE statements
$value = array_map('strval', $value);
}
return $value;
}
}
new acf_field_post_object();
?> | PHP |
<?php
class acf_field_google_map extends acf_field
{
/*
* __construct
*
* Set name / label needed for actions / filters
*
* @since 3.6
* @date 23/01/13
*/
function __construct()
{
// vars
$this->name = 'google_map';
$this->label = __("Google Map",'acf');
$this->category = __("jQuery",'acf');
$this->defaults = array(
'height' => '',
'center_lat' => '',
'center_lng' => '',
'zoom' => ''
);
$this->default_values = array(
'height' => '400',
'center_lat' => '-37.81411',
'center_lng' => '144.96328',
'zoom' => '14'
);
$this->l10n = array(
'locating' => __("Locating",'acf'),
'browser_support' => __("Sorry, this browser does not support geolocation",'acf'),
);
// do not delete!
parent::__construct();
}
/*
* create_field()
*
* Create the HTML interface for your field
*
* @param $field - an array holding all the field's data
*
* @type action
* @since 3.6
* @date 23/01/13
*/
function create_field( $field )
{
// require the googlemaps JS ( this script is now lazy loaded via JS )
//wp_enqueue_script('acf-googlemaps');
// default value
if( !is_array($field['value']) )
{
$field['value'] = array();
}
$field['value'] = wp_parse_args($field['value'], array(
'address' => '',
'lat' => '',
'lng' => ''
));
// default options
foreach( $this->default_values as $k => $v )
{
if( ! $field[ $k ] )
{
$field[ $k ] = $v;
}
}
// vars
$o = array(
'class' => '',
);
if( $field['value']['address'] )
{
$o['class'] = 'active';
}
$atts = '';
$keys = array(
'data-id' => 'id',
'data-lat' => 'center_lat',
'data-lng' => 'center_lng',
'data-zoom' => 'zoom'
);
foreach( $keys as $k => $v )
{
$atts .= ' ' . $k . '="' . esc_attr( $field[ $v ] ) . '"';
}
?>
<div class="acf-google-map <?php echo $o['class']; ?>" <?php echo $atts; ?>>
<div style="display:none;">
<?php foreach( $field['value'] as $k => $v ): ?>
<input type="hidden" class="input-<?php echo $k; ?>" name="<?php echo esc_attr($field['name']); ?>[<?php echo $k; ?>]" value="<?php echo esc_attr( $v ); ?>" />
<?php endforeach; ?>
</div>
<div class="title">
<div class="has-value">
<a href="#" class="acf-sprite-remove ir" title="<?php _e("Clear location",'acf'); ?>">Remove</a>
<h4><?php echo $field['value']['address']; ?></h4>
</div>
<div class="no-value">
<a href="#" class="acf-sprite-locate ir" title="<?php _e("Find current location",'acf'); ?>">Locate</a>
<input type="text" placeholder="<?php _e("Search for address...",'acf'); ?>" class="search" />
</div>
</div>
<div class="canvas" style="height: <?php echo $field['height']; ?>px">
</div>
</div>
<?php
}
/*
* create_options()
*
* Create extra options for your field. This is rendered when editing a field.
* The value of $field['name'] can be used (like bellow) to save extra data to the $field
*
* @type action
* @since 3.6
* @date 23/01/13
*
* @param $field - an array holding all the field's data
*/
function create_options( $field )
{
// vars
$key = $field['name'];
?>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Center",'acf'); ?></label>
<p class="description"><?php _e('Center the initial map','acf'); ?></p>
</td>
<td>
<ul class="hl clearfix">
<li style="width:48%;">
<?php
do_action('acf/create_field', array(
'type' => 'text',
'name' => 'fields['.$key.'][center_lat]',
'value' => $field['center_lat'],
'prepend' => 'lat',
'placeholder' => $this->default_values['center_lat']
));
?>
</li>
<li style="width:48%; margin-left:4%;">
<?php
do_action('acf/create_field', array(
'type' => 'text',
'name' => 'fields['.$key.'][center_lng]',
'value' => $field['center_lng'],
'prepend' => 'lng',
'placeholder' => $this->default_values['center_lng']
));
?>
</li>
</ul>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Zoom",'acf'); ?></label>
<p class="description"><?php _e('Set the initial zoom level','acf'); ?></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'number',
'name' => 'fields['.$key.'][zoom]',
'value' => $field['zoom'],
'placeholder' => $this->default_values['zoom']
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Height",'acf'); ?></label>
<p class="description"><?php _e('Customise the map height','acf'); ?></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'number',
'name' => 'fields['.$key.'][height]',
'value' => $field['height'],
'append' => 'px',
'placeholder' => $this->default_values['height']
));
?>
</td>
</tr>
<?php
}
}
new acf_field_google_map();
?> | PHP |
<?php
class acf_field_color_picker extends acf_field
{
/*
* __construct
*
* Set name / label needed for actions / filters
*
* @since 3.6
* @date 23/01/13
*/
function __construct()
{
// vars
$this->name = 'color_picker';
$this->label = __("Color Picker",'acf');
$this->category = __("jQuery",'acf');
$this->defaults = array(
'default_value' => '',
);
// do not delete!
parent::__construct();
}
/*
* create_field()
*
* Create the HTML interface for your field
*
* @param $field - an array holding all the field's data
*
* @type action
* @since 3.6
* @date 23/01/13
*/
function create_field( $field )
{
// vars
$o = array( 'id', 'class', 'name', 'value' );
$e = '';
$e .= '<div class="acf-color_picker">';
$e .= '<input type="text"';
foreach( $o as $k )
{
$e .= ' ' . $k . '="' . esc_attr( $field[ $k ] ) . '"';
}
$e .= ' />';
$e .= '</div>';
// return
echo $e;
}
/*
* create_options()
*
* Create extra options for your field. This is rendered when editing a field.
* The value of $field['name'] can be used (like bellow) to save extra data to the $field
*
* @type action
* @since 3.6
* @date 23/01/13
*
* @param $field - an array holding all the field's data
*/
function create_options( $field )
{
// vars
$key = $field['name'];
?>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Default Value",'acf'); ?></label>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'text',
'name' => 'fields[' .$key.'][default_value]',
'value' => $field['default_value'],
'placeholder' => '#ffffff'
));
?>
</td>
</tr>
<?php
}
}
new acf_field_color_picker();
?> | PHP |
<?php
class acf_field_date_picker extends acf_field
{
/*
* __construct
*
* Set name / label needed for actions / filters
*
* @since 3.6
* @date 23/01/13
*/
function __construct()
{
// vars
$this->name = 'date_picker';
$this->label = __("Date Picker",'acf');
$this->category = __("jQuery",'acf');
$this->defaults = array(
'date_format' => 'yymmdd',
'display_format' => 'dd/mm/yy',
'first_day' => 1, // monday
);
// actions
add_action('init', array($this, 'init'));
// do not delete!
parent::__construct();
}
/*
* init
*
* This function is run on the 'init' action to set the field's $l10n data. Before the init action,
* access to the $wp_locale variable is not possible.
*
* @type action (init)
* @date 3/09/13
*
* @param N/A
* @return N/A
*/
function init()
{
global $wp_locale;
$this->l10n = array(
'closeText' => __( 'Done', 'acf' ),
'currentText' => __( 'Today', 'acf' ),
'monthNames' => array_values( $wp_locale->month ),
'monthNamesShort' => array_values( $wp_locale->month_abbrev ),
'monthStatus' => __( 'Show a different month', 'acf' ),
'dayNames' => array_values( $wp_locale->weekday ),
'dayNamesShort' => array_values( $wp_locale->weekday_abbrev ),
'dayNamesMin' => array_values( $wp_locale->weekday_initial ),
'isRTL' => isset($wp_locale->is_rtl) ? $wp_locale->is_rtl : false,
);
}
/*
* create_field()
*
* Create the HTML interface for your field
*
* @param $field - an array holding all the field's data
*
* @type action
* @since 3.6
* @date 23/01/13
*/
function create_field( $field )
{
// make sure it's not blank
if( !$field['date_format'] )
{
$field['date_format'] = 'yymmdd';
}
if( !$field['display_format'] )
{
$field['display_format'] = 'dd/mm/yy';
}
// html
echo '<div class="acf-date_picker" data-save_format="' . $field['date_format'] . '" data-display_format="' . $field['display_format'] . '" data-first_day="' . $field['first_day'] . '">';
echo '<input type="hidden" value="' . $field['value'] . '" name="' . $field['name'] . '" class="input-alt" />';
echo '<input type="text" value="" class="input" />';
echo '</div>';
}
/*
* create_options()
*
* Create extra options for your field. This is rendered when editing a field.
* The value of $field['name'] can be used (like bellow) to save extra data to the $field
*
* @type action
* @since 3.6
* @date 23/01/13
*
* @param $field - an array holding all the field's data
*/
function create_options( $field )
{
// global
global $wp_locale;
// vars
$key = $field['name'];
?>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Save format",'acf'); ?></label>
<p class="description"><?php _e("This format will determin the value saved to the database and returned via the API",'acf'); ?></p>
<p><?php _e("\"yymmdd\" is the most versatile save format. Read more about",'acf'); ?> <a href="http://docs.jquery.com/UI/Datepicker/formatDate"><?php _e("jQuery date formats",'acf'); ?></a></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'text',
'name' => 'fields[' .$key.'][date_format]',
'value' => $field['date_format'],
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Display format",'acf'); ?></label>
<p class="description"><?php _e("This format will be seen by the user when entering a value",'acf'); ?></p>
<p><?php _e("\"dd/mm/yy\" or \"mm/dd/yy\" are the most used display formats. Read more about",'acf'); ?> <a href="http://docs.jquery.com/UI/Datepicker/formatDate" target="_blank"><?php _e("jQuery date formats",'acf'); ?></a></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'text',
'name' => 'fields[' .$key.'][display_format]',
'value' => $field['display_format'],
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label for=""><?php _e("Week Starts On",'acf'); ?></label>
</td>
<td>
<?php
$choices = array_values( $wp_locale->weekday );
do_action('acf/create_field', array(
'type' => 'select',
'name' => 'fields['.$key.'][first_day]',
'value' => $field['first_day'],
'choices' => $choices,
));
?>
</td>
</tr>
<?php
}
}
new acf_field_date_picker();
?> | PHP |
<?php
/*
* acf_field_group
*
* @description: controller for editing a field group
* @since: 3.6
* @created: 25/01/13
*/
class acf_field_group
{
var $settings;
/*
* __construct
*
* @description:
* @since 3.1.8
* @created: 23/06/12
*/
function __construct()
{
// actions
add_action('admin_enqueue_scripts', array($this,'admin_enqueue_scripts'));
// filters
add_filter('acf/get_field_groups', array($this, 'get_field_groups'), 1, 1);
add_filter('acf/field_group/get_fields', array($this, 'get_fields'), 5, 2);
add_filter('acf/field_group/get_location', array($this, 'get_location'), 5, 2);
add_filter('acf/field_group/get_options', array($this, 'get_options'), 5, 2);
add_filter('acf/field_group/get_next_field_id', array($this, 'get_next_field_id'), 5, 1);
// save
add_filter('name_save_pre', array($this, 'name_save_pre'));
add_action('save_post', array($this, 'save_post'));
// ajax
add_action('wp_ajax_acf/field_group/render_options', array($this, 'ajax_render_options'));
add_action('wp_ajax_acf/field_group/render_location', array($this, 'ajax_render_location'));
}
/*
* get_field_groups
*
* @description:
* @since: 3.6
* @created: 27/01/13
*/
function get_field_groups( $array )
{
// cache
$found = false;
$cache = wp_cache_get( 'field_groups', 'acf', false, $found );
if( $found )
{
return $cache;
}
// get acf's
$posts = get_posts(array(
'numberposts' => -1,
'post_type' => 'acf',
'orderby' => 'menu_order title',
'order' => 'asc',
'suppress_filters' => false,
));
// populate acfs
if( $posts ){ foreach( $posts as $post ){
$array[] = array(
'id' => $post->ID,
'title' => $post->post_title,
'menu_order' => $post->menu_order,
);
}}
// set cache
wp_cache_set( 'field_groups', $array, 'acf' );
return $array;
}
/*
* get_fields
*
* @description: returns all fields for a field group
* @since: 3.6
* @created: 26/01/13
*/
function get_fields( $fields, $post_id )
{
// global
global $wpdb;
// loaded by PHP already?
if( !empty($fields) )
{
return $fields;
}
// get field from postmeta
$rows = $wpdb->get_results( $wpdb->prepare("SELECT meta_key FROM $wpdb->postmeta WHERE post_id = %d AND meta_key LIKE %s", $post_id, 'field_%'), ARRAY_A);
if( $rows )
{
foreach( $rows as $row )
{
$field = apply_filters('acf/load_field', false, $row['meta_key'], $post_id );
$fields[ $field['order_no'] ] = $field;
}
// sort
ksort( $fields );
}
// return
return $fields;
}
/*
* get_location
*
* @description:
* @since: 3.6
* @created: 26/01/13
*/
function get_location( $location, $post_id )
{
// loaded by PHP already?
if( !empty($location) )
{
return $location;
}
// vars
$groups = array();
$group_no = 0;
// get all rules
$rules = get_post_meta($post_id, 'rule', false);
if( is_array($rules) )
{
foreach( $rules as $rule )
{
// if field group was duplicated, it may now be a serialized string!
$rule = maybe_unserialize($rule);
// does this rule have a group?
// + groups were added in 4.0.4
if( !isset($rule['group_no']) )
{
$rule['group_no'] = $group_no;
// sperate groups?
if( get_post_meta($post_id, 'allorany', true) == 'any' )
{
$group_no++;
}
}
// add to group
$groups[ $rule['group_no'] ][ $rule['order_no'] ] = $rule;
// sort rules
ksort( $groups[ $rule['group_no'] ] );
}
// sort groups
ksort( $groups );
}
// return fields
return $groups;
}
/*
* get_options
*
* @description:
* @since: 3.6
* @created: 26/01/13
*/
function get_options( $options, $post_id )
{
// loaded by PHP already?
if( !empty($options) )
{
return $options;
}
// defaults
$options = array(
'position' => 'normal',
'layout' => 'no_box',
'hide_on_screen' => array(),
);
// vars
$position = get_post_meta($post_id, 'position', true);
if( $position )
{
$options['position'] = $position;
}
$layout = get_post_meta($post_id, 'layout', true);
if( $layout )
{
$options['layout'] = $layout;
}
$hide_on_screen = get_post_meta($post_id, 'hide_on_screen', true);
if( $hide_on_screen )
{
$hide_on_screen = maybe_unserialize($hide_on_screen);
$options['hide_on_screen'] = $hide_on_screen;
}
// return
return $options;
}
/*
* validate_page
*
* @description:
* @since 3.2.6
* @created: 23/06/12
*/
function validate_page()
{
// global
global $pagenow, $typenow;
// vars
$return = false;
// validate page
if( in_array( $pagenow, array('post.php', 'post-new.php') ) )
{
// validate post type
if( $typenow == "acf" )
{
$return = true;
}
}
// return
return $return;
}
/*
* admin_enqueue_scripts
*
* @description: run after post query but before any admin script / head actions. A good place to register all actions.
* @since: 3.6
* @created: 26/01/13
*/
function admin_enqueue_scripts()
{
// validate page
if( ! $this->validate_page() ){ return; }
// settings
$this->settings = apply_filters('acf/get_info', 'all');
// no autosave
wp_dequeue_script( 'autosave' );
// custom scripts
wp_enqueue_script(array(
'acf-field-group',
));
// custom styles
wp_enqueue_style(array(
'acf-global',
'acf-field-group',
));
// actions
do_action('acf/field_group/admin_enqueue_scripts');
add_action('admin_head', array($this,'admin_head'));
}
/*
* admin_head
*
* @description:
* @since 3.1.8
* @created: 23/06/12
*/
function admin_head()
{
global $post;
// l10n
$l10n = array(
'move_to_trash' => __("Move to trash. Are you sure?",'acf'),
'checked' => __("checked",'acf'),
'no_fields' => __("No toggle fields available",'acf'),
'title' => __("Field group title is required",'acf'),
'copy' => __("copy",'acf'),
'or' => __("or",'acf'),
'fields' => __("Fields",'acf'),
'parent_fields' => __("Parent fields",'acf'),
'sibling_fields' => __("Sibling fields",'acf'),
'hide_show_all' => __("Hide / Show All",'acf')
);
?>
<script type="text/javascript">
(function($) {
// vars
acf.post_id = <?php echo $post->ID; ?>;
acf.nonce = "<?php echo wp_create_nonce( 'acf_nonce' ); ?>";
acf.admin_url = "<?php echo admin_url(); ?>";
acf.ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ); ?>";
// l10n
acf.l10n = <?php echo json_encode( $l10n ); ?>;
})(jQuery);
</script>
<?php
// new action
do_action('acf/field_group/admin_head');
// add metaboxes
add_meta_box('acf_fields', __("Fields",'acf'), array($this, 'html_fields'), 'acf', 'normal', 'high');
add_meta_box('acf_location', __("Location",'acf'), array($this, 'html_location'), 'acf', 'normal', 'high');
add_meta_box('acf_options', __("Options",'acf'), array($this, 'html_options'), 'acf', 'normal', 'high');
// add screen settings
add_filter('screen_settings', array($this, 'screen_settings'), 10, 1);
}
/*
* html_fields
*
* @description:
* @since 1.0.0
* @created: 23/06/12
*/
function html_fields()
{
include( $this->settings['path'] . 'core/views/meta_box_fields.php' );
}
/*
* html_location
*
* @description:
* @since 1.0.0
* @created: 23/06/12
*/
function html_location()
{
include( $this->settings['path'] . 'core/views/meta_box_location.php' );
}
/*
* html_options
*
* @description:
* @since 1.0.0
* @created: 23/06/12
*/
function html_options()
{
include( $this->settings['path'] . 'core/views/meta_box_options.php' );
}
/*
* screen_settings
*
* @description:
* @since: 3.6
* @created: 26/01/13
*/
function screen_settings( $current )
{
$current .= '<h5>' . __("Fields",'acf') . '</h5>';
$current .= '<div class="show-field_key">' . __("Show Field Key:",'acf');
$current .= '<label class="show-field_key-no"><input checked="checked" type="radio" value="0" name="show-field_key" />' . __("No",'acf') . '</label>';
$current .= '<label class="show-field_key-yes"><input type="radio" value="1" name="show-field_key" />' . __("Yes",'acf') . '</label>';
$current .= '</div>';
return $current;
}
/*
* ajax_render_options
*
* @description: creates the HTML for a field's options (field group edit page)
* @since 3.1.6
* @created: 23/06/12
*/
function ajax_render_options()
{
// vars
$options = array(
'field_key' => '',
'field_type' => '',
'post_id' => 0,
'nonce' => ''
);
// load post options
$options = array_merge($options, $_POST);
// verify nonce
if( ! wp_verify_nonce($options['nonce'], 'acf_nonce') )
{
die(0);
}
// required
if( ! $options['field_type'] )
{
die(0);
}
// find key (not actual field key, more the html attr name)
$options['field_key'] = str_replace("fields[", "", $options['field_key']);
$options['field_key'] = str_replace("][type]", "", $options['field_key']) ;
// render options
$field = array(
'type' => $options['field_type'],
'name' => $options['field_key']
);
do_action('acf/create_field_options', $field );
die();
}
/*
* ajax_render_location
*
* @description: creates the HTML for the field group location metabox. Called from both Ajax and PHP
* @since 3.1.6
* @created: 23/06/12
*/
function ajax_render_location( $options = array() )
{
// defaults
$defaults = array(
'group_id' => 0,
'rule_id' => 0,
'value' => null,
'param' => null,
);
$is_ajax = false;
if( isset($_POST['nonce']) && wp_verify_nonce($_POST['nonce'], 'acf_nonce') )
{
$is_ajax = true;
}
// Is AJAX call?
if( $is_ajax )
{
$options = array_merge($defaults, $_POST);
}
else
{
$options = array_merge($defaults, $options);
}
// vars
$choices = array();
// some case's have the same outcome
if($options['param'] == "page_parent")
{
$options['param'] = "page";
}
switch($options['param'])
{
case "post_type":
// all post types except attachment
$choices = apply_filters('acf/get_post_types', array(), array('attachment'));
break;
case "page":
$post_type = 'page';
$posts = get_posts(array(
'posts_per_page' => -1,
'post_type' => $post_type,
'orderby' => 'menu_order title',
'order' => 'ASC',
'post_status' => 'any',
'suppress_filters' => false,
'update_post_meta_cache' => false,
));
if( $posts )
{
// sort into hierachial order!
if( is_post_type_hierarchical( $post_type ) )
{
$posts = get_page_children( 0, $posts );
}
foreach( $posts as $page )
{
$title = '';
$ancestors = get_ancestors($page->ID, 'page');
if($ancestors)
{
foreach($ancestors as $a)
{
$title .= '- ';
}
}
$title .= apply_filters( 'the_title', $page->post_title, $page->ID );
// status
if($page->post_status != "publish")
{
$title .= " ($page->post_status)";
}
$choices[ $page->ID ] = $title;
}
// foreach($pages as $page)
}
break;
case "page_type" :
$choices = array(
'front_page' => __("Front Page",'acf'),
'posts_page' => __("Posts Page",'acf'),
'top_level' => __("Top Level Page (parent of 0)",'acf'),
'parent' => __("Parent Page (has children)",'acf'),
'child' => __("Child Page (has parent)",'acf'),
);
break;
case "page_template" :
$choices = array(
'default' => __("Default Template",'acf'),
);
$templates = get_page_templates();
foreach($templates as $k => $v)
{
$choices[$v] = $k;
}
break;
case "post" :
$post_types = get_post_types();
unset( $post_types['page'], $post_types['attachment'], $post_types['revision'] , $post_types['nav_menu_item'], $post_types['acf'] );
if( $post_types )
{
foreach( $post_types as $post_type )
{
$posts = get_posts(array(
'numberposts' => '-1',
'post_type' => $post_type,
'post_status' => array('publish', 'private', 'draft', 'inherit', 'future'),
'suppress_filters' => false,
));
if( $posts)
{
$choices[$post_type] = array();
foreach($posts as $post)
{
$title = apply_filters( 'the_title', $post->post_title, $post->ID );
// status
if($post->post_status != "publish")
{
$title .= " ($post->post_status)";
}
$choices[$post_type][$post->ID] = $title;
}
// foreach($posts as $post)
}
// if( $posts )
}
// foreach( $post_types as $post_type )
}
// if( $post_types )
break;
case "post_category" :
$category_ids = get_all_category_ids();
foreach($category_ids as $cat_id)
{
$cat_name = get_cat_name($cat_id);
$choices[$cat_id] = $cat_name;
}
break;
case "post_format" :
$choices = get_post_format_strings();
break;
case "post_status" :
$choices = array(
'publish' => __( 'Publish' ),
'pending' => __( 'Pending Review' ),
'draft' => __( 'Draft' ),
'future' => __( 'Future' ),
'private' => __( 'Private' ),
'inherit' => __( 'Revision' ),
'trash' => __( 'Trash' )
);
break;
case "user_type" :
global $wp_roles;
$choices = $wp_roles->get_names();
if( is_multisite() )
{
$choices['super_admin'] = __('Super Admin');
}
break;
case "taxonomy" :
$choices = array();
$simple_value = true;
$choices = apply_filters('acf/get_taxonomies_for_select', $choices, $simple_value);
break;
case "ef_taxonomy" :
$choices = array('all' => __('All', 'acf'));
$taxonomies = get_taxonomies( array('public' => true), 'objects' );
foreach($taxonomies as $taxonomy)
{
$choices[ $taxonomy->name ] = $taxonomy->labels->name;
}
// unset post_format (why is this a public taxonomy?)
if( isset($choices['post_format']) )
{
unset( $choices['post_format']) ;
}
break;
case "ef_user" :
global $wp_roles;
$choices = array_merge( array('all' => __('All', 'acf')), $wp_roles->get_names() );
break;
case "ef_media" :
$choices = array('all' => __('All', 'acf'));
break;
}
// allow custom location rules
$choices = apply_filters( 'acf/location/rule_values/' . $options['param'], $choices );
// create field
do_action('acf/create_field', array(
'type' => 'select',
'name' => 'location[' . $options['group_id'] . '][' . $options['rule_id'] . '][value]',
'value' => $options['value'],
'choices' => $choices,
));
// ajax?
if( $is_ajax )
{
die();
}
}
/*
* name_save_pre
*
* @description: intercepts the acf post obejct and adds an "acf_" to the start of
* it's name to stop conflicts between acf's and page's urls
* @since 1.0.0
* @created: 23/06/12
*/
function name_save_pre($name)
{
// validate
if( !isset($_POST['post_type']) || $_POST['post_type'] != 'acf' )
{
return $name;
}
// need a title
if( !$_POST['post_title'] )
{
$_POST['post_title'] = 'Unnamed Field Group';
}
$name = 'acf_' . sanitize_title($_POST['post_title']);
return $name;
}
/*
* save_post
*
* @description: Saves the field / location / option data for a field group
* @since 1.0.0
* @created: 23/06/12
*/
function save_post($post_id)
{
// do not save if this is an auto save routine
if( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
{
return $post_id;
}
// verify nonce
if( !isset($_POST['acf_nonce']) || !wp_verify_nonce($_POST['acf_nonce'], 'field_group') )
{
return $post_id;
}
// only save once! WordPress save's a revision as well.
if( wp_is_post_revision($post_id) )
{
return $post_id;
}
/*
* save fields
*/
// vars
$dont_delete = array();
if( isset($_POST['fields']) && is_array($_POST['fields']) )
{
$i = -1;
// remove clone field
unset( $_POST['fields']['field_clone'] );
// loop through and save fields
foreach( $_POST['fields'] as $key => $field )
{
$i++;
// order + key
$field['order_no'] = $i;
$field['key'] = $key;
// save
do_action('acf/update_field', $field, $post_id );
// add to dont delete array
$dont_delete[] = $field['key'];
}
}
unset( $_POST['fields'] );
// delete all other field
$keys = get_post_custom_keys($post_id);
foreach( $keys as $key )
{
if( strpos($key, 'field_') !== false && !in_array($key, $dont_delete) )
{
// this is a field, and it wasn't found in the dont_delete array
do_action('acf/delete_field', $post_id, $key);
}
}
/*
* save location rules
*/
if( isset($_POST['location']) && is_array($_POST['location']) )
{
delete_post_meta( $post_id, 'rule' );
// clean array keys
$_POST['location'] = array_values( $_POST['location'] );
foreach( $_POST['location'] as $group_id => $group )
{
if( is_array($group) )
{
// clean array keys
$group = array_values( $group );
foreach( $group as $rule_id => $rule )
{
$rule['order_no'] = $rule_id;
$rule['group_no'] = $group_id;
add_post_meta( $post_id, 'rule', $rule );
}
}
}
unset( $_POST['location'] );
}
/*
* save options
*/
if( isset($_POST['options']) && is_array($_POST['options']) )
{
update_post_meta($post_id, 'position', $_POST['options']['position']);
update_post_meta($post_id, 'layout', $_POST['options']['layout']);
update_post_meta($post_id, 'hide_on_screen', $_POST['options']['hide_on_screen']);
}
unset( $_POST['options'] );
}
}
new acf_field_group();
?> | PHP |
<?php
/*
* acf_field_groups
*
* @description:
* @since: 3.6
* @created: 25/01/13
*/
class acf_field_groups
{
/*
* __construct
*
* @description:
* @since 3.1.8
* @created: 23/06/12
*/
function __construct()
{
// actions
add_action('admin_menu', array($this,'admin_menu'));
}
/*
* admin_menu
*
* @description:
* @created: 2/08/12
*/
function admin_menu()
{
// validate page
if( ! $this->validate_page() )
{
return;
}
// actions
add_action('admin_print_scripts', array($this,'admin_print_scripts'));
add_action('admin_print_styles', array($this,'admin_print_styles'));
add_action('admin_footer', array($this,'admin_footer'));
// columns
add_filter( 'manage_edit-acf_columns', array($this,'acf_edit_columns'), 10, 1 );
add_action( 'manage_acf_posts_custom_column' , array($this,'acf_columns_display'), 10, 2 );
}
/*
* validate_page
*
* @description: returns true | false. Used to stop a function from continuing
* @since 3.2.6
* @created: 23/06/12
*/
function validate_page()
{
// global
global $pagenow;
// vars
$return = false;
// validate page
if( in_array( $pagenow, array('edit.php') ) )
{
// validate post type
if( isset($_GET['post_type']) && $_GET['post_type'] == 'acf' )
{
$return = true;
}
if( isset($_GET['page']) )
{
$return = false;
}
}
// return
return $return;
}
/*
* admin_print_scripts
*
* @description:
* @since 3.1.8
* @created: 23/06/12
*/
function admin_print_scripts()
{
wp_enqueue_script(array(
'jquery',
'thickbox',
));
}
/*
* admin_print_styles
*
* @description:
* @since 3.1.8
* @created: 23/06/12
*/
function admin_print_styles()
{
wp_enqueue_style(array(
'thickbox',
'acf-global',
'acf',
));
}
/*
* acf_edit_columns
*
* @description:
* @created: 2/08/12
*/
function acf_edit_columns( $columns )
{
$columns = array(
'cb' => '<input type="checkbox" />',
'title' => __("Title"),
'fields' => __("Fields", 'acf')
);
return $columns;
}
/*
* acf_columns_display
*
* @description:
* @created: 2/08/12
*/
function acf_columns_display( $column, $post_id )
{
// vars
switch ($column)
{
case "fields":
// vars
$count =0;
$keys = get_post_custom_keys( $post_id );
if($keys)
{
foreach($keys as $key)
{
if(strpos($key, 'field_') !== false)
{
$count++;
}
}
}
echo $count;
break;
}
}
/*
* admin_footer
*
* @description:
* @since 3.1.8
* @created: 23/06/12
*/
function admin_footer()
{
// vars
$version = apply_filters('acf/get_info', 'version');
$dir = apply_filters('acf/get_info', 'dir');
$path = apply_filters('acf/get_info', 'path');
$show_tab = isset($_GET['info']);
$tab = isset($_GET['info']) ? $_GET['info'] : 'changelog';
?>
<script type="text/html" id="tmpl-acf-col-right">
<div id="acf-col-right">
<div class="wp-box">
<div class="inner">
<h2><?php _e("Advanced Custom Fields",'acf'); ?> <?php echo $version; ?></h2>
<h3><?php _e("Changelog",'acf'); ?></h3>
<p><?php _e("See what's new in",'acf'); ?> <a href="<?php echo admin_url('edit.php?post_type=acf&info=changelog'); ?>"><?php _e("version",'acf'); ?> <?php echo $version; ?></a>
<h3><?php _e("Resources",'acf'); ?></h3>
<ul>
<li><a href="http://www.advancedcustomfields.com/resources/#getting-started" target="_blank"><?php _e("Getting Started",'acf'); ?></a></li>
<li><a href="http://www.advancedcustomfields.com/resources/#field-types" target="_blank"><?php _e("Field Types",'acf'); ?></a></li>
<li><a href="http://www.advancedcustomfields.com/resources/#functions" target="_blank"><?php _e("Functions",'acf'); ?></a></li>
<li><a href="http://www.advancedcustomfields.com/resources/#actions" target="_blank"><?php _e("Actions",'acf'); ?></a></li>
<li><a href="http://www.advancedcustomfields.com/resources/#filters" target="_blank"><?php _e("Filters",'acf'); ?></a></li>
<li><a href="http://www.advancedcustomfields.com/resources/#how-to" target="_blank"><?php _e("'How to' guides",'acf'); ?></a></li>
<li><a href="http://www.advancedcustomfields.com/resources/#tutorials" target="_blank"><?php _e("Tutorials",'acf'); ?></a></li>
</ul>
</div>
<div class="footer footer-blue">
<ul class="hl">
<li><?php _e("Created by",'acf'); ?> Elliot Condon</li>
</ul>
</div>
</div>
</div>
</script>
<script type="text/html" id="tmpl-acf-about">
<!-- acf-about -->
<div id="acf-about" class="acf-content">
<!-- acf-content-title -->
<div class="acf-content-title">
<h1><?php _e("Welcome to Advanced Custom Fields",'acf'); ?> <?php echo $version; ?></h1>
<h2><?php _e("Thank you for updating to the latest version!",'acf'); ?> <br />ACF <?php echo $version; ?> <?php _e("is more polished and enjoyable than ever before. We hope you like it.",'acf'); ?></h2>
</div>
<!-- / acf-content-title -->
<!-- acf-content-body -->
<div class="acf-content-body">
<h2 class="nav-tab-wrapper">
<a class="acf-tab-toggle nav-tab <?php if( $tab == 'whats-new' ){ echo 'nav-tab-active'; } ?>" href="<?php echo admin_url('edit.php?post_type=acf&info=whats-new'); ?>"><?php _e("What’s New",'acf'); ?></a>
<a class="acf-tab-toggle nav-tab <?php if( $tab == 'changelog' ){ echo 'nav-tab-active'; } ?>" href="<?php echo admin_url('edit.php?post_type=acf&info=changelog'); ?>"><?php _e("Changelog",'acf'); ?></a>
<?php if( $tab == 'download-add-ons' ): ?>
<a class="acf-tab-toggle nav-tab nav-tab-active" href="<?php echo admin_url('edit.php?post_type=acf&info=download-add-ons'); ?>"><?php _e("Download Add-ons",'acf'); ?></a>
<?php endif; ?>
</h2>
<?php if( $tab == 'whats-new' ):
$activation_codes = array(
'repeater' => get_option('acf_repeater_ac', ''),
'gallery' => get_option('acf_gallery_ac', ''),
'options_page' => get_option('acf_options_page_ac', ''),
'flexible_content' => get_option('acf_flexible_content_ac', '')
);
$active = array(
'repeater' => class_exists('acf_field_repeater'),
'gallery' => class_exists('acf_field_gallery'),
'options_page' => class_exists('acf_options_page_plugin'),
'flexible_content' => class_exists('acf_field_flexible_content')
);
$update_required = false;
$update_complete = true;
foreach( $activation_codes as $k => $v )
{
if( $v )
{
$update_required = true;
if( !$active[ $k ] )
{
$update_complete = false;
}
}
}
?>
<table id="acf-add-ons-table" class="alignright">
<tr>
<td><img src="<?php echo $dir; ?>images/add-ons/repeater-field-thumb.jpg" /></td>
<td><img src="<?php echo $dir; ?>images/add-ons/gallery-field-thumb.jpg" /></td>
</tr>
<tr>
<td><img src="<?php echo $dir; ?>images/add-ons/options-page-thumb.jpg" /></td>
<td><img src="<?php echo $dir; ?>images/add-ons/flexible-content-field-thumb.jpg" /></td>
</tr>
</table>
<div style="margin-right: 300px;">
<h3><?php _e("Add-ons",'acf'); ?></h3>
<h4><?php _e("Activation codes have grown into plugins!",'acf'); ?></h4>
<p><?php _e("Add-ons are now activated by downloading and installing individual plugins. Although these plugins will not be hosted on the wordpress.org repository, each Add-on will continue to receive updates in the usual way.",'acf'); ?></p>
<?php if( $update_required ): ?>
<?php if( $update_complete ): ?>
<div class="acf-alert acf-alert-success">
<p><?php _e("All previous Add-ons have been successfully installed",'acf'); ?></p>
</div>
<?php else: ?>
<div class="acf-alert acf-alert-success">
<p><?php _e("This website uses premium Add-ons which need to be downloaded",'acf'); ?> <a href="<?php echo admin_url('edit.php?post_type=acf&info=download-add-ons'); ?>" class="acf-button" style="display: inline-block;"><?php _e("Download your activated Add-ons",'acf'); ?></a></p>
</div>
<?php endif; ?>
<?php else: ?>
<div class="acf-alert acf-alert-success">
<p><?php _e("This website does not use premium Add-ons and will not be affected by this change.",'acf'); ?></p>
</div>
<?php endif; ?>
</div>
<div class="clear"></div>
<hr />
<h3><?php _e("Easier Development",'acf'); ?></h3>
<h4><?php _e("New Field Types",'acf'); ?></h4>
<ul>
<li><?php _e("Taxonomy Field",'acf'); ?></li>
<li><?php _e("User Field",'acf'); ?></li>
<li><?php _e("Email Field",'acf'); ?></li>
<li><?php _e("Password Field",'acf'); ?></li>
</ul>
<h4><?php _e("Custom Field Types",'acf'); ?></h4>
<p><?php _e("Creating your own field type has never been easier! Unfortunately, version 3 field types are not compatible with version 4.",'acf'); ?><br />
<?php _e("Migrating your field types is easy, please",'acf'); ?> <a href="http://www.advancedcustomfields.com/docs/tutorials/creating-a-new-field-type/" target="_blank"><?php _e("follow this tutorial",'acf'); ?></a> <?php _e("to learn more.",'acf'); ?></p>
<h4><?php _e("Actions & Filters",'acf'); ?></h4>
<p><?php _e("All actions & filters have received a major facelift to make customizing ACF even easier! Please",'acf'); ?> <a href="http://www.advancedcustomfields.com/resources/getting-started/migrating-from-v3-to-v4/" target="_blank"><?php _e("read this guide",'acf'); ?></a> <?php _e("to find the updated naming convention.",'acf'); ?></p>
<h4><?php _e("Preview draft is now working!",'acf'); ?></h4>
<p><?php _e("This bug has been squashed along with many other little critters!",'acf'); ?> <a class="acf-tab-toggle" href="<?php echo admin_url('edit.php?post_type=acf&info=changelog'); ?>" data-tab="2"><?php _e("See the full changelog",'acf'); ?></a></p>
<hr />
<h3><?php _e("Important",'acf'); ?></h3>
<h4><?php _e("Database Changes",'acf'); ?></h4>
<p><?php _e("Absolutely <strong>no</strong> changes have been made to the database between versions 3 and 4. This means you can roll back to version 3 without any issues.",'acf'); ?></p>
<h4><?php _e("Potential Issues",'acf'); ?></h4>
<p><?php _e("Do to the sizable changes surounding Add-ons, field types and action/filters, your website may not operate correctly. It is important that you read the full",'acf'); ?> <a href="http://www.advancedcustomfields.com/resources/getting-started/migrating-from-v3-to-v4/" target="_blank"><?php _e("Migrating from v3 to v4",'acf'); ?></a> <?php _e("guide to view the full list of changes.",'acf'); ?></p>
<div class="acf-alert acf-alert-error">
<p><strong><?php _e("Really Important!",'acf'); ?></strong> <?php _e("If you updated the ACF plugin without prior knowledge of such changes, please roll back to the latest",'acf'); ?> <a href="http://wordpress.org/extend/plugins/advanced-custom-fields/developers/"><?php _e("version 3",'acf'); ?></a> <?php _e("of this plugin.",'acf'); ?></p>
</div>
<hr />
<h3><?php _e("Thank You",'acf'); ?></h3>
<p><?php _e("A <strong>BIG</strong> thank you to everyone who has helped test the version 4 beta and for all the support I have received.",'acf'); ?></p>
<p><?php _e("Without you all, this release would not have been possible!",'acf'); ?></p>
<?php elseif( $tab == 'changelog' ): ?>
<h3><?php _e("Changelog for",'acf'); ?> <?php echo $version; ?></h3>
<?php
$items = file_get_contents( $path . 'readme.txt' );
$items = explode('= ' . $version . ' =', $items);
$items = end( $items );
$items = current( explode("\n\n", $items) );
$items = array_filter( array_map('trim', explode("*", $items)) );
?>
<ul class="acf-changelog">
<?php foreach( $items as $item ):
$item = explode('http', $item);
?>
<li><?php echo $item[0]; ?><?php if( isset($item[1]) ): ?><a href="http<?php echo $item[1]; ?>" target="_blank"><?php _e("Learn more",'acf'); ?></a><?php endif; ?></li>
<?php endforeach; ?>
</ul>
<?php elseif( $tab == 'download-add-ons' ): ?>
<h3><?php _e("Overview",'acf'); ?></h3>
<p><?php _e("Previously, all Add-ons were unlocked via an activation code (purchased from the ACF Add-ons store). New to v4, all Add-ons act as separate plugins which need to be individually downloaded, installed and updated.",'acf'); ?></p>
<p><?php _e("This page will assist you in downloading and installing each available Add-on.",'acf'); ?></p>
<h3><?php _e("Available Add-ons",'acf'); ?></h3>
<p><?php _e("The following Add-ons have been detected as activated on this website.",'acf'); ?></p>
<?php
$ac_repeater = get_option('acf_repeater_ac', '');
$ac_options_page = get_option('acf_options_page_ac', '');
$ac_flexible_content = get_option('acf_flexible_content_ac', '');
$ac_gallery = get_option('acf_gallery_ac', '');
?>
<table class="widefat" id="acf-download-add-ons-table">
<thead>
<tr>
<th colspan="2"><?php _e("Name",'acf'); ?></th>
<th><?php _e("Activation Code",'acf'); ?></th>
<th><?php _e("Download",'acf'); ?></th>
</tr>
</thead>
<tbody>
<?php if( $ac_repeater ): ?>
<tr>
<td class="td-image"><img src="<?php echo $dir; ?>images/add-ons/repeater-field-thumb.jpg" style="width:50px" /></td>
<th class="td-name"><?php _e("Repeater Field",'acf'); ?></th>
<td class="td-code">XXXX-XXXX-XXXX-<?php echo substr($ac_repeater,-4); ?></td>
<td class="td-download"><a class="button" href="http://download.advancedcustomfields.com/<?php echo $ac_repeater; ?>/trunk"><?php _e("Download",'acf'); ?></a></td>
</tr>
<?php endif; ?>
<?php if( $ac_gallery ): ?>
<tr>
<td><img src="<?php echo $dir; ?>images/add-ons/gallery-field-thumb.jpg" /></td>
<th><?php _e("Gallery Field",'acf'); ?></th>
<td>XXXX-XXXX-XXXX-<?php echo substr($ac_gallery,-4); ?></td>
<td><a class="button" href="http://download.advancedcustomfields.com/<?php echo $ac_gallery; ?>/trunk"><?php _e("Download",'acf'); ?></a></td>
</tr>
<?php endif; ?>
<?php if( $ac_options_page ): ?>
<tr>
<td><img src="<?php echo $dir; ?>images/add-ons/options-page-thumb.jpg" /></td>
<th><?php _e("Options Page",'acf'); ?></th>
<td>XXXX-XXXX-XXXX-<?php echo substr($ac_options_page,-4); ?></td>
<td><a class="button" href="http://download.advancedcustomfields.com/<?php echo $ac_options_page; ?>/trunk"><?php _e("Download",'acf'); ?></a></td>
</tr>
<?php endif; ?>
<?php if($ac_flexible_content): ?>
<tr>
<td><img src="<?php echo $dir; ?>images/add-ons/flexible-content-field-thumb.jpg" /></td>
<th><?php _e("Flexible Content",'acf'); ?></th>
<td>XXXX-XXXX-XXXX-<?php echo substr($ac_flexible_content,-4); ?></td>
<td><a class="button" href="http://download.advancedcustomfields.com/<?php echo $ac_flexible_content; ?>/trunk"><?php _e("Download",'acf'); ?></a></td>
</tr>
<?php endif; ?>
</tbody>
</table>
<h3><?php _e("Installation",'acf'); ?></h3>
<p><?php _e("For each Add-on available, please perform the following:",'acf'); ?></p>
<ol>
<li><?php _e("Download the Add-on plugin (.zip file) to your desktop",'acf'); ?></li>
<li><?php _e("Navigate to",'acf'); ?> <a target="_blank" href="<?php echo admin_url('plugin-install.php?tab=upload'); ?>"><?php _e("Plugins > Add New > Upload",'acf'); ?></a></li>
<li><?php _e("Use the uploader to browse, select and install your Add-on (.zip file)",'acf'); ?></li>
<li><?php _e("Once the plugin has been uploaded and installed, click the 'Activate Plugin' link",'acf'); ?></li>
<li><?php _e("The Add-on is now installed and activated!",'acf'); ?></li>
</ol>
<?php endif; ?>
</div>
<!-- / acf-content-body -->
<!-- acf-content-footer -->
<div class="acf-content-footer">
<ul class="hl clearfix">
<li><a class="acf-button acf-button-big" href="<?php echo admin_url('edit.php?post_type=acf'); ?>"><?php _e("Awesome. Let's get to work",'acf'); ?></a></li>
</ul>
</div>
<!-- / acf-content-footer -->
</div>
<!-- / acf-about -->
</script>
<script type="text/javascript">
(function($){
// wrap
$('#wpbody .wrap').attr('id', 'acf-field_groups');
$('#acf-field_groups').wrapInner('<div id="acf-col-left" />');
$('#acf-field_groups').wrapInner('<div id="acf-cols" />');
// add sidebar
$('#acf-cols').prepend( $('#tmpl-acf-col-right').html() );
// take out h2 + icon
$('#acf-col-left > .icon32').insertBefore('#acf-cols');
$('#acf-col-left > h2').insertBefore('#acf-cols');
<?php if( $show_tab ): ?>
// add about copy
$('#wpbody-content').prepend( $('#tmpl-acf-about').html() );
$('#acf-field_groups').hide();
$('#screen-meta-links').hide();
<?php endif; ?>
})(jQuery);
</script>
<?php
}
}
new acf_field_groups();
?>
| PHP |
<?php
class acf_everything_fields
{
var $settings,
$data;
/*
* __construct
*
* @description:
* @since 3.1.8
* @created: 23/06/12
*/
function __construct()
{
// data for passing variables
$this->data = array(
'page_id' => '', // a string used to load values
'metabox_ids' => array(),
'page_type' => '', // taxonomy / user / media
'page_action' => '', // add / edit
'option_name' => '', // key used to find value in wp_options table. eg: user_1, category_4
);
// actions
add_action('admin_menu', array($this,'admin_menu'));
add_action('wp_ajax_acf/everything_fields', array($this, 'acf_everything_fields'));
// attachment
add_filter('attachment_fields_to_edit', array($this, 'attachment_fields_to_edit'), 10, 2);
add_filter('attachment_fields_to_save', array($this, 'save_attachment'), 10, 2);
// save
add_action('create_term', array($this, 'save_taxonomy'));
add_action('edited_term', array($this, 'save_taxonomy'));
add_action('edit_user_profile_update', array($this, 'save_user'));
add_action('personal_options_update', array($this, 'save_user'));
add_action('user_register', array($this, 'save_user'));
// shopp
add_action('shopp_category_saved', array($this, 'shopp_category_saved'));
// delete
add_action('delete_term', array($this, 'delete_term'), 10, 4);
}
/*
* attachment_fields_to_edit
*
* Adds ACF fields to the attachment form fields
*
* @type filter
* @date 14/07/13
*
* @param {array} $form_fields
* @return {object} $post
*/
function attachment_fields_to_edit( $form_fields, $post )
{
// vars
$screen = get_current_screen();
$post_id = $post->ID;
if( !empty($screen) )
{
return $form_fields;
}
// get field groups
$filter = array( 'post_type' => 'attachment' );
$metabox_ids = array();
$metabox_ids = apply_filters( 'acf/location/match_field_groups', $metabox_ids, $filter );
// validate
if( empty($metabox_ids) )
{
return $form_fields;
}
$acfs = apply_filters('acf/get_field_groups', array());
if( is_array($acfs) ){ foreach( $acfs as $acf ){
// only add the chosen field groups
if( !in_array( $acf['id'], $metabox_ids ) )
{
continue;
}
// load fields
$fields = apply_filters('acf/field_group/get_fields', array(), $acf['id']);
if( is_array($fields) ){ foreach( $fields as $i => $field ){
// if they didn't select a type, skip this field
if( !$field || !$field['type'] || $field['type'] == 'null' )
{
continue;
}
// set value
if( !isset($field['value']) )
{
$field['value'] = apply_filters('acf/load_value', false, $post_id, $field);
$field['value'] = apply_filters('acf/format_value', $field['value'], $post_id, $field);
}
// create field
$field['name'] = 'fields[' . $field['key'] . ']';
ob_start();
do_action('acf/create_field', $field);
$html = ob_get_contents();
ob_end_clean();
$form_fields[ $field['name'] ] = array(
'label' => $field['label'],
'input' => 'html',
'html' => $html
);
}};
}}
// return
return $form_fields;
}
/*
* save_attachment
*
* Triggers the acf/save_post action
*
* @type action
* @date 14/07/13
*
* @param {array} $post
* @return {array} $attachment
*/
function save_attachment( $post, $attachment )
{
// verify nonce
/*
if( !isset($_POST['acf_nonce']) || !wp_verify_nonce($_POST['acf_nonce'], 'input') )
{
return $post;
}
*/
// $post_id to save against
$post_id = $post['ID'];
// update the post
do_action('acf/save_post', $post_id);
return $post;
}
/*
* validate_page
*
* @description: returns true | false. Used to stop a function from continuing
* @since 3.2.6
* @created: 23/06/12
*/
function validate_page()
{
// global
global $pagenow;
// vars
$return = false;
// validate page
if( in_array( $pagenow, array( 'edit-tags.php', 'profile.php', 'user-new.php', 'user-edit.php', 'media.php' ) ) )
{
$return = true;
}
// validate page (Shopp)
if( $pagenow == "admin.php" && isset( $_GET['page'], $_GET['id'] ) && $_GET['page'] == "shopp-categories" )
{
$return = true;
}
// return
return $return;
}
/*--------------------------------------------------------------------------------------
*
* admin_menu
*
* @author Elliot Condon
* @since 3.1.8
*
*-------------------------------------------------------------------------------------*/
function admin_menu()
{
global $pagenow;
// validate page
if( ! $this->validate_page() ) return;
// set page type
$filter = array();
if( $pagenow == "admin.php" && isset( $_GET['page'], $_GET['id'] ) && $_GET['page'] == "shopp-categories" )
{
// filter
$_GET['id'] = filter_var($_GET['id'], FILTER_SANITIZE_STRING);
$this->data['page_type'] = "shopp_category";
$filter['ef_taxonomy'] = "shopp_category";
$this->data['page_action'] = "add";
$this->data['option_name'] = "";
if( $_GET['id'] != "new" )
{
$this->data['page_action'] = "edit";
$this->data['option_name'] = "shopp_category_" . $_GET['id'];
}
}
if( $pagenow == "edit-tags.php" && isset($_GET['taxonomy']) )
{
// filter
$_GET['taxonomy'] = filter_var($_GET['taxonomy'], FILTER_SANITIZE_STRING);
$this->data['page_type'] = "taxonomy";
$filter['ef_taxonomy'] = $_GET['taxonomy'];
$this->data['page_action'] = "add";
$this->data['option_name'] = "";
if( isset($_GET['action']) && $_GET['action'] == "edit" )
{
// filter
$_GET['tag_ID'] = filter_var($_GET['tag_ID'], FILTER_SANITIZE_NUMBER_INT);
$this->data['page_action'] = "edit";
$this->data['option_name'] = $_GET['taxonomy'] . "_" . $_GET['tag_ID'];
}
}
elseif( $pagenow == "profile.php" )
{
$this->data['page_type'] = "user";
$filter['ef_user'] = get_current_user_id();
$this->data['page_action'] = "edit";
$this->data['option_name'] = "user_" . get_current_user_id();
}
elseif( $pagenow == "user-edit.php" && isset($_GET['user_id']) )
{
// filter
$_GET['user_id'] = filter_var($_GET['user_id'], FILTER_SANITIZE_NUMBER_INT);
$this->data['page_type'] = "user";
$filter['ef_user'] = $_GET['user_id'];
$this->data['page_action'] = "edit";
$this->data['option_name'] = "user_" . $_GET['user_id'];
}
elseif( $pagenow == "user-new.php" )
{
$this->data['page_type'] = "user";
$filter['ef_user'] ='all';
$this->data['page_action'] = "add";
$this->data['option_name'] = "";
}
elseif( $pagenow == "media.php" )
{
$this->data['page_type'] = "media";
$filter['post_type'] = 'attachment';
$this->data['page_action'] = "add";
$this->data['option_name'] = "";
if(isset($_GET['attachment_id']))
{
// filter
$_GET['attachment_id'] = filter_var($_GET['attachment_id'], FILTER_SANITIZE_NUMBER_INT);
$this->data['page_action'] = "edit";
$this->data['option_name'] = $_GET['attachment_id'];
}
}
// get field groups
$metabox_ids = array();
$this->data['metabox_ids'] = apply_filters( 'acf/location/match_field_groups', $metabox_ids, $filter );
// dont continue if no ids were found
if( empty( $this->data['metabox_ids'] ) )
{
return false;
}
// actions
add_action('admin_enqueue_scripts', array($this,'admin_enqueue_scripts'));
add_action('admin_head', array($this,'admin_head'));
}
/*
* admin_enqueue_scripts
*
* @description:
* @since: 3.6
* @created: 30/01/13
*/
function admin_enqueue_scripts()
{
do_action('acf/input/admin_enqueue_scripts');
}
/*--------------------------------------------------------------------------------------
*
* admin_head
*
* @author Elliot Condon
* @since 3.1.8
*
*-------------------------------------------------------------------------------------*/
function admin_head()
{
global $pagenow;
// add user js + css
do_action('acf/input/admin_head');
?>
<script type="text/javascript">
(function($){
acf.data = {
action : 'acf/everything_fields',
metabox_ids : '<?php echo implode( ',', $this->data['metabox_ids'] ); ?>',
page_type : '<?php echo $this->data['page_type']; ?>',
page_action : '<?php echo $this->data['page_action']; ?>',
option_name : '<?php echo $this->data['option_name']; ?>'
};
$(document).ready(function(){
$.ajax({
url: ajaxurl,
data: acf.data,
type: 'post',
dataType: 'html',
success: function(html){
<?php
if($this->data['page_type'] == "user")
{
if($this->data['page_action'] == "add")
{
echo "$('#createuser > table.form-table:last > tbody').append( html );";
}
else
{
echo "$('#your-profile .form-table:last').after( html );";
}
}
elseif($this->data['page_type'] == "shopp_category")
{
echo "$('#post-body-content').append( html );";
}
elseif($this->data['page_type'] == "taxonomy")
{
if($this->data['page_action'] == "add")
{
echo "$('#addtag > p.submit').before( html );";
}
else
{
echo "$('#edittag > table.form-table:first > tbody').append( html );";
}
}
elseif($this->data['page_type'] == "media")
{
if($this->data['page_action'] == "add")
{
echo "$('#addtag > p.submit').before( html );";
}
else
{
echo "$('#media-single-form table tbody tr.submit').before( html );";
}
}
?>
setTimeout( function(){
$(document).trigger('acf/setup_fields', $('#wpbody') );
}, 200);
}
});
/*
* Taxonomy Add
*
* @description:
* @since: 3.6
* @created: 24/02/13
*/
$(document).ajaxComplete(function(event, xhr, settings) {
// vars
data = acf.helpers.url_to_object(settings.data);
// validate
if( data.action != 'add-tag' )
{
return;
}
// vars
var $el = $('#addtag');
// clear WYSIWYG field
$el.find('.acf_wysiwyg textarea').each(function(){
// vars
var textarea = $(this),
id = textarea.attr('id'),
editor = tinyMCE.get( id );
if( editor )
{
editor.setContent('');
editor.save();
}
});
// clear image / file fields
$el.find('.field .active').removeClass('active');
// clear checkbox
$el.find('input[type="checkbox"]').removeAttr('checked');
});
});
})(jQuery);
</script>
<?php
}
/*--------------------------------------------------------------------------------------
*
* save_taxonomy
*
* @author Elliot Condon
* @since 3.1.8
*
*-------------------------------------------------------------------------------------*/
function save_taxonomy( $term_id )
{
// verify nonce
if( !isset($_POST['acf_nonce']) || !wp_verify_nonce($_POST['acf_nonce'], 'input') )
{
return $term_id;
}
// for some weird reason, this is triggered by saving a menu...
if( !isset($_POST['taxonomy']) )
{
return;
}
// $post_id to save against
$post_id = $_POST['taxonomy'] . '_' . $term_id;
// update the post
do_action('acf/save_post', $post_id);
}
/*--------------------------------------------------------------------------------------
*
* profile_save
*
* @author Elliot Condon
* @since 3.1.8
*
*-------------------------------------------------------------------------------------*/
function save_user( $user_id )
{
// verify nonce
if( !isset($_POST['acf_nonce']) || !wp_verify_nonce($_POST['acf_nonce'], 'input') )
{
return $user_id;
}
// $post_id to save against
$post_id = 'user_' . $user_id;
// update the post
do_action('acf/save_post', $post_id);
}
/*
* shopp_category_saved
*
* @description:
* @since 3.5.2
* @created: 27/11/12
*/
function shopp_category_saved( $category )
{
// verify nonce
if( !isset($_POST['acf_nonce']) || !wp_verify_nonce($_POST['acf_nonce'], 'input') )
{
return $category;
}
// $post_id to save against
$post_id = 'shopp_category_' . $category->id;
// update the post
do_action('acf/save_post', $post_id);
}
/*--------------------------------------------------------------------------------------
*
* acf_everything_fields
*
* @description Ajax call that renders the html needed for the page
* @author Elliot Condon
* @since 3.1.8
*
*-------------------------------------------------------------------------------------*/
function acf_everything_fields()
{
// defaults
$defaults = array(
'metabox_ids' => '',
'page_type' => '',
'page_action' => '',
'option_name' => '',
);
// load post options
$options = array_merge($defaults, $_POST);
// metabox ids is a string with commas
$options['metabox_ids'] = explode( ',', $options['metabox_ids'] );
// get acfs
$acfs = apply_filters('acf/get_field_groups', false);
// layout
$layout = 'tr';
if( $options['page_type'] == "taxonomy" && $options['page_action'] == "add")
{
$layout = 'div';
}
if( $options['page_type'] == "shopp_category")
{
$layout = 'metabox';
}
if( $acfs )
{
foreach( $acfs as $acf )
{
// load options
$acf['options'] = apply_filters('acf/field_group/get_options', array(), $acf['id']);
// only add the chosen field groups
if( !in_array( $acf['id'], $options['metabox_ids'] ) )
{
continue;
}
// layout dictates heading
$title = true;
if( $acf['options']['layout'] == 'no_box' )
{
$title = false;
}
// title
if( $options['page_action'] == "edit" && $options['page_type'] == 'user' )
{
if( $title )
{
echo '<h3>' .$acf['title'] . '</h3>';
}
echo '<table class="form-table"><tbody>';
}
// wrapper
if( $layout == 'tr' )
{
//nonce
echo '<tr style="display:none;"><td colspan="2"><input type="hidden" name="acf_nonce" value="' . wp_create_nonce( 'input' ) . '" /></td></tr>';
}
else
{
//nonce
echo '<input type="hidden" name="acf_nonce" value="' . wp_create_nonce( 'input' ) . '" />';
}
if( $layout == 'metabox' )
{
echo '<div class="postbox acf_postbox" id="acf_'. $acf['id'] .'">';
echo '<div title="Click to toggle" class="handlediv"><br></div><h3 class="hndle"><span>' . $acf['title'] . '</span></h3>';
echo '<div class="inside">';
}
// load fields
$fields = apply_filters('acf/field_group/get_fields', array(), $acf['id']);
if( is_array($fields) ){ foreach( $fields as $field ){
// if they didn't select a type, skip this field
if( !$field['type'] || $field['type'] == 'null' ) continue;
// set value
if( !isset($field['value']) )
{
$field['value'] = apply_filters('acf/load_value', false, $options['option_name'], $field);
$field['value'] = apply_filters('acf/format_value', $field['value'], $options['option_name'], $field);
}
// required
$required_class = "";
$required_label = "";
if( $field['required'] )
{
$required_class = ' required';
$required_label = ' <span class="required">*</span>';
}
if( $layout == 'metabox' )
{
echo '<div id="acf-' . $field['name'] . '" class="field field_type-' . $field['type'] . ' field_key-' . $field['key'] . $required_class . '" data-field_name="' . $field['name'] . '" data-field_key="' . $field['key'] . '" data-field_type="' . $field['type'] . '">';
echo '<p class="label">';
echo '<label for="fields[' . $field['key'] . ']">' . $field['label'] . $required_label . '</label>';
echo $field['instructions'];
echo '</p>';
$field['name'] = 'fields[' . $field['key'] . ']';
do_action('acf/create_field', $field);
echo '</div>';
}
elseif( $layout == 'div' )
{
echo '<div id="acf-' . $field['name'] . '" class="form-field field field_type-' . $field['type'] . ' field_key-' . $field['key'] . $required_class . '" data-field_name="' . $field['name'] . '" data-field_key="' . $field['key'] . '" data-field_type="' . $field['type'] . '">';
echo '<label for="fields[' . $field['key'] . ']">' . $field['label'] . $required_label . '</label>';
$field['name'] = 'fields[' . $field['key'] . ']';
do_action('acf/create_field', $field );
if($field['instructions']) echo '<p class="description">' . $field['instructions'] . '</p>';
echo '</div>';
}
else
{
echo '<tr id="acf-' . $field['name'] . '" class="form-field field field_type-' . $field['type'] . ' field_key-'.$field['key'] . $required_class . '" data-field_name="' . $field['name'] . '" data-field_key="' . $field['key'] . '" data-field_type="' . $field['type'] . '">';
echo '<th valign="top" scope="row"><label for="fields[' . $field['key'] . ']">' . $field['label'] . $required_label . '</label></th>';
echo '<td>';
$field['name'] = 'fields[' . $field['key'] . ']';
do_action('acf/create_field', $field );
if($field['instructions']) echo '<p class="description">' . $field['instructions'] . '</p>';
echo '</td>';
echo '</tr>';
}
}}
// wrapper
if( $layout == 'metabox' )
{
echo '</div></div>';
}
// title
if( $options['page_action'] == "edit" && $options['page_type'] == 'user' )
{
echo '</tbody></table>';
}
}
// foreach($acfs as $acf)
}
// if($acfs)
// exit for ajax
die();
}
/*
* delete_term
*
* @description:
* @since: 3.5.7
* @created: 12/01/13
*/
function delete_term( $term, $tt_id, $taxonomy, $deleted_term )
{
global $wpdb;
$values = $wpdb->query($wpdb->prepare(
"DELETE FROM $wpdb->options WHERE option_name LIKE %s",
'%' . $taxonomy . '_' . $term . '%'
));
}
}
new acf_everything_fields();
?> | PHP |
<?php
/*
* Revisions
*
* This Class contains all the functionality for adding ACF fields to the WP revisions interface
*
* @type class
* @date 11/08/13
*/
class acf_revisions
{
/*
* __construct
*
* A good place to add actions / filters
*
* @type function
* @date 11/08/13
*
* @param N/A
* @return N/A
*/
function __construct()
{
// actions
add_action('wp_restore_post_revision', array($this, 'wp_restore_post_revision'), 10, 2 );
// filters
add_filter('_wp_post_revision_fields', array($this, 'wp_post_revision_fields') );
add_filter('wp_save_post_revision_check_for_changes', array($this, 'force_save_revision'), 10, 3);
}
/*
* force_save_revision
*
* This filter will return false and force WP to save a revision. This is required due to
* WP checking only post_title, post_excerpt and post_content values, not custom fields.
*
* @type filter
* @date 19/09/13
*
* @param $return (boolean) defaults to true
* @param $last_revision (object) the last revision that WP will compare against
* @param $post (object) the $post that WP will compare against
* @return $return (boolean)
*/
function force_save_revision( $return, $last_revision, $post )
{
// preview hack
if( isset($_POST['acf_has_changed']) && $_POST['acf_has_changed'] == '1' )
{
$return = false;
}
// return
return $return;
}
/*
* wp_post_revision_fields
*
* This filter will add the ACF fields to the returned array
* Versions 3.5 and 3.6 of WP feature different uses of the revisions filters, so there are
* some hacks to allow both versions to work correctly
*
* @type filter
* @date 11/08/13
*
* @param $post_id (int)
* @return $post_id (int)
*/
function wp_post_revision_fields( $return ) {
//globals
global $post, $pagenow;
// validate
$allowed = false;
// Normal revisions page
if( $pagenow == 'revision.php' )
{
$allowed = true;
}
// WP 3.6 AJAX revision
if( $pagenow == 'admin-ajax.php' && isset($_POST['action']) && $_POST['action'] == 'get-revision-diffs' )
{
$allowed = true;
}
// bail
if( !$allowed )
{
return $return;
}
// vars
$post_id = 0;
// determin $post_id
if( isset($_POST['post_id']) )
{
$post_id = $_POST['post_id'];
}
elseif( isset($post->ID) )
{
$post_id = $post->ID;
}
else
{
return $return;
}
// get field objects
$fields = get_field_objects( $post_id, array('format_value' => false ) );
if( $fields )
{
foreach( $fields as $field )
{
// dud field?
if( !$field || !isset($field['name']) || !$field['name'] )
{
continue;
}
// Add field key / label
$return[ $field['name'] ] = $field['label'];
// load value
add_filter('_wp_post_revision_field_' . $field['name'], array($this, 'wp_post_revision_field'), 10, 4);
// WP 3.5: left vs right
// Add a value of the revision ID (as there is no way to determin this within the '_wp_post_revision_field_' filter!)
if( isset($_GET['action'], $_GET['left'], $_GET['right']) && $_GET['action'] == 'diff' )
{
global $left_revision, $right_revision;
$left_revision->$field['name'] = 'revision_id=' . $_GET['left'];
$right_revision->$field['name'] = 'revision_id=' . $_GET['right'];
}
}
}
return $return;
}
/*
* wp_post_revision_field
*
* This filter will load the value for the given field and return it for rendering
*
* @type filter
* @date 11/08/13
*
* @param $value (mixed) should be false as it has not yet been loaded
* @param $field_name (string) The name of the field
* @param $post (mixed) Holds the $post object to load from - in WP 3.5, this is not passed!
* @param $direction (string) to / from - not used
* @return $value (string)
*/
function wp_post_revision_field( $value, $field_name, $post = null, $direction = false)
{
// vars
$post_id = 0;
// determin $post_id
if( isset($post->ID) )
{
// WP 3.6
$post_id = $post->ID;
}
elseif( isset($_GET['revision']) )
{
// WP 3.5
$post_id = (int) $_GET['revision'];
}
elseif( strpos($value, 'revision_id=') !== false )
{
// WP 3.5 (left vs right)
$post_id = (int) str_replace('revision_id=', '', $value);
}
// load field
$field = get_field_object($field_name, $post_id, array('format_value' => false ));
$value = $field['value'];
// default formatting
if( is_array($value) )
{
$value = implode(', ', $value);
}
// format
if( $value )
{
// image?
if( $field['type'] == 'image' || $field['type'] == 'file' )
{
$url = wp_get_attachment_url($value);
$value = $value . ' (' . $url . ')';
}
}
// return
return $value;
}
/*
* wp_restore_post_revision
*
* This action will copy and paste the metadata from a revision to the post
*
* @type action
* @date 11/08/13
*
* @param $parent_id (int) the destination post
* @return $revision_id (int) the source post
*/
function wp_restore_post_revision( $post_id, $revision_id ) {
// global
global $wpdb;
// vars
$fields = array();
// get field from postmeta
$rows = $wpdb->get_results( $wpdb->prepare(
"SELECT * FROM $wpdb->postmeta WHERE post_id=%d",
$revision_id
), ARRAY_A);
// populate $fields
if( $rows )
{
foreach( $rows as $row )
{
// meta_key must start with '_'
if( substr($row['meta_key'], 0, 1) !== '_' )
{
continue;
}
// meta_value must start with 'field_'
if( substr($row['meta_value'], 0, 6) !== 'field_' )
{
continue;
}
// this is an ACF field, append to $fields
$fields[] = substr($row['meta_key'], 1);
}
}
// save data
if( $rows )
{
foreach( $rows as $row )
{
if( in_array($row['meta_key'], $fields) )
{
update_post_meta( $post_id, $row['meta_key'], $row['meta_value'] );
}
}
}
}
}
new acf_revisions();
?> | PHP |
<?php
/*
* Locations
*
* @description: controller for location match functionality
* @since: 3.6
* @created: 25/01/13
*/
class acf_location
{
/*
* __construct
*
* @description:
* @since 3.1.8
* @created: 23/06/12
*/
function __construct()
{
// ajax
add_action('wp_ajax_acf/location/match_field_groups_ajax', array($this, 'match_field_groups_ajax'));
add_action('wp_ajax_nopriv_acf/location/match_field_groups_ajax', array($this, 'match_field_groups_ajax'));
// filters
add_filter('acf/location/match_field_groups', array($this, 'match_field_groups'), 10, 2);
// Basic
add_filter('acf/location/rule_match/post_type', array($this, 'rule_match_post_type'), 10, 3);
add_filter('acf/location/rule_match/user_type', array($this, 'rule_match_user_type'), 10, 3);
// Page
add_filter('acf/location/rule_match/page', array($this, 'rule_match_post'), 10, 3);
add_filter('acf/location/rule_match/page_type', array($this, 'rule_match_page_type'), 10, 3);
add_filter('acf/location/rule_match/page_parent', array($this, 'rule_match_page_parent'), 10, 3);
add_filter('acf/location/rule_match/page_template', array($this, 'rule_match_page_template'), 10, 3);
// Post
add_filter('acf/location/rule_match/post', array($this, 'rule_match_post'), 10, 3);
add_filter('acf/location/rule_match/post_category', array($this, 'rule_match_post_category'), 10, 3);
add_filter('acf/location/rule_match/post_format', array($this, 'rule_match_post_format'), 10, 3);
add_filter('acf/location/rule_match/post_status', array($this, 'rule_match_post_status'), 10, 3);
add_filter('acf/location/rule_match/taxonomy', array($this, 'rule_match_taxonomy'), 10, 3);
// Other
add_filter('acf/location/rule_match/ef_taxonomy', array($this, 'rule_match_ef_taxonomy'), 10, 3);
add_filter('acf/location/rule_match/ef_user', array($this, 'rule_match_ef_user'), 10, 3);
add_filter('acf/location/rule_match/ef_media', array($this, 'rule_match_ef_media'), 10, 3);
// Options Page
add_filter('acf/location/rule_match/options_page', array($this, 'rule_match_options_page'), 10, 3);
}
/*
* match_field_groups_ajax
*
* @description:
* @since: 3.5.7
* @created: 3/01/13
*/
function match_field_groups_ajax()
{
// vars
$options = array(
'nonce' => '',
'ajax' => true
);
// load post options
$options = array_merge($options, $_POST);
// verify nonce
if( ! wp_verify_nonce($options['nonce'], 'acf_nonce') )
{
die(0);
}
// return array
$return = apply_filters( 'acf/location/match_field_groups', array(), $options );
// echo json
echo json_encode( $return );
die();
}
/*
* match_field_groups
*
* @description:
* @since: 3.5.7
* @created: 3/01/13
*/
function match_field_groups( $return, $options )
{
// vars
$defaults = array(
'post_id' => 0,
'post_type' => 0,
'page_template' => 0,
'page_parent' => 0,
'page_type' => 0,
'post_category' => array(),
'post_format' => 0,
'taxonomy' => array(),
'ef_taxonomy' => 0,
'ef_user' => 0,
'ef_media' => 0,
'lang' => 0,
'ajax' => false
);
// merge in $options
$options = array_merge($defaults, $options);
// Parse values
$options = apply_filters( 'acf/parse_types', $options );
// WPML
if( defined('ICL_LANGUAGE_CODE') )
{
$options['lang'] = ICL_LANGUAGE_CODE;
//global $sitepress;
//$sitepress->switch_lang( $options['lang'] );
}
// find all acf objects
$acfs = apply_filters('acf/get_field_groups', array());
// blank array to hold acfs
$return = array();
if( $acfs )
{
foreach( $acfs as $acf )
{
// load location
$acf['location'] = apply_filters('acf/field_group/get_location', array(), $acf['id']);
// vars
$add_box = false;
foreach( $acf['location'] as $group_id => $group )
{
// start of as true, this way, any rule that doesn't match will cause this varaible to false
$match_group = true;
if( is_array($group) )
{
foreach( $group as $rule_id => $rule )
{
// Hack for ef_media => now post_type = attachment
if( $rule['param'] == 'ef_media' )
{
$rule['param'] = 'post_type';
$rule['value'] = 'attachment';
}
// $match = true / false
$match = apply_filters( 'acf/location/rule_match/' . $rule['param'] , false, $rule, $options );
if( !$match )
{
$match_group = false;
}
}
}
// all rules must havematched!
if( $match_group )
{
$add_box = true;
}
}
// add ID to array
if( $add_box )
{
$return[] = $acf['id'];
}
}
}
return $return;
}
/*
* rule_match_post_type
*
* @description:
* @since: 3.5.7
* @created: 3/01/13
*/
function rule_match_post_type( $match, $rule, $options )
{
$post_type = $options['post_type'];
if( !$post_type )
{
if( !$options['post_id'] )
{
return false;
}
$post_type = get_post_type( $options['post_id'] );
}
if( $rule['operator'] == "==" )
{
$match = ( $post_type === $rule['value'] );
}
elseif( $rule['operator'] == "!=" )
{
$match = ( $post_type !== $rule['value'] );
}
return $match;
}
/*
* rule_match_post
*
* @description:
* @since: 3.5.7
* @created: 3/01/13
*/
function rule_match_post( $match, $rule, $options )
{
// validation
if( !$options['post_id'] )
{
return false;
}
// translate $rule['value']
// - this variable will hold the original post_id, but $options['post_id'] will hold the translated version
//if( function_exists('icl_object_id') )
//{
// $rule['value'] = icl_object_id( $rule['value'], $options['post_type'], true );
//}
if($rule['operator'] == "==")
{
$match = ( $options['post_id'] == $rule['value'] );
}
elseif($rule['operator'] == "!=")
{
$match = ( $options['post_id'] != $rule['value'] );
}
return $match;
}
/*
* rule_match_page_type
*
* @description:
* @since: 3.5.7
* @created: 3/01/13
*/
function rule_match_page_type( $match, $rule, $options )
{
// validation
if( !$options['post_id'] )
{
return false;
}
$post = get_post( $options['post_id'] );
if( $rule['value'] == 'front_page')
{
$front_page = (int) get_option('page_on_front');
if($rule['operator'] == "==")
{
$match = ( $front_page == $post->ID );
}
elseif($rule['operator'] == "!=")
{
$match = ( $front_page != $post->ID );
}
}
elseif( $rule['value'] == 'posts_page')
{
$posts_page = (int) get_option('page_for_posts');
if($rule['operator'] == "==")
{
$match = ( $posts_page == $post->ID );
}
elseif($rule['operator'] == "!=")
{
$match = ( $posts_page != $post->ID );
}
}
elseif( $rule['value'] == 'top_level')
{
$post_parent = $post->post_parent;
if( $options['page_parent'] )
{
$post_parent = $options['page_parent'];
}
if($rule['operator'] == "==")
{
$match = ( $post_parent == 0 );
}
elseif($rule['operator'] == "!=")
{
$match = ( $post_parent != 0 );
}
}
elseif( $rule['value'] == 'parent')
{
$children = get_pages(array(
'post_type' => $post->post_type,
'child_of' => $post->ID,
));
if($rule['operator'] == "==")
{
$match = ( count($children) > 0 );
}
elseif($rule['operator'] == "!=")
{
$match = ( count($children) == 0 );
}
}
elseif( $rule['value'] == 'child')
{
$post_parent = $post->post_parent;
if( $options['page_parent'] )
{
$post_parent = $options['page_parent'];
}
if($rule['operator'] == "==")
{
$match = ( $post_parent != 0 );
}
elseif($rule['operator'] == "!=")
{
$match = ( $post_parent == 0 );
}
}
return $match;
}
/*
* rule_match_page_parent
*
* @description:
* @since: 3.5.7
* @created: 3/01/13
*/
function rule_match_page_parent( $match, $rule, $options )
{
// validation
if( !$options['post_id'] )
{
return false;
}
// vars
$post = get_post( $options['post_id'] );
$post_parent = $post->post_parent;
if( $options['page_parent'] )
{
$post_parent = $options['page_parent'];
}
if($rule['operator'] == "==")
{
$match = ( $post_parent == $rule['value'] );
}
elseif($rule['operator'] == "!=")
{
$match = ( $post_parent != $rule['value'] );
}
return $match;
}
/*
* rule_match_page_template
*
* @description:
* @since: 3.5.7
* @created: 3/01/13
*/
function rule_match_page_template( $match, $rule, $options )
{
$page_template = $options['page_template'];
if( ! $page_template )
{
$page_template = get_post_meta( $options['post_id'], '_wp_page_template', true );
}
if( ! $page_template )
{
$post_type = $options['post_type'];
if( !$post_type )
{
$post_type = get_post_type( $options['post_id'] );
}
if( $post_type == 'page' )
{
$page_template = "default";
}
}
if($rule['operator'] == "==")
{
$match = ( $page_template === $rule['value'] );
}
elseif($rule['operator'] == "!=")
{
$match = ( $page_template !== $rule['value'] );
}
return $match;
}
/*
* rule_match_post_category
*
* @description:
* @since: 3.5.7
* @created: 3/01/13
*/
function rule_match_post_category( $match, $rule, $options )
{
// validate
if( !$options['post_id'] )
{
return false;
}
// post type
if( !$options['post_type'] )
{
$options['post_type'] = get_post_type( $options['post_id'] );
}
// vars
$taxonomies = get_object_taxonomies( $options['post_type'] );
$terms = $options['post_category'];
// not AJAX
if( !$options['ajax'] )
{
// no terms? Load them from the post_id
if( empty($terms) )
{
$all_terms = get_the_terms( $options['post_id'], 'category' );
if($all_terms)
{
foreach($all_terms as $all_term)
{
$terms[] = $all_term->term_id;
}
}
}
// no terms at all?
if( empty($terms) )
{
// If no ters, this is a new post and should be treated as if it has the "Uncategorized" (1) category ticked
if( is_array($taxonomies) && in_array('category', $taxonomies) )
{
$terms[] = '1';
}
}
}
if($rule['operator'] == "==")
{
$match = false;
if($terms)
{
if( in_array($rule['value'], $terms) )
{
$match = true;
}
}
}
elseif($rule['operator'] == "!=")
{
$match = true;
if($terms)
{
if( in_array($rule['value'], $terms) )
{
$match = false;
}
}
}
return $match;
}
/*
* rule_match_user_type
*
* @description:
* @since: 3.5.7
* @created: 3/01/13
*/
function rule_match_user_type( $match, $rule, $options )
{
$user = wp_get_current_user();
if( $rule['operator'] == "==" )
{
if( $rule['value'] == 'super_admin' )
{
$match = is_super_admin( $user->ID );
}
else
{
$match = in_array( $rule['value'], $user->roles );
}
}
elseif( $rule['operator'] == "!=" )
{
if( $rule['value'] == 'super_admin' )
{
$match = !is_super_admin( $user->ID );
}
else
{
$match = ( ! in_array( $rule['value'], $user->roles ) );
}
}
return $match;
}
/*
* rule_match_user_type
*
* @description:
* @since: 3.5.7
* @created: 3/01/13
*/
function rule_match_options_page( $match, $rule, $options )
{
global $plugin_page;
// NOTE
// comment out below code as it was interfering with custom slugs
// older location rules may be "options-pagename"
/*
if( substr($rule['value'], 0, 8) == 'options-' )
{
$rule['value'] = 'acf-' . $rule['value'];
}
*/
// older location ruels may be "Pagename"
/*
if( substr($rule['value'], 0, 11) != 'acf-options' )
{
$rule['value'] = 'acf-options-' . sanitize_title( $rule['value'] );
// value may now be wrong (acf-options-options)
if( $rule['value'] == 'acf-options-options' )
{
$rule['value'] = 'acf-options';
}
}
*/
if($rule['operator'] == "==")
{
$match = ( $plugin_page === $rule['value'] );
}
elseif($rule['operator'] == "!=")
{
$match = ( $plugin_page !== $rule['value'] );
}
return $match;
}
/*
* rule_match_post_format
*
* @description:
* @since: 3.5.7
* @created: 3/01/13
*/
function rule_match_post_format( $match, $rule, $options )
{
// vars
$post_format = $options['post_format'];
if( !$post_format )
{
// validate
if( !$options['post_id'] )
{
return false;
}
// post type
if( !$options['post_type'] )
{
$options['post_type'] = get_post_type( $options['post_id'] );
}
// does post_type support 'post-format'
if( post_type_supports( $options['post_type'], 'post-formats' ) )
{
$post_format = get_post_format( $options['post_id'] );
if( $post_format === false )
{
$post_format = 'standard';
}
}
}
if($rule['operator'] == "==")
{
$match = ( $post_format === $rule['value'] );
}
elseif($rule['operator'] == "!=")
{
$match = ( $post_format !== $rule['value'] );
}
return $match;
}
/*
* rule_match_post_status
*
* @description:
* @since: 3.5.7
* @created: 3/01/13
*/
function rule_match_post_status( $match, $rule, $options )
{
// validate
if( !$options['post_id'] )
{
return false;
}
// vars
$post_status = get_post_status( $options['post_id'] );
// auto-draft = draft
if( $post_status == 'auto-draft' )
{
$post_status = 'draft';
}
// match
if($rule['operator'] == "==")
{
$match = ( $post_status === $rule['value'] );
}
elseif($rule['operator'] == "!=")
{
$match = ( $post_status !== $rule['value'] );
}
// return
return $match;
}
/*
* rule_match_taxonomy
*
* @description:
* @since: 3.5.7
* @created: 3/01/13
*/
function rule_match_taxonomy( $match, $rule, $options )
{
// validate
if( !$options['post_id'] )
{
return false;
}
// post type
if( !$options['post_type'] )
{
$options['post_type'] = get_post_type( $options['post_id'] );
}
// vars
$taxonomies = get_object_taxonomies( $options['post_type'] );
$terms = $options['taxonomy'];
// not AJAX
if( !$options['ajax'] )
{
// no terms? Load them from the post_id
if( empty($terms) )
{
if( is_array($taxonomies) )
{
foreach( $taxonomies as $tax )
{
$all_terms = get_the_terms( $options['post_id'], $tax );
if($all_terms)
{
foreach($all_terms as $all_term)
{
$terms[] = $all_term->term_id;
}
}
}
}
}
// no terms at all?
if( empty($terms) )
{
// If no ters, this is a new post and should be treated as if it has the "Uncategorized" (1) category ticked
if( is_array($taxonomies) && in_array('category', $taxonomies) )
{
$terms[] = '1';
}
}
}
if($rule['operator'] == "==")
{
$match = false;
if($terms)
{
if( in_array($rule['value'], $terms) )
{
$match = true;
}
}
}
elseif($rule['operator'] == "!=")
{
$match = true;
if($terms)
{
if( in_array($rule['value'], $terms) )
{
$match = false;
}
}
}
return $match;
}
/*
* rule_match_ef_taxonomy
*
* @description:
* @since: 3.5.7
* @created: 3/01/13
*/
function rule_match_ef_taxonomy( $match, $rule, $options )
{
$ef_taxonomy = $options['ef_taxonomy'];
if( $ef_taxonomy )
{
if($rule['operator'] == "==")
{
$match = ( $ef_taxonomy == $rule['value'] );
// override for "all"
if( $rule['value'] == "all" )
{
$match = true;
}
}
elseif($rule['operator'] == "!=")
{
$match = ( $ef_taxonomy != $rule['value'] );
// override for "all"
if( $rule['value'] == "all" )
{
$match = false;
}
}
}
return $match;
}
/*
* rule_match_ef_user
*
* @description:
* @since: 3.5.7
* @created: 3/01/13
*/
function rule_match_ef_user( $match, $rule, $options )
{
$ef_user = $options['ef_user'];
if( $ef_user )
{
if($rule['operator'] == "==")
{
$match = ( user_can($ef_user, $rule['value']) );
// override for "all"
if( $rule['value'] === "all" )
{
$match = true;
}
}
elseif($rule['operator'] == "!=")
{
$match = ( !user_can($ef_user, $rule['value']) );
// override for "all"
if( $rule['value'] === "all" )
{
$match = false;
}
}
}
return $match;
}
}
new acf_location();
?> | PHP |
<?php
/*
* acf_addons
*
* @description: controller for add-ons sub menu page
* @since: 3.6
* @created: 25/01/13
*/
class acf_addons
{
var $action;
/*
* __construct
*
* @description:
* @since 3.1.8
* @created: 23/06/12
*/
function __construct()
{
// actions
add_action('admin_menu', array($this,'admin_menu'), 11, 0);
}
/*
* admin_menu
*
* @description:
* @created: 2/08/12
*/
function admin_menu()
{
// add page
$page = add_submenu_page('edit.php?post_type=acf', __('Add-ons','acf'), __('Add-ons','acf'), 'manage_options', 'acf-addons', array($this,'html'));
// actions
add_action('load-' . $page, array($this,'load'));
add_action('admin_print_scripts-' . $page, array($this, 'admin_print_scripts'));
add_action('admin_print_styles-' . $page, array($this, 'admin_print_styles'));
add_action('admin_head-' . $page, array($this,'admin_head'));
}
/*
* load
*
* @description:
* @since 3.5.2
* @created: 16/11/12
* @thanks: Kevin Biloski and Charlie Eriksen via Secunia SVCRP
*/
function load()
{
}
/*
* admin_print_scripts
*
* @description:
* @since 3.1.8
* @created: 23/06/12
*/
function admin_print_scripts()
{
}
/*
* admin_print_styles
*
* @description:
* @since 3.1.8
* @created: 23/06/12
*/
function admin_print_styles()
{
wp_enqueue_style(array(
'wp-pointer',
'acf-global',
'acf',
));
}
/*
* admin_head
*
* @description:
* @since 3.1.8
* @created: 23/06/12
*/
function admin_head()
{
}
/*
* html
*
* @description:
* @since 3.1.8
* @created: 23/06/12
*/
function html()
{
// vars
$dir = apply_filters('acf/get_info', 'dir');
$premium = array();
$premium[] = array(
'title' => __("Repeater Field",'acf'),
'description' => __("Create infinite rows of repeatable data with this versatile interface!",'acf'),
'thumbnail' => $dir . 'images/add-ons/repeater-field-thumb.jpg',
'active' => class_exists('acf_field_repeater'),
'url' => 'http://www.advancedcustomfields.com/add-ons/repeater-field/'
);
$premium[] = array(
'title' => __("Gallery Field",'acf'),
'description' => __("Create image galleries in a simple and intuitive interface!",'acf'),
'thumbnail' => $dir . 'images/add-ons/gallery-field-thumb.jpg',
'active' => class_exists('acf_field_gallery'),
'url' => 'http://www.advancedcustomfields.com/add-ons/gallery-field/'
);
$premium[] = array(
'title' => __("Options Page",'acf'),
'description' => __("Create global data to use throughout your website!",'acf'),
'thumbnail' => $dir . 'images/add-ons/options-page-thumb.jpg',
'active' => class_exists('acf_options_page_plugin'),
'url' => 'http://www.advancedcustomfields.com/add-ons/options-page/'
);
$premium[] = array(
'title' => __("Flexible Content Field",'acf'),
'description' => __("Create unique designs with a flexible content layout manager!",'acf'),
'thumbnail' => $dir . 'images/add-ons/flexible-content-field-thumb.jpg',
'active' => class_exists('acf_field_flexible_content'),
'url' => 'http://www.advancedcustomfields.com/add-ons/flexible-content-field/'
);
$free = array();
$free[] = array(
'title' => __("Gravity Forms Field",'acf'),
'description' => __("Creates a select field populated with Gravity Forms!",'acf'),
'thumbnail' => $dir . 'images/add-ons/gravity-forms-field-thumb.jpg',
'active' => class_exists('gravity_forms_field'),
'url' => 'https://github.com/stormuk/Gravity-Forms-ACF-Field/'
);
$free[] = array(
'title' => __("Date & Time Picker",'acf'),
'description' => __("jQuery date & time picker",'acf'),
'thumbnail' => $dir . 'images/add-ons/date-time-field-thumb.jpg',
'active' => class_exists('acf_field_date_time_picker'),
'url' => 'http://wordpress.org/extend/plugins/acf-field-date-time-picker/'
);
$free[] = array(
'title' => __("Location Field",'acf'),
'description' => __("Find addresses and coordinates of a desired location",'acf'),
'thumbnail' => $dir . 'images/add-ons/google-maps-field-thumb.jpg',
'active' => class_exists('acf_field_location'),
'url' => 'https://github.com/elliotcondon/acf-location-field/'
);
$free[] = array(
'title' => __("Contact Form 7 Field",'acf'),
'description' => __("Assign one or more contact form 7 forms to a post",'acf'),
'thumbnail' => $dir . 'images/add-ons/cf7-field-thumb.jpg',
'active' => class_exists('acf_field_cf7'),
'url' => 'https://github.com/taylormsj/acf-cf7-field/'
);
?>
<div class="wrap" style="max-width:970px;">
<div class="icon32" id="icon-acf"><br></div>
<h2 style="margin: 4px 0 15px;"><?php _e("Advanced Custom Fields Add-Ons",'acf'); ?></h2>
<div class="acf-alert">
<p style=""><?php _e("The following Add-ons are available to increase the functionality of the Advanced Custom Fields plugin.",'acf'); ?><br />
<?php _e("Each Add-on can be installed as a separate plugin (receives updates) or included in your theme (does not receive updates).",'acf'); ?></p>
</div>
<?php /*
<div class="acf-alert">
<p><strong><?php _e("Just updated to version 4?",'acf'); ?></strong> <?php _e("Activation codes have changed to plugins! Download your purchased add-ons",'acf'); ?> <a href="http://www.advancedcustomfields.com/add-ons-download/" target="_blank"><?php _e("here",'acf'); ?></a></p>
</div>
*/ ?>
<div id="add-ons" class="clearfix">
<div class="add-on-group clearfix">
<?php foreach( $premium as $addon ): ?>
<div class="add-on wp-box <?php if( $addon['active'] ): ?>add-on-active<?php endif; ?>">
<a target="_blank" href="<?php echo $addon['url']; ?>">
<img src="<?php echo $addon['thumbnail']; ?>" />
</a>
<div class="inner">
<h3><a target="_blank" href="<?php echo $addon['url']; ?>"><?php echo $addon['title']; ?></a></h3>
<p><?php echo $addon['description']; ?></p>
</div>
<div class="footer">
<?php if( $addon['active'] ): ?>
<a class="button button-disabled"><span class="acf-sprite-tick"></span><?php _e("Installed",'acf'); ?></a>
<?php else: ?>
<a target="_blank" href="<?php echo $addon['url']; ?>" class="button"><?php _e("Purchase & Install",'acf'); ?></a>
<?php endif; ?>
</div>
</div>
<?php endforeach; ?>
</div>
<div class="add-on-group clearfix">
<?php foreach( $free as $addon ): ?>
<div class="add-on wp-box <?php if( $addon['active'] ): ?>add-on-active<?php endif; ?>">
<a target="_blank" href="<?php echo $addon['url']; ?>">
<img src="<?php echo $addon['thumbnail']; ?>" />
</a>
<div class="inner">
<h3><a target="_blank" href="<?php echo $addon['url']; ?>"><?php echo $addon['title']; ?></a></h3>
<p><?php echo $addon['description']; ?></p>
</div>
<div class="footer">
<?php if( $addon['active'] ): ?>
<a class="button button-disabled"><span class="acf-sprite-tick"></span><?php _e("Installed",'acf'); ?></a>
<?php else: ?>
<a target="_blank" href="<?php echo $addon['url']; ?>" class="button"><?php _e("Download",'acf'); ?></a>
<?php endif; ?>
</div>
</div>
<?php endforeach; ?>
</div>
</div>
</div>
<script type="text/javascript">
(function($) {
$(window).load(function(){
$('#add-ons .add-on-group').each(function(){
var $el = $(this),
h = 0;
$el.find('.add-on').each(function(){
h = Math.max( $(this).height(), h );
});
$el.find('.add-on').height( h );
});
});
})(jQuery);
</script>
<?php
return;
}
}
new acf_addons();
?> | PHP |
<?php
/*
* acf_export
*
* @description: controller for export sub menu page
* @since: 3.6
* @created: 25/01/13
*/
class acf_export
{
var $action;
/*
* __construct
*
* @description:
* @since 3.1.8
* @created: 23/06/12
*/
function __construct()
{
// vars
$this->action = '';
// actions
add_action('admin_menu', array($this,'admin_menu'), 11, 0);
// filters
add_filter('acf/export/clean_fields', array($this,'clean_fields'), 10, 1);
}
/*
* admin_menu
*
* @description:
* @created: 2/08/12
*/
function admin_menu()
{
// add page
$page = add_submenu_page('edit.php?post_type=acf', __('Export','acf'), __('Export','acf'), 'manage_options', 'acf-export', array($this,'html'));
// actions
add_action('load-' . $page, array($this,'load'));
add_action('admin_print_scripts-' . $page, array($this, 'admin_print_scripts'));
add_action('admin_print_styles-' . $page, array($this, 'admin_print_styles'));
add_action('admin_head-' . $page, array($this,'admin_head'));
}
/*
* load
*
* @description:
* @since 3.5.2
* @created: 16/11/12
* @thanks: Kevin Biloski and Charlie Eriksen via Secunia SVCRP
*/
function load()
{
// vars
$path = apply_filters('acf/get_info', 'path');
// verify nonce
if( isset($_POST['nonce']) && wp_verify_nonce($_POST['nonce'], 'export') )
{
if( isset($_POST['export_to_xml']) )
{
$this->action = 'export_to_xml';
}
elseif( isset($_POST['export_to_php']) )
{
$this->action = 'export_to_php';
}
}
// include export action
if( $this->action == 'export_to_xml' )
{
include_once($path . 'core/actions/export.php');
die;
}
}
/*
* admin_print_scripts
*
* @description:
* @since 3.1.8
* @created: 23/06/12
*/
function admin_print_scripts()
{
}
/*
* admin_print_styles
*
* @description:
* @since 3.1.8
* @created: 23/06/12
*/
function admin_print_styles()
{
wp_enqueue_style(array(
'wp-pointer',
'acf-global',
'acf',
));
}
/*
* admin_head
*
* @description:
* @since 3.1.8
* @created: 23/06/12
*/
function admin_head()
{
}
/*
* html
*
* @description:
* @since 3.1.8
* @created: 23/06/12
*/
function html()
{
?>
<div class="wrap">
<div class="icon32" id="icon-acf"><br></div>
<h2 style="margin: 4px 0 25px;"><?php _e("Export",'acf'); ?></h2>
<?php
if( $this->action == "export_to_php" )
{
$this->html_php();
}
else
{
$this->html_index();
}
?>
</div>
<?php
return;
}
/*
* html_index
*
* @description:
* @created: 9/08/12
*/
function html_index()
{
// vars
$acfs = get_posts(array(
'numberposts' => -1,
'post_type' => 'acf',
'orderby' => 'menu_order title',
'order' => 'asc',
));
// blank array to hold acfs
$choices = array();
if($acfs)
{
foreach($acfs as $acf)
{
// find title. Could use get_the_title, but that uses get_post(), so I think this uses less Memory
$title = apply_filters( 'the_title', $acf->post_title, $acf->ID );
$choices[$acf->ID] = $title;
}
}
?>
<form method="post">
<input type="hidden" name="nonce" value="<?php echo wp_create_nonce( 'export' ); ?>" />
<div class="wp-box">
<div class="title">
<h3><?php _e("Export Field Groups",'acf'); ?></h3>
</div>
<table class="acf_input widefat">
<tr>
<td class="label">
<label><?php _e("Field Groups",'acf'); ?></label>
<p class="description"><?php _e("Select the field groups to be exported",'acf'); ?></p>
</td>
<td>
<?php do_action('acf/create_field', array(
'type' => 'select',
'name' => 'acf_posts',
'value' => '',
'choices' => $choices,
'multiple' => 1,
)); ?>
</td>
</tr>
<tr>
<td class="label"></td>
<td>
<ul class="hl clearfix">
<li>
<input type="submit" class="acf-button" name="export_to_xml" value="<?php _e("Export to XML",'acf'); ?>" />
</li>
<li>
<input type="submit" class="acf-button" name="export_to_php" value="<?php _e("Export to PHP",'acf'); ?>" />
</li>
</ul>
</td>
</tr>
</table>
</div>
</form>
<p><br /></p>
<h3><?php _e("Export to XML",'acf'); ?></h3>
<p><?php _e("ACF will create a .xml export file which is compatible with the native WP import plugin.",'acf'); ?></p>
<p><?php _e("Imported field groups <b>will</b> appear in the list of editable field groups. This is useful for migrating fields groups between Wp websites.",'acf'); ?></p>
<ol>
<li><?php _e("Select field group(s) from the list and click \"Export XML\"",'acf'); ?></li>
<li><?php _e("Save the .xml file when prompted",'acf'); ?></li>
<li><?php _e("Navigate to Tools » Import and select WordPress",'acf'); ?></li>
<li><?php _e("Install WP import plugin if prompted",'acf'); ?></li>
<li><?php _e("Upload and import your exported .xml file",'acf'); ?></li>
<li><?php _e("Select your user and ignore Import Attachments",'acf'); ?></li>
<li><?php _e("That's it! Happy WordPressing",'acf'); ?></li>
</ol>
<p><br /></p>
<h3><?php _e("Export to PHP",'acf'); ?></h3>
<p><?php _e("ACF will create the PHP code to include in your theme.",'acf'); ?></p>
<p><?php _e("Registered field groups <b>will not</b> appear in the list of editable field groups. This is useful for including fields in themes.",'acf'); ?></p>
<p><?php _e("Please note that if you export and register field groups within the same WP, you will see duplicate fields on your edit screens. To fix this, please move the original field group to the trash or remove the code from your functions.php file.",'acf'); ?></p>
<ol>
<li><?php _e("Select field group(s) from the list and click \"Create PHP\"",'acf'); ?></li>
<li><?php _e("Copy the PHP code generated",'acf'); ?></li>
<li><?php _e("Paste into your functions.php file",'acf'); ?></li>
<li><?php _e("To activate any Add-ons, edit and use the code in the first few lines.",'acf'); ?></li>
</ol>
<?php
}
/*
* html_php
*
* @description:
* @created: 9/08/12
*/
function html_php()
{
?>
<div class="wp-box">
<div class="title">
<h3><?php _e("Export Field Groups to PHP",'acf'); ?></h3>
</div>
<table class="acf_input widefat">
<tr>
<td class="label">
<h3><?php _e("Instructions",'acf'); ?></h3>
<ol>
<li><?php _e("Copy the PHP code generated",'acf'); ?></li>
<li><?php _e("Paste into your functions.php file",'acf'); ?></li>
<li><?php _e("To activate any Add-ons, edit and use the code in the first few lines.",'acf'); ?></li>
</ol>
<p><br /></p>
<h3><?php _e("Notes",'acf'); ?></h3>
<p><?php _e("Registered field groups <b>will not</b> appear in the list of editable field groups. This is useful for including fields in themes.",'acf'); ?></p>
<p><?php _e("Please note that if you export and register field groups within the same WP, you will see duplicate fields on your edit screens. To fix this, please move the original field group to the trash or remove the code from your functions.php file.",'acf'); ?></p>
<p><br /></p>
<h3><?php _e("Include in theme",'acf'); ?></h3>
<p><?php _e("The Advanced Custom Fields plugin can be included within a theme. To do so, move the ACF plugin inside your theme and add the following code to your functions.php file:",'acf'); ?></p>
<pre>
include_once('advanced-custom-fields/acf.php');
</pre>
<p><?php _e("To remove all visual interfaces from the ACF plugin, you can use a constant to enable lite mode. Add the following code to your functions.php file <b>before</b> the include_once code:",'acf'); ?></p>
<pre>
define( 'ACF_LITE', true );
</pre>
<p><br /></p>
<p><a href="">« <?php _e("Back to export",'acf'); ?></a></p>
</td>
<td>
<textarea class="pre" readonly="true"><?php
$acfs = array();
if( isset($_POST['acf_posts']) )
{
$acfs = get_posts(array(
'numberposts' => -1,
'post_type' => 'acf',
'orderby' => 'menu_order title',
'order' => 'asc',
'include' => $_POST['acf_posts'],
'suppress_filters' => false,
));
}
if( $acfs )
{
?>
if(function_exists("register_field_group"))
{
<?php
foreach( $acfs as $i => $acf )
{
// populate acfs
$var = array(
'id' => $acf->post_name,
'title' => $acf->post_title,
'fields' => apply_filters('acf/field_group/get_fields', array(), $acf->ID),
'location' => apply_filters('acf/field_group/get_location', array(), $acf->ID),
'options' => apply_filters('acf/field_group/get_options', array(), $acf->ID),
'menu_order' => $acf->menu_order,
);
$var['fields'] = apply_filters('acf/export/clean_fields', $var['fields']);
// create html
$html = var_export($var, true);
// change double spaces to tabs
$html = str_replace(" ", "\t", $html);
// correctly formats "=> array("
$html = preg_replace('/([\t\r\n]+?)array/', 'array', $html);
// Remove number keys from array
$html = preg_replace('/[0-9]+ => array/', 'array', $html);
// add extra tab at start of each line
$html = str_replace("\n", "\n\t", $html);
// add the WP __() function to specific strings for translation in theme
//$html = preg_replace("/'label'(.*?)('.*?')/", "'label'$1__($2)", $html);
//$html = preg_replace("/'instructions'(.*?)('.*?')/", "'instructions'$1__($2)", $html);
?> register_field_group(<?php echo $html ?>);
<?php
}
?>
}
<?php
}
else
{
_e("No field groups were selected",'acf');
}
?></textarea>
</td>
</tr>
</table>
</div>
<script type="text/javascript">
(function($){
var i = 0;
$(document).on('click', 'textarea.pre', function(){
if( i == 0 )
{
i++;
$(this).focus().select();
return false;
}
});
$(document).on('keyup', 'textarea.pre', function(){
$(this).height( 0 );
$(this).height( this.scrollHeight );
});
$(document).ready(function(){
$('textarea.pre').trigger('keyup');
});
})(jQuery);
</script>
<?php
}
/*
* clean_fields
*
* @description:
* @since: 3.5.7
* @created: 7/03/13
*/
function clean_fields( $fields )
{
// trim down the fields
if( $fields )
{
foreach( $fields as $i => $field )
{
// unset unneccessary bits
unset( $field['id'], $field['class'], $field['order_no'], $field['field_group'], $field['_name'] );
// instructions
if( !$field['instructions'] )
{
unset( $field['instructions'] );
}
// Required
if( !$field['required'] )
{
unset( $field['required'] );
}
// conditional logic
if( !$field['conditional_logic']['status'] )
{
unset( $field['conditional_logic'] );
}
// children
if( isset($field['sub_fields']) )
{
$field['sub_fields'] = apply_filters('acf/export/clean_fields', $field['sub_fields']);
}
elseif( isset($field['layouts']) )
{
foreach( $field['layouts'] as $l => $layout )
{
$field['layouts'][ $l ]['sub_fields'] = apply_filters('acf/export/clean_fields', $layout['sub_fields']);
}
}
// override field
$fields[ $i ] = $field;
}
}
return $fields;
}
}
new acf_export();
?> | PHP |
<?php
/*
* acf_third_party
*
* @description: controller for add-ons sub menu page
* @since: 3.6
* @created: 25/01/13
*/
class acf_third_party
{
/*
* __construct
*
* @description:
* @since 3.1.8
* @created: 23/06/12
*/
function __construct()
{
// Tabify Edit Screen - http://wordpress.org/extend/plugins/tabify-edit-screen/
add_action('admin_head-settings_page_tabify-edit-screen', array($this,'admin_head_tabify'));
// Duplicate Post - http://wordpress.org/extend/plugins/duplicate-post/
add_action('dp_duplicate_page', array($this, 'dp_duplicate_page'), 11, 2);
// Post Type Switcher - http://wordpress.org/extend/plugins/post-type-switcher/
add_filter('pts_post_type_filter', array($this, 'pts_post_type_filter'));
}
/*
* pts_allowed_pages
*
* @description:
* @since 3.5.3
* @created: 19/11/12
*/
function pts_post_type_filter( $args )
{
// global
global $typenow;
if( $typenow == "acf" )
{
$args = array(
'public' => false,
'show_ui' => true
);
}
// return
return $args;
}
/*
* admin_head_tabify
*
* @description:
* @since 3.5.1
* @created: 9/10/12
*/
function admin_head_tabify()
{
// remove ACF from the tabs
add_filter('tabify_posttypes', array($this, 'tabify_posttypes'));
// add acf metaboxes to list
add_action('tabify_add_meta_boxes' , array($this,'tabify_add_meta_boxes'));
}
/*
* tabify_posttypes
*
* @description:
* @since 3.5.1
* @created: 9/10/12
*/
function tabify_posttypes( $posttypes )
{
if( isset($posttypes['acf']) )
{
unset( $posttypes['acf'] );
}
return $posttypes;
}
/*
* tabify_add_meta_boxes
*
* @description:
* @since 3.5.1
* @created: 9/10/12
*/
function tabify_add_meta_boxes( $post_type )
{
// get acf's
$acfs = apply_filters('acf/get_field_groups', array());
if($acfs)
{
foreach($acfs as $acf)
{
// add meta box
add_meta_box(
'acf_' . $acf['id'],
$acf['title'],
array($this, 'dummy'),
$post_type
);
}
// foreach($acfs as $acf)
}
// if($acfs)
}
function dummy(){ /* Do Nothing */ }
/*
* dp_duplicate_page
*
* @description:
* @since 3.5.1
* @created: 9/10/12
*/
function dp_duplicate_page( $new_post_id, $old_post_object )
{
// only for acf
if( $old_post_object->post_type != "acf" )
{
return;
}
// update keys
$metas = get_post_custom( $new_post_id );
if( $metas )
{
foreach( $metas as $field_key => $field )
{
if( strpos($field_key, 'field_') !== false )
{
$field = $field[0];
$field = maybe_unserialize( $field );
$field = maybe_unserialize( $field ); // just to be sure!
// delete old field
delete_post_meta($new_post_id, $field_key);
// set new keys (recursive for sub fields)
$this->create_new_field_keys( $field );
// save it!
update_post_meta($new_post_id, $field['key'], $field);
}
// if( strpos($field_key, 'field_') !== false )
}
// foreach( $metas as $field_key => $field )
}
// if( $metas )
}
/*
* create_new_field_keys
*
* @description:
* @since 3.5.1
* @created: 9/10/12
*/
function create_new_field_keys( &$field )
{
// update key
$field['key'] = 'field_' . uniqid();
if( isset($field['sub_fields']) && is_array($field['sub_fields']) )
{
foreach( $field['sub_fields'] as $f )
{
$this->create_new_field_keys( $f );
}
}
elseif( isset($field['layouts']) && is_array($field['layouts']) )
{
foreach( $field['layouts'] as $layout )
{
if( isset($layout['sub_fields']) && is_array($layout['sub_fields']) )
{
foreach( $layout['sub_fields'] as $f )
{
$this->create_new_field_keys( $f );
}
}
}
}
}
}
new acf_third_party();
?> | PHP |
<?php
/*
* acf_controller_post
*
* This class contains the functionality to add ACF fields to a post edit form
*
* @type class
* @date 5/09/13
* @since 3.1.8
*
*/
class acf_controller_post
{
/*
* Constructor
*
* This function will construct all the neccessary actions and filters
*
* @type function
* @date 23/06/12
* @since 3.1.8
*
* @param N/A
* @return N/A
*/
function __construct()
{
// actions
add_action('admin_enqueue_scripts', array($this, 'admin_enqueue_scripts'));
add_action('save_post', array($this, 'save_post'), 10, 1);
// ajax
add_action('wp_ajax_acf/post/render_fields', array($this, 'ajax_render_fields'));
add_action('wp_ajax_acf/post/get_style', array($this, 'ajax_get_style'));
}
/*
* validate_page
*
* This function will check if the current page is for a post/page edit form
*
* @type function
* @date 23/06/12
* @since 3.1.8
*
* @param N/A
* @return (boolean)
*/
function validate_page()
{
// global
global $pagenow, $typenow;
// vars
$return = false;
// validate page
if( in_array( $pagenow, array('post.php', 'post-new.php') ) )
{
// validate post type
global $typenow;
if( $typenow != "acf" )
{
$return = true;
}
}
// validate page (Shopp)
if( $pagenow == "admin.php" && isset( $_GET['page'] ) && $_GET['page'] == "shopp-products" && isset( $_GET['id'] ) )
{
$return = true;
}
// return
return $return;
}
/*
* admin_enqueue_scripts
*
* This action is run after post query but before any admin script / head actions.
* It is a good place to register all actions.
*
* @type action (admin_enqueue_scripts)
* @date 26/01/13
* @since 3.6.0
*
* @param N/A
* @return N/A
*/
function admin_enqueue_scripts()
{
// validate page
if( ! $this->validate_page() )
{
return;
}
// actions
do_action('acf/input/admin_enqueue_scripts');
add_action('admin_head', array($this,'admin_head'));
}
/*
* admin_head
*
* This action will find and add field groups to the current edit page
*
* @type action (admin_head)
* @date 23/06/12
* @since 3.1.8
*
* @param N/A
* @return N/A
*/
function admin_head()
{
// globals
global $post, $pagenow, $typenow;
// shopp
if( $pagenow == "admin.php" && isset( $_GET['page'] ) && $_GET['page'] == "shopp-products" && isset( $_GET['id'] ) )
{
$typenow = "shopp_product";
}
// vars
$post_id = $post ? $post->ID : 0;
// get field groups
$filter = array(
'post_id' => $post_id,
'post_type' => $typenow
);
$metabox_ids = array();
$metabox_ids = apply_filters( 'acf/location/match_field_groups', $metabox_ids, $filter );
// get style of first field group
$style = '';
if( isset($metabox_ids[0]) )
{
$style = $this->get_style( $metabox_ids[0] );
}
// Style
echo '<style type="text/css" id="acf_style" >' . $style . '</style>';
// add user js + css
do_action('acf/input/admin_head');
// get field groups
$acfs = apply_filters('acf/get_field_groups', array());
if( $acfs )
{
foreach( $acfs as $acf )
{
// load options
$acf['options'] = apply_filters('acf/field_group/get_options', array(), $acf['id']);
// vars
$show = in_array( $acf['id'], $metabox_ids ) ? 1 : 0;
// priority
$priority = 'high';
if( $acf['options']['position'] == 'side' )
{
$priority = 'core';
}
$priority = apply_filters('acf/input/meta_box_priority', $priority, $acf);
// add meta box
add_meta_box(
'acf_' . $acf['id'],
$acf['title'],
array($this, 'meta_box_input'),
$typenow,
$acf['options']['position'],
$priority,
array( 'field_group' => $acf, 'show' => $show, 'post_id' => $post_id )
);
}
// foreach($acfs as $acf)
}
// if($acfs)
// Allow 'acf_after_title' metabox position
add_action('edit_form_after_title', array($this, 'edit_form_after_title'));
// remove ACF from meta postbox
add_filter( 'is_protected_meta', array($this, 'is_protected_meta'), 10, 3 );
}
/*
* edit_form_after_title
*
* This action will allow ACF to render metaboxes after the title
*
* @type action
* @date 17/08/13
*
* @param N/A
* @return N/A
*/
function edit_form_after_title()
{
// globals
global $post, $wp_meta_boxes;
// render
do_meta_boxes( get_current_screen(), 'acf_after_title', $post);
// clean up
unset( $wp_meta_boxes['post']['acf_after_title'] );
// preview hack
// the following code will add a hidden input which will trigger WP to create a revision apon save
// http://support.advancedcustomfields.com/forums/topic/preview-solution/#post-4106
?>
<div style="display:none">
<input type="hidden" name="acf_has_changed" id="acf-has-changed" value="0" />
</div>
<?php
}
/*
* meta_box_input
*
* @description:
* @since 1.0.0
* @created: 23/06/12
*/
function meta_box_input( $post, $args )
{
// extract $args
extract( $args );
// classes
$class = 'acf_postbox ' . $args['field_group']['options']['layout'];
$toggle_class = 'acf_postbox-toggle';
if( ! $args['show'] )
{
$class .= ' acf-hidden';
$toggle_class .= ' acf-hidden';
}
// HTML
if( $args['show'] )
{
$fields = apply_filters('acf/field_group/get_fields', array(), $args['field_group']['id']);
do_action('acf/create_fields', $fields, $args['post_id']);
}
else
{
echo '<div class="acf-replace-with-fields"><div class="acf-loading"></div></div>';
}
// nonce
echo '<div style="display:none">';
echo '<input type="hidden" name="acf_nonce" value="' . wp_create_nonce( 'input' ) . '" />';
?>
<script type="text/javascript">
(function($) {
$('#<?php echo $id; ?>').addClass('<?php echo $class; ?>').removeClass('hide-if-js');
$('#adv-settings label[for="<?php echo $id; ?>-hide"]').addClass('<?php echo $toggle_class; ?>');
})(jQuery);
</script>
<?php
echo '</div>';
}
/*
* get_style
*
* @description: called by admin_head to generate acf css style (hide other metaboxes)
* @since 2.0.5
* @created: 23/06/12
*/
function get_style( $acf_id )
{
// vars
$options = apply_filters('acf/field_group/get_options', array(), $acf_id);
$html = '';
// add style to html
if( in_array('permalink',$options['hide_on_screen']) )
{
$html .= '#edit-slug-box {display: none;} ';
}
if( in_array('the_content',$options['hide_on_screen']) )
{
$html .= '#postdivrich {display: none;} ';
}
if( in_array('excerpt',$options['hide_on_screen']) )
{
$html .= '#postexcerpt, #screen-meta label[for=postexcerpt-hide] {display: none;} ';
}
if( in_array('custom_fields',$options['hide_on_screen']) )
{
$html .= '#postcustom, #screen-meta label[for=postcustom-hide] { display: none; } ';
}
if( in_array('discussion',$options['hide_on_screen']) )
{
$html .= '#commentstatusdiv, #screen-meta label[for=commentstatusdiv-hide] {display: none;} ';
}
if( in_array('comments',$options['hide_on_screen']) )
{
$html .= '#commentsdiv, #screen-meta label[for=commentsdiv-hide] {display: none;} ';
}
if( in_array('slug',$options['hide_on_screen']) )
{
$html .= '#slugdiv, #screen-meta label[for=slugdiv-hide] {display: none;} ';
}
if( in_array('author',$options['hide_on_screen']) )
{
$html .= '#authordiv, #screen-meta label[for=authordiv-hide] {display: none;} ';
}
if( in_array('format',$options['hide_on_screen']) )
{
$html .= '#formatdiv, #screen-meta label[for=formatdiv-hide] {display: none;} ';
}
if( in_array('featured_image',$options['hide_on_screen']) )
{
$html .= '#postimagediv, #screen-meta label[for=postimagediv-hide] {display: none;} ';
}
if( in_array('revisions',$options['hide_on_screen']) )
{
$html .= '#revisionsdiv, #screen-meta label[for=revisionsdiv-hide] {display: none;} ';
}
if( in_array('categories',$options['hide_on_screen']) )
{
$html .= '#categorydiv, #screen-meta label[for=categorydiv-hide] {display: none;} ';
}
if( in_array('tags',$options['hide_on_screen']) )
{
$html .= '#tagsdiv-post_tag, #screen-meta label[for=tagsdiv-post_tag-hide] {display: none;} ';
}
if( in_array('send-trackbacks',$options['hide_on_screen']) )
{
$html .= '#trackbacksdiv, #screen-meta label[for=trackbacksdiv-hide] {display: none;} ';
}
return $html;
}
/*
* ajax_get_input_style
*
* @description: called by input-actions.js to hide / show other metaboxes
* @since 2.0.5
* @created: 23/06/12
*/
function ajax_get_style()
{
// vars
$options = array(
'acf_id' => 0,
'nonce' => ''
);
// load post options
$options = array_merge($options, $_POST);
// verify nonce
if( ! wp_verify_nonce($options['nonce'], 'acf_nonce') )
{
die(0);
}
// return style
echo $this->get_style( $options['acf_id'] );
// die
die;
}
/*
* ajax_render_fields
*
* @description:
* @since 3.1.6
* @created: 23/06/12
*/
function ajax_render_fields()
{
// defaults
$options = array(
'acf_id' => 0,
'post_id' => 0,
'nonce' => ''
);
// load post options
$options = array_merge($options, $_POST);
// verify nonce
if( ! wp_verify_nonce($options['nonce'], 'acf_nonce') )
{
die(0);
}
// get acfs
$acfs = apply_filters('acf/get_field_groups', array());
if( $acfs )
{
foreach( $acfs as $acf )
{
if( $acf['id'] == $options['acf_id'] )
{
$fields = apply_filters('acf/field_group/get_fields', array(), $acf['id']);
do_action('acf/create_fields', $fields, $options['post_id']);
break;
}
}
}
die();
}
/*
* save_post
*
* @description: Saves the field / location / option data for a field group
* @since 1.0.0
* @created: 23/06/12
*/
function save_post( $post_id )
{
// do not save if this is an auto save routine
if( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
{
return $post_id;
}
// verify nonce
if( !isset($_POST['acf_nonce'], $_POST['fields']) || !wp_verify_nonce($_POST['acf_nonce'], 'input') )
{
return $post_id;
}
// if save lock contains a value, the save_post action is already running for another post.
// this would imply that the user is hooking into an ACF update_value or save_post action and inserting a new post
// if this is the case, we do not want to save all the $POST data to this post.
if( isset($GLOBALS['acf_save_lock']) && $GLOBALS['acf_save_lock'] )
{
return $post_id;
}
// update the post (may even be a revision / autosave preview)
do_action('acf/save_post', $post_id);
}
/*
* is_protected_meta
*
* This function will remove any ACF meta from showing in the meta postbox
*
* @type function
* @date 12/04/2014
* @since 5.0.0
*
* @param $post_id (int)
* @return $post_id (int)
*/
function is_protected_meta( $protected, $meta_key, $meta_type ) {
// globals
global $post;
// if acf_get_field_reference returns a valid key, this is an acf value, so protect it!
if( !$protected ) {
$reference = get_field_reference( $meta_key, $post->ID );
if( substr($reference, 0, 6) === 'field_' ) {
$protected = true;
}
}
// return
return $protected;
}
}
new acf_controller_post();
?> | PHP |
<?php
/*
* acf_controller_input
*
* This class contains the functionality for input actions used throughout ACF
*
* @type class
* @date 5/09/13
* @since 3.1.8
*
*/
class acf_controller_input
{
/*
* __construct
*
* @description:
* @since 3.1.8
* @created: 23/06/12
*/
function __construct()
{
// actions
add_action('acf/input/admin_head', array($this, 'input_admin_head'));
add_action('acf/input/admin_enqueue_scripts', array($this, 'input_admin_enqueue_scripts'));
}
/*
* input_admin_head
*
* action called when rendering the head of an admin screen. Used primarily for passing PHP to JS
*
* @type action
* @date 27/05/13
*
* @param N/A
* @return N/A
*/
function input_admin_head()
{
// global
global $wp_version, $post;
// vars
$toolbars = apply_filters( 'acf/fields/wysiwyg/toolbars', array() );
$post_id = 0;
if( $post )
{
$post_id = intval( $post->ID );
}
// l10n
$l10n = apply_filters( 'acf/input/admin_l10n', array(
'core' => array(
'expand_details' => __("Expand Details",'acf'),
'collapse_details' => __("Collapse Details",'acf')
),
'validation' => array(
'error' => __("Validation Failed. One or more fields below are required.",'acf')
)
));
// options
$o = array(
'post_id' => $post_id,
'nonce' => wp_create_nonce( 'acf_nonce' ),
'admin_url' => admin_url(),
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'wp_version' => $wp_version
);
// toolbars
$t = array();
if( is_array($toolbars) ){ foreach( $toolbars as $label => $rows ){
$label = sanitize_title( $label );
$label = str_replace('-', '_', $label);
$t[ $label ] = array();
if( is_array($rows) ){ foreach( $rows as $k => $v ){
$t[ $label ][ 'theme_advanced_buttons' . $k ] = implode(',', $v);
}}
}}
?>
<script type="text/javascript">
(function($) {
// vars
acf.post_id = <?php echo is_numeric($post_id) ? $post_id : '"' . $post_id . '"'; ?>;
acf.nonce = "<?php echo wp_create_nonce( 'acf_nonce' ); ?>";
acf.admin_url = "<?php echo admin_url(); ?>";
acf.ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ); ?>";
acf.wp_version = "<?php echo $wp_version; ?>";
// new vars
acf.o = <?php echo json_encode( $o ); ?>;
acf.l10n = <?php echo json_encode( $l10n ); ?>;
acf.fields.wysiwyg.toolbars = <?php echo json_encode( $t ); ?>;
})(jQuery);
</script>
<?php
}
/*
* input_admin_enqueue_scripts
*
* @description:
* @since: 3.6
* @created: 30/01/13
*/
function input_admin_enqueue_scripts()
{
// scripts
wp_enqueue_script(array(
'jquery',
'jquery-ui-core',
'jquery-ui-tabs',
'jquery-ui-sortable',
'wp-color-picker',
'thickbox',
'media-upload',
'acf-input',
'acf-datepicker',
));
// 3.5 media gallery
if( function_exists('wp_enqueue_media') && !did_action( 'wp_enqueue_media' ))
{
wp_enqueue_media();
}
// styles
wp_enqueue_style(array(
'thickbox',
'wp-color-picker',
'acf-global',
'acf-input',
'acf-datepicker',
));
}
}
new acf_controller_input();
?> | PHP |
<?php
/*
* Upgrade
*
* @description: All the functionality for upgrading ACF
* @since 3.2.6
* @created: 23/06/12
*/
class acf_upgrade
{
/*
* __construct
*
* @description:
* @since 3.1.8
* @created: 23/06/12
*/
function __construct()
{
// actions
add_action('admin_menu', array($this,'admin_menu'), 11);
// ajax
add_action('wp_ajax_acf_upgrade', array($this, 'upgrade_ajax'));
}
/*
* admin_menu
*
* @description:
* @since 3.1.8
* @created: 23/06/12
*/
function admin_menu()
{
// dont run on plugin activate!
if( isset($_GET['action']) && $_GET['action'] == 'activate-plugin' )
{
return;
}
// vars
$new_version = apply_filters('acf/get_info', 'version');
$old_version = get_option('acf_version', false);
if( $new_version != $old_version )
{
update_option('acf_version', $new_version );
if( !$old_version )
{
// do nothing, this is a fresh install
}
elseif( $old_version < '4.0.0' && $new_version >= '4.0.0')
{
$url = admin_url('edit.php?post_type=acf&info=whats-new');
wp_redirect( $url );
exit;
}
}
// update admin page
add_submenu_page('edit.php?post_type=acf', __('Upgrade','acf'), __('Upgrade','acf'), 'manage_options','acf-upgrade', array($this,'html') );
}
/*
* html
*
* @description:
* @since 3.1.8
* @created: 23/06/12
*/
function html()
{
$version = get_option('acf_version','1.0.5');
$next = false;
// list of starting points
if( $version < '3.0.0' )
{
$next = '3.0.0';
}
elseif( $version < '3.1.8' )
{
$next = '3.1.8';
}
elseif( $version < '3.2.5' )
{
$next = '3.2.5';
}
elseif( $version < '3.3.3' )
{
$next = '3.3.3';
}
elseif( $version < '3.4.1' )
{
$next = '3.4.1';
}
?>
<script type="text/javascript">
(function($){
function add_message(messaage)
{
$('#wpbody-content').append('<p>' + messaage + '</p>');
}
function run_upgrade(version)
{
$.ajax({
url: ajaxurl,
data: {
action : 'acf_upgrade',
version : version
},
type: 'post',
dataType: 'json',
success: function(json){
if(json)
{
if(json.status)
{
add_message(json.message);
// next update?
if(json.next)
{
run_upgrade(json.next);
}
else
{
// all done
add_message('Upgrade Complete! <a href="<?php echo admin_url(); ?>edit.php?post_type=acf">Continue to ACF »</a>');
}
}
else
{
// error!
add_message('Error: ' + json.message);
}
}
else
{
// major error!
add_message('Sorry. Something went wrong during the upgrade process. Please report this on the support forum');
}
}
});
}
<?php if($next){ echo 'run_upgrade("' . $next . '");'; } ?>
})(jQuery);
</script>
<style type="text/css">
#message {
display: none;
}
</style>
<?php
if(!$next)
{
echo '<p>No Upgrade Required</p>';
}
}
/*
* upgrade_ajax
*
* @description:
* @since 3.1.8
* @created: 23/06/12
*/
function upgrade_ajax()
{
// global
global $wpdb;
// tables
$acf_fields = $wpdb->prefix.'acf_fields';
$acf_values = $wpdb->prefix.'acf_values';
$acf_rules = $wpdb->prefix.'acf_rules';
$wp_postmeta = $wpdb->prefix.'postmeta';
$wp_options = $wpdb->prefix.'options';
// vars
$return = array(
'status' => false,
'message' => "",
'next' => false,
);
// versions
switch($_POST['version'])
{
/*---------------------
*
* 3.0.0
*
*--------------------*/
case '3.0.0':
// upgrade options first as "field_group_layout" will cause get_fields to fail!
// get acf's
$acfs = get_posts(array(
'numberposts' => -1,
'post_type' => 'acf',
'orderby' => 'menu_order title',
'order' => 'asc',
'suppress_filters' => false,
));
if($acfs)
{
foreach($acfs as $acf)
{
// position
update_post_meta($acf->ID, 'position', 'normal');
//layout
$layout = get_post_meta($acf->ID, 'field_group_layout', true) ? get_post_meta($acf->ID, 'field_group_layout', true) : 'in_box';
if($layout == 'in_box')
{
$layout = 'default';
}
else
{
$layout = 'no_box';
}
update_post_meta($acf->ID, 'layout', $layout);
delete_post_meta($acf->ID, 'field_group_layout');
// show_on_page
$show_on_page = get_post_meta($acf->ID, 'show_on_page', true) ? get_post_meta($acf->ID, 'show_on_page', true) : array();
if($show_on_page)
{
$show_on_page = unserialize($show_on_page);
}
update_post_meta($acf->ID, 'show_on_page', $show_on_page);
}
}
$return = array(
'status' => true,
'message' => "Migrating Options...",
'next' => '3.0.0 (step 2)',
);
break;
/*---------------------
*
* 3.0.0
*
*--------------------*/
case '3.0.0 (step 2)':
// get acf's
$acfs = get_posts(array(
'numberposts' => -1,
'post_type' => 'acf',
'orderby' => 'menu_order title',
'order' => 'asc',
'suppress_filters' => false,
));
if($acfs)
{
foreach($acfs as $acf)
{
// allorany doesn't need to change!
$rules = $wpdb->get_results("SELECT * FROM $acf_rules WHERE acf_id = '$acf->ID' ORDER BY order_no ASC", ARRAY_A);
if($rules)
{
foreach($rules as $rule)
{
// options rule has changed
if($rule['param'] == 'options_page')
{
$rule['value'] = 'Options';
}
add_post_meta($acf->ID, 'rule', $rule);
}
}
}
}
$return = array(
'status' => true,
'message' => "Migrating Location Rules...",
'next' => '3.0.0 (step 3)',
);
break;
/*---------------------
*
* 3.0.0
*
*--------------------*/
case '3.0.0 (step 3)':
$message = "Migrating Fields?";
$parent_id = 0;
$fields = $wpdb->get_results("SELECT * FROM $acf_fields WHERE parent_id = $parent_id ORDER BY order_no, name", ARRAY_A);
if($fields)
{
// loop through fields
foreach($fields as $field)
{
// unserialize options
if(@unserialize($field['options']))
{
$field['options'] = unserialize($field['options']);
}
else
{
$field['options'] = array();
}
// sub fields
if($field['type'] == 'repeater')
{
$field['options']['sub_fields'] = array();
$parent_id = $field['id'];
$sub_fields = $wpdb->get_results("SELECT * FROM $acf_fields WHERE parent_id = $parent_id ORDER BY order_no, name", ARRAY_A);
// if fields are empty, this must be a new or broken acf.
if(empty($sub_fields))
{
$field['options']['sub_fields'] = array();
}
else
{
// loop through fields
foreach($sub_fields as $sub_field)
{
// unserialize options
if(@unserialize($sub_field['options']))
{
$sub_field['options'] = @unserialize($sub_field['options']);
}
else
{
$sub_field['options'] = array();
}
// merge options with field
$sub_field = array_merge($sub_field, $sub_field['options']);
unset($sub_field['options']);
// each field has a unique id!
if(!isset($sub_field['key'])) $sub_field['key'] = 'field_' . $sub_field['id'];
$field['options']['sub_fields'][] = $sub_field;
}
}
}
// end if sub field
// merge options with field
$field = array_merge($field, $field['options']);
unset($field['options']);
// each field has a unique id!
if(!isset($field['key'])) $field['key'] = 'field_' . $field['id'];
// update field
$this->parent->update_field( $field['post_id'], $field);
// create field name (field_rand)
//$message .= print_r($field, true) . '<br /><br />';
}
// end foreach $fields
}
$return = array(
'status' => true,
'message' => $message,
'next' => '3.0.0 (step 4)',
);
break;
/*---------------------
*
* 3.0.0
*
*--------------------*/
case '3.0.0 (step 4)':
$message = "Migrating Values...";
// update normal values
$values = $wpdb->get_results("SELECT v.field_id, m.post_id, m.meta_key, m.meta_value FROM $acf_values v LEFT JOIN $wp_postmeta m ON v.value = m.meta_id WHERE v.sub_field_id = 0", ARRAY_A);
if($values)
{
foreach($values as $value)
{
// options page
if($value['post_id'] == 0) $value['post_id'] = 999999999;
// unserialize value (relationship, multi select, etc)
if(@unserialize($value['meta_value']))
{
$value['meta_value'] = unserialize($value['meta_value']);
}
update_post_meta($value['post_id'], $value['meta_key'], $value['meta_value']);
update_post_meta($value['post_id'], '_' . $value['meta_key'], 'field_' . $value['field_id']);
}
}
// update repeater values
$values = $wpdb->get_results("SELECT v.field_id, v.sub_field_id, v.order_no, m.post_id, m.meta_key, m.meta_value FROM $acf_values v LEFT JOIN $wp_postmeta m ON v.value = m.meta_id WHERE v.sub_field_id != 0", ARRAY_A);
if($values)
{
$rows = array();
foreach($values as $value)
{
// update row count
$row = (int) $value['order_no'] + 1;
// options page
if($value['post_id'] == 0) $value['post_id'] = 999999999;
// unserialize value (relationship, multi select, etc)
if(@unserialize($value['meta_value']))
{
$value['meta_value'] = unserialize($value['meta_value']);
}
// current row
$current_row = isset($rows[$value['post_id']][$value['field_id']]) ? $rows[$value['post_id']][$value['field_id']] : 0;
if($row > $current_row) $rows[$value['post_id']][$value['field_id']] = (int) $row;
// get field name
$field_name = $wpdb->get_var($wpdb->prepare("SELECT name FROM $acf_fields WHERE id = %d", $value['field_id']));
// get sub field name
$sub_field_name = $wpdb->get_var($wpdb->prepare("SELECT name FROM $acf_fields WHERE id = %d", $value['sub_field_id']));
// save new value
$new_meta_key = $field_name . '_' . $value['order_no'] . '_' . $sub_field_name;
update_post_meta($value['post_id'], $new_meta_key , $value['meta_value']);
// save value hidden field id
update_post_meta($value['post_id'], '_' . $new_meta_key, 'field_' . $value['sub_field_id']);
}
foreach($rows as $post_id => $field_ids)
{
foreach($field_ids as $field_id => $row_count)
{
// get sub field name
$field_name = $wpdb->get_var($wpdb->prepare("SELECT name FROM $acf_fields WHERE id = %d", $field_id));
delete_post_meta($post_id, $field_name);
update_post_meta($post_id, $field_name, $row_count);
update_post_meta($post_id, '_' . $field_name, 'field_' . $field_id);
}
}
}
// update version (only upgrade 1 time)
update_option('acf_version','3.0.0');
$return = array(
'status' => true,
'message' => $message,
'next' => '3.1.8',
);
break;
/*---------------------
*
* 3.1.8
*
*--------------------*/
case '3.1.8':
// vars
$message = __("Migrating options values from the $wp_postmeta table to the $wp_options table",'acf') . '...';
// update normal values
$rows = $wpdb->get_results( $wpdb->prepare("SELECT meta_key FROM $wp_postmeta WHERE post_id = %d", 999999999) , ARRAY_A);
if($rows)
{
foreach($rows as $row)
{
// original name
$field_name = $row['meta_key'];
// name
$new_name = "";
if( substr($field_name, 0, 1) == "_" )
{
$new_name = '_options' . $field_name;
}
else
{
$new_name = 'options_' . $field_name;
}
// value
$value = get_post_meta( 999999999, $field_name, true );
// update option
update_option( $new_name, $value );
// deleet old postmeta
delete_post_meta( 999999999, $field_name );
}
// foreach($values as $value)
}
// if($values)
// update version
update_option('acf_version','3.1.8');
$return = array(
'status' => true,
'message' => $message,
'next' => '3.2.5',
);
break;
/*---------------------
*
* 3.1.8
*
*--------------------*/
case '3.2.5':
// vars
$message = __("Modifying field group options 'show on page'",'acf') . '...';
// get acf's
$acfs = get_posts(array(
'numberposts' => -1,
'post_type' => 'acf',
'orderby' => 'menu_order title',
'order' => 'asc',
'suppress_filters' => false,
));
$show_all = array('the_content', 'discussion', 'custom_fields', 'comments', 'slug', 'author');
// populate acfs
if($acfs)
{
foreach($acfs as $acf)
{
$show_on_page = get_post_meta($acf->ID, 'show_on_page', true) ? get_post_meta($acf->ID, 'show_on_page', true) : array();
$hide_on_screen = array_diff($show_all, $show_on_page);
update_post_meta($acf->ID, 'hide_on_screen', $hide_on_screen);
delete_post_meta($acf->ID, 'show_on_page');
}
}
// update version
update_option('acf_version','3.2.5');
$return = array(
'status' => true,
'message' => $message,
'next' => '3.3.3',
);
break;
/*
* 3.3.3
*
* @description: changed field option: taxonomies filter on relationship / post object and page link fields.
* @created: 20/07/12
*/
case '3.3.3':
// vars
$message = __("Modifying field option 'taxonomy'",'acf') . '...';
$wp_term_taxonomy = $wpdb->prefix.'term_taxonomy';
$term_taxonomies = array();
$rows = $wpdb->get_results("SELECT * FROM $wp_term_taxonomy", ARRAY_A);
if($rows)
{
foreach($rows as $row)
{
$term_taxonomies[ $row['term_id'] ] = $row['taxonomy'] . ":" . $row['term_id'];
}
}
// get acf's
$acfs = get_posts(array(
'numberposts' => -1,
'post_type' => 'acf',
'orderby' => 'menu_order title',
'order' => 'asc',
'suppress_filters' => false,
));
// populate acfs
if($acfs)
{
foreach($acfs as $acf)
{
$fields = $this->parent->get_acf_fields($acf->ID);
if( $fields )
{
foreach( $fields as $field )
{
// only edit the option: taxonomy
if( !isset($field['taxonomy']) )
{
continue;
}
if( is_array($field['taxonomy']) )
{
foreach( $field['taxonomy'] as $k => $v )
{
// could be "all"
if( !is_numeric($v) )
{
continue;
}
$field['taxonomy'][ $k ] = $term_taxonomies[ $v ];
}
// foreach( $field['taxonomy'] as $k => $v )
}
// if( $field['taxonomy'] )
$this->parent->update_field( $acf->ID, $field);
}
// foreach( $fields as $field )
}
// if( $fields )
}
// foreach($acfs as $acf)
}
// if($acfs)
// update version
update_option('acf_version','3.3.3');
$return = array(
'status' => true,
'message' => $message,
'next' => '3.4.1',
);
break;
/*
* 3.4.1
*
* @description: Move user custom fields from wp_options to wp_usermeta
* @created: 20/07/12
*/
case '3.4.1':
// vars
$message = __("Moving user custom fields from wp_options to wp_usermeta'",'acf') . '...';
$option_row_ids = array();
$option_rows = $wpdb->get_results("SELECT option_id, option_name, option_value FROM $wpdb->options WHERE option_name LIKE 'user%' OR option_name LIKE '\_user%'", ARRAY_A);
if( $option_rows )
{
foreach( $option_rows as $k => $row)
{
preg_match('/user_([0-9]+)_(.*)/', $row['option_name'], $matches);
// if no matches, this is not an acf value, ignore it
if( !$matches )
{
continue;
}
// add to $delete_option_rows
$option_row_ids[] = $row['option_id'];
// meta_key prefix
$meta_key_prefix = "";
if( substr($row['option_name'], 0, 1) == "_" )
{
$meta_key_prefix = '_';
}
// update user meta
update_user_meta( $matches[1], $meta_key_prefix . $matches[2], $row['option_value'] );
}
}
// clear up some memory ( aprox 14 kb )
unset( $option_rows );
// remove $option_row_ids
if( $option_row_ids )
{
$option_row_ids = implode(', ', $option_row_ids);
$wpdb->query("DELETE FROM $wpdb->options WHERE option_id IN ($option_row_ids)");
}
// update version
update_option('acf_version','3.4.1');
$return = array(
'status' => true,
'message' => $message,
'next' => false,
);
break;
}
// return json
echo json_encode($return);
die;
}
}
new acf_upgrade();
?> | PHP |
<?php
/*
* get_field_reference()
*
* This function will find the $field_key that is related to the $field_name.
* This is know as the field value reference
*
* @type function
* @since 3.6
* @date 29/01/13
*
* @param mixed $field_name: the name of the field - 'sub_heading'
* @param int $post_id: the post_id of which the value is saved against
*
* @return string $return: a string containing the field_key
*/
function get_field_reference( $field_name, $post_id ) {
// cache
$found = false;
$cache = wp_cache_get( 'field_reference/post_id=' . $post_id . '/name=' . $field_name, 'acf', false, $found );
if( $found )
{
return $cache;
}
// vars
$return = '';
// get field key
if( is_numeric($post_id) )
{
$return = get_post_meta($post_id, '_' . $field_name, true);
}
elseif( strpos($post_id, 'user_') !== false )
{
$temp_post_id = str_replace('user_', '', $post_id);
$return = get_user_meta($temp_post_id, '_' . $field_name, true);
}
else
{
$return = get_option('_' . $post_id . '_' . $field_name);
}
// set cache
wp_cache_set( 'field_reference/post_id=' . $post_id . '/name=' . $field_name, $return, 'acf' );
// return
return $return;
}
/*
* get_field_objects()
*
* This function will return an array containing all the custom field objects for a specific post_id.
* The function is not very elegant and wastes a lot of PHP memory / SQL queries if you are not using all the fields / values.
*
* @type function
* @since 3.6
* @date 29/01/13
*
* @param mixed $post_id: the post_id of which the value is saved against
*
* @return array $return: an array containin the field groups
*/
function get_field_objects( $post_id = false, $options = array() ) {
// global
global $wpdb;
// filter post_id
$post_id = apply_filters('acf/get_post_id', $post_id );
// vars
$field_key = '';
$value = array();
// get field_names
if( is_numeric($post_id) )
{
$keys = $wpdb->get_col($wpdb->prepare(
"SELECT meta_value FROM $wpdb->postmeta WHERE post_id = %d and meta_key LIKE %s AND meta_value LIKE %s",
$post_id,
'_%',
'field_%'
));
}
elseif( strpos($post_id, 'user_') !== false )
{
$user_id = str_replace('user_', '', $post_id);
$keys = $wpdb->get_col($wpdb->prepare(
"SELECT meta_value FROM $wpdb->usermeta WHERE user_id = %d and meta_key LIKE %s AND meta_value LIKE %s",
$user_id,
'_%',
'field_%'
));
}
else
{
$keys = $wpdb->get_col($wpdb->prepare(
"SELECT option_value FROM $wpdb->options WHERE option_name LIKE %s",
'_' . $post_id . '_%'
));
}
if( is_array($keys) )
{
foreach( $keys as $key )
{
$field = get_field_object( $key, $post_id, $options );
if( !is_array($field) )
{
continue;
}
$value[ $field['name'] ] = $field;
}
}
// no value
if( empty($value) )
{
return false;
}
// return
return $value;
}
/*
* get_fields()
*
* This function will return an array containing all the custom field values for a specific post_id.
* The function is not very elegant and wastes a lot of PHP memory / SQL queries if you are not using all the values.
*
* @type function
* @since 3.6
* @date 29/01/13
*
* @param mixed $post_id: the post_id of which the value is saved against
*
* @return array $return: an array containin the field values
*/
function get_fields( $post_id = false, $format_value = true ) {
// vars
$options = array(
'load_value' => true,
'format_value' => $format_value
);
$fields = get_field_objects( $post_id, $options );
if( is_array($fields) )
{
foreach( $fields as $k => $field )
{
$fields[ $k ] = $field['value'];
}
}
return $fields;
}
/*
* get_field()
*
* This function will return a custom field value for a specific field name/key + post_id.
* There is a 3rd parameter to turn on/off formating. This means that an Image field will not use
* its 'return option' to format the value but return only what was saved in the database
*
* @type function
* @since 3.6
* @date 29/01/13
*
* @param string $field_key: string containing the name of teh field name / key ('sub_field' / 'field_1')
* @param mixed $post_id: the post_id of which the value is saved against
* @param boolean $format_value: whether or not to format the value as described above
*
* @return mixed $value: the value found
*/
function get_field( $field_key, $post_id = false, $format_value = true ) {
// vars
$return = false;
$options = array(
'load_value' => true,
'format_value' => $format_value
);
$field = get_field_object( $field_key, $post_id, $options);
if( is_array($field) )
{
$return = $field['value'];
}
return $return;
}
/*
* get_field_object()
*
* This function will return an array containing all the field data for a given field_name
*
* @type function
* @since 3.6
* @date 3/02/13
*
* @param string $field_key: string containing the name of teh field name / key ('sub_field' / 'field_1')
* @param mixed $post_id: the post_id of which the value is saved against
* @param array $options: an array containing options
* boolean + load_value: load the field value or not. Defaults to true
* boolean + format_value: format the field value or not. Defaults to true
*
* @return array $return: an array containin the field groups
*/
function get_field_object( $field_key, $post_id = false, $options = array() ) {
// make sure add-ons are included
acf()->include_3rd_party();
// filter post_id
$post_id = apply_filters('acf/get_post_id', $post_id );
$field = false;
$orig_field_key = $field_key;
// defaults for options
$defaults = array(
'load_value' => true,
'format_value' => true,
);
$options = array_merge($defaults, $options);
// is $field_name a name? pre 3.4.0
if( substr($field_key, 0, 6) !== 'field_' )
{
// get field key
$field_key = get_field_reference( $field_key, $post_id );
}
// get field
if( substr($field_key, 0, 6) === 'field_' )
{
$field = apply_filters('acf/load_field', false, $field_key );
}
// validate field
if( !$field )
{
// treat as text field
$field = array(
'type' => 'text',
'name' => $orig_field_key,
'key' => 'field_' . $orig_field_key,
);
$field = apply_filters('acf/load_field', $field, $field['key'] );
}
// load value
if( $options['load_value'] )
{
$field['value'] = apply_filters('acf/load_value', false, $post_id, $field);
// format value
if( $options['format_value'] )
{
$field['value'] = apply_filters('acf/format_value_for_api', $field['value'], $post_id, $field);
}
}
return $field;
}
/*
* the_field()
*
* This function is the same as echo get_field().
*
* @type function
* @since 1.0.3
* @date 29/01/13
*
* @param string $field_name: the name of the field - 'sub_heading'
* @param mixed $post_id: the post_id of which the value is saved against
*
* @return string $value
*/
function the_field( $field_name, $post_id = false ) {
$value = get_field($field_name, $post_id);
if( is_array($value) )
{
$value = @implode(', ',$value);
}
echo $value;
}
/*
* have_rows
*
* This function will instantiate a global variable containing the rows of a repeater or flexible content field,
* afterwhich, it will determin if another row exists to loop through
*
* @type function
* @date 2/09/13
* @since 4.3.0
*
* @param $field_name (string) the name of the field - 'images'
* @return $post_id (mixed) the post_id of which the value is saved against
*/
function have_rows( $field_name, $post_id = false ) {
// vars
$depth = 0;
$row = array();
$new_parent_loop = false;
$new_child_loop = false;
// reference
$_post_id = $post_id;
// filter post_id
$post_id = apply_filters('acf/get_post_id', $post_id );
// empty?
if( empty($GLOBALS['acf_field']) )
{
// reset
reset_rows( true );
// create a new loop
$new_parent_loop = true;
}
else
{
// vars
$row = end( $GLOBALS['acf_field'] );
$prev = prev( $GLOBALS['acf_field'] );
// If post_id has changed, this is most likely an archive loop
if( $post_id != $row['post_id'] )
{
if( $prev && $prev['post_id'] == $post_id )
{
// case: Change in $post_id was due to a nested loop ending
// action: move up one level through the loops
reset_rows();
}
elseif( empty($_post_id) && isset($row['value'][ $row['i'] ][ $field_name ]) )
{
// case: Change in $post_id was due to this being a nested loop and not specifying the $post_id
// action: move down one level into a new loop
$new_child_loop = true;
}
else
{
// case: Chang in $post_id is the most obvious, used in an WP_Query loop with multiple $post objects
// action: leave this current loop alone and create a new parent loop
$new_parent_loop = true;
}
}
elseif( $field_name != $row['name'] )
{
if( $prev && $prev['name'] == $field_name && $prev['post_id'] == $post_id )
{
// case: Change in $field_name was due to a nested loop ending
// action: move up one level through the loops
reset_rows();
}
elseif( isset($row['value'][ $row['i'] ][ $field_name ]) )
{
// case: Change in $field_name was due to this being a nested loop
// action: move down one level into a new loop
$new_child_loop = true;
}
else
{
// case: Chang in $field_name is the most obvious, this is a new loop for a different field within the $post
// action: leave this current loop alone and create a new parent loop
$new_parent_loop = true;
}
}
}
if( $new_parent_loop )
{
// vars
$f = get_field_object( $field_name, $post_id );
$v = $f['value'];
unset( $f['value'] );
// add row
$GLOBALS['acf_field'][] = array(
'name' => $field_name,
'value' => $v,
'field' => $f,
'i' => -1,
'post_id' => $post_id,
);
}
elseif( $new_child_loop )
{
// vars
$f = acf_get_child_field_from_parent_field( $field_name, $row['field'] );
$v = $row['value'][ $row['i'] ][ $field_name ];
$GLOBALS['acf_field'][] = array(
'name' => $field_name,
'value' => $v,
'field' => $f,
'i' => -1,
'post_id' => $post_id,
);
}
// update vars
$row = end( $GLOBALS['acf_field'] );
if( is_array($row['value']) && array_key_exists( $row['i']+1, $row['value'] ) )
{
// next row exists
return true;
}
// no next row!
reset_rows();
// return
return false;
}
/*
* the_row
*
* This function will progress the global repeater or flexible content value 1 row
*
* @type function
* @date 2/09/13
* @since 4.3.0
*
* @param N/A
* @return N/A
*/
function the_row() {
// vars
$depth = count( $GLOBALS['acf_field'] ) - 1;
// increase row
$GLOBALS['acf_field'][ $depth ]['i']++;
// get row
$value = $GLOBALS['acf_field'][ $depth ]['value'];
$i = $GLOBALS['acf_field'][ $depth ]['i'];
// return
return $value[ $i ];
}
/*
* reset_rows
*
* This function will find the current loop and unset it from the global array.
* To bo used when loop finishes or a break is used
*
* @type function
* @date 26/10/13
* @since 5.0.0
*
* @param $post_id (int)
* @return $post_id (int)
*/
function reset_rows( $hard_reset = false ) {
// completely destroy?
if( $hard_reset )
{
$GLOBALS['acf_field'] = array();
}
else
{
// vars
$depth = count( $GLOBALS['acf_field'] ) - 1;
// remove
unset( $GLOBALS['acf_field'][$depth] );
// refresh index
$GLOBALS['acf_field'] = array_values($GLOBALS['acf_field']);
}
// return
return true;
}
/*
* has_sub_field()
*
* This function is used inside a while loop to return either true or false (loop again or stop).
* When using a repeater or flexible content field, it will loop through the rows until
* there are none left or a break is detected
*
* @type function
* @since 1.0.3
* @date 29/01/13
*
* @param string $field_name: the name of the field - 'sub_heading'
* @param mixed $post_id: the post_id of which the value is saved against
*
* @return bool
*/
function has_sub_field( $field_name, $post_id = false ) {
// vars
$r = have_rows( $field_name, $post_id );
// if has rows, progress through 1 row for the while loop to work
if( $r )
{
the_row();
}
// return
return $r;
}
/*
* has_sub_fields()
*
* This function is a replica of 'has_sub_field'
*
* @type function
* @since 4.0.0
* @date 29/01/13
*
* @param string $field_name: the name of the field - 'sub_heading'
* @param mixed $post_id: the post_id of which the value is saved against
*
* @return bool
*/
function has_sub_fields( $field_name, $post_id = false )
{
return has_sub_field( $field_name, $post_id );
}
/*
* get_sub_field()
*
* This function is used inside a 'has_sub_field' while loop to return a sub field value
*
* @type function
* @since 1.0.3
* @date 29/01/13
*
* @param string $field_name: the name of the field - 'sub_heading'
*
* @return mixed $value
*/
function get_sub_field( $field_name ) {
// no field?
if( empty($GLOBALS['acf_field']) )
{
return false;
}
// vars
$row = end( $GLOBALS['acf_field'] );
// return value
if( isset($row['value'][ $row['i'] ][ $field_name ]) )
{
return $row['value'][ $row['i'] ][ $field_name ];
}
// return false
return false;
}
/*
* get_sub_field()
*
* This function is the same as echo get_sub_field
*
* @type function
* @since 1.0.3
* @date 29/01/13
*
* @param string $field_name: the name of the field - 'sub_heading'
*
* @return string $value
*/
function the_sub_field($field_name)
{
$value = get_sub_field($field_name);
if(is_array($value))
{
$value = implode(', ',$value);
}
echo $value;
}
/*
* get_sub_field_object()
*
* This function is used inside a 'has_sub_field' while loop to return a sub field object
*
* @type function
* @since 3.5.8.1
* @date 29/01/13
*
* @param string $field_name: the name of the field - 'sub_heading'
*
* @return array $sub_field
*/
function get_sub_field_object( $child_name )
{
// no field?
if( empty($GLOBALS['acf_field']) )
{
return false;
}
// vars
$depth = count( $GLOBALS['acf_field'] ) - 1;
$parent = $GLOBALS['acf_field'][$depth]['field'];
// return
return acf_get_child_field_from_parent_field( $child_name, $parent );
}
/*
* acf_get_sub_field_from_parent_field()
*
* This function is used by the get_sub_field_object to find a sub field within a parent field
*
* @type function
* @since 3.5.8.1
* @date 29/01/13
*
* @param string $child_name: the name of the field - 'sub_heading'
* @param array $parent: the parent field object
*
* @return array $sub_field
*/
function acf_get_child_field_from_parent_field( $child_name, $parent )
{
// vars
$return = false;
// find child
if( isset($parent['sub_fields']) && is_array($parent['sub_fields']) )
{
foreach( $parent['sub_fields'] as $child )
{
if( $child['name'] == $child_name || $child['key'] == $child_name )
{
$return = $child;
break;
}
// perhaps child has grand children?
$grand_child = acf_get_child_field_from_parent_field( $child_name, $child );
if( $grand_child )
{
$return = $grand_child;
break;
}
}
}
elseif( isset($parent['layouts']) && is_array($parent['layouts']) )
{
foreach( $parent['layouts'] as $layout )
{
$child = acf_get_child_field_from_parent_field( $child_name, $layout );
if( $child )
{
$return = $child;
break;
}
}
}
// return
return $return;
}
/*
* register_field_group()
*
* This function is used to register a field group via code. It acceps 1 array containing
* all the field group data. This data can be obtained by using teh export tool within ACF
*
* @type function
* @since 3.0.6
* @date 29/01/13
*
* @param array $array: an array holding all the field group data
*
* @return
*/
$GLOBALS['acf_register_field_group'] = array();
function register_field_group( $array )
{
// add id
if( !isset($array['id']) )
{
$array['id'] = uniqid();
}
// 3.2.5 - changed show_on_page option
if( !isset($array['options']['hide_on_screen']) && isset($array['options']['show_on_page']) )
{
$show_all = array('the_content', 'discussion', 'custom_fields', 'comments', 'slug', 'author');
$array['options']['hide_on_screen'] = array_diff($show_all, $array['options']['show_on_page']);
unset( $array['options']['show_on_page'] );
}
// 4.0.4 - changed location rules architecture
if( isset($array['location']['rules']) )
{
// vars
$groups = array();
$group_no = 0;
if( is_array($array['location']['rules']) )
{
foreach( $array['location']['rules'] as $rule )
{
$rule['group_no'] = $group_no;
// sperate groups?
if( $array['location']['allorany'] == 'any' )
{
$group_no++;
}
// add to group
$groups[ $rule['group_no'] ][ $rule['order_no'] ] = $rule;
// sort rules
ksort( $groups[ $rule['group_no'] ] );
}
// sort groups
ksort( $groups );
}
$array['location'] = $groups;
}
$GLOBALS['acf_register_field_group'][] = $array;
}
add_filter('acf/get_field_groups', 'api_acf_get_field_groups', 2, 1);
function api_acf_get_field_groups( $return )
{
// validate
if( empty($GLOBALS['acf_register_field_group']) )
{
return $return;
}
foreach( $GLOBALS['acf_register_field_group'] as $acf )
{
$return[] = array(
'id' => $acf['id'],
'title' => $acf['title'],
'menu_order' => $acf['menu_order'],
);
}
// order field groups based on menu_order, title
// Obtain a list of columns
foreach( $return as $key => $row )
{
$menu_order[ $key ] = $row['menu_order'];
$title[ $key ] = $row['title'];
}
// Sort the array with menu_order ascending
// Add $array as the last parameter, to sort by the common key
if(isset($menu_order))
{
array_multisort($menu_order, SORT_ASC, $title, SORT_ASC, $return);
}
return $return;
}
add_filter('acf/field_group/get_fields', 'api_acf_field_group_get_fields', 1, 2);
function api_acf_field_group_get_fields( $fields, $post_id )
{
// validate
if( !empty($GLOBALS['acf_register_field_group']) )
{
foreach( $GLOBALS['acf_register_field_group'] as $acf )
{
if( $acf['id'] == $post_id )
{
foreach( $acf['fields'] as $f )
{
$fields[] = apply_filters('acf/load_field', $f, $f['key']);
}
break;
}
}
}
return $fields;
}
add_filter('acf/load_field', 'api_acf_load_field', 1, 2);
function api_acf_load_field( $field, $field_key )
{
// validate
if( !empty($GLOBALS['acf_register_field_group']) )
{
foreach( $GLOBALS['acf_register_field_group'] as $acf )
{
if( !empty($acf['fields']) )
{
foreach( $acf['fields'] as $f )
{
if( $f['key'] == $field_key )
{
$field = $f;
break;
}
}
}
}
}
return $field;
}
add_filter('acf/field_group/get_location', 'api_acf_field_group_get_location', 1, 2);
function api_acf_field_group_get_location( $location, $post_id )
{
// validate
if( !empty($GLOBALS['acf_register_field_group']) )
{
foreach( $GLOBALS['acf_register_field_group'] as $acf )
{
if( $acf['id'] == $post_id )
{
$location = $acf['location'];
break;
}
}
}
return $location;
}
add_filter('acf/field_group/get_options', 'api_acf_field_group_get_options', 1, 2);
function api_acf_field_group_get_options( $options, $post_id )
{
// validate
if( !empty($GLOBALS['acf_register_field_group']) )
{
foreach( $GLOBALS['acf_register_field_group'] as $acf )
{
if( $acf['id'] == $post_id )
{
$options = $acf['options'];
break;
}
}
}
return $options;
}
/*
* get_row_layout()
*
* This function will return a string representation of the current row layout within a 'has_sub_field' loop
*
* @type function
* @since 3.0.6
* @date 29/01/13
*
* @return $value - string containing the layout
*/
function get_row_layout()
{
// vars
$value = get_sub_field('acf_fc_layout');
return $value;
}
/*
* acf_shortcode()
*
* This function is used to add basic shortcode support for the ACF plugin
*
* @type function
* @since 1.1.1
* @date 29/01/13
*
* @param array $atts: an array holding the shortcode options
* string + field: the field name
* mixed + post_id: the post_id to load from
*
* @return string $value: the value found by get_field
*/
function acf_shortcode( $atts )
{
// extract attributs
extract( shortcode_atts( array(
'field' => "",
'post_id' => false,
), $atts ) );
// $field is requird
if( !$field || $field == "" )
{
return "";
}
// get value and return it
$value = get_field( $field, $post_id );
if( is_array($value) )
{
$value = @implode( ', ',$value );
}
return $value;
}
add_shortcode( 'acf', 'acf_shortcode' );
/*
* acf_form_head()
*
* This function is placed at the very top of a template (before any HTML is rendered) and saves the $_POST data sent by acf_form.
*
* @type function
* @since 1.1.4
* @date 29/01/13
*
* @param N/A
*
* @return N/A
*/
function acf_form_head()
{
// global vars
global $post_id;
// verify nonce
if( isset($_POST['acf_nonce']) && wp_verify_nonce($_POST['acf_nonce'], 'input') )
{
// $post_id to save against
$post_id = $_POST['post_id'];
// allow for custom save
$post_id = apply_filters('acf/pre_save_post', $post_id);
// save the data
do_action('acf/save_post', $post_id);
// redirect
if(isset($_POST['return']))
{
wp_redirect($_POST['return']);
exit;
}
}
// need wp styling
wp_enqueue_style(array(
'colors-fresh'
));
// actions
do_action('acf/input/admin_enqueue_scripts');
add_action('wp_head', 'acf_form_wp_head');
}
function acf_form_wp_head()
{
do_action('acf/input/admin_head');
}
/*
* acf_form()
*
* This function is used to create an ACF form.
*
* @type function
* @since 1.1.4
* @date 29/01/13
*
* @param array $options: an array containing many options to customize the form
* string + post_id: post id to get field groups from and save data to. Default is false
* array + field_groups: an array containing field group ID's. If this option is set,
* the post_id will not be used to dynamically find the field groups
* boolean + form: display the form tag or not. Defaults to true
* array + form_attributes: an array containg attributes which will be added into the form tag
* string + return: the return URL
* string + html_before_fields: html inside form before fields
* string + html_after_fields: html inside form after fields
* string + submit_value: value of submit button
* string + updated_message: default updated message. Can be false
*
* @return N/A
*/
function acf_form( $options = array() )
{
global $post;
// defaults
$defaults = array(
'post_id' => false,
'field_groups' => array(),
'form' => true,
'form_attributes' => array(
'id' => 'post',
'class' => '',
'action' => '',
'method' => 'post',
),
'return' => add_query_arg( 'updated', 'true', get_permalink() ),
'html_before_fields' => '',
'html_after_fields' => '',
'submit_value' => __("Update", 'acf'),
'updated_message' => __("Post updated", 'acf'),
);
// merge defaults with options
$options = array_merge($defaults, $options);
// merge sub arrays
foreach( $options as $k => $v )
{
if( is_array($v) )
{
$options[ $k ] = array_merge($defaults[ $k ], $options[ $k ]);
}
}
// filter post_id
$options['post_id'] = apply_filters('acf/get_post_id', $options['post_id'] );
// attributes
$options['form_attributes']['class'] .= 'acf-form';
// register post box
if( empty($options['field_groups']) )
{
// get field groups
$filter = array(
'post_id' => $options['post_id']
);
if( strpos($options['post_id'], 'user_') !== false )
{
$user_id = str_replace('user_', '', $options['post_id']);
$filter = array(
'ef_user' => $user_id
);
}
elseif( strpos($options['post_id'], 'taxonomy_') !== false )
{
$taxonomy_id = str_replace('taxonomy_', '', $options['post_id']);
$filter = array(
'ef_taxonomy' => $taxonomy_id
);
}
$options['field_groups'] = array();
$options['field_groups'] = apply_filters( 'acf/location/match_field_groups', $options['field_groups'], $filter );
}
// updated message
if(isset($_GET['updated']) && $_GET['updated'] == 'true' && $options['updated_message'])
{
echo '<div id="message" class="updated"><p>' . $options['updated_message'] . '</p></div>';
}
// display form
if( $options['form'] ): ?>
<form <?php if($options['form_attributes']){foreach($options['form_attributes'] as $k => $v){echo $k . '="' . $v .'" '; }} ?>>
<?php endif; ?>
<div style="display:none">
<script type="text/javascript">
acf.o.post_id = <?php echo is_numeric($options['post_id']) ? $options['post_id'] : '"' . $options['post_id'] . '"'; ?>;
</script>
<input type="hidden" name="acf_nonce" value="<?php echo wp_create_nonce( 'input' ); ?>" />
<input type="hidden" name="post_id" value="<?php echo $options['post_id']; ?>" />
<input type="hidden" name="return" value="<?php echo $options['return']; ?>" />
<?php wp_editor('', 'acf_settings'); ?>
</div>
<div id="poststuff">
<?php
// html before fields
echo $options['html_before_fields'];
$acfs = apply_filters('acf/get_field_groups', array());
if( is_array($acfs) ){ foreach( $acfs as $acf ){
// only add the chosen field groups
if( !in_array( $acf['id'], $options['field_groups'] ) )
{
continue;
}
// load options
$acf['options'] = apply_filters('acf/field_group/get_options', array(), $acf['id']);
// load fields
$fields = apply_filters('acf/field_group/get_fields', array(), $acf['id']);
echo '<div id="acf_' . $acf['id'] . '" class="postbox acf_postbox ' . $acf['options']['layout'] . '">';
echo '<h3 class="hndle"><span>' . $acf['title'] . '</span></h3>';
echo '<div class="inside">';
do_action('acf/create_fields', $fields, $options['post_id']);
echo '</div></div>';
}}
// html after fields
echo $options['html_after_fields'];
?>
<?php if( $options['form'] ): ?>
<!-- Submit -->
<div class="field">
<input type="submit" value="<?php echo $options['submit_value']; ?>" />
</div>
<!-- / Submit -->
<?php endif; ?>
</div><!-- <div id="poststuff"> -->
<?php if( $options['form'] ): ?>
</form>
<?php endif;
}
/*
* update_field()
*
* This function will update a value in the database
*
* @type function
* @since 3.1.9
* @date 29/01/13
*
* @param mixed $field_name: the name of the field - 'sub_heading'
* @param mixed $value: the value to save in the database. The variable type is dependant on the field type
* @param mixed $post_id: the post_id of which the value is saved against
*
* @return N/A
*/
function update_field( $field_key, $value, $post_id = false )
{
// filter post_id
$post_id = apply_filters('acf/get_post_id', $post_id );
// vars
$options = array(
'load_value' => false,
'format_value' => false
);
$field = get_field_object( $field_key, $post_id, $options);
// sub fields? They need formatted data
if( $field['type'] == 'repeater' )
{
$value = acf_convert_field_names_to_keys( $value, $field );
}
elseif( $field['type'] == 'flexible_content' )
{
if( $field['layouts'] )
{
foreach( $field['layouts'] as $layout )
{
$value = acf_convert_field_names_to_keys( $value, $layout );
}
}
}
// save
do_action('acf/update_value', $value, $post_id, $field );
return true;
}
/*
* delete_field()
*
* This function will remove a value from the database
*
* @type function
* @since 3.1.9
* @date 29/01/13
*
* @param mixed $field_name: the name of the field - 'sub_heading'
* @param mixed $post_id: the post_id of which the value is saved against
*
* @return N/A
*/
function delete_field( $field_name, $post_id )
{
do_action('acf/delete_value', $post_id, $field_name );
}
/*
* create_field()
*
* This function will creat the HTML for a field
*
* @type function
* @since 4.0.0
* @date 17/03/13
*
* @param array $field - an array containing all the field attributes
*
* @return N/A
*/
function create_field( $field )
{
do_action('acf/create_field', $field );
}
/*
* acf_convert_field_names_to_keys()
*
* Helper for the update_field function
*
* @type function
* @since 4.0.0
* @date 17/03/13
*
* @param array $value: the value returned via get_field
* @param array $field: the field or layout to find sub fields from
*
* @return N/A
*/
function acf_convert_field_names_to_keys( $value, $field )
{
// only if $field has sub fields
if( !isset($field['sub_fields']) )
{
return $value;
}
// define sub field keys
$sub_fields = array();
if( $field['sub_fields'] )
{
foreach( $field['sub_fields'] as $sub_field )
{
$sub_fields[ $sub_field['name'] ] = $sub_field;
}
}
// loop through the values and format the array to use sub field keys
if( is_array($value) )
{
foreach( $value as $row_i => $row)
{
if( $row )
{
foreach( $row as $sub_field_name => $sub_field_value )
{
// sub field must exist!
if( !isset($sub_fields[ $sub_field_name ]) )
{
continue;
}
// vars
$sub_field = $sub_fields[ $sub_field_name ];
$sub_field_value = acf_convert_field_names_to_keys( $sub_field_value, $sub_field );
// set new value
$value[$row_i][ $sub_field['key'] ] = $sub_field_value;
// unset old value
unset( $value[$row_i][$sub_field_name] );
}
// foreach( $row as $sub_field_name => $sub_field_value )
}
// if( $row )
}
// foreach( $value as $row_i => $row)
}
// if( $value )
return $value;
}
/*
* Depreceated Functions
*
* @description:
* @created: 23/07/12
*/
/*--------------------------------------------------------------------------------------
*
* reset_the_repeater_field
*
* @author Elliot Condon
* @depreciated: 3.3.4 - now use has_sub_field
* @since 1.0.3
*
*-------------------------------------------------------------------------------------*/
function reset_the_repeater_field()
{
// do nothing
}
/*--------------------------------------------------------------------------------------
*
* the_repeater_field
*
* @author Elliot Condon
* @depreciated: 3.3.4 - now use has_sub_field
* @since 1.0.3
*
*-------------------------------------------------------------------------------------*/
function the_repeater_field($field_name, $post_id = false)
{
return has_sub_field($field_name, $post_id);
}
/*--------------------------------------------------------------------------------------
*
* the_flexible_field
*
* @author Elliot Condon
* @depreciated: 3.3.4 - now use has_sub_field
* @since 3.?.?
*
*-------------------------------------------------------------------------------------*/
function the_flexible_field($field_name, $post_id = false)
{
return has_sub_field($field_name, $post_id);
}
/*
* acf_filter_post_id()
*
* This is a deprecated function which is now run through a filter
*
* @type function
* @since 3.6
* @date 29/01/13
*
* @param mixed $post_id
*
* @return mixed $post_id
*/
function acf_filter_post_id( $post_id )
{
return apply_filters('acf/get_post_id', $post_id );
}
?> | PHP |
<?php
/*
Plugin Name: Advanced Custom Fields
Plugin URI: http://www.advancedcustomfields.com/
Description: Fully customise WordPress edit screens with powerful fields. Boasting a professional interface and a powerful API, it’s a must have for any web developer working with WordPress. Field types include: Wysiwyg, text, textarea, image, file, select, checkbox, page link, post object, date picker, color picker, repeater, flexible content, gallery and more!
Version: 4.3.8
Author: Elliot Condon
Author URI: http://www.elliotcondon.com/
License: GPL
Copyright: Elliot Condon
*/
if( !class_exists('acf') ):
class acf
{
// vars
var $settings;
/*
* Constructor
*
* This function will construct all the neccessary actions, filters and functions for the ACF plugin to work
*
* @type function
* @date 23/06/12
* @since 1.0.0
*
* @param N/A
* @return N/A
*/
function __construct()
{
// helpers
add_filter('acf/helpers/get_path', array($this, 'helpers_get_path'), 1, 1);
add_filter('acf/helpers/get_dir', array($this, 'helpers_get_dir'), 1, 1);
// vars
$this->settings = array(
'path' => apply_filters('acf/helpers/get_path', __FILE__),
'dir' => apply_filters('acf/helpers/get_dir', __FILE__),
'hook' => basename( dirname( __FILE__ ) ) . '/' . basename( __FILE__ ),
'version' => '4.3.8',
'upgrade_version' => '3.4.1',
'include_3rd_party' => false
);
// set text domain
load_textdomain('acf', $this->settings['path'] . 'lang/acf-' . get_locale() . '.mo');
// actions
add_action('init', array($this, 'init'), 1);
add_action('acf/pre_save_post', array($this, 'save_post_lock'), 0);
add_action('acf/pre_save_post', array($this, 'save_post_unlock'), 999);
add_action('acf/save_post', array($this, 'save_post_lock'), 0);
add_action('acf/save_post', array($this, 'save_post'), 10);
add_action('acf/save_post', array($this, 'save_post_unlock'), 999);
add_action('acf/create_fields', array($this, 'create_fields'), 1, 2);
// filters
add_filter('acf/get_info', array($this, 'get_info'), 1, 1);
add_filter('acf/parse_types', array($this, 'parse_types'), 1, 1);
add_filter('acf/get_post_types', array($this, 'get_post_types'), 1, 3);
add_filter('acf/get_taxonomies_for_select', array($this, 'get_taxonomies_for_select'), 1, 2);
add_filter('acf/get_image_sizes', array($this, 'get_image_sizes'), 1, 1);
add_filter('acf/get_post_id', array($this, 'get_post_id'), 1, 1);
// includes
$this->include_before_theme();
add_action('after_setup_theme', array($this, 'include_after_theme'), 1);
add_action('after_setup_theme', array($this, 'include_3rd_party'), 1);
}
/*
* helpers_get_path
*
* This function will calculate the path to a file
*
* @type function
* @date 30/01/13
* @since 3.6.0
*
* @param $file (file) a reference to the file
* @return (string)
*/
function helpers_get_path( $file )
{
return trailingslashit(dirname($file));
}
/*
* helpers_get_dir
*
* This function will calculate the directory (URL) to a file
*
* @type function
* @date 30/01/13
* @since 3.6.0
*
* @param $file (file) a reference to the file
* @return (string)
*/
function helpers_get_dir( $file )
{
$dir = trailingslashit(dirname($file));
$count = 0;
// sanitize for Win32 installs
$dir = str_replace('\\' ,'/', $dir);
// if file is in plugins folder
$wp_plugin_dir = str_replace('\\' ,'/', WP_PLUGIN_DIR);
$dir = str_replace($wp_plugin_dir, plugins_url(), $dir, $count);
if( $count < 1 )
{
// if file is in wp-content folder
$wp_content_dir = str_replace('\\' ,'/', WP_CONTENT_DIR);
$dir = str_replace($wp_content_dir, content_url(), $dir, $count);
}
if( $count < 1 )
{
// if file is in ??? folder
$wp_dir = str_replace('\\' ,'/', ABSPATH);
$dir = str_replace($wp_dir, site_url('/'), $dir);
}
return $dir;
}
/*
* acf/get_post_id
*
* A helper function to filter the post_id variable.
*
* @type filter
* @date 27/05/13
*
* @param {mixed} $post_id
* @return {mixed} $post_id
*/
function get_post_id( $post_id )
{
// set post_id to global
if( !$post_id )
{
global $post;
if( $post )
{
$post_id = intval( $post->ID );
}
}
// allow for option == options
if( $post_id == "option" )
{
$post_id = "options";
}
// object
if( is_object($post_id) )
{
if( isset($post_id->roles, $post_id->ID) )
{
$post_id = 'user_' . $post_id->ID;
}
elseif( isset($post_id->taxonomy, $post_id->term_id) )
{
$post_id = $post_id->taxonomy . '_' . $post_id->term_id;
}
elseif( isset($post_id->ID) )
{
$post_id = $post_id->ID;
}
}
/*
* Override for preview
*
* If the $_GET['preview_id'] is set, then the user wants to see the preview data.
* There is also the case of previewing a page with post_id = 1, but using get_field
* to load data from another post_id.
* In this case, we need to make sure that the autosave revision is actually related
* to the $post_id variable. If they match, then the autosave data will be used, otherwise,
* the user wants to load data from a completely different post_id
*/
if( isset($_GET['preview_id']) )
{
$autosave = wp_get_post_autosave( $_GET['preview_id'] );
if( $autosave->post_parent == $post_id )
{
$post_id = intval( $autosave->ID );
}
}
// return
return $post_id;
}
/*
* get_info
*
* This function will return a setting from the settings array
*
* @type function
* @date 24/01/13
* @since 3.6.0
*
* @param $i (string) the setting to get
* @return (mixed)
*/
function get_info( $i )
{
// vars
$return = false;
// specific
if( isset($this->settings[ $i ]) )
{
$return = $this->settings[ $i ];
}
// all
if( $i == 'all' )
{
$return = $this->settings;
}
// return
return $return;
}
/*
* parse_types
*
* @description: helper function to set the 'types' of variables
* @since: 2.0.4
* @created: 9/12/12
*/
function parse_types( $value )
{
// vars
$restricted = array(
'label',
'name',
'_name',
'value',
'instructions'
);
// is value another array?
if( is_array($value) )
{
foreach( $value as $k => $v )
{
// bail early for restricted pieces
if( in_array($k, $restricted, true) )
{
continue;
}
// filter piece
$value[ $k ] = apply_filters( 'acf/parse_types', $v );
}
}
else
{
// string
if( is_string($value) )
{
$value = trim( $value );
}
// numbers
if( is_numeric($value) )
{
// check for non numeric characters
if( preg_match('/[^0-9]/', $value) )
{
// leave value if it contains such characters: . + - e
//$value = floatval( $value );
}
else
{
$value = intval( $value );
}
}
}
// return
return $value;
}
/*
* include_before_theme
*
* This function will include core files before the theme's functions.php file has been excecuted.
*
* @type action (plugins_loaded)
* @date 3/09/13
* @since 4.3.0
*
* @param N/A
* @return N/A
*/
function include_before_theme()
{
// incudes
include_once('core/api.php');
include_once('core/controllers/input.php');
include_once('core/controllers/location.php');
include_once('core/controllers/field_group.php');
// admin only includes
if( is_admin() )
{
include_once('core/controllers/post.php');
include_once('core/controllers/revisions.php');
include_once('core/controllers/everything_fields.php');
include_once('core/controllers/field_groups.php');
}
// register fields
include_once('core/fields/_functions.php');
include_once('core/fields/_base.php');
include_once('core/fields/text.php');
include_once('core/fields/textarea.php');
include_once('core/fields/number.php');
include_once('core/fields/email.php');
include_once('core/fields/password.php');
include_once('core/fields/wysiwyg.php');
include_once('core/fields/image.php');
include_once('core/fields/file.php');
include_once('core/fields/select.php');
include_once('core/fields/checkbox.php');
include_once('core/fields/radio.php');
include_once('core/fields/true_false.php');
include_once('core/fields/page_link.php');
include_once('core/fields/post_object.php');
include_once('core/fields/relationship.php');
include_once('core/fields/taxonomy.php');
include_once('core/fields/user.php');
include_once('core/fields/google-map.php');
include_once('core/fields/date_picker/date_picker.php');
include_once('core/fields/color_picker.php');
include_once('core/fields/message.php');
include_once('core/fields/tab.php');
}
/*
* include_3rd_party
*
* This function will include 3rd party add-ons
*
* @type function
* @date 29/01/2014
* @since 5.0.0
*
* @param N/A
* @return N/A
*/
function include_3rd_party() {
// run only once
if( $this->settings['include_3rd_party'] )
{
return false;
}
// update setting
$this->settings['include_3rd_party'] = true;
// include 3rd party fields
do_action('acf/register_fields');
}
/*
* include_after_theme
*
* This function will include core files after the theme's functions.php file has been excecuted.
*
* @type action (after_setup_theme)
* @date 3/09/13
* @since 4.3.0
*
* @param N/A
* @return N/A
*/
function include_after_theme() {
// bail early if user has defined LITE_MODE as true
if( defined('ACF_LITE') && ACF_LITE )
{
return;
}
// admin only includes
if( is_admin() )
{
include_once('core/controllers/export.php');
include_once('core/controllers/addons.php');
include_once('core/controllers/third_party.php');
include_once('core/controllers/upgrade.php');
}
}
/*
* init
*
* This function is called during the 'init' action and will do things such as:
* create post_type, register scripts, add actions / filters
*
* @type action (init)
* @date 23/06/12
* @since 1.0.0
*
* @param N/A
* @return N/A
*/
function init()
{
// Create ACF post type
$labels = array(
'name' => __( 'Field Groups', 'acf' ),
'singular_name' => __( 'Advanced Custom Fields', 'acf' ),
'add_new' => __( 'Add New' , 'acf' ),
'add_new_item' => __( 'Add New Field Group' , 'acf' ),
'edit_item' => __( 'Edit Field Group' , 'acf' ),
'new_item' => __( 'New Field Group' , 'acf' ),
'view_item' => __('View Field Group', 'acf'),
'search_items' => __('Search Field Groups', 'acf'),
'not_found' => __('No Field Groups found', 'acf'),
'not_found_in_trash' => __('No Field Groups found in Trash', 'acf'),
);
register_post_type('acf', array(
'labels' => $labels,
'public' => false,
'show_ui' => true,
'_builtin' => false,
'capability_type' => 'page',
'hierarchical' => true,
'rewrite' => false,
'query_var' => "acf",
'supports' => array(
'title',
),
'show_in_menu' => false,
));
// min
$min = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';
// register acf scripts
$scripts = array();
$scripts[] = array(
'handle' => 'acf-field-group',
'src' => $this->settings['dir'] . "js/field-group{$min}.js",
'deps' => array('jquery')
);
$scripts[] = array(
'handle' => 'acf-input',
'src' => $this->settings['dir'] . "js/input{$min}.js",
'deps' => array('jquery', 'jquery-ui-core', 'jquery-ui-datepicker')
);
foreach( $scripts as $script )
{
wp_register_script( $script['handle'], $script['src'], $script['deps'], $this->settings['version'] );
}
// register acf styles
$styles = array(
'acf' => $this->settings['dir'] . 'css/acf.css',
'acf-field-group' => $this->settings['dir'] . 'css/field-group.css',
'acf-global' => $this->settings['dir'] . 'css/global.css',
'acf-input' => $this->settings['dir'] . 'css/input.css',
'acf-datepicker' => $this->settings['dir'] . 'core/fields/date_picker/style.date_picker.css',
);
foreach( $styles as $k => $v )
{
wp_register_style( $k, $v, false, $this->settings['version'] );
}
// bail early if user has defined LITE_MODE as true
if( defined('ACF_LITE') && ACF_LITE )
{
return;
}
// admin only
if( is_admin() )
{
add_action('admin_menu', array($this,'admin_menu'));
add_action('admin_head', array($this,'admin_head'));
add_filter('post_updated_messages', array($this, 'post_updated_messages'));
}
}
/*
* admin_menu
*
* @description:
* @since 1.0.0
* @created: 23/06/12
*/
function admin_menu()
{
add_menu_page(__("Custom Fields",'acf'), __("Custom Fields",'acf'), 'manage_options', 'edit.php?post_type=acf', false, false, '80.025');
}
/*
* post_updated_messages
*
* @description: messages for saving a field group
* @since 1.0.0
* @created: 23/06/12
*/
function post_updated_messages( $messages )
{
global $post, $post_ID;
$messages['acf'] = array(
0 => '', // Unused. Messages start at index 1.
1 => __('Field group updated.', 'acf'),
2 => __('Custom field updated.', 'acf'),
3 => __('Custom field deleted.', 'acf'),
4 => __('Field group updated.', 'acf'),
/* translators: %s: date and time of the revision */
5 => isset($_GET['revision']) ? sprintf( __('Field group restored to revision from %s', 'acf'), wp_post_revision_title( (int) $_GET['revision'], false ) ) : false,
6 => __('Field group published.', 'acf'),
7 => __('Field group saved.', 'acf'),
8 => __('Field group submitted.', 'acf'),
9 => __('Field group scheduled for.', 'acf'),
10 => __('Field group draft updated.', 'acf'),
);
return $messages;
}
/*--------------------------------------------------------------------------------------
*
* admin_head
*
* @author Elliot Condon
* @since 1.0.0
*
*-------------------------------------------------------------------------------------*/
function admin_head()
{
?>
<style type="text/css">
#adminmenu #toplevel_page_edit-post_type-acf a[href="edit.php?post_type=acf&page=acf-upgrade"]{ display: none; }
#adminmenu #toplevel_page_edit-post_type-acf .wp-menu-image { background-position: 1px -33px; }
#adminmenu #toplevel_page_edit-post_type-acf:hover .wp-menu-image,
#adminmenu #toplevel_page_edit-post_type-acf.wp-menu-open .wp-menu-image { background-position: 1px -1px; }
</style>
<?php
}
/*
* get_taxonomies_for_select
*
* @description:
* @since: 3.6
* @created: 27/01/13
*/
function get_taxonomies_for_select( $choices, $simple_value = false )
{
// vars
$post_types = get_post_types();
if($post_types)
{
foreach($post_types as $post_type)
{
$post_type_object = get_post_type_object($post_type);
$taxonomies = get_object_taxonomies($post_type);
if($taxonomies)
{
foreach($taxonomies as $taxonomy)
{
if(!is_taxonomy_hierarchical($taxonomy)) continue;
$terms = get_terms($taxonomy, array('hide_empty' => false));
if($terms)
{
foreach($terms as $term)
{
$value = $taxonomy . ':' . $term->term_id;
if( $simple_value )
{
$value = $term->term_id;
}
$choices[$post_type_object->label . ': ' . $taxonomy][$value] = $term->name;
}
}
}
}
}
}
return $choices;
}
/*
* get_post_types
*
* @description:
* @since: 3.5.5
* @created: 16/12/12
*/
function get_post_types( $post_types, $exclude = array(), $include = array() )
{
// get all custom post types
$post_types = array_merge($post_types, get_post_types());
// core include / exclude
$acf_includes = array_merge( array(), $include );
$acf_excludes = array_merge( array( 'acf', 'revision', 'nav_menu_item' ), $exclude );
// include
foreach( $acf_includes as $p )
{
if( post_type_exists($p) )
{
$post_types[ $p ] = $p;
}
}
// exclude
foreach( $acf_excludes as $p )
{
unset( $post_types[ $p ] );
}
return $post_types;
}
/*
* get_image_sizes
*
* @description: returns an array holding all the image sizes
* @since 3.2.8
* @created: 6/07/12
*/
function get_image_sizes( $sizes )
{
// find all sizes
$all_sizes = get_intermediate_image_sizes();
// define default sizes
$sizes = array_merge($sizes, array(
'thumbnail' => __("Thumbnail",'acf'),
'medium' => __("Medium",'acf'),
'large' => __("Large",'acf'),
'full' => __("Full",'acf')
));
// add extra registered sizes
foreach( $all_sizes as $size )
{
if( !isset($sizes[ $size ]) )
{
$sizes[ $size ] = ucwords( str_replace('-', ' ', $size) );
}
}
// return array
return $sizes;
}
/*
* render_fields_for_input
*
* @description:
* @since 3.1.6
* @created: 23/06/12
*/
function create_fields( $fields, $post_id )
{
if( is_array($fields) ){ foreach( $fields as $field ){
// if they didn't select a type, skip this field
if( !$field || !$field['type'] || $field['type'] == 'null' )
{
continue;
}
// set value
if( !isset($field['value']) )
{
$field['value'] = apply_filters('acf/load_value', false, $post_id, $field);
$field['value'] = apply_filters('acf/format_value', $field['value'], $post_id, $field);
}
// required
$required_class = "";
$required_label = "";
if( $field['required'] )
{
$required_class = ' required';
$required_label = ' <span class="required">*</span>';
}
echo '<div id="acf-' . $field['name'] . '" class="field field_type-' . $field['type'] . ' field_key-' . $field['key'] . $required_class . '" data-field_name="' . $field['name'] . '" data-field_key="' . $field['key'] . '" data-field_type="' . $field['type'] . '">';
echo '<p class="label">';
echo '<label for="' . $field['id'] . '">' . $field['label'] . $required_label . '</label>';
echo $field['instructions'];
echo '</p>';
$field['name'] = 'fields[' . $field['key'] . ']';
do_action('acf/create_field', $field, $post_id);
echo '</div>';
}}
}
/*
* save_post_lock
*
* This action sets a global variable which locks the ACF save functions to this ID.
* This prevents an inifinite loop if a user was to hook into the save and create a new post
*
* @type function
* @date 16/07/13
*
* @param {int} $post_id
* @return {int} $post_id
*/
function save_post_lock( $post_id )
{
$GLOBALS['acf_save_lock'] = $post_id;
return $post_id;
}
/*
* save_post_unlock
*
* This action sets a global variable which unlocks the ACF save functions to this ID.
* This prevents an inifinite loop if a user was to hook into the save and create a new post
*
* @type function
* @date 16/07/13
*
* @param {int} $post_id
* @return {int} $post_id
*/
function save_post_unlock( $post_id )
{
$GLOBALS['acf_save_lock'] = false;
return $post_id;
}
/*
* save_post
*
* @description:
* @since: 3.6
* @created: 28/01/13
*/
function save_post( $post_id )
{
// load from post
if( !isset($_POST['fields']) )
{
return $post_id;
}
// loop through and save
if( !empty($_POST['fields']) )
{
// loop through and save $_POST data
foreach( $_POST['fields'] as $k => $v )
{
// get field
$f = apply_filters('acf/load_field', false, $k );
// update field
do_action('acf/update_value', $v, $post_id, $f );
}
// foreach($fields as $key => $value)
}
// if($fields)
return $post_id;
}
}
/*
* acf
*
* The main function responsible for returning the one true acf Instance to functions everywhere.
* Use this function like you would a global variable, except without needing to declare the global.
*
* Example: <?php $acf = acf(); ?>
*
* @type function
* @date 4/09/13
* @since 4.3.0
*
* @param N/A
* @return (object)
*/
function acf()
{
global $acf;
if( !isset($acf) )
{
$acf = new acf();
}
return $acf;
}
// initialize
acf();
endif; // class_exists check
?>
| PHP |
<?php
/*
Plugin Name: Custom Post Type UI
Plugin URI: http://webdevstudios.com/plugin/custom-post-type-ui/
Description: Admin panel for creating custom post types and custom taxonomies in WordPress
Author: WebDevStudios.com
Version: 0.8.3
Author URI: http://webdevstudios.com/
Text Domain: cpt-plugin
License: GPLv2
*/
// Define current version constant
define( 'CPT_VERSION', '0.8.3' );
// Define current WordPress version constant
define( 'CPTUI_WP_VERSION', get_bloginfo( 'version' ) );
// Define plugin URL constant
$CPT_URL = cpt_check_return( 'add' );
//load translated strings
add_action( 'init', 'cpt_load_textdomain' );
// create custom plugin settings menu
add_action( 'admin_menu', 'cpt_plugin_menu' );
//call delete post function
add_action( 'admin_init', 'cpt_delete_post_type' );
//call register settings function
add_action( 'admin_init', 'cpt_register_settings' );
//process custom taxonomies if they exist
add_action( 'init', 'cpt_create_custom_taxonomies', 0 );
//process custom taxonomies if they exist
add_action( 'init', 'cpt_create_custom_post_types', 0 );
add_action( 'admin_head', 'cpt_help_style' );
//flush rewrite rules on deactivation
register_deactivation_hook( __FILE__, 'cpt_deactivation' );
function cpt_deactivation() {
// Clear the permalinks to remove our post type's rules
flush_rewrite_rules();
}
function cpt_load_textdomain() {
load_plugin_textdomain( 'cpt-plugin', false, basename( dirname( __FILE__ ) ) . '/languages' );
}
function cpt_plugin_menu() {
//create custom post type menu
add_menu_page( __( 'Custom Post Types', 'cpt-plugin' ), __( 'CPT UI', 'cpt-plugin' ), 'manage_options', 'cpt_main_menu', 'cpt_settings' );
//create submenu items
add_submenu_page( 'cpt_main_menu', __( 'Add New', 'cpt-plugin' ), __( 'Add New', 'cpt-plugin' ), 'manage_options', 'cpt_sub_add_new', 'cpt_add_new' );
add_submenu_page( 'cpt_main_menu', __( 'Manage Post Types', 'cpt-plugin' ), __( 'Manage Post Types', 'cpt-plugin' ), 'manage_options', 'cpt_sub_manage_cpt', 'cpt_manage_cpt' );
add_submenu_page( 'cpt_main_menu', __( 'Manage Taxonomies', 'cpt-plugin' ), __( 'Manage Taxonomies', 'cpt-plugin' ), 'manage_options', 'cpt_sub_manage_taxonomies', 'cpt_manage_taxonomies' );
}
//temp fix, should do: http://planetozh.com/blog/2008/04/how-to-load-javascript-with-your-wordpress-plugin/
//only load JS if on a CPT page
if ( strpos( $_SERVER['REQUEST_URI'], 'cpt' ) > 0 ) {
add_action( 'admin_head', 'cpt_wp_add_styles' );
}
// Add JS Scripts
function cpt_wp_add_styles() {
wp_enqueue_script( 'jquery' ); ?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
$(".comment_button").click(function() {
var element = $(this), I = element.attr("id");
$("#slidepanel"+I).slideToggle(300);
$(this).toggleClass("active");
return false;
});
});
</script>
<?php
}
function cpt_create_custom_post_types() {
//register custom post types
$cpt_post_types = get_option('cpt_custom_post_types');
//check if option value is an Array before proceeding
if ( is_array( $cpt_post_types ) ) {
foreach ($cpt_post_types as $cpt_post_type) {
//set post type values
$cpt_label = ( !empty( $cpt_post_type["label"] ) ) ? esc_html( $cpt_post_type["label"] ) : esc_html( $cpt_post_type["name"] ) ;
$cpt_singular = ( !empty( $cpt_post_type["singular_label"] ) ) ? esc_html( $cpt_post_type["singular_label"] ) : esc_html( $cpt_label );
$cpt_rewrite_slug = ( !empty( $cpt_post_type["rewrite_slug"] ) ) ? esc_html( $cpt_post_type["rewrite_slug"] ) : esc_html( $cpt_post_type["name"] );
$cpt_rewrite_withfront = ( !empty( $cpt_post_type["rewrite_withfront"] ) ) ? true : get_disp_boolean( $cpt_post_type["rewrite_withfront"] ); //reversed because false is empty
$cpt_menu_position = ( !empty( $cpt_post_type["menu_position"] ) ) ? intval( $cpt_post_type["menu_position"] ) : null; //must be null
$cpt_menu_icon = ( !empty( $cpt_post_type["menu_icon"] ) ) ? esc_attr( $cpt_post_type["menu_icon"] ) : null; //must be null
$cpt_taxonomies = ( !empty( $cpt_post_type[1] ) ) ? $cpt_post_type[1] : array();
$cpt_supports = ( !empty( $cpt_post_type[0] ) ) ? $cpt_post_type[0] : array();
//Show UI must be true
if ( true == get_disp_boolean( $cpt_post_type["show_ui"] ) ) {
//If the string is empty, we will need boolean, else use the string.
if ( empty( $cpt_post_type['show_in_menu_string'] ) ) {
$cpt_show_in_menu = ( $cpt_post_type["show_in_menu"] == 1 ) ? true : false;
} else {
$cpt_show_in_menu = $cpt_post_type['show_in_menu_string'];
}
} else {
$cpt_show_in_menu = false;
}
//set custom label values
$cpt_labels['name'] = $cpt_label;
$cpt_labels['singular_name'] = $cpt_post_type["singular_label"];
if ( isset ( $cpt_post_type[2]["menu_name"] ) ) {
$cpt_labels['menu_name'] = ( !empty( $cpt_post_type[2]["menu_name"] ) ) ? $cpt_post_type[2]["menu_name"] : $cpt_label;
}
$cpt_has_archive = ( !empty( $cpt_post_type["has_archive"] ) ) ? get_disp_boolean( $cpt_post_type["has_archive"] ) : '';
$cpt_exclude_from_search = ( !empty( $cpt_post_type["exclude_from_search"] ) ) ? get_disp_boolean( $cpt_post_type["exclude_from_search"] ) : '';
$cpt_labels['add_new'] = ( !empty( $cpt_post_type[2]["add_new"] ) ) ? $cpt_post_type[2]["add_new"] : 'Add ' .$cpt_singular;
$cpt_labels['add_new_item'] = ( !empty( $cpt_post_type[2]["add_new_item"] ) ) ? $cpt_post_type[2]["add_new_item"] : 'Add New ' .$cpt_singular;
$cpt_labels['edit'] = ( !empty( $cpt_post_type[2]["edit"] ) ) ? $cpt_post_type[2]["edit"] : 'Edit';
$cpt_labels['edit_item'] = ( !empty( $cpt_post_type[2]["edit_item"] ) ) ? $cpt_post_type[2]["edit_item"] : 'Edit ' .$cpt_singular;
$cpt_labels['new_item'] = ( !empty( $cpt_post_type[2]["new_item"] ) ) ? $cpt_post_type[2]["new_item"] : 'New ' .$cpt_singular;
$cpt_labels['view'] = ( !empty( $cpt_post_type[2]["view"] ) ) ? $cpt_post_type[2]["view"] : 'View ' .$cpt_singular;
$cpt_labels['view_item'] = ( !empty( $cpt_post_type[2]["view_item"] ) ) ? $cpt_post_type[2]["view_item"] : 'View ' .$cpt_singular;
$cpt_labels['search_items'] = ( !empty( $cpt_post_type[2]["search_items"] ) ) ? $cpt_post_type[2]["search_items"] : 'Search ' .$cpt_label;
$cpt_labels['not_found'] = ( !empty( $cpt_post_type[2]["not_found"] ) ) ? $cpt_post_type[2]["not_found"] : 'No ' .$cpt_label. ' Found';
$cpt_labels['not_found_in_trash'] = ( !empty( $cpt_post_type[2]["not_found_in_trash"] ) ) ? $cpt_post_type[2]["not_found_in_trash"] : 'No ' .$cpt_label. ' Found in Trash';
$cpt_labels['parent'] = ( $cpt_post_type[2]["parent"] ) ? $cpt_post_type[2]["parent"] : 'Parent ' .$cpt_singular;
register_post_type( $cpt_post_type["name"], array( 'label' => __($cpt_label),
'public' => get_disp_boolean($cpt_post_type["public"]),
'singular_label' => $cpt_post_type["singular_label"],
'show_ui' => get_disp_boolean($cpt_post_type["show_ui"]),
'has_archive' => $cpt_has_archive,
'show_in_menu' => $cpt_show_in_menu,
'capability_type' => $cpt_post_type["capability_type"],
'map_meta_cap' => true,
'hierarchical' => get_disp_boolean($cpt_post_type["hierarchical"]),
'exclude_from_search' => $cpt_exclude_from_search,
'rewrite' => array( 'slug' => $cpt_rewrite_slug, 'with_front' => $cpt_rewrite_withfront ),
'query_var' => get_disp_boolean($cpt_post_type["query_var"]),
'description' => esc_html($cpt_post_type["description"]),
'menu_position' => $cpt_menu_position,
'menu_icon' => $cpt_menu_icon,
'supports' => $cpt_supports,
'taxonomies' => $cpt_taxonomies,
'labels' => $cpt_labels
) );
}
}
}
function cpt_create_custom_taxonomies() {
//register custom taxonomies
$cpt_tax_types = get_option('cpt_custom_tax_types');
//check if option value is an array before proceeding
if ( is_array( $cpt_tax_types ) ) {
foreach ($cpt_tax_types as $cpt_tax_type) {
//set custom taxonomy values
$cpt_label = ( !empty( $cpt_tax_type["label"] ) ) ? esc_html( $cpt_tax_type["label"] ) : esc_html( $cpt_tax_type["name"] );
$cpt_singular_label = ( !empty( $cpt_tax_type["singular_label"] ) ) ? esc_html( $cpt_tax_type["singular_label"] ) : esc_html( $cpt_tax_type["name"] );
$cpt_rewrite_slug = ( !empty( $cpt_tax_type["rewrite_slug"] ) ) ? esc_html( $cpt_tax_type["rewrite_slug"] ) : esc_html( $cpt_tax_type["name"] );
$cpt_tax_show_admin_column = ( !empty( $cpt_tax_type["show_admin_column"] ) ) ? esc_html( $cpt_tax_type["show_admin_column"] ) : false;
$cpt_post_types = ( !empty( $cpt_tax_type[1] ) ) ? $cpt_tax_type[1] : $cpt_tax_type["cpt_name"];
//set custom label values
$cpt_labels['name'] = $cpt_label;
$cpt_labels['singular_name'] = $cpt_tax_type["singular_label"];
$cpt_labels['search_items'] = ( $cpt_tax_type[0]["search_items"] ) ? $cpt_tax_type[0]["search_items"] : 'Search ' .$cpt_label;
$cpt_labels['popular_items'] = ( $cpt_tax_type[0]["popular_items"] ) ? $cpt_tax_type[0]["popular_items"] : 'Popular ' .$cpt_label;
$cpt_labels['all_items'] = ( $cpt_tax_type[0]["all_items"] ) ? $cpt_tax_type[0]["all_items"] : 'All ' .$cpt_label;
$cpt_labels['parent_item'] = ( $cpt_tax_type[0]["parent_item"] ) ? $cpt_tax_type[0]["parent_item"] : 'Parent ' .$cpt_singular_label;
$cpt_labels['parent_item_colon'] = ( $cpt_tax_type[0]["parent_item_colon"] ) ? $cpt_tax_type[0]["parent_item_colon"] : 'Parent ' .$cpt_singular_label. ':';
$cpt_labels['edit_item'] = ( $cpt_tax_type[0]["edit_item"] ) ? $cpt_tax_type[0]["edit_item"] : 'Edit ' .$cpt_singular_label;
$cpt_labels['update_item'] = ( $cpt_tax_type[0]["update_item"] ) ? $cpt_tax_type[0]["update_item"] : 'Update ' .$cpt_singular_label;
$cpt_labels['add_new_item'] = ( $cpt_tax_type[0]["add_new_item"] ) ? $cpt_tax_type[0]["add_new_item"] : 'Add New ' .$cpt_singular_label;
$cpt_labels['new_item_name'] = ( $cpt_tax_type[0]["new_item_name"] ) ? $cpt_tax_type[0]["new_item_name"] : 'New ' .$cpt_singular_label. ' Name';
$cpt_labels['separate_items_with_commas'] = ( $cpt_tax_type[0]["separate_items_with_commas"] ) ? $cpt_tax_type[0]["separate_items_with_commas"] : 'Separate ' .$cpt_label. ' with commas';
$cpt_labels['add_or_remove_items'] = ( $cpt_tax_type[0]["add_or_remove_items"] ) ? $cpt_tax_type[0]["add_or_remove_items"] : 'Add or remove ' .$cpt_label;
$cpt_labels['choose_from_most_used'] = ( $cpt_tax_type[0]["choose_from_most_used"] ) ? $cpt_tax_type[0]["choose_from_most_used"] : 'Choose from the most used ' .$cpt_label;
//register our custom taxonomies
register_taxonomy( $cpt_tax_type["name"],
$cpt_post_types,
array( 'hierarchical' => get_disp_boolean($cpt_tax_type["hierarchical"]),
'label' => $cpt_label,
'show_ui' => get_disp_boolean($cpt_tax_type["show_ui"]),
'query_var' => get_disp_boolean($cpt_tax_type["query_var"]),
'rewrite' => array('slug' => $cpt_rewrite_slug),
'singular_label' => $cpt_singular_label,
'labels' => $cpt_labels,
'show_admin_column' => $cpt_tax_show_admin_column
) );
}
}
}
//delete custom post type or custom taxonomy
function cpt_delete_post_type() {
global $CPT_URL;
//check if we are deleting a custom post type
if( isset( $_GET['deltype'] ) ) {
//nonce security check
check_admin_referer( 'cpt_delete_post_type' );
$delType = intval( $_GET['deltype'] );
$cpt_post_types = get_option( 'cpt_custom_post_types' );
unset( $cpt_post_types[$delType] );
$cpt_post_types = array_values( $cpt_post_types );
update_option( 'cpt_custom_post_types', $cpt_post_types );
if ( isset( $_GET['return'] ) ) {
$RETURN_URL = cpt_check_return( esc_attr( $_GET['return'] ) );
} else {
$RETURN_URL = $CPT_URL;
}
wp_redirect( $RETURN_URL .'&cpt_msg=del' );
}
//check if we are deleting a custom taxonomy
if( isset( $_GET['deltax'] ) ) {
check_admin_referer( 'cpt_delete_tax' );
$delType = intval( $_GET['deltax'] );
$cpt_taxonomies = get_option( 'cpt_custom_tax_types' );
unset( $cpt_taxonomies[$delType] );
$cpt_taxonomies = array_values( $cpt_taxonomies );
update_option( 'cpt_custom_tax_types', $cpt_taxonomies );
if ( isset( $_GET['return'] ) ) {
$RETURN_URL = cpt_check_return( esc_attr( $_GET['return'] ) );
} else {
$RETURN_URL = $CPT_URL;
}
wp_redirect( $RETURN_URL .'&cpt_msg=del' );
}
}
function cpt_register_settings() {
global $cpt_error, $CPT_URL;
if ( isset( $_POST['cpt_edit'] ) ) {
//edit a custom post type
check_admin_referer( 'cpt_add_custom_post_type' );
//custom post type to edit
$cpt_edit = intval( $_POST['cpt_edit'] );
//edit the custom post type
$cpt_form_fields = $_POST['cpt_custom_post_type'];
//add support checkbox values to array
$cpt_supports = ( isset( $_POST['cpt_supports'] ) ) ? $_POST['cpt_supports'] : null;
array_push($cpt_form_fields, $cpt_supports);
//add taxonomies support checkbox values to array
$cpt_addon_taxes = ( isset( $_POST['cpt_addon_taxes'] ) ) ? $_POST['cpt_addon_taxes'] : null;
array_push( $cpt_form_fields, $cpt_addon_taxes );
//add label values to array
array_push( $cpt_form_fields, $_POST['cpt_labels'] );
//load custom posts saved in WP
$cpt_options = get_option( 'cpt_custom_post_types' );
if ( is_array( $cpt_options ) ) {
unset( $cpt_options[$cpt_edit] );
//insert new custom post type into the array
array_push( $cpt_options, $cpt_form_fields );
$cpt_options = array_values( $cpt_options );
$cpt_options = stripslashes_deep( $cpt_options );
//save custom post types
update_option( 'cpt_custom_post_types', $cpt_options );
if ( isset( $_GET['return'] ) ) {
$RETURN_URL = cpt_check_return( esc_attr( $_GET['return'] ) );
} else {
$RETURN_URL = $CPT_URL;
}
wp_redirect( $RETURN_URL );
}
} elseif ( isset( $_POST['cpt_submit'] ) ) {
//create a new custom post type
//nonce security check
check_admin_referer( 'cpt_add_custom_post_type' );
//retrieve new custom post type values
$cpt_form_fields = $_POST['cpt_custom_post_type'];
if ( empty( $cpt_form_fields["name"] ) ) {
if ( isset( $_GET['return'] ) ) {
$RETURN_URL = cpt_check_return( esc_attr( $_GET['return'] ) );
} else {
$RETURN_URL = $CPT_URL;
}
wp_redirect( $RETURN_URL .'&cpt_error=1' );
exit();
}
if ( false !== strpos( $cpt_form_fields["name"], '\'' ) ||
false !== strpos( $cpt_form_fields["name"], '\"' ) ||
false !== strpos( $cpt_form_fields["rewrite_slug"], '\'' ) ||
false !== strpos( $cpt_form_fields["rewrite_slug"], '\"' ) ) {
if ( isset( $_GET['return'] ) ) {
$RETURN_URL = cpt_check_return( esc_attr( $_GET['return'] ) );
} else {
$RETURN_URL = $CPT_URL;
}
wp_redirect( $RETURN_URL .'&cpt_error=4' );
exit();
}
//add support checkbox values to array
$cpt_supports = ( isset( $_POST['cpt_supports'] ) ) ? $_POST['cpt_supports'] : null;
array_push( $cpt_form_fields, $cpt_supports );
//add taxonomies support checkbox values to array
$cpt_addon_taxes = ( isset( $_POST['cpt_addon_taxes'] ) ) ? $_POST['cpt_addon_taxes'] : null;
array_push( $cpt_form_fields, $cpt_addon_taxes );
//add label values to array
array_push( $cpt_form_fields, $_POST['cpt_labels'] );
//load custom posts saved in WP
$cpt_options = get_option( 'cpt_custom_post_types' );
//check if option exists, if not create an array for it
if ( !is_array( $cpt_options ) ) {
$cpt_options = array();
}
//insert new custom post type into the array
array_push( $cpt_options, $cpt_form_fields );
$cpt_options = stripslashes_deep( $cpt_options );
//save new custom post type array in the CPT option
update_option( 'cpt_custom_post_types', $cpt_options );
if ( isset( $_GET['return'] ) ) {
$RETURN_URL = cpt_check_return( esc_attr( $_GET['return'] ) );
} else {
$RETURN_URL = $CPT_URL;
}
wp_redirect( $RETURN_URL .'&cpt_msg=1' );
}
if ( isset( $_POST['cpt_edit_tax'] ) ) {
//edit a custom taxonomy
//nonce security check
check_admin_referer( 'cpt_add_custom_taxonomy' );
//custom taxonomy to edit
$cpt_edit = intval( $_POST['cpt_edit_tax'] );
//edit the custom taxonomy
$cpt_form_fields = $_POST['cpt_custom_tax'];
//add label values to array
array_push( $cpt_form_fields, $_POST['cpt_tax_labels'] );
//add attached post type values to array
array_push( $cpt_form_fields, $_POST['cpt_post_types'] );
//load custom posts saved in WP
$cpt_options = get_option( 'cpt_custom_tax_types' );
if ( is_array( $cpt_options ) ) {
unset( $cpt_options[$cpt_edit] );
//insert new custom post type into the array
array_push( $cpt_options, $cpt_form_fields );
$cpt_options = array_values( $cpt_options );
//save custom post types
update_option( 'cpt_custom_tax_types', $cpt_options );
if ( isset( $_GET['return'] ) ) {
$RETURN_URL = cpt_check_return( esc_attr( $_GET['return'] ) );
} else {
$RETURN_URL = $CPT_URL;
}
wp_redirect( $RETURN_URL );
}
} elseif ( isset( $_POST['cpt_add_tax'] ) ) {
//create new custom taxonomy
//nonce security check
check_admin_referer( 'cpt_add_custom_taxonomy' );
//retrieve new custom taxonomy values
$cpt_form_fields = $_POST['cpt_custom_tax'];
//verify required fields are filled out
if ( empty( $cpt_form_fields["name"] ) ) {
if ( isset( $_GET['return'] ) ) {
$RETURN_URL = cpt_check_return( esc_attr( $_GET['return'] ) );
} else {
$RETURN_URL = $CPT_URL;
}
wp_redirect( $RETURN_URL .'&cpt_error=2' );
exit();
} elseif ( empty( $_POST['cpt_post_types'] ) ) {
if ( isset( $_GET['return'] ) ) {
$RETURN_URL = cpt_check_return( esc_attr( $_GET['return'] ) );
} else {
$RETURN_URL = $CPT_URL;
}
wp_redirect( $RETURN_URL .'&cpt_error=3' );
exit();
}
if ( false !== strpos( $cpt_form_fields["name"], '\'' ) ||
false !== strpos( $cpt_form_fields["name"], '\"' ) ||
false !== strpos( $cpt_form_fields["rewrite_slug"], '\'' ) ||
false !== strpos( $cpt_form_fields["rewrite_slug"], '\"' ) ) {
if ( isset( $_GET['return'] ) ) {
$RETURN_URL = cpt_check_return( esc_attr( $_GET['return'] ) );
} else {
$RETURN_URL = $CPT_URL;
}
wp_redirect( $RETURN_URL .'&cpt_error=5' );
exit();
}
//add label values to array
array_push( $cpt_form_fields, $_POST['cpt_tax_labels'] );
//add attached post type values to array
array_push( $cpt_form_fields, $_POST['cpt_post_types'] );
//load custom taxonomies saved in WP
$cpt_options = get_option( 'cpt_custom_tax_types' );
//check if option exists, if not create an array for it
if ( !is_array( $cpt_options ) ) {
$cpt_options = array();
}
//insert new custom taxonomy into the array
array_push( $cpt_options, $cpt_form_fields );
//save new custom taxonomy array in the CPT option
update_option( 'cpt_custom_tax_types', $cpt_options );
if ( isset( $_GET['return'] ) ) {
$RETURN_URL = cpt_check_return( esc_attr( $_GET['return'] ) );
} else {
$RETURN_URL = $CPT_URL;
}
wp_redirect( $RETURN_URL .'&cpt_msg=2' );
}
}
//main welcome/settings page
function cpt_settings() {
global $CPT_URL, $wp_post_types;
//flush rewrite rules
flush_rewrite_rules();
?>
<div class="wrap">
<?php screen_icon( 'plugins' ); ?>
<h2><?php _e( 'Custom Post Type UI', 'cpt-plugin' ); ?> <?php _e( 'version', 'cpt-plugin' ); ?>: <?php echo CPT_VERSION; ?></h2>
<h2><?php _e( 'Frequently Asked Questions', 'cpt-plugin' ); ?></h2>
<p><?php _e( 'Please note that this plugin will NOT handle display of registered post types or taxonomies in your current theme. It will simply register them for you.', 'cpt-plugin' ); ?>
<h3><?php _e( 'Q: <strong>How can I display content from a custom post type on my website?</strong>', 'cpt-plugin' ); ?></h3>
<p>
<?php _e( 'A: Justin Tadlock has written some great posts on the topic:', 'cpt-plugin' ); ?><br />
<a href="http://justintadlock.com/archives/2010/02/02/showing-custom-post-types-on-your-home-blog-page" target="_blank"><?php _e( 'Showing Custom Post Types on your Home Page', 'cpt-plugin' ); ?></a><br />
<a href="http://justintadlock.com/archives/2010/04/29/custom-post-types-in-wordpress" target="_blank"><?php _e( 'Custom Post Types in WordPress', 'cpt-plugin' ); ?></a>
</p>
<h3><?php _e( 'Q: <strong>How can I add custom meta boxes to my custom post types?</strong>', 'cpt-plugin' ); ?></h3>
<p><?php _e( 'A: The More Fields plugin does a great job at creating custom meta boxes and fully supports custom post types: ', 'cpt-plugin' ); ?><a href="http://wordpress.org/extend/plugins/more-fields/" target="_blank">http://wordpress.org/extend/plugins/more-fields/</a>. The <a href="https://github.com/jaredatch/Custom-Metaboxes-and-Fields-for-WordPress" target="_blank">Custom Metaboxes and Fields for WordPress</a> class is a great alternative to a plugin for more advanced users.</p>
<h3><?php _e( 'Q: <strong>I changed my custom post type name and now I can\'t get to my posts</strong>', 'cpt-plugin' ); ?></h3>
<p><?php _e( 'A: You can either change the custom post type name back to the original name or try the Post Type Switcher plugin: ', 'cpt-plugin' ); ?><a href="http://wordpress.org/extend/plugins/post-type-switcher/" target="_blank">http://wordpress.org/extend/plugins/post-type-switcher/</a></p>
<div class="cp-rss-widget">
<table border="0">
<tr>
<td colspan="3"><h2><?php _e( 'Help Support This Plugin!', 'cpt-plugin' ); ?></h2></td>
</tr>
<tr>
<td width="33%"><h3><?php _e( 'PayPal Donation', 'cpt-plugin' ); ?></h3></td>
<td width="33%"><h3><?php _e( 'Professional WordPress<br />Second Edition', 'cpt-plugin' ); ?></h3></td>
<td width="33%"><h3><?php _e( 'Professional WordPress<br />Plugin Development', 'cpt-plugin' ); ?></h3></td>
</tr>
<tr>
<td valign="top" width="33%">
<p><?php _e( 'Please donate to the development<br />of Custom Post Type UI:', 'cpt-plugin'); ?>
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="YJEDXPHE49Q3U">
<input type="image" src="https://www.paypal.com/en_US/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form>
</p>
</td>
<td valign="top" width="33%"><a href="http://bit.ly/prowp2" target="_blank"><img src="<?php echo plugins_url( '/images/professional-wordpress-secondedition.jpg', __FILE__ ); ?>" width="200"></a><br /><?php _e( 'The leading book on WordPress design and development!<br /><strong>Brand new second edition!', 'cpt-plugin'); ?></strong></td>
<td valign="top" width="33%"><a href="http://amzn.to/plugindevbook" target="_blank"><img src="<?php echo plugins_url( '/images/professional-wordpress-plugin-development.png', __FILE__ ); ?>" width="200"></a><br /><?php _e( 'Highest rated WordPress development book on Amazon!', 'cpt-plugin' ); ?></td>
</tr>
</table>
<h2><?php _e( 'WebDevStudios.com Recent News', 'cpt-plugin' ); ?></h2>
<?php
wp_widget_rss_output( array(
'url' => esc_url( 'http://webdevstudios.com/feed/' ),
'title' => __( 'WebDevStudios.com News', 'cpt-plugin' ),
'items' => 3,
'show_summary' => 1,
'show_author' => 0,
'show_date' => 1
) );
?>
</div>
</div>
<?php
//load footer
cpt_footer();
}
//manage custom post types page
function cpt_manage_cpt() {
global $CPT_URL;
$MANAGE_URL = cpt_check_return( 'add' );
?>
<div class="wrap">
<?php
//check for success/error messages
if ( isset($_GET['cpt_msg'] ) && $_GET['cpt_msg'] == 'del' ) { ?>
<div id="message" class="updated">
<?php _e('Custom post type deleted successfully', 'cpt-plugin'); ?>
</div>
<?php
}
?>
<?php screen_icon( 'plugins' ); ?>
<h2><?php _e('Manage Custom Post Types', 'cpt-plugin') ?></h2>
<p><?php _e('Deleting custom post types will <strong>NOT</strong> delete any content into the database or added to those post types. You can easily recreate your post types and the content will still exist.', 'cpt-plugin') ?></p>
<?php
$cpt_post_types = get_option( 'cpt_custom_post_types', array() );
if (is_array($cpt_post_types)) {
?>
<table width="100%" class="widefat">
<thead>
<tr>
<th><?php _e('Action', 'cpt-plugin');?></th>
<th><?php _e('Name', 'cpt-plugin');?></th>
<th><?php _e('Label', 'cpt-plugin');?></th>
<th><?php _e('Public', 'cpt-plugin');?></th>
<th><?php _e('Show UI', 'cpt-plugin');?></th>
<th><?php _e('Hierarchical', 'cpt-plugin');?></th>
<th><?php _e('Rewrite', 'cpt-plugin');?></th>
<th><?php _e('Rewrite Slug', 'cpt-plugin');?></th>
<th><?php _e('Total Published', 'cpt-plugin');?></th>
<th><?php _e('Total Drafts', 'cpt-plugin');?></th>
<th><?php _e('Supports', 'cpt-plugin');?></th>
</tr>
</thead>
<tfoot>
<tr>
<th><?php _e('Action', 'cpt-plugin');?></th>
<th><?php _e('Name', 'cpt-plugin');?></th>
<th><?php _e('Label', 'cpt-plugin');?></th>
<th><?php _e('Public', 'cpt-plugin');?></th>
<th><?php _e('Show UI', 'cpt-plugin');?></th>
<th><?php _e('Hierarchical', 'cpt-plugin');?></th>
<th><?php _e('Rewrite', 'cpt-plugin');?></th>
<th><?php _e('Rewrite Slug', 'cpt-plugin');?></th>
<th><?php _e('Total Published', 'cpt-plugin');?></th>
<th><?php _e('Total Drafts', 'cpt-plugin');?></th>
<th><?php _e('Supports', 'cpt-plugin');?></th>
</tr>
</tfoot>
<?php
$thecounter=0;
$cpt_names = array();
//Create urls for management
foreach ( $cpt_post_types as $cpt_post_type ) {
$del_url = cpt_check_return( 'cpt' ) .'&deltype=' .$thecounter .'&return=cpt';
$del_url = ( function_exists('wp_nonce_url') ) ? wp_nonce_url($del_url, 'cpt_delete_post_type') : $del_url;
$edit_url = $MANAGE_URL .'&edittype=' .$thecounter .'&return=cpt';
$edit_url = ( function_exists('wp_nonce_url') ) ? wp_nonce_url($edit_url, 'cpt_edit_post_type') : $edit_url;
$cpt_counts = wp_count_posts($cpt_post_type["name"]);
$rewrite_slug = ( $cpt_post_type["rewrite_slug"] ) ? $cpt_post_type["rewrite_slug"] : $cpt_post_type["name"];
?>
<tr>
<td valign="top"><a href="<?php echo $del_url; ?>"><?php _e( 'Delete', 'cpt-plugin' ); ?></a> / <a href="<?php echo $edit_url; ?>"><?php _e( 'Edit', 'cpt-plugin' ); ?></a> / <a href="#" class="comment_button" id="<?php echo $thecounter; ?>"><?php _e( 'Get Code', 'cpt-plugin' ); ?></a></td>
<td valign="top"><?php echo stripslashes($cpt_post_type["name"]); ?></td>
<td valign="top"><?php echo stripslashes($cpt_post_type["label"]); ?></td>
<td valign="top"><?php echo disp_boolean($cpt_post_type["public"]); ?></td>
<td valign="top"><?php echo disp_boolean($cpt_post_type["show_ui"]); ?></td>
<td valign="top"><?php echo disp_boolean($cpt_post_type["hierarchical"]); ?></td>
<td valign="top"><?php echo disp_boolean($cpt_post_type["rewrite"]); ?></td>
<td valign="top"><?php echo $rewrite_slug; ?></td>
<td valign="top"><?php echo $cpt_counts->publish; ?></td>
<td valign="top"><?php echo $cpt_counts->draft; ?></td>
<td>
<?php
if (is_array($cpt_post_type[0])) {
foreach ($cpt_post_type[0] as $cpt_supports) {
echo $cpt_supports .'<br />';
}
}
?>
</td>
</tr>
<tr>
<td colspan="12">
<div style="display:none;" id="slidepanel<?php echo $thecounter; ?>">
<?php
// Begin the display for the "Get code" feature
//display register_post_type code
$custom_post_type = '';
$cpt_support_array = '';
$cpt_tax_array = '';
$cpt_label = ( empty( $cpt_post_type["label"] ) ) ? esc_html($cpt_post_type["name"]) : esc_html($cpt_post_type["label"]);
$cpt_singular = ( empty( $cpt_post_type["singular_label"] ) ) ? $cpt_label : esc_html($cpt_post_type["singular_label"]);
$cpt_rewrite_slug = ( empty( $cpt_post_type["rewrite_slug"] ) ) ? esc_html($cpt_post_type["name"]) : esc_html($cpt_post_type["rewrite_slug"]);
$cpt_menu_position = ( empty( $cpt_post_type["menu_position"] ) ) ? null : intval($cpt_post_type["menu_position"]);
$cpt_menu_icon = ( !empty( $cpt_post_type["menu_icon"] ) ) ? esc_attr($cpt_post_type["menu_icon"]) : null;
if ( true == $cpt_post_type["show_ui"] ) {
$cpt_show_in_menu = ( $cpt_post_type["show_in_menu"] == 1 ) ? 1 : 0;
$cpt_show_in_menu = ( $cpt_post_type["show_in_menu_string"] ) ? '\''.$cpt_post_type["show_in_menu_string"].'\'' : $cpt_show_in_menu;
} else {
$cpt_show_in_menu = 0;
}
//set custom label values
$cpt_labels['name'] = $cpt_label;
$cpt_labels['singular_name'] = $cpt_post_type["singular_label"];
$cpt_labels['menu_name'] = ( $cpt_post_type[2]["menu_name"] ) ? $cpt_post_type[2]["menu_name"] : $cpt_label;
$cpt_labels['add_new'] = ( $cpt_post_type[2]["add_new"] ) ? $cpt_post_type[2]["add_new"] : 'Add ' .$cpt_singular;
$cpt_labels['add_new_item'] = ( $cpt_post_type[2]["add_new_item"] ) ? $cpt_post_type[2]["add_new_item"] : 'Add New ' .$cpt_singular;
$cpt_labels['edit'] = ( $cpt_post_type[2]["edit"] ) ? $cpt_post_type[2]["edit"] : 'Edit';
$cpt_labels['edit_item'] = ( $cpt_post_type[2]["edit_item"] ) ? $cpt_post_type[2]["edit_item"] : 'Edit ' .$cpt_singular;
$cpt_labels['new_item'] = ( $cpt_post_type[2]["new_item"] ) ? $cpt_post_type[2]["new_item"] : 'New ' .$cpt_singular;
$cpt_labels['view'] = ( $cpt_post_type[2]["view"] ) ? $cpt_post_type[2]["view"] : 'View ' .$cpt_singular;
$cpt_labels['view_item'] = ( $cpt_post_type[2]["view_item"] ) ? $cpt_post_type[2]["view_item"] : 'View ' .$cpt_singular;
$cpt_labels['search_items'] = ( $cpt_post_type[2]["search_items"] ) ? $cpt_post_type[2]["search_items"] : 'Search ' .$cpt_label;
$cpt_labels['not_found'] = ( $cpt_post_type[2]["not_found"] ) ? $cpt_post_type[2]["not_found"] : 'No ' .$cpt_label. ' Found';
$cpt_labels['not_found_in_trash'] = ( $cpt_post_type[2]["not_found_in_trash"] ) ? $cpt_post_type[2]["not_found_in_trash"] : 'No ' .$cpt_label. ' Found in Trash';
$cpt_labels['parent'] = ( $cpt_post_type[2]["parent"] ) ? $cpt_post_type[2]["parent"] : 'Parent ' .$cpt_singular;
if( is_array( $cpt_post_type[0] ) ) {
$counter = 1;
$count = count( $cpt_post_type[0] );
foreach ( $cpt_post_type[0] as $cpt_supports ) {
//build supports variable
$cpt_support_array .= '\'' . $cpt_supports . '\'';
if ( $counter != $count )
$cpt_support_array .= ',';
$counter++;
}
}
if( is_array( $cpt_post_type[1] ) ) {
$counter = 1;
$count = count( $cpt_post_type[1] );
foreach ( $cpt_post_type[1] as $cpt_taxes ) {
//build taxonomies variable
$cpt_tax_array .= '\''.$cpt_taxes.'\'';
if ( $counter != $count )
$cpt_tax_array .= ',';
$counter++;
}
}
$custom_post_type = "add_action('init', 'cptui_register_my_cpt_" . $cpt_post_type["name"] . "');\n";
$custom_post_type .= "function cptui_register_my_cpt_" . $cpt_post_type["name"] . "() {\n";
$custom_post_type .= "register_post_type('" . $cpt_post_type["name"] . "', array(\n'label' => '" . $cpt_label . "',\n";
$custom_post_type .= "'description' => '" . $cpt_post_type["description"] . "',\n";
$custom_post_type .= "'public' => " . disp_boolean( $cpt_post_type["public"]) . ",\n";
$custom_post_type .= "'show_ui' => " . disp_boolean( $cpt_post_type["show_ui"]) . ",\n";
$custom_post_type .= "'show_in_menu' => " . disp_boolean( $cpt_show_in_menu) . ",\n";
$custom_post_type .= "'capability_type' => '" . $cpt_post_type["capability_type"] . "',\n";
$custom_post_type .= "'map_meta_cap' => " . disp_boolean( '1' ) . ",\n";
$custom_post_type .= "'hierarchical' => " . disp_boolean( $cpt_post_type["hierarchical"] ) . ",\n";
if ( !empty( $cpt_post_type["rewrite_slug"] ) ) {
$custom_post_type .= "'rewrite' => array('slug' => '" . $cpt_post_type["rewrite_slug"] . "', 'with_front' => " . $cpt_post_type['rewrite_withfront'] . "),\n";
} else {
if( empty( $cpt_post_type['rewrite_withfront'] ) ) $cpt_post_type['rewrite_withfront'] = 1;
$custom_post_type .= "'rewrite' => array('slug' => '" . $cpt_post_type["name"] . "', 'with_front' => " . disp_boolean( $cpt_post_type['rewrite_withfront'] ) . "),\n";
}
$custom_post_type .= "'query_var' => " . disp_boolean($cpt_post_type["query_var"]) . ",\n";
if ( !empty( $cpt_post_type["has_archive"] ) ) {
$custom_post_type .= "'has_archive' => " . disp_boolean( $cpt_post_type["has_archive"] ) . ",\n";
}
if ( !empty( $cpt_post_type["exclude_from_search"] ) ) {
$custom_post_type .= "'exclude_from_search' => " . disp_boolean( $cpt_post_type["exclude_from_search"] ) . ",\n";
}
if ( !empty( $cpt_post_type["menu_position"] ) ) {
$custom_post_type .= "'menu_position' => '" . $cpt_post_type["menu_position"] . "',\n";
}
if ( !empty( $cpt_post_type["menu_icon"] ) ) {
$custom_post_type .= "'menu_icon' => '" . $cpt_post_type["menu_icon"] . "',\n";
}
$custom_post_type .= "'supports' => array(" . $cpt_support_array . "),\n";
if ( !empty( $cpt_tax_array ) ) {
$custom_post_type .= "'taxonomies' => array(" . $cpt_tax_array . "),\n";
}
if ( !empty( $cpt_labels ) ) {
$custom_post_type .= "'labels' => " . var_export( $cpt_labels, true ) . "\n";
}
$custom_post_type .= ") ); }";
echo '<p>';
_e( 'Place the below code in your themes functions.php file to manually create this custom post type.', 'cpt-plugin' ).'<br>';
_e('This is a <strong>BETA</strong> feature. Please <a href="https://github.com/WebDevStudios/custom-post-type-ui">report bugs</a>.','cpt-plugin').'</p>';
echo '<textarea rows="10" cols="100">' .$custom_post_type .'</textarea>';
?>
</div>
</td>
</tr>
<?php
$thecounter++;
$cpt_names[] = strtolower( $cpt_post_type["name"] );
}
$args=array(
'public' => true,
'_builtin' => false
);
$output = 'objects'; // or objects
$post_types = get_post_types( $args, $output );
$cpt_first = false;
if ( $post_types ) {
?></table>
<h3><?php _e('Additional Custom Post Types', 'cpt-plugin') ?></h3>
<p><?php _e('The custom post types below are registered in WordPress but were not created by the Custom Post Type UI Plugin.', 'cpt-plugin') ?></p>
<?php
foreach ( $post_types as $post_type ) {
if ( !in_array( strtolower( $post_type->name ), $cpt_names ) ) {
if ( isset( $cpt_first ) && !$cpt_first ) {
?>
<table width="100%" class="widefat">
<thead>
<tr>
<th><?php _e('Name', 'cpt-plugin');?></th>
<th><?php _e('Label', 'cpt-plugin');?></th>
<th><?php _e('Public', 'cpt-plugin');?></th>
<th><?php _e('Show UI', 'cpt-plugin');?></th>
<th><?php _e('Hierarchical', 'cpt-plugin');?></th>
<th><?php _e('Rewrite', 'cpt-plugin');?></th>
<th><?php _e('Rewrite Slug', 'cpt-plugin');?></th>
<th><?php _e('Query Var', 'cpt-plugin');?></th>
</tr>
</thead>
<tfoot>
<tr>
<th><?php _e('Name', 'cpt-plugin');?></th>
<th><?php _e('Label', 'cpt-plugin');?></th>
<th><?php _e('Public', 'cpt-plugin');?></th>
<th><?php _e('Show UI', 'cpt-plugin');?></th>
<th><?php _e('Hierarchical', 'cpt-plugin');?></th>
<th><?php _e('Rewrite', 'cpt-plugin');?></th>
<th><?php _e('Rewrite Slug', 'cpt-plugin');?></th>
<th><?php _e('Query Var', 'cpt-plugin');?></th>
</tr>
</tfoot>
<?php
$cpt_first = true;
}
$rewrite_slug = ( isset( $post_type->rewrite_slug ) ) ? $post_type->rewrite_slug : $post_type->name;
?>
<tr>
<td valign="top"><?php echo $post_type->name; ?></td>
<td valign="top"><?php echo $post_type->label; ?></td>
<td valign="top"><?php echo disp_boolean($post_type->public); ?></td>
<td valign="top"><?php echo disp_boolean($post_type->show_ui); ?></td>
<td valign="top"><?php echo disp_boolean($post_type->hierarchical); ?></td>
<td valign="top"><?php echo disp_boolean($post_type->rewrite); ?></td>
<td valign="top"><?php echo $rewrite_slug; ?></td>
<td valign="top"><?php echo disp_boolean($post_type->query_var); ?></td>
</tr>
<?php
}
}
}
if ( isset($cpt_first) && !$cpt_first ) {
echo '<tr><td><strong>';
_e( 'No additional post types found', 'cpt-plugin' );
echo '</strong></td></tr>';
}
?>
</table>
</div><?php
//load footer
cpt_footer();
}
}
//manage custom taxonomies page
function cpt_manage_taxonomies() {
global $CPT_URL;
$MANAGE_URL = cpt_check_return( 'add' );
?>
<div class="wrap">
<?php
//check for success/error messages
if (isset($_GET['cpt_msg']) && $_GET['cpt_msg']=='del') { ?>
<div id="message" class="updated">
<?php _e('Custom taxonomy deleted successfully', 'cpt-plugin'); ?>
</div>
<?php
}
?>
<?php screen_icon( 'plugins' ); ?>
<h2><?php _e('Manage Custom Taxonomies', 'cpt-plugin') ?></h2>
<p><?php _e('Deleting custom taxonomies does <strong>NOT</strong> delete any content added to those taxonomies. You can easily recreate your taxonomies and the content will still exist.', 'cpt-plugin') ?></p>
<?php
$cpt_tax_types = get_option( 'cpt_custom_tax_types', array() );
if (is_array($cpt_tax_types)) {
?>
<table width="100%" class="widefat">
<thead>
<tr>
<th><?php _e('Action', 'cpt-plugin');?></th>
<th><?php _e('Name', 'cpt-plugin');?></th>
<th><?php _e('Label', 'cpt-plugin');?></th>
<th><?php _e('Singular Label', 'cpt-plugin');?></th>
<th><?php _e('Attached Post Types', 'cpt-plugin');?></th>
<th><?php _e('Hierarchical', 'cpt-plugin');?></th>
<th><?php _e('Show UI', 'cpt-plugin');?></th>
<th><?php _e('Rewrite', 'cpt-plugin');?></th>
<th><?php _e('Rewrite Slug', 'cpt-plugin');?></th>
</tr>
</thead>
<tfoot>
<tr>
<th><?php _e('Action', 'cpt-plugin');?></th>
<th><?php _e('Name', 'cpt-plugin');?></th>
<th><?php _e('Label', 'cpt-plugin');?></th>
<th><?php _e('Singular Label', 'cpt-plugin');?></th>
<th><?php _e('Attached Post Types', 'cpt-plugin');?></th>
<th><?php _e('Hierarchical', 'cpt-plugin');?></th>
<th><?php _e('Show UI', 'cpt-plugin');?></th>
<th><?php _e('Rewrite', 'cpt-plugin');?></th>
<th><?php _e('Rewrite Slug', 'cpt-plugin');?></th>
</tr>
</tfoot>
<?php
$thecounter=0;
foreach ($cpt_tax_types as $cpt_tax_type) {
$del_url = cpt_check_return( 'cpt' ) .'&deltax=' .$thecounter .'&return=tax';
$del_url = ( function_exists('wp_nonce_url') ) ? wp_nonce_url($del_url, 'cpt_delete_tax') : $del_url;
$edit_url = $MANAGE_URL .'&edittax=' .$thecounter .'&return=tax';
$edit_url = ( function_exists('wp_nonce_url') ) ? wp_nonce_url($edit_url, 'cpt_edit_tax') : $edit_url;
$rewrite_slug = ( $cpt_tax_type["rewrite_slug"] ) ? $cpt_tax_type["rewrite_slug"] : $cpt_tax_type["name"];
?>
<tr>
<td valign="top"><a href="<?php echo $del_url; ?>"><?php _e( 'Delete', 'cpt-plugin' ); ?></a> / <a href="<?php echo $edit_url; ?>"><?php _e( 'Edit', 'cpt-plugin' ); ?></a> / <a href="#" class="comment_button" id="<?php echo $thecounter; ?>"><?php _e( 'Get Code', 'cpt-plugin' ); ?></a></td>
<td valign="top"><?php echo stripslashes($cpt_tax_type["name"]); ?></td>
<td valign="top"><?php echo stripslashes($cpt_tax_type["label"]); ?></td>
<td valign="top"><?php echo stripslashes($cpt_tax_type["singular_label"]); ?></td>
<td valign="top">
<?php
if ( isset( $cpt_tax_type["cpt_name"] ) ) {
echo stripslashes($cpt_tax_type["cpt_name"]);
} elseif ( is_array( $cpt_tax_type[1] ) ) {
foreach ($cpt_tax_type[1] as $cpt_post_types) {
echo $cpt_post_types .'<br />';
}
}
?>
</td>
<td valign="top"><?php echo disp_boolean($cpt_tax_type["hierarchical"]); ?></td>
<td valign="top"><?php echo disp_boolean($cpt_tax_type["show_ui"]); ?></td>
<td valign="top"><?php echo disp_boolean($cpt_tax_type["rewrite"]); ?></td>
<td valign="top"><?php echo $rewrite_slug; ?></td>
</tr>
<tr>
<td colspan="10">
<div style="display:none;" id="slidepanel<?php echo $thecounter; ?>">
<?php
//display register_taxonomy code
$custom_tax = '';
$custom_tax = "add_action('init', 'cptui_register_my_taxes_" . $cpt_tax_type['name'] . "');\n";
$custom_tax .= "function cptui_register_my_taxes_" . $cpt_tax_type['name'] . "() {\n";
if ( !$cpt_tax_type["label"] ) {
$cpt_label = esc_html( $cpt_tax_type["name"] );
} else {
$cpt_label = esc_html( $cpt_tax_type["label"] );
}
//check if singular label was filled out
if ( !$cpt_tax_type["singular_label"] ) {
$cpt_singular_label = esc_html( $cpt_tax_type["name"] );
} else {
$cpt_singular_label = esc_html( $cpt_tax_type["singular_label"] );
}
$labels = var_export( array(
'search_items' => ( !empty( $cpt_tax_type["singular_label"] ) ) ? esc_html( $cpt_tax_type["singular_label"] ) : '',
'popular_items' => ( !empty( $cpt_tax_type[0]["popular_items"] ) ) ? esc_html( $cpt_tax_type[0]["popular_items"] ) : '',
'all_items' => ( !empty( $cpt_tax_type[0]["all_items"] ) ) ? esc_html( $cpt_tax_type[0]["all_items"] ) : '',
'parent_item' => ( !empty( $cpt_tax_type[0]["parent_item"] ) ) ? esc_html( $cpt_tax_type[0]["parent_item"] ) : '',
'parent_item_colon' => ( !empty( $cpt_tax_type[0]["parent_item_colon"] ) ) ? esc_html( $cpt_tax_type[0]["parent_item_colon"] ) : '',
'edit_item' => ( !empty( $cpt_tax_type[0]["edit_item"] ) ) ? esc_html( $cpt_tax_type[0]["edit_item"] ) : '',
'update_item' => ( !empty( $cpt_tax_type[0]["update_item"] ) ) ? esc_html( $cpt_tax_type[0]["update_item"] ) : '',
'add_new_item' => ( !empty( $cpt_tax_type[0]["add_new_item"] ) ) ? esc_html( $cpt_tax_type[0]["add_new_item"] ) : '',
'new_item_name' => ( !empty( $cpt_tax_type[0]["new_item_name"] ) ) ? esc_html( $cpt_tax_type[0]["new_item_name"] ) : '',
'separate_items_with_commas' => ( !empty( $cpt_tax_type[0]["separate_items_with_commas"] ) ) ? esc_html( $cpt_tax_type[0]["separate_items_with_commas"] ) : '',
'add_or_remove_items' => ( !empty( $cpt_tax_type[0]["add_or_remove_items"] ) ) ? esc_html( $cpt_tax_type[0]["add_or_remove_items"] ) : '',
'choose_from_most_used' => ( !empty( $cpt_tax_type[0]["choose_from_most_used"] ) ) ? esc_html( $cpt_tax_type[0]["choose_from_most_used"] ) : ''
), true );
$cpt_post_types = ( !$cpt_tax_type[1] ) ? $cpt_tax_type["cpt_name"] : var_export( $cpt_tax_type[1], true );
//register our custom taxonomies
$custom_tax .= "register_taxonomy( '" . $cpt_tax_type["name"] . "',";
$custom_tax .= $cpt_post_types . ",\n";
$custom_tax .= "array( 'hierarchical' => " . disp_boolean( $cpt_tax_type["hierarchical"] ) . ",\n";
$custom_tax .= "\t'label' => '" . $cpt_label . "',\n";
$custom_tax .= "\t'show_ui' => " . disp_boolean( $cpt_tax_type["show_ui"] ) . ",\n";
$custom_tax .= "\t'query_var' => " . disp_boolean( $cpt_tax_type["query_var"] ) . ",\n";
if ( !empty( $cpt_tax_type["rewrite_slug"] ) ) {
$custom_tax .= "\t'rewrite' => array( 'slug' => '" . $cpt_tax_type["rewrite_slug"] . "' ),\n";
}
if ( version_compare( CPTUI_WP_VERSION, '3.5', '>' ) ) {
$custom_tax .= "\t'show_admin_column' => " . disp_boolean( $cpt_tax_type["show_admin_column"] ) . ",\n";
}
if ( !empty( $labels ) )
$custom_tax .= "\t'labels' => " . $labels . "\n";
$custom_tax .= ") ); \n}";
echo '<br>';
echo _e('Place the below code in your themes functions.php file to manually create this custom taxonomy','cpt-plugin').'<br>';
echo _e('This is a <strong>BETA</strong> feature. Please <a href="http://webdevstudios.com/support/forum/custom-post-type-ui/">report bugs</a>.','cpt-plugin').'<br>';
echo '<textarea rows="10" cols="100">' .$custom_tax .'</textarea>';
?>
</div>
</td>
</tr>
<?php
$thecounter++;
}
?></table>
</div>
<?php
//load footer
cpt_footer();
}
}
//add new custom post type / taxonomy page
function cpt_add_new() {
global $cpt_error, $CPT_URL;
$RETURN_URL = ( isset( $_GET['return'] ) ) ? 'action="' . cpt_check_return( esc_attr( $_GET['return'] ) ) . '"' : '';
//check if we are editing a custom post type or creating a new one
if ( isset( $_GET['edittype'] ) && !isset( $_GET['cpt_edit'] ) ) {
check_admin_referer('cpt_edit_post_type');
//get post type to edit. This will reference array index for our option.
$editType = intval($_GET['edittype']);
//load custom posts saved in WP
$cpt_options = get_option('cpt_custom_post_types');
//load custom post type values to edit
$cpt_post_type_name = ( isset( $cpt_options[ $editType ]["name"] ) ) ? $cpt_options[ $editType ]["name"] : null;
$cpt_label = ( isset( $cpt_options[ $editType ]["label"] ) ) ? $cpt_options[ $editType ]["label"] : null;
$cpt_singular_label = ( isset( $cpt_options[ $editType ]["singular_label"] ) ) ? $cpt_options[ $editType ]["singular_label"] : null;
$cpt_public = ( isset( $cpt_options[ $editType ]["public"] ) ) ? $cpt_options[ $editType ]["public"] : null;
$cpt_showui = ( isset( $cpt_options[ $editType ]["show_ui"] ) ) ? $cpt_options[ $editType ]["show_ui"] : null;
$cpt_capability = ( isset( $cpt_options[ $editType ]["capability_type"] ) ) ? $cpt_options[ $editType ]["capability_type"] : null;
$cpt_hierarchical = ( isset( $cpt_options[ $editType ]["hierarchical"] ) ) ? $cpt_options[ $editType ]["hierarchical"] : null;
$cpt_rewrite = ( isset( $cpt_options[ $editType ]["rewrite"] ) ) ? $cpt_options[ $editType ]["rewrite"] : null;
$cpt_rewrite_slug = ( isset( $cpt_options[ $editType ]["rewrite_slug"] ) ) ? $cpt_options[ $editType ]["rewrite_slug"] : null;
$cpt_rewrite_withfront = ( isset( $cpt_options[ $editType ]["rewrite_withfront"] ) ) ? $cpt_options[ $editType ]["rewrite_withfront"] : null;
$cpt_query_var = ( isset( $cpt_options[ $editType ]["query_var"] ) ) ? $cpt_options[ $editType ]["query_var"] : null;
$cpt_description = ( isset( $cpt_options[ $editType ]["description"] ) ) ? $cpt_options[ $editType ]["description"] : null;
$cpt_menu_position = ( isset( $cpt_options[ $editType ]["menu_position"] ) ) ? $cpt_options[ $editType ]["menu_position"] : null;
$cpt_menu_icon = ( isset( $cpt_options[ $editType ]["menu_icon"] ) ) ? $cpt_options[ $editType ]["menu_icon"] : null;
$cpt_supports = ( isset( $cpt_options[ $editType ][0] ) ) ? $cpt_options[ $editType ][0] : null;
$cpt_taxes = ( isset( $cpt_options[ $editType ][1] ) )? $cpt_options[ $editType ][1] : null;
$cpt_labels = ( isset( $cpt_options[ $editType ][2] ) ) ? $cpt_options[ $editType ][2] : null;
$cpt_has_archive = ( isset( $cpt_options[$editType]["has_archive"] ) ) ? $cpt_options[$editType]["has_archive"] : null;
$cpt_exclude_from_search = ( isset( $cpt_options[$editType]["exclude_from_search"] ) ) ? $cpt_options[$editType]["exclude_from_search"] : null;
$cpt_show_in_menu = ( isset( $cpt_options[$editType]["show_in_menu"] ) ) ? $cpt_options[$editType]["show_in_menu"] : true;
$cpt_show_in_menu_string = ( isset( $cpt_options[$editType]["show_in_menu_string"] ) ) ? $cpt_options[$editType]["show_in_menu_string"] : null;
$cpt_submit_name = __( 'Save Custom Post Type', 'cpt-plugin' );
} else {
$cpt_submit_name = __( 'Create Custom Post Type', 'cpt-plugin' );
}
if ( isset( $_GET['edittax'] ) && !isset( $_GET['cpt_edit'] ) ) {
check_admin_referer('cpt_edit_tax');
//get post type to edit
$editTax = intval($_GET['edittax']);
//load custom posts saved in WP
$cpt_options = get_option('cpt_custom_tax_types');
//load custom taxonomy values to edit
$cpt_tax_name = $cpt_options[$editTax]["name"];
$cpt_tax_label = stripslashes( $cpt_options[$editTax]["label"] );
$cpt_singular_label_tax = stripslashes( $cpt_options[$editTax]["singular_label"] );
$cpt_tax_object_type = ( isset( $cpt_options[$editTax]["cpt_name"] ) ) ? $cpt_options[$editTax]["cpt_name"] : null;
$cpt_tax_hierarchical = $cpt_options[$editTax]["hierarchical"];
$cpt_tax_showui = $cpt_options[$editTax]["show_ui"];
$cpt_tax_query_var = $cpt_options[$editTax]["query_var"];
$cpt_tax_rewrite = $cpt_options[$editTax]["rewrite"];
$cpt_tax_rewrite_slug = $cpt_options[$editTax]["rewrite_slug"];
$cpt_tax_show_admin_column = $cpt_options[$editTax]["show_admin_column"];
$cpt_tax_labels = stripslashes_deep( $cpt_options[$editTax][0] );
$cpt_post_types = $cpt_options[$editTax][1];
$cpt_tax_submit_name = __( 'Save Custom Taxonomy', 'cpt-plugin' );
} else {
$cpt_tax_submit_name = __( 'Create Custom Taxonomy', 'cpt-plugin' );
}
//flush rewrite rules
flush_rewrite_rules();
/*
BEGIN 'ADD NEW' PAGE OUTPUT
*/
?>
<div class="wrap">
<?php
//check for success/error messages
if ( isset( $_GET['cpt_msg'] ) ) : ?>
<div id="message" class="updated">
<?php if ( $_GET['cpt_msg'] == 1 ) {
_e( 'Custom post type created successfully. You may need to refresh to view the new post type in the admin menu.', 'cpt-plugin' );
echo '<a href="' . cpt_check_return( 'cpt' ) . '"> ' . __( 'Manage custom post types', 'cpt-plugin') . '</a>';
} elseif ( $_GET['cpt_msg'] == 2 ) {
_e('Custom taxonomy created successfully. You may need to refresh to view the new taxonomy in the admin menu.', 'cpt-plugin' );
echo '<a href="' . cpt_check_return( 'tax' ) . '"> ' . __( 'Manage custom taxonomies', 'cpt-plugin') . '</a>';
} ?>
</div>
<?php
else :
if ( isset( $_GET['cpt_error'] ) ) : ?>
<div class="error">
<?php if ( $_GET['cpt_error'] == 1 ) {
_e( 'Post type name is a required field.', 'cpt-plugin' );
}
if ( $_GET['cpt_error'] == 2 ) {
_e( 'Taxonomy name is a required field.', 'cpt-plugin' );
}
if ( $_GET['cpt_error'] == 3 ) {
_e( 'You must assign your custom taxonomy to at least one post type.', 'cpt-plugin' );
}
if ( $_GET['cpt_error'] == 4 ) {
_e( 'Please doe not use quotes in your post type slug or rewrite slug.', 'cpt-plugin' );
}
if ( $_GET['cpt_error'] == 5 ) {
_e( 'Please doe not use quotes in your taxonomy slug or rewrite slug.', 'cpt-plugin' );
} ?>
</div>
<?php
endif;
endif;
screen_icon( 'plugins' );
if ( isset( $_GET['edittype'] ) || isset( $_GET['edittax'] ) ) { ?>
<h2>
<?php _e('Edit Custom Post Type or Taxonomy', 'cpt-plugin') ?> ·
<a href="<?php echo cpt_check_return( 'add' ); ?>">
<?php _e('Reset', 'cpt-plugin');?>
</a>
</h2>
<?php } else { ?>
<h2>
<?php _e('Create New Custom Post Type or Taxonomy', 'cpt-plugin') ?> ·
<a href="<?php echo cpt_check_return( 'add' ); ?>">
<?php _e('Reset', 'cpt-plugin');?>
</a>
</h2>
<?php } ?>
<table border="0" cellspacing="10" class="widefat">
<?php
//BEGIN CPT HALF
?>
<tr>
<td width="50%" valign="top">
<p><?php _e('If you are unfamiliar with the options below only fill out the <strong>Post Type Name</strong> and <strong>Label</strong> fields and check which meta boxes to support. The other settings are set to the most common defaults for custom post types. Hover over the question mark for more details.', 'cpt-plugin'); ?></p>
<form method="post" <?php echo $RETURN_URL; ?>>
<?php
if ( function_exists( 'wp_nonce_field' ) )
wp_nonce_field( 'cpt_add_custom_post_type' );
?>
<?php if ( isset( $_GET['edittype'] ) ) { ?>
<input type="hidden" name="cpt_edit" value="<?php echo esc_attr( $editType ); ?>" />
<?php } ?>
<table class="form-table">
<tr valign="top">
<th scope="row"><?php _e('Post Type Name', 'cpt-plugin') ?> <span class="required">*</span> <a href="#" title="<?php esc_attr_e( 'The post type name. Used to retrieve custom post type content. Should be short and sweet', 'cpt-plugin'); ?>" class="help">?</a></th>
<td><input type="text" name="cpt_custom_post_type[name]" tabindex="1" value="<?php if (isset($cpt_post_type_name)) { echo esc_attr($cpt_post_type_name); } ?>" maxlength="20" onblur="this.value=this.value.toLowerCase()" /> <?php _e( '(e.g. movie)', 'cpt-plugin' ); ?>
<br />
<p><strong><?php _e( 'Max 20 characters, can not contain capital letters or spaces. Reserved post types: post, page, attachment, revision, nav_menu_item.', 'cpt-plugin' ); ?></strong></p>
</td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Label', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Post type label. Used in the admin menu for displaying post types.', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td><input type="text" name="cpt_custom_post_type[label]" tabindex="2" value="<?php if (isset($cpt_label)) { echo esc_attr($cpt_label); } ?>" /> <?php _e( '(e.g. Movies)', 'cpt-plugin' ); ?></td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Singular Label', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Custom Post Type Singular label. Used in WordPress when a singular label is needed.', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td><input type="text" name="cpt_custom_post_type[singular_label]" tabindex="3" value="<?php if (isset($cpt_singular_label)) { echo esc_attr($cpt_singular_label); } ?>" /> <?php _e( '(e.g. Movie)', 'cpt-plugin' ); ?></td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Description', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Custom Post Type Description. Describe what your custom post type is used for.', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td><textarea name="cpt_custom_post_type[description]" tabindex="4" rows="4" cols="40"><?php if (isset($cpt_description)) { echo esc_attr($cpt_description); } ?></textarea></td>
</tr>
<tr valign="top">
<td colspan="2">
<p align="center">
<?php echo '<a href="#" class="comment_button" id="1">' . __( 'Advanced Label Options', 'cpt-plugin' ) . '</a>'; ?> |
<?php echo '<a href="#" class="comment_button" id="2">' . __( 'Advanced Options', 'cpt-plugin' ) . '</a>'; ?>
</p>
</td>
</tr>
</table>
<div style="display:none;" id="slidepanel1">
<p><?php _e('Below are the advanced label options for custom post types. If you are unfamiliar with these labels, leave them blank and the plugin will automatically create labels based off of your custom post type name', 'cpt-plugin'); ?></p>
<table class="form-table">
<tr valign="top">
<th scope="row"><?php _e('Menu Name', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Custom menu name for your custom post type.', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td><input type="text" name="cpt_labels[menu_name]" tabindex="2" value="<?php if (isset($cpt_labels["menu_name"])) { echo esc_attr($cpt_labels["menu_name"]); } ?>" /><br/>
<?php _e( '(e.g. My Movies)', 'cpt-plugin' ); ?></td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Add New', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Post type label. Used in the admin menu for displaying post types.', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td><input type="text" name="cpt_labels[add_new]" tabindex="2" value="<?php if (isset($cpt_labels["add_new"])) { echo esc_attr($cpt_labels["add_new"]); } ?>" /><br/>
<?php _e( '(e.g. Add New)', 'cpt-plugin' ); ?></td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Add New Item', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Post type label. Used in the admin menu for displaying post types.', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td><input type="text" name="cpt_labels[add_new_item]" tabindex="2" value="<?php if (isset($cpt_labels["add_new_item"])) { echo esc_attr($cpt_labels["add_new_item"]); } ?>" /><br/>
<?php _e( '(e.g. Add New Movie)', 'cpt-plugin' ); ?></td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Edit', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Post type label. Used in the admin menu for displaying post types.', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td><input type="text" name="cpt_labels[edit]" tabindex="2" value="<?php if (isset($cpt_labels["edit"])) { echo esc_attr($cpt_labels["edit"]); } ?>" /><br/>
<?php _e( '(e.g. Edit)', 'cpt-plugin' ); ?></td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Edit Item', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Post type label. Used in the admin menu for displaying post types.', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td><input type="text" name="cpt_labels[edit_item]" tabindex="2" value="<?php if (isset($cpt_labels["edit_item"])) { echo esc_attr($cpt_labels["edit_item"]); } ?>" /><br/>
<?php _e( '(e.g. Edit Movie)', 'cpt-plugin' ); ?></td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('New Item', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Post type label. Used in the admin menu for displaying post types.', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td><input type="text" name="cpt_labels[new_item]" tabindex="2" value="<?php if (isset($cpt_labels["new_item"])) { echo esc_attr($cpt_labels["new_item"]); } ?>" /><br/>
<?php _e( '(e.g. New Movie)', 'cpt-plugin' ); ?></td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('View', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Post type label. Used in the admin menu for displaying post types.', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td><input type="text" name="cpt_labels[view]" tabindex="2" value="<?php if (isset($cpt_labels["view"])) { echo esc_attr($cpt_labels["view"]); } ?>" /><br/>
<?php _e( '(e.g. View Movie)', 'cpt-plugin' ); ?></td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('View Item', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Post type label. Used in the admin menu for displaying post types.', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td><input type="text" name="cpt_labels[view_item]" tabindex="2" value="<?php if (isset($cpt_labels["view_item"])) { echo esc_attr($cpt_labels["view_item"]); } ?>" /><br/>
<?php _e( '(e.g. View Movie)', 'cpt-plugin' ); ?></td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Search Items', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Post type label. Used in the admin menu for displaying post types.', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td><input type="text" name="cpt_labels[search_items]" tabindex="2" value="<?php if (isset($cpt_labels["search_items"])) { echo esc_attr($cpt_labels["search_items"]); } ?>" /><br/>
<?php _e( '(e.g. Search Movies)', 'cpt-plugin' ); ?></td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Not Found', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Post type label. Used in the admin menu for displaying post types.', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td><input type="text" name="cpt_labels[not_found]" tabindex="2" value="<?php if (isset($cpt_labels["not_found"])) { echo esc_attr($cpt_labels["not_found"]); } ?>" /><br/>
<?php _e( '(e.g. No Movies Found)', 'cpt-plugin' ); ?></td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Not Found in Trash', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Post type label. Used in the admin menu for displaying post types.', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td><input type="text" name="cpt_labels[not_found_in_trash]" tabindex="2" value="<?php if (isset($cpt_labels["not_found_in_trash"])) { echo esc_attr($cpt_labels["not_found_in_trash"]); } ?>" /><br/>
<?php _e( '(e.g. No Movies found in Trash)', 'cpt-plugin' ); ?></td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Parent', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Post type label. Used in the admin menu for displaying post types.', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td><input type="text" name="cpt_labels[parent]" tabindex="2" value="<?php if (isset($cpt_labels["parent"])) { echo esc_attr($cpt_labels["parent"]); } ?>" /><br/>
<?php _e( '(e.g. Parent Movie)', 'cpt-plugin' ); ?></td>
</tr>
</table>
</div>
<div style="display:none;" id="slidepanel2">
<table class="form-table">
<tr valign="top">
<th scope="row"><?php _e('Public', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Whether posts of this type should be shown in the admin UI', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td>
<select name="cpt_custom_post_type[public]" tabindex="4">
<option value="0" <?php if (isset($cpt_public)) { if ($cpt_public == 0 && $cpt_public != '') { echo 'selected="selected"'; } } ?>><?php _e( 'False', 'cpt-plugin' ); ?></option>
<option value="1" <?php if (isset($cpt_public)) { if ($cpt_public == 1 || is_null($cpt_public)) { echo 'selected="selected"'; } } else { echo 'selected="selected"'; } ?>><?php _e( 'True', 'cpt-plugin' ); ?></option>
</select> <?php _e( '(default: True)', 'cpt-plugin' ); ?>
</td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Show UI', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Whether to generate a default UI for managing this post type', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td>
<select name="cpt_custom_post_type[show_ui]" tabindex="5">
<option value="0" <?php if (isset($cpt_showui)) { if ($cpt_showui == 0 && $cpt_showui != '') { echo 'selected="selected"'; } } ?>><?php _e( 'False', 'cpt-plugin' ); ?></option>
<option value="1" <?php if (isset($cpt_showui)) { if ($cpt_showui == 1 || is_null($cpt_showui)) { echo 'selected="selected"'; } } else { echo 'selected="selected"'; } ?>><?php _e( 'True', 'cpt-plugin' ); ?></option>
</select> <?php _e( '(default: True)', 'cpt-plugin' ); ?>
</td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Has Archive', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Whether the post type will have a post type archive page', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td>
<select name="cpt_custom_post_type[has_archive]" tabindex="6">
<option value="0" <?php if (isset($cpt_has_archive)) { if ($cpt_has_archive == 0) { echo 'selected="selected"'; } } else { echo 'selected="selected"'; } ?>><?php _e( 'False', 'cpt-plugin' ); ?></option>
<option value="1" <?php if (isset($cpt_has_archive)) { if ($cpt_has_archive == 1) { echo 'selected="selected"'; } } ?>><?php _e( 'True', 'cpt-plugin' ); ?></option>
</select> <?php _e( '(default: False)', 'cpt-plugin' ); ?>
</td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Exclude From Search', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Whether the post type will be searchable', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td>
<select name="cpt_custom_post_type[exclude_from_search]" tabindex="6">
<option value="0" <?php if (isset($cpt_exclude_from_search)) { if ($cpt_exclude_from_search == 0) { echo 'selected="selected"'; } } else { echo 'selected="selected"'; } ?>><?php _e( 'False', 'cpt-plugin' ); ?></option>
<option value="1" <?php if (isset($cpt_exclude_from_search)) { if ($cpt_exclude_from_search == 1) { echo 'selected="selected"'; } } ?>><?php _e( 'True', 'cpt-plugin' ); ?></option>
</select> <?php _e( '(default: False)', 'cpt-plugin' ); ?>
</td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Capability Type', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'The post type to use for checking read, edit, and delete capabilities', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td><input type="text" name="cpt_custom_post_type[capability_type]" tabindex="6" value="<?php if ( isset( $cpt_capability ) ) { echo esc_attr( $cpt_capability ); } else { echo 'post'; } ?>" /></td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Hierarchical', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Whether the post type can have parent-child relationships', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td>
<select name="cpt_custom_post_type[hierarchical]" tabindex="8">
<option value="0" <?php if (isset($cpt_hierarchical)) { if ($cpt_hierarchical == 0) { echo 'selected="selected"'; } } else { echo 'selected="selected"'; } ?>><?php _e( 'False', 'cpt-plugin' ); ?></option>
<option value="1" <?php if (isset($cpt_hierarchical)) { if ($cpt_hierarchical == 1) { echo 'selected="selected"'; } } ?>><?php _e( 'True', 'cpt-plugin' ); ?></option>
</select> <?php _e( '(default: False)', 'cpt-plugin' ); ?>
</td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Rewrite', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Triggers the handling of rewrites for this post type', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td>
<select name="cpt_custom_post_type[rewrite]" tabindex="9">
<option value="0" <?php if (isset($cpt_rewrite)) { if ($cpt_rewrite == 0 && $cpt_rewrite != '') { echo 'selected="selected"'; } } ?>><?php _e( 'False', 'cpt-plugin' ); ?></option>
<option value="1" <?php if (isset($cpt_rewrite)) { if ($cpt_rewrite == 1 || is_null($cpt_rewrite)) { echo 'selected="selected"'; } } else { echo 'selected="selected"'; } ?>><?php _e( 'True', 'cpt-plugin' ); ?></option>
</select> <?php _e( '(default: True)', 'cpt-plugin' ); ?>
</td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Custom Rewrite Slug', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Custom slug to use instead of the default.' ,'cpt-plugin' ); ?>" class="help">?</a></th>
<td><input type="text" name="cpt_custom_post_type[rewrite_slug]" tabindex="10" value="<?php if (isset($cpt_rewrite_slug)) { echo esc_attr($cpt_rewrite_slug); } ?>" /> <?php _e( '(default: post type name)', 'cpt-plugin' ); ?></td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('With Front', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Should the permastruct be prepended with the front base.', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td>
<select name="cpt_custom_post_type[rewrite_withfront]" tabindex="4">
<option value="0" <?php if (isset($cpt_rewrite_withfront)) { if ($cpt_rewrite_withfront == 0 && $cpt_rewrite_withfront != '') { echo 'selected="selected"'; } } ?>><?php _e( 'False', 'cpt-plugin' ); ?></option>
<option value="1" <?php if (isset($cpt_rewrite_withfront)) { if ($cpt_rewrite_withfront == 1 || is_null($cpt_rewrite_withfront)) { echo 'selected="selected"'; } } else { echo 'selected="selected"'; } ?>><?php _e( 'True', 'cpt-plugin' ); ?></option>
</select> <?php _e( '(default: True)', 'cpt-plugin' ); ?>
</td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Query Var', 'cpt-plugin') ?> <a href="#" title="" class="help">?</a></th>
<td>
<select name="cpt_custom_post_type[query_var]" tabindex="10">
<option value="0" <?php if (isset($cpt_query_var)) { if ($cpt_query_var == 0 && $cpt_query_var != '') { echo 'selected="selected"'; } } ?>><?php _e( 'False', 'cpt-plugin' ); ?></option>
<option value="1" <?php if (isset($cpt_query_var)) { if ($cpt_query_var == 1 || is_null($cpt_query_var)) { echo 'selected="selected"'; } } else { echo 'selected="selected"'; } ?>><?php _e( 'True', 'cpt-plugin' ); ?></option>
</select> <?php _e( '(default: True)', 'cpt-plugin' ); ?>
</td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Menu Position', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'The position in the menu order the post type should appear. show_in_menu must be true.', 'cpt-plugin' ); ?>" class="help">?</a>
<p><?php _e( 'See <a href="http://codex.wordpress.org/Function_Reference/register_post_type#Parameters">Available options</a> in the "menu_position" section. Range of 5-100', 'cpt-plugin' ); ?></p>
</th>
<td><input type="text" name="cpt_custom_post_type[menu_position]" tabindex="11" size="5" value="<?php if (isset($cpt_menu_position)) { echo esc_attr($cpt_menu_position); } ?>" /></td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Show in Menu', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Whether to show the post type in the admin menu and where to show that menu. Note that show_ui must be true', 'cpt-plugin' ); ?>" class="help">?</a>
<p><?php _e( '"Show UI" must be "true". If an existing top level page such as "tools.php" is indicated for second input, post type will be sub menu of that.', 'cpt-plugins' ); ?></p>
</th>
<td>
<p><select name="cpt_custom_post_type[show_in_menu]" tabindex="10">
<option value="0" <?php if (isset($cpt_show_in_menu)) { if ($cpt_show_in_menu == 0) { echo 'selected="selected"'; } } ?>><?php _e( 'False', 'cpt-plugin' ); ?></option>
<option value="1" <?php if (isset($cpt_show_in_menu)) { if ($cpt_show_in_menu == 1 || is_null($cpt_show_in_menu)) { echo 'selected="selected"'; } } else { echo 'selected="selected"'; } ?>><?php _e( 'True', 'cpt-plugin' ); ?></option>
</select></p>
<p>
<input type="text" name="cpt_custom_post_type[show_in_menu_string]" tabindex="12" size="20" value="<?php if (isset($cpt_show_in_menu_string)) { echo esc_attr($cpt_show_in_menu_string); } ?>" /></p></td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Menu Icon', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'URL to image to be used as menu icon.', 'cpt-plugin' ); ?>" class="help">?</a>
</th>
<td><input type="text" name="cpt_custom_post_type[menu_icon]" tabindex="11" size="20" value="<?php if (isset($cpt_menu_icon)) { echo esc_attr($cpt_menu_icon); } ?>" /> (Full URL for icon)</td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Supports', 'cpt-plugin') ?></th>
<td>
<input type="checkbox" name="cpt_supports[]" tabindex="11" value="title" <?php if (isset($cpt_supports) && is_array($cpt_supports)) { if (in_array('title', $cpt_supports)) { echo 'checked="checked"'; } } elseif (!isset($_GET['edittype'])) { echo 'checked="checked"'; } ?> /> <?php _e( 'Title' , 'cpt-plugin' ); ?> <a href="#" title="<?php esc_attr_e( 'Adds the title meta box when creating content for this custom post type', 'cpt-plugin' ); ?>" class="help">?</a> <br/ >
<input type="checkbox" name="cpt_supports[]" tabindex="12" value="editor" <?php if (isset($cpt_supports) && is_array($cpt_supports)) { if (in_array('editor', $cpt_supports)) { echo 'checked="checked"'; } } elseif (!isset($_GET['edittype'])) { echo 'checked="checked"'; } ?> /> <?php _e( 'Editor' , 'cpt-plugin' ); ?> <a href="#" title="<?php esc_attr_e( 'Adds the content editor meta box when creating content for this custom post type', 'cpt-plugin' ); ?>" class="help">?</a> <br/ >
<input type="checkbox" name="cpt_supports[]" tabindex="13" value="excerpt" <?php if (isset($cpt_supports) && is_array($cpt_supports)) { if (in_array('excerpt', $cpt_supports)) { echo 'checked="checked"'; } } elseif (!isset($_GET['edittype'])) { echo 'checked="checked"'; } ?> /> <?php _e( 'Excerpt' , 'cpt-plugin' ); ?> <a href="#" title="<?php esc_attr_e( 'Adds the excerpt meta box when creating content for this custom post type', 'cpt-plugin' ); ?>" class="help">?</a> <br/ >
<input type="checkbox" name="cpt_supports[]" tabindex="14" value="trackbacks" <?php if (isset($cpt_supports) && is_array($cpt_supports)) { if (in_array('trackbacks', $cpt_supports)) { echo 'checked="checked"'; } } elseif (!isset($_GET['edittype'])) { echo 'checked="checked"'; } ?> /> <?php _e( 'Trackbacks' , 'cpt-plugin' ); ?> <a href="#" title="<?php esc_attr_e( 'Adds the trackbacks meta box when creating content for this custom post type', 'cpt-plugin' ); ?>" class="help">?</a> <br/ >
<input type="checkbox" name="cpt_supports[]" tabindex="15" value="custom-fields" <?php if (isset($cpt_supports) && is_array($cpt_supports)) { if (in_array('custom-fields', $cpt_supports)) { echo 'checked="checked"'; } } elseif (!isset($_GET['edittype'])) { echo 'checked="checked"'; } ?> /> <?php _e( 'Custom Fields' , 'cpt-plugin' ); ?> <a href="#" title="<?php esc_attr_e( 'Adds the custom fields meta box when creating content for this custom post type', 'cpt-plugin' ); ?>" class="help">?</a> <br/ >
<input type="checkbox" name="cpt_supports[]" tabindex="16" value="comments" <?php if (isset($cpt_supports) && is_array($cpt_supports)) { if (in_array('comments', $cpt_supports)) { echo 'checked="checked"'; } } elseif (!isset($_GET['edittype'])) { echo 'checked="checked"'; } ?> /> <?php _e( 'Comments' , 'cpt-plugin' ); ?> <a href="#" title="<?php esc_attr_e( 'Adds the comments meta box when creating content for this custom post type', 'cpt-plugin' ); ?>" class="help">?</a> <br/ >
<input type="checkbox" name="cpt_supports[]" tabindex="17" value="revisions" <?php if (isset($cpt_supports) && is_array($cpt_supports)) { if (in_array('revisions', $cpt_supports)) { echo 'checked="checked"'; } } elseif (!isset($_GET['edittype'])) { echo 'checked="checked"'; } ?> /> <?php _e( 'Revisions' , 'cpt-plugin' ); ?> <a href="#" title="<?php esc_attr_e( 'Adds the revisions meta box when creating content for this custom post type', 'cpt-plugin' ); ?>" class="help">?</a> <br/ >
<input type="checkbox" name="cpt_supports[]" tabindex="18" value="thumbnail" <?php if (isset($cpt_supports) && is_array($cpt_supports)) { if (in_array('thumbnail', $cpt_supports)) { echo 'checked="checked"'; } } elseif (!isset($_GET['edittype'])) { echo 'checked="checked"'; } ?> /> <?php _e( 'Featured Image' , 'cpt-plugin' ); ?> <a href="#" title="<?php esc_attr_e( 'Adds the featured image meta box when creating content for this custom post type', 'cpt-plugin' ); ?>" class="help">?</a> <br/ >
<input type="checkbox" name="cpt_supports[]" tabindex="19" value="author" <?php if (isset($cpt_supports) && is_array($cpt_supports)) { if (in_array('author', $cpt_supports)) { echo 'checked="checked"'; } } elseif (!isset($_GET['edittype'])) { echo 'checked="checked"'; } ?> /> <?php _e( 'Author' , 'cpt-plugin' ); ?> <a href="#" title="<?php esc_attr_e( 'Adds the author meta box when creating content for this custom post type', 'cpt-plugin' ); ?>" class="help">?</a> <br/ >
<input type="checkbox" name="cpt_supports[]" tabindex="20" value="page-attributes" <?php if (isset($cpt_supports) && is_array($cpt_supports)) { if (in_array('page-attributes', $cpt_supports)) { echo 'checked="checked"'; } } elseif (!isset($_GET['edittype'])) { echo 'checked="checked"'; } ?> /> <?php _e( 'Page Attributes' , 'cpt-plugin' ); ?> <a href="#" title="<?php esc_attr_e( 'Adds the page attribute meta box when creating content for this custom post type', 'cpt-plugin' ); ?>" class="help">?</a> <br/ >
<input type="checkbox" name="cpt_supports[]" tabindex="21" value="post-formats" <?php if (isset($cpt_supports) && is_array($cpt_supports)) { if (in_array('post-formats', $cpt_supports)) { echo 'checked="checked"'; } } elseif (!isset($_GET['edittype'])) { echo 'checked="checked"'; } ?> /> <?php _e( 'Post Formats' , 'cpt-plugin' ); ?> <a href="#" title="<?php esc_attr_e( 'Adds post format support', 'cpt-plugin' ); ?>" class="help">?</a> <br/ >
</td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Built-in Taxonomies', 'cpt-plugin') ?></th>
<td>
<?php
//load built-in WP Taxonomies
$args=array( 'public' => true );
$output = 'objects';
$add_taxes = get_taxonomies($args,$output);
foreach ($add_taxes as $add_tax ) {
if ( $add_tax->name != 'nav_menu' && $add_tax->name != 'post_format') {
?>
<input type="checkbox" name="cpt_addon_taxes[]" tabindex="20" value="<?php echo $add_tax->name; ?>" <?php if (isset($cpt_taxes) && is_array($cpt_taxes)) { if (in_array($add_tax->name, $cpt_taxes)) { echo 'checked="checked"'; } } ?> /> <?php echo $add_tax->label; ?><br />
<?php
}
}
?>
</td>
</tr>
</table>
</div>
<p class="submit">
<input type="submit" class="button-primary" tabindex="21" name="cpt_submit" value="<?php echo $cpt_submit_name; ?>" />
</p>
</form>
</td>
<?php //BEGIN TAXONOMY SIDE ?>
<td width="50%" valign="top">
<?php
//debug area
$cpt_options = get_option('cpt_custom_tax_types');
?>
<p><?php _e( 'If you are unfamiliar with the options below only fill out the <strong>Taxonomy Name</strong> and <strong>Post Type Name</strong> fields. The other settings are set to the most common defaults for custom taxonomies. Hover over the question mark for more details.', 'cpt-plugin' );?></p>
<form method="post" <?php echo $RETURN_URL; ?>>
<?php if ( function_exists('wp_nonce_field') )
wp_nonce_field('cpt_add_custom_taxonomy'); ?>
<?php if (isset($_GET['edittax'])) { ?>
<input type="hidden" name="cpt_edit_tax" value="<?php echo $editTax; ?>" />
<?php } ?>
<table class="form-table">
<tr valign="top">
<th scope="row"><?php _e('Taxonomy Name', 'cpt-plugin') ?> <span class="required">*</span> <a href="#" title="<?php esc_attr_e( 'The taxonomy name. Used to retrieve custom taxonomy content. Should be short and sweet', 'cpt-plugin' ); ?>" class="help">?</a>
<p><?php _e('Note: Changing the name, after adding terms to the taxonomy, will not update the terms in the database.', 'cpt-plugin' ); ?></p>
</th>
<td><input type="text" name="cpt_custom_tax[name]" maxlength="32" onblur="this.value=this.value.toLowerCase()" tabindex="21" value="<?php if (isset($cpt_tax_name)) { echo esc_attr($cpt_tax_name); } ?>" /> <?php _e( '(e.g. actors)', 'cpt-plugin' ); ?>
<p><strong><?php _e( 'Max 32 characters, should only contain alphanumeric lowercase characters and underscores in place of spaces.', 'cpt-plugin' ); ?></strong></p>
</td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Label', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Taxonomy label. Used in the admin menu for displaying custom taxonomy.', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td><input type="text" name="cpt_custom_tax[label]" tabindex="22" value="<?php if (isset($cpt_tax_label)) { echo esc_attr( $cpt_tax_label ); } ?>" /> <?php _e( '(e.g. Actors)', 'cpt-plugin' ); ?></td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Singular Label', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Taxonomy Singular label. Used in WordPress when a singular label is needed.', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td><input type="text" name="cpt_custom_tax[singular_label]" tabindex="23" value="<?php if (isset($cpt_singular_label_tax)) { echo esc_attr( $cpt_singular_label_tax ); } ?>" /> <?php _e( '(e.g. Actor)', 'cpt-plugin' ); ?></td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Attach to Post Type', 'cpt-plugin') ?> <span class="required">*</span> <a href="#" title="<?php esc_attr_e ('What post type object to attach the custom taxonomy to. Can be post, page, or link by default. Can also be any custom post type name.', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td>
<?php if ( isset( $cpt_tax_object_type ) ) { ?>
<strong><?php _e( 'This is the old method. Delete the post type from the textbox and check which post type to attach this taxonomy to</strong>', 'cpt-plugin' ); ?>
<input type="text" name="cpt_custom_tax[cpt_name]" tabindex="24" value="<?php if (isset($cpt_tax_object_type)) { echo esc_attr($cpt_tax_object_type); } ?>" /> <?php _e( '(e.g. movies)', 'cpt-plugin' ); ?>
<?php } ?>
<?php
$args=array(
'public' => true
);
$output = 'objects'; // or objects
$post_types=get_post_types($args,$output);
foreach ($post_types as $post_type ) {
if ( $post_type->name != 'attachment' ) {
?>
<input type="checkbox" name="cpt_post_types[]" tabindex="20" value="<?php echo $post_type->name; ?>" <?php if (isset($cpt_post_types) && is_array($cpt_post_types)) { if (in_array($post_type->name, $cpt_post_types)) { echo 'checked="checked"'; } } ?> /> <?php echo $post_type->label; ?><br />
<?php
}
}
?>
</td>
</tr>
<tr valign="top">
<td colspan="2">
<p align="center">
<?php echo '<a href="#" class="comment_button" id="3">' . __('Advanced Label Options', 'cpt-plugin') . '</a>'; ?> |
<?php echo '<a href="#" class="comment_button" id="4">' . __('Advanced Options', 'cpt-plugin') . '</a>'; ?>
</p>
</td>
</tr>
</table>
<div style="display:none;" id="slidepanel3">
<p><?php _e('Below are the advanced label options for custom taxonomies. If you are unfamiliar with these labels the plugin will automatically create labels based off of your custom taxonomy name', 'cpt-plugin'); ?></p>
<table class="form-table">
<tr valign="top">
<th scope="row"><?php _e('Search Items', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Custom taxonomy label. Used in the admin menu for displaying taxonomies.', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td><input type="text" name="cpt_tax_labels[search_items]" tabindex="2" value="<?php if (isset($cpt_tax_labels["search_items"])) { echo esc_attr($cpt_tax_labels["search_items"]); } ?>" /><br/>
<?php _e('(e.g. Search Actors)', 'cpt-plugin' ); ?></td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Popular Items', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Custom taxonomy label. Used in the admin menu for displaying taxonomies.', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td><input type="text" name="cpt_tax_labels[popular_items]" tabindex="2" value="<?php if (isset($cpt_tax_labels["popular_items"])) { echo esc_attr($cpt_tax_labels["popular_items"]); } ?>" /><br/>
<?php _e('(e.g. Popular Actors)', 'cpt-plugin' ); ?></td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('All Items', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Custom taxonomy label. Used in the admin menu for displaying taxonomies.', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td><input type="text" name="cpt_tax_labels[all_items]" tabindex="2" value="<?php if (isset($cpt_tax_labels["all_items"])) { echo esc_attr($cpt_tax_labels["all_items"]); } ?>" /><br/>
<?php _e('(e.g. All Actors)', 'cpt-plugin' ); ?></td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Parent Item', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Custom taxonomy label. Used in the admin menu for displaying taxonomies.', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td><input type="text" name="cpt_tax_labels[parent_item]" tabindex="2" value="<?php if (isset($cpt_tax_labels["parent_item"])) { echo esc_attr($cpt_tax_labels["parent_item"]); } ?>" /><br/>
<?php _e('(e.g. Parent Actor)', 'cpt-plugin' ); ?></td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Parent Item Colon', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Custom taxonomy label. Used in the admin menu for displaying taxonomies.', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td><input type="text" name="cpt_tax_labels[parent_item_colon]" tabindex="2" value="<?php if (isset($cpt_tax_labels["parent_item_colon"])) { echo esc_attr($cpt_tax_labels["parent_item_colon"]); } ?>" /><br/>
<?php _e('(e.g. Parent Actor:)', 'cpt-plugin' ); ?></td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Edit Item', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Custom taxonomy label. Used in the admin menu for displaying taxonomies.', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td><input type="text" name="cpt_tax_labels[edit_item]" tabindex="2" value="<?php if (isset($cpt_tax_labels["edit_item"])) { echo esc_attr($cpt_tax_labels["edit_item"]); } ?>" /><br/>
<?php _e( '(e.g. Edit Actor)', 'cpt-plugin' ); ?></td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Update Item', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Custom taxonomy label. Used in the admin menu for displaying taxonomies.', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td><input type="text" name="cpt_tax_labels[update_item]" tabindex="2" value="<?php if (isset($cpt_tax_labels["update_item"])) { echo esc_attr($cpt_tax_labels["update_item"]); } ?>" /><br/>
<?php _e( '(e.g. Update Actor)', 'cpt-plugin' ); ?></td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Add New Item', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Custom taxonomy label. Used in the admin menu for displaying taxonomies.', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td><input type="text" name="cpt_tax_labels[add_new_item]" tabindex="2" value="<?php if (isset($cpt_tax_labels["add_new_item"])) { echo esc_attr($cpt_tax_labels["add_new_item"]); } ?>" /><br/>
<?php _e( '(e.g. Add New Actor)', 'cpt-plugin' ); ?></td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('New Item Name', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Custom taxonomy label. Used in the admin menu for displaying taxonomies.', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td><input type="text" name="cpt_tax_labels[new_item_name]" tabindex="2" value="<?php if (isset($cpt_tax_labels["new_item_name"])) { echo esc_attr($cpt_tax_labels["new_item_name"]); } ?>" /><br/>
<?php _e( '(e.g. New Actor Name)', 'cpt-plugin' ); ?></td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Separate Items with Commas', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Custom taxonomy label. Used in the admin menu for displaying taxonomies.', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td><input type="text" name="cpt_tax_labels[separate_items_with_commas]" tabindex="2" value="<?php if (isset($cpt_tax_labels["separate_items_with_commas"])) { echo esc_attr($cpt_tax_labels["separate_items_with_commas"]); } ?>" /><br/>
<?php _e( '(e.g. Separate actors with commas)', 'cpt-plugin' ); ?></td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Add or Remove Items', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Custom taxonomy label. Used in the admin menu for displaying taxonomies.', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td><input type="text" name="cpt_tax_labels[add_or_remove_items]" tabindex="2" value="<?php if (isset($cpt_tax_labels["add_or_remove_items"])) { echo esc_attr($cpt_tax_labels["add_or_remove_items"]); } ?>" /><br/>
<?php _e( '(e.g. Add or remove actors)', 'cpt-plugin' ); ?></td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Choose From Most Used', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Custom taxonomy label. Used in the admin menu for displaying taxonomies.', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td><input type="text" name="cpt_tax_labels[choose_from_most_used]" tabindex="2" value="<?php if (isset($cpt_tax_labels["choose_from_most_used"])) { echo esc_attr($cpt_tax_labels["choose_from_most_used"]); } ?>" /><br/>
<?php _e( '(e.g. Choose from the most used actors)', 'cpt-plugin' ); ?></td>
</tr>
</table>
</div>
<div style="display:none;" id="slidepanel4">
<table class="form-table">
<tr valign="top">
<th scope="row"><?php _e('Hierarchical', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Whether the taxonomy can have parent-child relationships', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td>
<select name="cpt_custom_tax[hierarchical]" tabindex="25">
<option value="0" <?php if (isset($cpt_tax_hierarchical)) { if ($cpt_tax_hierarchical == 0) { echo 'selected="selected"'; } } else { echo 'selected="selected"'; } ?>>False</option>
<option value="1" <?php if (isset($cpt_tax_hierarchical)) { if ($cpt_tax_hierarchical == 1) { echo 'selected="selected"'; } } ?>>True</option>
</select> <?php _e('(default: False)', 'cpt-plugin' ); ?>
</td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Show UI', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Whether to generate a default UI for managing this custom taxonomy', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td>
<select name="cpt_custom_tax[show_ui]" tabindex="26">
<option value="0" <?php if (isset($cpt_tax_showui)) { if ($cpt_tax_showui == 0 && $cpt_tax_showui != '') { echo 'selected="selected"'; } } ?>><?php _e( 'False', 'cpt-plugin' ); ?></option>
<option value="1" <?php if (isset($cpt_tax_showui)) { if ($cpt_tax_showui == 1 || is_null($cpt_tax_showui)) { echo 'selected="selected"'; } } else { echo 'selected="selected"'; } ?>><?php _e( 'True', 'cpt-plugin' ); ?></option>
</select> <?php _e('(default: True)', 'cpt-plugin' ); ?>
</td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Query Var', 'cpt-plugin') ?> <a href="#" title="" class="help">?</a></th>
<td>
<select name="cpt_custom_tax[query_var]" tabindex="27">
<option value="0" <?php if (isset($cpt_tax_query_var)) { if ($cpt_tax_query_var == 0 && $cpt_tax_query_var != '') { echo 'selected="selected"'; } } ?>><?php _e( 'False', 'cpt-plugin' ); ?></option>
<option value="1" <?php if (isset($cpt_tax_query_var)) { if ($cpt_tax_query_var == 1 || is_null($cpt_tax_query_var)) { echo 'selected="selected"'; } } else { echo 'selected="selected"'; } ?>><?php _e( 'True', 'cpt-plugin' ); ?></option>
</select> <?php _e( '(default: True)', 'cpt-plugin' ); ?>
</td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Rewrite', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Triggers the handling of rewrites for this taxonomy', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td>
<select name="cpt_custom_tax[rewrite]" tabindex="28">
<option value="0" <?php if (isset($cpt_tax_rewrite)) { if ($cpt_tax_rewrite == 0 && $cpt_tax_rewrite != '') { echo 'selected="selected"'; } } ?>><?php _e( 'False', 'cpt-plugin' ); ?></option>
<option value="1" <?php if (isset($cpt_tax_rewrite)) { if ($cpt_tax_rewrite == 1 || is_null($cpt_tax_rewrite)) { echo 'selected="selected"'; } } else { echo 'selected="selected"'; } ?>><?php _e( 'True', 'cpt-plugin' ); ?></option>
</select> <?php _e( '(default: True)', 'cpt-plugin' ); ?>
</td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Custom Rewrite Slug', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Custom Taxonomy Rewrite Slug', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td><input type="text" name="cpt_custom_tax[rewrite_slug]" tabindex="9" value="<?php if (isset($cpt_tax_rewrite_slug)) { echo esc_attr($cpt_tax_rewrite_slug); } ?>" /> <?php _e( '(default: taxonomy name)', 'cpt-plugin' ); ?></td>
</tr>
<?php if ( version_compare( CPTUI_WP_VERSION, '3.5', '>' ) ) { ?>
<tr valign="top">
<th scope="row"><?php _e('Show Admin Column', 'cpt-plugin') ?> <a href="#" title="<?php esc_attr_e( 'Whether to allow automatic creation of taxonomy columns on associated post-types.', 'cpt-plugin' ); ?>" class="help">?</a></th>
<td>
<select name="cpt_custom_tax[show_admin_column]" tabindex="28">
<?php if ( !isset( $cpt_tax_show_admin_column ) || $cpt_tax_show_admin_column == 0 ) { ?>
<option value="0" selected="selected"><?php _e( 'False', 'cpt-plugin' ); ?></option>
<option value="1"><?php _e( 'True', 'cpt-plugin' ); ?></option>
<?php } else { ?>
<option value="0"><?php _e( 'False', 'cpt-plugin' ); ?></option>
<option value="1" selected="selected"><?php _e( 'True', 'cpt-plugin' ); ?></option>
<?php } ?>
</select> <?php _e( '(default: False)', 'cpt-plugin' ); ?>
</td>
</tr>
<?php } ?>
</table>
</div>
<p class="submit">
<input type="submit" class="button-primary" tabindex="29" name="cpt_add_tax" value="<?php echo $cpt_tax_submit_name; ?>" />
</p>
</form>
</td>
</tr>
</table>
</div>
<?php
//load footer
cpt_footer();
}
function cpt_footer() {
?>
<hr />
<p class="cp_about"><a target="_blank" href="http://webdevstudios.com/support/forum/custom-post-type-ui/"><?php _e( 'Custom Post Type UI', 'cpt-plugin' ); ?></a> <?php _e( 'version', 'cpt-plugin' ); echo ' '.CPT_VERSION; ?> by <a href="http://webdevstudios.com" target="_blank">WebDevStudios</a> - <a href="https://github.com/WebDevStudios/custom-post-type-ui" target="_blank"><?php _e( 'Please Report Bugs', 'cpt-plugin' ); ?></a> · <?php _e( 'Follow on Twitter:', 'cpt-plugin' ); ?> <a href="http://twitter.com/williamsba" target="_blank">Brad</a> · <a href="http://twitter.com/webdevstudios" target="_blank">WebDevStudios</a></p>
<?php
}
function cpt_check_return( $return ) {
global $CPT_URL;
if ( $return == 'cpt' ) {
return ( isset( $_GET['return'] ) ) ? admin_url( 'admin.php?page=cpt_sub_manage_cpt&return=cpt' ) : admin_url( 'admin.php?page=cpt_sub_manage_cpt' );
} elseif ( $return == 'tax' ){
return ( isset( $_GET['return'] ) ) ? admin_url( 'admin.php?page=cpt_sub_manage_taxonomies&return=tax' ) : admin_url( 'admin.php?page=cpt_sub_manage_taxonomies' );
} elseif ( $return == 'add' ) {
return admin_url( 'admin.php?page=cpt_sub_add_new' );
} else {
return admin_url( 'admin.php?page=cpt_sub_add_new' );
}
}
function get_disp_boolean($booText) {
if ( empty( $booText ) || $booText == '0') {
return false;
}
return true;
}
function disp_boolean($booText) {
if ( empty( $booText ) || $booText == '0' ) {
return 'false';
}
return 'true';
}
function cpt_help_style() { ?>
<style>
.help:hover {
font-weight: bold;
}
.required { color: rgb(255,0,0); }
</style>
<?php
}
| PHP |
<?php
/**
* Implement Custom Header functionality for Asahi Kasei
*
* @package WordPress
*/
/**
* Set up the WordPress core custom header settings.
*
*
* @uses asahikasei_header_style()
* @uses asahikasei_admin_header_style()
* @uses asahikasei_admin_header_image()
*/
function asahikasei_custom_header_setup() {
/**
* Filter Asahi Kasei custom-header support arguments.
*
*
* @param array $args {
* An array of custom-header support arguments.
*
* @type bool $header_text Whether to display custom header text. Default false.
* @type int $width Width in pixels of the custom header image. Default 1260.
* @type int $height Height in pixels of the custom header image. Default 240.
* @type bool $flex_height Whether to allow flexible-height header images. Default true.
* @type string $admin_head_callback Callback function used to style the image displayed in
* the Appearance > Header screen.
* @type string $admin_preview_callback Callback function used to create the custom header markup in
* the Appearance > Header screen.
* }
*/
add_theme_support( 'custom-header', apply_filters( 'asahikasei_custom_header_args', array(
'default-text-color' => 'fff',
'width' => 245,
'height' => 75,
'flex-height' => true,
'wp-head-callback' => 'asahikasei_header_style',
'admin-head-callback' => 'asahikasei_admin_header_style',
'admin-preview-callback' => 'asahikasei_admin_header_image',
) ) );
}
add_action( 'after_setup_theme', 'asahikasei_custom_header_setup' );
if ( ! function_exists( 'asahikasei_header_style' ) ) :
/**
* Styles the header image and text displayed on the blog
*
* @see asahikasei_custom_header_setup().
*
*/
function asahikasei_header_style() {
$text_color = get_header_textcolor();
// If no custom color for text is set, let's bail.
if ( display_header_text() && $text_color === get_theme_support( 'custom-header', 'default-text-color' ) )
return;
// If we get this far, we have custom styles.
?>
<style type="text/css" id="twentyfourteen-header-css">
<?php
// Has the text been hidden?
if ( ! display_header_text() ) :
?>
.site-title,
.site-description {
clip: rect(1px 1px 1px 1px); /* IE7 */
clip: rect(1px, 1px, 1px, 1px);
position: absolute;
}
<?php
// If the user has set a custom color for the text, use that.
elseif ( $text_color != get_theme_support( 'custom-header', 'default-text-color' ) ) :
?>
.site-title a {
color: #<?php echo esc_attr( $text_color ); ?>;
}
<?php endif; ?>
</style>
<?php
}
endif; // asahikasei_header_style
if ( ! function_exists( 'asahikasei_admin_header_style' ) ) :
/**
* Style the header image displayed on the Appearance > Header screen.
*
* @see asahikasei_custom_header_setup()
*
*/
function asahikasei_admin_header_style() {
?>
<style type="text/css" id="twentyfourteen-admin-header-css">
.appearance_page_custom-header #headimg {
background-color: #000;
border: none;
max-width: 1260px;
min-height: 48px;
}
#headimg h1 {
font-family: Lato, sans-serif;
font-size: 18px;
line-height: 48px;
margin: 0 0 0 30px;
}
#headimg h1 a {
color: #fff;
text-decoration: none;
}
#headimg img {
vertical-align: middle;
}
</style>
<?php
}
endif; // asahikasei_admin_header_style
if ( ! function_exists( 'asahikasei_admin_header_image' ) ) :
/**
* Create the custom header image markup displayed on the Appearance > Header screen.
*
* @see asahikasei_custom_header_setup()
*
*/
function asahikasei_admin_header_image() {
?>
<div id="headimg">
<?php if ( get_header_image() ) : ?>
<img src="<?php header_image(); ?>" alt="">
<?php endif; ?>
<h1 class="displaying-header-text"><a id="name"<?php echo sprintf( ' style="color:#%s;"', get_header_textcolor() ); ?> onclick="return false;" href="<?php echo esc_url( home_url( '/' ) ); ?>"><?php bloginfo( 'name' ); ?></a></h1>
</div>
<?php
}
endif; // asahikasei_admin_header_image
| PHP |
<?php get_template_part('templates/head'); ?>
<body <?php body_class(); ?>>
<!--[if lt IE 8]>
<div class="alert alert-warning">
<?php _e('You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.', 'roots'); ?>
</div>
<![endif]-->
<?php
do_action('get_header');
get_template_part('templates/header');
?>
<div class="mainBody">
<div class="container">
<div class="row">
<?php if (function_exists('asahi_kasei_breadcrumb') && !is_home()) { asahi_kasei_breadcrumb(); } ?>
</div>
<div class="row">
<h2 class="title01">
<?php
$category = get_the_category();
$num_cat = count($category);
$parentCat = get_category_parents($category[0]->cat_ID,true,'');
//echo $parentCat;
$parentCatList = get_category_parents(11,false,',');
$parentCatListArray = split(",",$parentCatList);
$topParentName = $parentCatListArray[0];
$sdacReplace = array(" " => " ", "(" => "", ")" => "");
//$topParent = strtoupper(strtr($topParentName,$sdacReplace));
echo $topParentName;
?>
</h2>
<?php if (is_single() || is_category() || is_page()){ ?>
<aside>
<div class="col-md-3">
<?php include roots_sidebar_path(); ?>
</div>
</aside>
<?php
}
elseif(is_home()){
get_template_part('templates/home');
}
else{
include roots_template_path();
}
?>
<section>
<div class="col-md-9">
<h2 class="title02">
<?php echo $parentCatListArray[1]; ?>
</h2>
<h3 class="title03"><?php echo roots_title(); ?></h3>
<?php while (have_posts()) : the_post(); ?>
<article <?php //post_class(); ?>>
<h4 class="title04"><?php the_title(); ?></h4>
<?php //get_template_part('templates/entry-meta'); ?>
<div class="inner">
<a href="<?php echo get_permalink(); ?>"><?php //the_post_thumbnail(); ?></a>
<?php the_content(); ?>
</div>
<?php //comments_template('/templates/comments.php'); ?>
</article>
<?php endwhile; ?>
<?php
wpbeginner_numeric_posts_nav();
get_next_posts_link();
get_previous_posts_link();
paginate_links();
$args = array(
'base' => '%_%',
'format' => '?page=%#%',
'total' => 1,
'current' => 0,
'show_all' => False,
'end_size' => 1,
'mid_size' => 2,
'prev_next' => True,
'prev_text' => __('« Previous'),
'next_text' => __('Next »'),
'type' => 'plain',
'add_args' => False,
'add_fragment' => '',
'before_page_number' => '',
'after_page_number' => ''
);
echo paginate_links( $args );
?>
</div>
</section>
</div>
<div class="row">
<a class="backToTop pull-right" href="#">このページのトップへ戻る</a>
</div>
</div>
</div><!-- end mainBody -->
<?php get_template_part('templates/footer'); ?>
</body>
</html> | PHP |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.