/[drupal]/contributions/modules/trackback/trackback-receive.inc
ViewVC logotype

Diff of /contributions/modules/trackback/trackback-receive.inc

Parent Directory Parent Directory | Revision Log Revision Log | View Revision Graph Revision Graph | View Patch Patch

revision 1.1, Mon Jul 27 12:00:46 2009 UTC revision 1.1.2.1, Mon Jul 27 12:00:46 2009 UTC
# Line 0  Line 1 
1    <?php
2    // $Id;$
3    
4    /**
5     * Function called when a POST/GET trackback is beeng received
6     * @param $nid: the NodeID
7     */
8    function _trackback_receive_post($nid) {
9      /*
10      if (empty($nid))
11        return;
12      print(__function__."(". var_export($nid, TRUE).") TODO<br>\n");
13      print(__function__."(". var_export($_GET['q'], TRUE).") TODO\n");
14      //_trackback_url_to_nid();
15      // trackback_received($trackback);
16    
17      $trackback = trackback_get_object_trackback();
18      $trackback->nid = 2;
19      $trackback->name = 'NAME'; // The sender site name of this trackback.
20      $trackback->subject = "title";
21      $trackback->url = "http://somewhere.". $_GET['q'];
22      $trackback->excerpt = "Excerpt -- " . $_GET['q'];
23      $trackback->status = TRACKBACK_STATUS_SPAM;
24    
25      // Notify Trackback of received Trackback
26      trackback_received($trackback);
27      */
28    
29      // Reading POST data
30      // Code taken from  xmlrpc_server() in "includes/xmlrpc.inc")
31      $data = file_get_contents('php://input');
32      if (!$data) {
33        die(t('Trackback Server accepts POST requests only.'));
34      }
35    
36      $content = explode('; charset=', $_SERVER['CONTENT_TYPE']);
37      $trackback = trackback_get_object_trackback();
38      $error = new stdClass();
39      $error->code = 0;
40    
41      if (!$content || (is_array($content) && $content[0] != 'application/x-www-form-urlencoded')) {
42        $error->message = t('Wrong Content-Type for this request, should be "application/x-www-form-urlencoded".');
43        return _trackback_receive_post_return($error);
44      }
45    
46      if (!trackback_node_enabled($nid)) {
47        $error->message = t('This URL cannot be used as a trackback: it is not a trackback-enabled resource.');
48        return _trackback_receive_post_return($error);
49      }
50      if (!isset($_POST['url']) || empty($_POST['url'])) {
51        $error-> message = t('Missing source Trackback url.');
52        return _trackback_receive_post_return($error);
53      }
54      else {
55        $trackback->url = $_POST['url'];
56      }
57    
58      $error->message = t('Trackback 6.x-2.x-DEV -- UNIMPLEMENTED --');
59      return _trackback_receive_post_return($error);
60      die();
61    
62      print_r($GLOBALS);
63      $trackback->nid = $nid;
64      $trackback->name = '--'; // The sender site name of this trackback.
65      $trackback->name = parse_url($pagelinkedfrom, PHP_URL_HOST);
66      $trackback->subject = $title;
67      $trackback->url = $_POST['url'];
68      $trackback->excerpt = $excerpt;
69      print_r($trackback);
70      die();
71    }
72    
73    /**
74     * Convert given $string in $encoding format to UTF-8 using a fallback if
75     *   $encoding is not setted
76     *
77     * @param $string
78     * @param $encoding
79     * @return Encoded string
80     */
81    function _trackback_convert_to_utf8($string, $encoding = NULL) {
82      // @todo: fix this method
83      if (!isset($encoding)) {
84        $encoding = 'uft-8';
85      }
86      return drupal_convert_to_utf8($string, $encoding);
87    }
88    
89    /**
90     * Helper function for returning POST result
91     */
92    function _trackback_receive_post_return($error) {
93      header('Content-Type: text/xml');
94      $output = array();
95      $output[] = '<?xml version="1.0" encoding="utf-8"?>';
96      $output[] = '<response>';
97      $output[] = '<error>'. $error->code. '</error>';
98      if ($error->code == 0) {
99        $output[] = '<message>'. $error->message .'</message>';
100      }
101      $output[] = '</response>';
102    
103      print implode("\n", $output);
104    }
105    
106    /**
107     * XML-RPC callback: process trackback.ping() call.
108     * Taken from pingback.module
109     */
110    function _trackback_receive_xmlrpc($pagelinkedfrom, $pagelinkedto) {
111      // return xmlrpc_server_error(0, 'abcdefgh');
112      // big thanks to WordPress codebase, specifically file xmlrpc.php, method pingback_ping()
113      // for becoming the reference implementation and theft victim ;)
114      // note: $pagelinkedto is a URL from our own site, $pagelinkedfrom is a foreign URL
115    
116      //don't really understand this part, supposed to unescape ampersand entities?
117      $pagelinkedfrom = str_replace('&amp;', '&', $pagelinkedfrom);
118      $pagelinkedto   = preg_replace('#&([^amp\;])#is', '&amp;$1', $pagelinkedto);
119      $error_code = -1;
120    
121      // Check if the page linked to is in our site
122      $pos1 = strpos($pagelinkedto, str_replace(array('http://www.', 'http://', 'https://www.', 'https://'), '', $GLOBALS['base_url']));
123      if (!$pos1) {
124        return xmlrpc_server_error(0, t('Is there no link to us?'));
125      }
126    
127      // let's find which post is linked to
128      $nid = _trackback_url_to_nid($pagelinkedto);
129    
130    
131      $can_receive = trackback_node_enabled($nid);
132    
133      $node = $nid ? node_load($nid) : FALSE;
134    
135      if($node && variable_get('trackback_merge_within_translations', TRUE)) {
136        // If we keep only the "original" source, send pingbacks only from original node?
137        if (isset($node->tnid) && ($node->nid == $node->tnid)) {
138          $nid = $node->tnid;
139        }
140      }
141    
142      $can_receive = $node->status && $can_receive;
143      print $nid;
144    
145      die($nid);
146      if (!$can_receive) { // node not found
147        return xmlrpc_server_error(33, t("The specified target URL cannot be used as a target. It either doesn't exist, or it is not a pingback-enabled resource.". $nid));
148      }
149    
150      if ($nid == _trackback_url_to_nid($pagelinkedfrom)) {
151        return xmlrpc_server_error(0, t('The source URL and the target URL cannot both point to the same resource.'));
152      }
153    
154      if (!$node->status) {
155        return xmlrpc_server_error(33, t("The specified target URL cannot be used as a target. It either doesn't exist, or it is not a pingback-enabled resource (NP)."));
156      }
157    
158      // Let's check that the remote site didn't already pingback this entry
159      if (trackback_exists($nid, $pagelinkedfrom)) { // We already have a Pingback from this URL
160        return xmlrpc_server_error(48, 'The pingback has already been registered.');
161      }
162    
163      // very stupid, but gives time to the 'from' server to publish !
164      sleep(1);
165    
166      // Let's check the remote site
167      $r = drupal_http_request($pagelinkedfrom);
168      if ($r->error)
169        return xmlrpc_server_error(16, 'The source URL does not exist.');
170      $linea = $r->data;
171    
172      // Work around bug in strip_tags():
173      $linea = str_replace('<!DOC', '<DOC', $linea);
174      $linea = preg_replace('/[\s\r\n\t]+/', ' ', $linea); // normalize spaces
175      $linea = preg_replace('/ <(h1|h2|h3|h4|h5|h6|p|th|td|li|dt|dd|pre|caption|input|textarea|button|body|br)[^>]*>/', "\n\n", $linea);
176    
177      preg_match('|<title>([^<]*?)</title>|is', $linea, $matchtitle);
178      $title = check_plain($matchtitle[1]);
179      if (empty($title)) {
180        return xmlrpc_server_error(32, 'We cannot find a title on that page.');
181      }
182    
183      $linea = strip_tags($linea, '<a>'); // just keep the tag we need
184    
185      $p = explode("\n\n", $linea);
186    
187      $preg_target = preg_quote($pagelinkedto);
188    
189      foreach ($p as $para) {
190        if (strpos($para, $pagelinkedto) !== FALSE) { // it exists, but is it a link?
191          preg_match('|<a[^>]+?'. $preg_target .'[^>]*>([^>]+?)</a>|', $para, $context);
192    
193          // If the URL isn't in a link context, keep looking
194          if (empty($context)) {
195            continue;
196          }
197    
198          // We're going to use this fake tag to mark the context in a bit
199          // the marker is needed in case the link text appears more than once in the paragraph
200          //I edited <wpcontext></wpcontext> to <dpcontext></dpcontext> so it becomes more Drupal-ish!
201          $excerpt = preg_replace('|\</?dpcontext\>|', '', $para);
202    
203          // prevent really long link text
204          if (drupal_strlen($context[1]) > 100) {
205            $context[1] = drupal_substr($context[1], 0, 100) .'...';
206          }
207    
208          $marker = '<dpcontext>'. $context[1] .'</dpcontext>';    // set up our marker
209          $excerpt = str_replace($context[0], $marker, $excerpt); // swap out the link for our marker
210          $excerpt = strip_tags($excerpt, '<dpcontext>');        // strip all tags but our context marker
211          $excerpt = trim($excerpt);
212          $preg_marker = preg_quote($marker);
213          $excerpt = preg_replace("|.*?\s(.{0,100}$preg_marker.{0,100})\s.*|s", '$1', $excerpt);
214          $excerpt = strip_tags($excerpt); // YES, again, to remove the marker wrapper
215    
216          break;
217        }
218      }
219    
220      if (empty($context)) { // Link to target not found
221        return xmlrpc_server_error(17, t('The source URL does not contain a link to the target URL, and so cannot be used as a source.'));
222      }
223    
224      //??? can someone explain about this?
225      $pagelinkedfrom = preg_replace('#&([^amp\;])#is', '&amp;$1', $pagelinkedfrom);
226    
227      $trackback = trackback_get_object_trackback();
228      $trackback->nid = $nid;
229      $trackback->name = '--'; // The sender site name of this trackback.
230      $trackback->name = parse_url($pagelinkedfrom, PHP_URL_HOST); // Use the domain name
231      $trackback->subject = $title;
232      $trackback->url = $pagelinkedfrom;
233      $trackback->excerpt = $excerpt;
234      /*
235      //TODO: a custom filter for $excerpt
236      $edit = array(
237        'nid' => $nid,
238        'subject' => t('Pingback'),
239        'comment' => '[...] '. $excerpt .' [...]',
240        'hostname' => ip_address(),
241        'format' => variable_get('pingback_input_format', FILTER_FORMAT_DEFAULT),
242        'name' => $title,
243        'homepage' => $pagelinkedfrom,
244      );
245      */
246    
247      // Notify Trackback of received Trackback
248      trackback_received($trackback);
249    
250      $message = t('Pingback from @source to @target registered! Keep the web talking! :-)', array('@source' => $pagelinkedfrom, '@target' => $pagelinkedto));
251      return $message;
252    }
253    
254    /**
255     * Map any absolute url from this Drupal site to nid if applicable.
256     *
257     * Can also be used to check whether an absolute path is in the site and points
258     * to a node (e.g. node/1).
259     * Taken from pingback.module
260     */
261    function _trackback_url_to_nid($url) {
262    
263      //first check if the url is really in our site, as well as getting the non-base-url part
264      if (preg_match($a = '#^'. preg_quote($GLOBALS['base_url'], '#') .'/(.+)$#', $url, $matches)) {
265        if (!variable_get('clean_url', 0)) {
266          // Clean URLs not enabled. Strip '?q=' from URL.
267          $matches[1] = str_replace('?q=', '', $matches[1]);
268        }
269    
270        // VEdere : language_initialize().
271        /*
272        global $language;
273        var_dump($language);
274    
275        var_export('drupal_get_normal_path:');
276        $mio = drupal_get_normal_path('post/drupal-iconizer-module', 'en');
277        var_dump($mio);
278        $mio = drupal_get_normal_path('en/post/drupal-iconizer-module', 'en');
279        var_dump($mio);
280        $mio = drupal_get_normal_path('post/drupal-iconizer-module');
281        var_dump($mio);
282        $mio = drupal_get_normal_path('post/modulo-drupal-iconizer');
283        var_dump($mio);
284        $mio = drupal_get_normal_path($matches[1], 'it');
285        var_dump($mio);
286        */
287        if (preg_match($b = '#^node/([0-9]+)$#', drupal_get_normal_path($matches[1]), $matches2)) {
288          //var_export($matches2[1]);
289          return $matches2[1];
290        }
291      }
292      return FALSE;
293    }
294    
295    /**
296    
297      TODO:  implement pingback.extension.getPingbacks ?
298    
299            /**
300             * Retrieve array of URLs that pingbacked the given URL.
301             *
302             * Specs on http://www.aquarionics.com/misc/archives/blogite/0198.html
303             *
304             * @since 1.5.0
305             *
306             * @param array $args Method parameters.
307             * @return array
308             *
309            function pingback_extensions_getPingbacks($args) {
310    
311                    global $wpdb;
312    
313                    do_action('xmlrpc_call', 'pingback.extensions.getPingsbacks');
314    
315                    $this->escape($args);
316    
317                    $url = $args;
318    
319                    $post_ID = url_to_postid($url);
320                    if (!$post_ID) {
321                            // We aren't sure that the resource is available and/or pingback enabled
322                            return new IXR_Error(33, __('The specified target URL cannot be used as a target. It either doesn\'t exist, or it is not a pingback-enabled resource.'));
323                    }
324    
325                    $actual_post = wp_get_single_post($post_ID, ARRAY_A);
326    
327                    if (!$actual_post) {
328                            // No such post = resource not found
329                            return new IXR_Error(32, __('The specified target URL does not exist.'));
330                    }
331    
332                    $comments = $wpdb->get_results( $wpdb->prepare("SELECT comment_author_url, comment_content, comment_author_IP, comment_type FROM $wpdb->comments WHERE comment_post_ID = %d", $post_ID) );
333    
334                    if (!$comments) {
335                            return array();
336                    }
337    
338                    $pingbacks = array();
339                    foreach($comments as $comment) {
340                            if ( 'pingback' == $comment->comment_type )
341                                    $pingbacks[] = $comment->comment_author_url;
342                    }
343    
344                    return $pingbacks;
345            }
346    
347      */

Legend:
Removed from v.1.1  
changed lines
  Added in v.1.1.2.1

  ViewVC Help
Powered by ViewVC 1.1.2