/**
  * The do_enclose method without the removing of enclosures that was causing issues for many users
  * This method has last been updated in WordPress 2.8
  */
 function do_enclose($content, $post_ID)
 {
     global $wpdb;
     include_once ABSPATH . WPINC . '/class-IXR.php';
     $log = debug_fopen(ABSPATH . 'enclosures.log', 'a');
     $post_links = array();
     debug_fwrite($log, 'BEGIN ' . date('YmdHis', time()) . "\n");
     $pung = get_enclosed($post_ID);
     $ltrs = '\\w';
     $gunk = '/#~:.?+=&%@!\\-';
     $punc = '.:?\\-';
     $any = $ltrs . $gunk . $punc;
     preg_match_all("{\\b http : [{$any}] +? (?= [{$punc}] * [^{$any}] | \$)}x", $content, $post_links_temp);
     debug_fwrite($log, 'Post contents:');
     debug_fwrite($log, $content . "\n");
     foreach ((array) $post_links_temp[0] as $link_test) {
         if (!in_array($link_test, $pung)) {
             // If we haven't pung it already
             $test = parse_url($link_test);
             if (isset($test['query'])) {
                 $post_links[] = $link_test;
             } elseif ($test['path'] != '/' && $test['path'] != '') {
                 $post_links[] = $link_test;
             }
         }
     }
     foreach ((array) $post_links as $url) {
         if ($url != '' && !$wpdb->get_var($wpdb->prepare("SELECT post_id FROM {$wpdb->postmeta} WHERE post_id = %d AND meta_key = 'enclosure' AND meta_value LIKE (%s)", $post_ID, $url . '%'))) {
             if ($headers = wp_get_http_headers($url)) {
                 $len = (int) $headers['content-length'];
                 $type = $headers['content-type'];
                 $allowed_types = array('video', 'audio');
                 if (in_array(substr($type, 0, strpos($type, "/")), $allowed_types)) {
                     $meta_value = "{$url}\n{$len}\n{$type}\n";
                     $wpdb->insert($wpdb->postmeta, array('post_id' => $post_ID, 'meta_key' => 'enclosure', 'meta_value' => $meta_value));
                 }
             }
         }
     }
 }
function pingback($content, $post_ID)
{
    global $wp_version, $wpdb;
    include_once ABSPATH . WPINC . '/class-IXR.php';
    // original code by Mort (http://mort.mine.nu:8080)
    $log = debug_fopen(ABSPATH . '/pingback.log', 'a');
    $post_links = array();
    debug_fwrite($log, 'BEGIN ' . date('YmdHis', time()) . "\n");
    $pung = get_pung($post_ID);
    // Variables
    $ltrs = '\\w';
    $gunk = '/#~:.?+=&%@!\\-';
    $punc = '.:?\\-';
    $any = $ltrs . $gunk . $punc;
    // Step 1
    // Parsing the post, external links (if any) are stored in the $post_links array
    // This regexp comes straight from phpfreaks.com
    // http://www.phpfreaks.com/quickcode/Extract_All_URLs_on_a_Page/15.php
    preg_match_all("{\\b http : [{$any}] +? (?= [{$punc}] * [^{$any}] | \$)}x", $content, $post_links_temp);
    // Debug
    debug_fwrite($log, 'Post contents:');
    debug_fwrite($log, $content . "\n");
    // Step 2.
    // Walking thru the links array
    // first we get rid of links pointing to sites, not to specific files
    // Example:
    // http://dummy-weblog.org
    // http://dummy-weblog.org/
    // http://dummy-weblog.org/post.php
    // We don't wanna ping first and second types, even if they have a valid <link/>
    foreach ($post_links_temp[0] as $link_test) {
        if (!in_array($link_test, $pung) && url_to_postid($link_test) != $post_ID && !is_local_attachment($link_test)) {
            // Also, let's never ping local attachments.
            $test = parse_url($link_test);
            if (isset($test['query'])) {
                $post_links[] = $link_test;
            } elseif ($test['path'] != '/' && $test['path'] != '') {
                $post_links[] = $link_test;
            }
            do_action('pre_ping', array(&$post_links, &$pung));
        }
    }
    foreach ($post_links as $pagelinkedto) {
        debug_fwrite($log, "Processing -- {$pagelinkedto}\n");
        $pingback_server_url = discover_pingback_server_uri($pagelinkedto, 2048);
        if ($pingback_server_url) {
            @set_time_limit(60);
            // Now, the RPC call
            debug_fwrite($log, "Page Linked To: {$pagelinkedto} \n");
            debug_fwrite($log, 'Page Linked From: ');
            $pagelinkedfrom = get_permalink($post_ID);
            debug_fwrite($log, $pagelinkedfrom . "\n");
            // using a timeout of 3 seconds should be enough to cover slow servers
            $client = new IXR_Client($pingback_server_url);
            $client->timeout = 3;
            $client->useragent .= ' -- WordPress/' . $wp_version;
            // when set to true, this outputs debug messages by itself
            $client->debug = false;
            if ($client->query('pingback.ping', $pagelinkedfrom, $pagelinkedto)) {
                add_ping($post_ID, $pagelinkedto);
            } else {
                debug_fwrite($log, "Error.\n Fault code: " . $client->getErrorCode() . " : " . $client->getErrorMessage() . "\n");
            }
        }
    }
    debug_fwrite($log, "\nEND: " . time() . "\n****************************\n");
    debug_fclose($log);
}
Esempio n. 3
0
/**
 * Check content for video and audio links to add as enclosures.
 *
 * Will not add enclosures that have already been added and will
 * remove enclosures that are no longer in the post. This is called as
 * pingbacks and trackbacks.
 *
 * @package WordPress
 * @since 1.5.0
 *
 * @uses $wpdb
 *
 * @param string $content Post Content
 * @param int $post_ID Post ID
 */
function do_enclose($content, $post_ID)
{
    global $wpdb;
    include_once ABSPATH . WPINC . '/class-IXR.php';
    $log = debug_fopen(ABSPATH . 'enclosures.log', 'a');
    $post_links = array();
    debug_fwrite($log, 'BEGIN ' . date('YmdHis', time()) . "\n");
    $pung = get_enclosed($post_ID);
    $ltrs = '\\w';
    $gunk = '/#~:.?+=&%@!\\-';
    $punc = '.:?\\-';
    $any = $ltrs . $gunk . $punc;
    preg_match_all("{\\b http : [{$any}] +? (?= [{$punc}] * [^{$any}] | \$)}x", $content, $post_links_temp);
    debug_fwrite($log, 'Post contents:');
    debug_fwrite($log, $content . "\n");
    foreach ($pung as $link_test) {
        if (!in_array($link_test, $post_links_temp[0])) {
            // link no longer in post
            $mid = $wpdb->get_col($wpdb->prepare("SELECT meta_id FROM {$wpdb->postmeta} WHERE post_id = %d AND meta_key = 'enclosure' AND meta_value LIKE (%s)", $post_ID, $link_test . '%'));
            do_action('delete_postmeta', $mid);
            $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->postmeta} WHERE meta_id IN(%s)", implode(',', $mid)));
            do_action('deleted_postmeta', $mid);
        }
    }
    foreach ((array) $post_links_temp[0] as $link_test) {
        if (!in_array($link_test, $pung)) {
            // If we haven't pung it already
            $test = @parse_url($link_test);
            if (false === $test) {
                continue;
            }
            if (isset($test['query'])) {
                $post_links[] = $link_test;
            } elseif ($test['path'] != '/' && $test['path'] != '') {
                $post_links[] = $link_test;
            }
        }
    }
    foreach ((array) $post_links as $url) {
        if ($url != '' && !$wpdb->get_var($wpdb->prepare("SELECT post_id FROM {$wpdb->postmeta} WHERE post_id = %d AND meta_key = 'enclosure' AND meta_value LIKE (%s)", $post_ID, $url . '%'))) {
            if ($headers = wp_get_http_headers($url)) {
                $len = (int) $headers['content-length'];
                $type = $headers['content-type'];
                $allowed_types = array('video', 'audio');
                // Check to see if we can figure out the mime type from
                // the extension
                $url_parts = @parse_url($url);
                if (false !== $url_parts) {
                    $extension = pathinfo($url_parts['path'], PATHINFO_EXTENSION);
                    if (!empty($extension)) {
                        foreach (get_allowed_mime_types() as $exts => $mime) {
                            if (preg_match('!^(' . $exts . ')$!i', $extension)) {
                                $type = $mime;
                                break;
                            }
                        }
                    }
                }
                if (in_array(substr($type, 0, strpos($type, "/")), $allowed_types)) {
                    $meta_value = "{$url}\n{$len}\n{$type}\n";
                    $wpdb->insert($wpdb->postmeta, array('post_id' => $post_ID, 'meta_key' => 'enclosure', 'meta_value' => $meta_value));
                    do_action('added_postmeta', $wpdb->insert_id, $post_ID, 'enclosure', $meta_value);
                }
            }
        }
    }
}
 function pingback($content, $post_ID)
 {
     // original code by Mort (http://mort.mine.nu:8080)
     $buf_keep = array();
     while (ob_get_level()) {
         $buf_keep[] = ob_get_contents();
         ob_end_clean();
     }
     $log = debug_fopen(wp_base() . '/log/pingback.log', 'a');
     $post_links = array();
     debug_fwrite($log, 'BEGIN ' . time() . "\n");
     // Variables
     $ltrs = '\\w';
     $gunk = '/#~:.?+=&%@!\\-';
     $punc = '.:?\\-';
     $any = $ltrs . $gunk . $punc;
     $pingback_str_dquote = 'rel="pingback"';
     $pingback_str_squote = 'rel=\'pingback\'';
     $x_pingback_str = 'x-pingback: ';
     $pingback_href_original_pos = 27;
     // Step 1
     // Parsing the post, external links (if any) are stored in the $post_links array
     // This regexp comes straight from phpfreaks.com
     // http://www.phpfreaks.com/quickcode/Extract_All_URLs_on_a_Page/15.php
     preg_match_all("{\\b http : [{$any}] +? (?= [{$punc}] * [^{$any}] | \$)}x", $content, $post_links_temp);
     // Debug
     debug_fwrite($log, 'Post contents:');
     debug_fwrite($log, $content . "\n");
     // Step 2.
     // Walking thru the links array
     // first we get rid of links pointing to sites, not to specific files
     // Example:
     // http://dummy-weblog.org
     // http://dummy-weblog.org/
     // http://dummy-weblog.org/post.php
     // We don't wanna ping first and second types, even if they have a valid <link/>
     foreach ($post_links_temp[0] as $link_test) {
         $test = parse_url($link_test);
         if (isset($test['query'])) {
             $post_links[] = $link_test;
         } elseif ($test['path'] != '/' && $test['path'] != '') {
             $post_links[] = $link_test;
         }
     }
     foreach ($post_links as $pagelinkedto) {
         debug_fwrite($log, 'Processing -- ' . $pagelinkedto . "\n\n");
         $bits = parse_url($pagelinkedto);
         if (!isset($bits['host'])) {
             debug_fwrite($log, 'Couldn\'t find a hostname for ' . $pagelinkedto . "\n\n");
             continue;
         }
         $host = $bits['host'];
         $path = isset($bits['path']) ? $bits['path'] : '';
         if (isset($bits['query'])) {
             $path .= '?' . $bits['query'];
         }
         if (!$path) {
             $path = '/';
         }
         $port = isset($bits['port']) ? $bits['port'] : 80;
         // Try to connect to the server at $host
         $fp = fsockopen($host, $port, $errno, $errstr, 30);
         if (!$fp) {
             debug_fwrite($log, 'Couldn\'t open a connection to ' . $host . "\n\n");
             continue;
         }
         // Send the GET request
         $request = "GET {$path} HTTP/1.1\r\nHost: {$host}\r\nUser-Agent: WordPress/{$GLOBALS['wp_version']} PHP/" . phpversion() . "\r\n\r\n";
         @ob_end_flush();
         fputs($fp, $request);
         // Start receiving headers and content
         $contents = '';
         $headers = '';
         $gettingHeaders = true;
         $found_pingback_server = 0;
         while (!feof($fp)) {
             $line = fgets($fp, 4096);
             if (trim($line) == '') {
                 $gettingHeaders = false;
             }
             if (!$gettingHeaders) {
                 $contents .= trim($line) . "\n";
                 $pingback_link_offset_dquote = strpos($contents, $pingback_str_dquote);
                 $pingback_link_offset_squote = strpos($contents, $pingback_str_squote);
             } else {
                 $headers .= trim($line) . "\n";
                 $x_pingback_header_offset = strpos(strtolower($headers), $x_pingback_str);
             }
             if ($x_pingback_header_offset) {
                 preg_match('#x-pingback: (.+)#is', $headers, $matches);
                 $pingback_server_url = trim($matches[1]);
                 debug_fwrite($log, "Pingback server found from X-Pingback header @ {$pingback_server_url}\n");
                 $found_pingback_server = 1;
                 break;
             }
             if ($pingback_link_offset_dquote || $pingback_link_offset_squote) {
                 $quote = $pingback_link_offset_dquote ? '"' : '\'';
                 $pingback_link_offset = $quote == '"' ? $pingback_link_offset_dquote : $pingback_link_offset_squote;
                 $pingback_href_pos = @strpos($contents, 'href=', $pingback_link_offset);
                 $pingback_href_start = $pingback_href_pos + 6;
                 $pingback_href_end = @strpos($contents, $quote, $pingback_href_start);
                 $pingback_server_url_len = $pingback_href_end - $pingback_href_start;
                 $pingback_server_url = substr($contents, $pingback_href_start, $pingback_server_url_len);
                 debug_fwrite($log, "Pingback server found from Pingback <link /> tag @ {$pingback_server_url}\n");
                 $found_pingback_server = 1;
                 break;
             }
         }
         if (!$found_pingback_server) {
             debug_fwrite($log, "Pingback server not found\n\n*************************\n\n");
             @fclose($fp);
         } else {
             debug_fwrite($log, "\n\nPingback server data\n");
             // Assuming there's a "http://" bit, let's get rid of it
             $host_clear = substr($pingback_server_url, 7);
             //  the trailing slash marks the end of the server name
             $host_end = strpos($host_clear, '/');
             // Another clear cut
             $host_len = $host_end - $host_start;
             $host = substr($host_clear, 0, $host_len);
             debug_fwrite($log, 'host: ' . $host . "\n");
             // If we got the server name right, the rest of the string is the server path
             $path = substr($host_clear, $host_end);
             debug_fwrite($log, 'path: ' . $path . "\n\n");
             // Now, the RPC call
             $method = 'pingback.ping';
             debug_fwrite($log, 'Page Linked To: ' . $pagelinkedto . "\n");
             debug_fwrite($log, 'Page Linked From: ');
             $pagelinkedfrom = get_permalink($post_ID);
             debug_fwrite($log, $pagelinkedfrom . "\n");
             $client = new xmlrpc_client($path, $host, 80);
             $message = new xmlrpcmsg($method, array(new xmlrpcval($pagelinkedfrom), new xmlrpcval($pagelinkedto)));
             $result = $client->send($message);
             if ($result) {
                 if (!$result->value()) {
                     debug_fwrite($log, $result->faultCode() . ' -- ' . $result->faultString());
                 } else {
                     $value = xmlrpc_decode1($result->value());
                     if (is_array($value)) {
                         $value_arr = '';
                         foreach ($value as $blah) {
                             $value_arr .= $blah . ' |||| ';
                         }
                         debug_fwrite($log, $value_arr);
                     } else {
                         debug_fwrite($log, $value);
                     }
                 }
             }
             @fclose($fp);
         }
     }
     debug_fwrite($log, "\nEND: " . time() . "\n****************************\n\r");
     debug_fclose($log);
     for ($i = count($buf_keep) - 1; $i >= 0; $i--) {
         ob_start();
         echo $buf_keep[$i];
     }
 }
Esempio n. 5
0
/**
 * Echo the XML-RPC call Result and optionally log into file
 *
 * @param object XMLRPC response object
 * @param boolean true to echo
 * @param mixed File resource or == '' for no file logging.
 */
function xmlrpc_displayresult($result, $display = true, $log = '')
{
    if (!$result) {
        // We got no response:
        if ($display) {
            echo T_('No response!') . "<br />\n";
        }
        return false;
    }
    if ($result->faultCode()) {
        // We got a remote error:
        if ($display) {
            echo T_('Remote error'), ': ', $result->faultString(), ' (', $result->faultCode(), ")<br />\n";
        }
        debug_fwrite($log, $result->faultCode() . ' -- ' . $result->faultString());
        return false;
    }
    // We'll display the response:
    $val = $result->value();
    $value = xmlrpc_decode_recurse($result->value());
    if (is_array($value)) {
        $out = '';
        foreach ($value as $l_value) {
            if (is_array($l_value)) {
                $out .= ' [';
                foreach ($l_value as $lv_key => $lv_val) {
                    $out .= $lv_key . ' => ' . (is_array($lv_val) ? '{' . implode('; ', $lv_val) . '}' : $lv_val) . '; ';
                }
                $out .= '] ';
            } else {
                $out .= ' [' . $l_value . '] ';
            }
        }
    } else {
        $out = $value;
    }
    debug_fwrite($log, $out);
    if ($display) {
        echo T_('Response') . ': ' . $out . "<br />\n";
    }
    return $value;
}
function do_enclose( $content, $post_ID ) {
	global $wpdb;
	include_once( ABSPATH . WPINC . '/class-IXR.php' );

	$log = debug_fopen( ABSPATH . 'enclosures.log', 'a' );
	$post_links = array();
	debug_fwrite( $log, 'BEGIN ' . date( 'YmdHis', time() ) . "\n" );

	$pung = get_enclosed( $post_ID );

	$ltrs = '\w';
	$gunk = '/#~:.?+=&%@!\-';
	$punc = '.:?\-';
	$any = $ltrs . $gunk . $punc;

	preg_match_all( "{\b http : [$any] +? (?= [$punc] * [^$any] | $)}x", $content, $post_links_temp );

	debug_fwrite( $log, 'Post contents:' );
	debug_fwrite( $log, $content . "\n" );

	foreach ( $post_links_temp[0] as $link_test ) {
		if ( !in_array( $link_test, $pung ) ) { // If we haven't pung it already
			$test = parse_url( $link_test );
			if ( isset( $test['query'] ) )
				$post_links[] = $link_test;
			elseif ( $test['path'] != '/' && $test['path'] != '' )
				$post_links[] = $link_test;
		}
	}

	foreach ( $post_links as $url ) {
		if ( $url != '' && !$wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = 'enclosure' AND meta_value LIKE (%s)", $post_ID, $url . '%' ) ) ) {
			if ( $headers = wp_get_http_headers( $url) ) {
				$len = (int) $headers['content-length'];
				$type = $wpdb->escape( $headers['content-type'] );
				$allowed_types = array( 'video', 'audio' );
				if ( in_array( substr( $type, 0, strpos( $type, "/" ) ), $allowed_types ) ) {
					$meta_value = "$url\n$len\n$type\n";
					$wpdb->query( $wpdb->prepare( "INSERT INTO `$wpdb->postmeta` ( `post_id` , `meta_key` , `meta_value` )
					VALUES ( %d, 'enclosure' , %s)", $post_ID, $meta_value ) );
				}
			}
		}
	}
}
Esempio n. 7
0
function pingback_ping($m)
{
    // original code by Mort (http://mort.mine.nu:8080)
    global $tableposts, $tablecomments, $comments_notify;
    global $siteurl, $blogfilename, $b2_version, $use_pingback;
    global $HTTP_SERVER_VARS;
    if (!$use_pingback) {
        return new xmlrpcresp(new xmlrpcval('Sorry, this weblog does not allow you to pingback its posts.'));
    }
    dbconnect();
    $log = debug_fopen('./xmlrpc.log', 'w');
    $title = '';
    $pagelinkedfrom = $m->getParam(0);
    $pagelinkedfrom = $pagelinkedfrom->scalarval();
    $pagelinkedto = $m->getParam(1);
    $pagelinkedto = $pagelinkedto->scalarval();
    $pagelinkedfrom = str_replace('&amp;', '&', $pagelinkedfrom);
    $pagelinkedto = preg_replace('#&([^amp\\;])#is', '&amp;$1', $pagelinkedto);
    debug_fwrite($log, 'BEGIN ' . time() . ' - ' . date('Y-m-d H:i:s') . "\n\n");
    debug_fwrite($log, 'Page linked from: ' . $pagelinkedfrom . "\n");
    debug_fwrite($log, 'Page linked to: ' . $pagelinkedto . "\n");
    $messages = array(htmlentities("Pingback from " . $pagelinkedfrom . " to " . $pagelinkedto . " registered. Keep the web talking! :-)"), htmlentities("We can't find the URL to the post you are trying to link to in your entry. Please check how you wrote the post's permalink in your entry."), htmlentities("We can't find the post you are trying to link to. Please check the post's permalink."));
    $message = $messages[0];
    // Check if the page linked to is in our site
    $pos1 = strpos($pagelinkedto, str_replace('http://', '', str_replace('www.', '', $siteurl)));
    if ($pos1) {
        // let's find which post is linked to
        $urltest = parse_url($pagelinkedto);
        if (preg_match('#p/[0-9]{1,}#', $urltest['path'], $match)) {
            // the path defines the post_ID (archives/p/XXXX)
            $blah = explode('/', $match[0]);
            $post_ID = $blah[1];
            $way = 'from the path';
        } elseif (preg_match('#p=[0-9]{1,}#', $urltest['query'], $match)) {
            // the querystring defines the post_ID (?p=XXXX)
            $blah = explode('=', $match[0]);
            $post_ID = $blah[1];
            $way = 'from the querystring';
        } elseif (isset($urltest['fragment'])) {
            // an #anchor is there, it's either...
            if (intval($urltest['fragment'])) {
                // ...an integer #XXXX (simpliest case)
                $post_ID = $urltest['fragment'];
                $way = 'from the fragment (numeric)';
            } elseif (is_string($urltest['fragment'])) {
                // ...or a string #title, a little more complicated
                $title = preg_replace('/[^a-zA-Z0-9]/', '.', $urltest['fragment']);
                $sql = "SELECT ID FROM {$tableposts} WHERE post_title RLIKE '{$title}'";
                $result = mysql_query($sql) or die("Query: {$sql}\n\nError: " . mysql_error());
                $blah = mysql_fetch_array($result);
                $post_ID = $blah['ID'];
                $way = 'from the fragment (title)';
            }
        } else {
            $post_ID = -1;
        }
        debug_fwrite($log, "Found post ID {$way}: {$post_ID}\n");
        $sql = 'SELECT post_author FROM ' . $tableposts . ' WHERE ID = ' . $post_ID;
        $result = mysql_query($sql);
        if (mysql_num_rows($result)) {
            debug_fwrite($log, 'Post exists' . "\n");
            // Let's check that the remote site didn't already pingback this entry
            $sql = 'SELECT * FROM ' . $tablecomments . ' WHERE comment_post_ID = ' . $post_ID . ' AND comment_author_url = \'' . $pagelinkedfrom . '\' AND comment_content LIKE \'%<pingback />%\'';
            $result = mysql_query($sql);
            if (mysql_num_rows($result) || 1 == 1) {
                // very stupid, but gives time to the 'from' server to publish !
                sleep(1);
                // Let's check the remote site
                $fp = @fopen($pagelinkedfrom, 'r');
                $puntero = 4096;
                while ($linea = fread($fp, $puntero)) {
                    $linea = strip_tags($linea, '<title><a>');
                    $linea = strip_all_but_one_link($linea, $pagelinkedto);
                    $linea = preg_replace('#&([^amp\\;])#is', '&amp;$1', $linea);
                    if (empty($matchtitle)) {
                        preg_match('|<title>([^<]*?)</title>|is', $linea, $matchtitle);
                    }
                    $pos2 = strpos($linea, $pagelinkedto);
                    $pos3 = strpos($linea, str_replace('http://www.', 'http://', $pagelinkedto));
                    if (is_integer($pos2) || is_integer($pos3)) {
                        debug_fwrite($log, 'The page really links to us :)' . "\n");
                        $pos4 = is_integer($pos2) ? $pos2 : $pos3;
                        $start = $pos4 - 100;
                        $context = substr($linea, $start, 250);
                        $context = str_replace("\n", ' ', $context);
                        $context = str_replace('&amp;', '&', $context);
                    } else {
                        debug_fwrite($log, 'The page doesn\'t link to us, here\'s an excerpt :' . "\n\n" . $linea . "\n\n");
                    }
                }
                debug_fwrite($log, '*****' . "\n\n");
                fclose($fp);
                if (!empty($context)) {
                    $pagelinkedfrom = preg_replace('#&([^amp\\;])#is', '&amp;$1', $pagelinkedfrom);
                    $title = !strlen($matchtitle[1]) ? $pagelinkedfrom : $matchtitle[1];
                    $original_context = $context;
                    $context = '<pingback />[...] ' . addslashes(trim($context)) . ' [...]';
                    $context = format_to_post($context);
                    $original_pagelinkedfrom = $pagelinkedfrom;
                    $pagelinkedfrom = addslashes($pagelinkedfrom);
                    $original_title = $title;
                    $title = addslashes(strip_tags(trim($title)));
                    $sql = "INSERT INTO {$tablecomments} (comment_post_ID, comment_author, comment_author_url, comment_date, comment_content) VALUES ({$post_ID}, '{$title}', '{$pagelinkedfrom}', NOW(), '{$context}')";
                    $consulta = mysql_query($sql);
                    if ($comments_notify) {
                        $notify_message = "New pingback on your post #{$post_ID}.\r\n\r\n";
                        $notify_message .= "website: {$original_title}\r\n";
                        $notify_message .= "url    : {$original_pagelinkedfrom}\r\n";
                        $notify_message .= "excerpt: \n[...] {$original_context} [...]\r\n\r\n";
                        $notify_message .= "You can see all pingbacks on this post there: \r\n";
                        $notify_message .= "{$siteurl}/{$blogfilename}?p={$post_ID}&pb=1\r\n\r\n";
                        $postdata = get_postdata($post_ID);
                        $authordata = get_userdata($postdata['Author_ID']);
                        $recipient = $authordata['user_email'];
                        $subject = "pingback on post #{$post_ID} \"" . $postdata['Title'] . '"';
                        @mail($recipient, $subject, $notify_message, "From: b2@" . $HTTP_SERVER_VARS['SERVER_NAME'] . "\r\n" . "X-Mailer: b2 {$b2_version} - PHP/" . phpversion());
                    }
                } else {
                    // URL pattern not found
                    $message = "Page linked to: {$pagelinkedto}\nPage linked from: {$pagelinkedfrom}\nTitle: {$title}\nContext: {$context}\n\n" . $messages[1];
                }
            } else {
                // We already have a Pingback from this URL
                $message = "Sorry, you already did a pingback to {$pagelinkedto} from {$pagelinkedfrom}.";
            }
        } else {
            // Post_ID not found
            $message = $messages[2];
            debug_fwrite($log, 'Post doesn\'t exist' . "\n");
        }
    }
    return new xmlrpcresp(new xmlrpcval($message));
}
function do_enclose( $content, $post_ID ) {
	global $wp_version, $wpdb;
	include_once (ABSPATH . WPINC . '/class-IXR.php');

	$log = debug_fopen(ABSPATH . '/enclosures.log', 'a');
	$post_links = array();
	debug_fwrite($log, 'BEGIN '.date('YmdHis', time())."\n");

	$pung = get_enclosed( $post_ID );

	$ltrs = '\w';
	$gunk = '/#~:.?+=&%@!\-';
	$punc = '.:?\-';
	$any = $ltrs . $gunk . $punc;

	preg_match_all("{\b http : [$any] +? (?= [$punc] * [^$any] | $)}x", $content, $post_links_temp);

	debug_fwrite($log, 'Post contents:');
	debug_fwrite($log, $content."\n");

	foreach($post_links_temp[0] as $link_test) :
		if ( !in_array($link_test, $pung) ) : // If we haven't pung it already
			$test = parse_url($link_test);
			if (isset($test['query']))
				$post_links[] = $link_test;
			elseif(($test['path'] != '/') && ($test['path'] != ''))
				$post_links[] = $link_test;
		endif;
	endforeach;

	foreach ($post_links as $url){
                if( $url != '' && in_array($url, $pung) == false ) {
                    set_time_limit( 60 ); 
                    $file = str_replace( "http://", "", $url );
                    $host = substr( $file, 0, strpos( $file, "/" ) );
                    $file = substr( $file, strpos( $file, "/" ) );
                    $headers = "HEAD $file HTTP/1.1\r\nHOST: $host\r\n\r\n";
                    $port    = 80;
                    $timeout = 3;
                    $fp = @fsockopen($host, $port, $err_num, $err_msg, $timeout);
                    if( $fp ) {
                        fputs($fp, $headers );
                        $response = '';
                        while ( !feof($fp) && strpos( $response, "\r\n\r\n" ) == false )
                            $response .= fgets($fp, 2048);
                        fclose( $fp );
                    } else {
                        $response = '';
                    }
                    if( $response != '' ) {
                        $len = substr( $response, strpos( $response, "Content-Length:" ) + 16 );
                        $len = substr( $len, 0, strpos( $len, "\n" ) );
                        $type = substr( $response, strpos( $response, "Content-Type:" ) + 14 );
                        $type = substr( $type, 0, strpos( $type, "\n" ) + 1 );
                        $allowed_types = array( 'video', 'audio' );
                        if( in_array( substr( $type, 0, strpos( $type, "/" ) ), $allowed_types ) ) {
                            $meta_value = "$url\n$len\n$type\n";
                            $query = "INSERT INTO `".$wpdb->postmeta."` ( `meta_id` , `post_id` , `meta_key` , `meta_value` )
                                VALUES ( NULL, '$post_ID', 'enclosure' , '".$meta_value."')";
                            $wpdb->query( $query );
                        }
                    }
                }
        }
}