Dotclear

source: inc/core/class.dc.trackback.php @ 1674:00146501e490

Revision 1674:00146501e490, 15.3 KB checked in by Florent Cotton <florent.cotton@…>, 11 years ago (diff)

Support des pingbacks : après le support de la détection et de l'envoi de pingbacks, au tour du support en réception.
Dans le détail (ou presque) :

  • Ajout d'un endpoint "pingback.ping" XML-RPC, mais le tout le gros du traitement est dans le fichier class.dc.trackback.php
  • Ajout d'une méthode "receive_pb" dans la classe dcTrackback pour la prise en charge quasi-complète de la réception et enregistrement d'un pingback.
  • Ajout d'une balise template {{tpl:BlogXMLRPCURL}} pour retourner l'URL du serveur XML-RPC du blog courant
  • Ajout d'un bloc au niveau des en-têtes dans les templates par défaut post.html et page.html pour la mise en oeuvre si besoin d'un <link rel="pingback" ../>
  • Ajout de l'envoi d'un en-tête HTTP supplémentaire "X-Pingback" dans les gestionnaires d'URLs pour les types "post" et "pages"

Reste plus qu'à tester en conditions réelles et à polir au besoin.

Line 
1<?php
2# -- BEGIN LICENSE BLOCK ---------------------------------------
3#
4# This file is part of Dotclear 2.
5#
6# Copyright (c) 2003-2013 Olivier Meunier & Association Dotclear
7# Licensed under the GPL version 2.0 license.
8# See LICENSE file or
9# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
10#
11# -- END LICENSE BLOCK -----------------------------------------
12if (!defined('DC_RC_PATH')) { return; }
13
14/**
15@ingroup DC_CORE
16@brief Trackbacks sender and server
17
18Sends and receives trackbacks. Also handles trackbacks auto discovery.
19*/
20class dcTrackback
21{
22     public $core;       ///< <b>dcCore</b> dcCore instance
23     public $table;      ///< <b>string</b> done pings table name
24     
25     /**
26     Object constructor
27     
28     @param    core      <b>dcCore</b>       dcCore instance
29     */
30     public function __construct($core)
31     {
32          $this->core =& $core;
33          $this->con =& $this->core->con;
34          $this->table = $this->core->prefix.'ping';
35     }
36     
37     /// @name Send trackbacks
38     //@{
39     /**
40     Get all pings sent for a given post.
41     
42     @param    post_id   <b>integer</b>      Post ID
43     @return   <b>record</b>
44     */
45     public function getPostPings($post_id)
46     {
47          $strReq = 'SELECT ping_url, ping_dt '.
48                    'FROM '.$this->table.' '.
49                    'WHERE post_id = '.(integer) $post_id;
50         
51          return $this->con->select($strReq);
52     }
53     
54     /**
55     Sends a ping to given <var>$url</var>.
56     
57     @param    url            <b>string</b>       URL to ping
58     @param    post_id        <b>integer</b>      Post ID
59     @param    post_title     <b>string</b>       Post title
60     @param    post_excerpt   <b>string</b>       Post excerpt
61     @param    post_url       <b>string</b>       Post URL
62     */
63     public function ping($url,$post_id,$post_title,$post_excerpt,$post_url)
64     {
65          if ($this->core->blog === null) {
66               return false;
67          }
68         
69          $post_id = (integer) $post_id;
70         
71          # Check for previously done trackback
72          $strReq = 'SELECT post_id, ping_url FROM '.$this->table.' '.
73                    'WHERE post_id = '.$post_id.' '.
74                    "AND ping_url = '".$this->con->escape($url)."' ";
75         
76          $rs = $this->con->select($strReq);
77         
78          if (!$rs->isEmpty()) {
79               throw new Exception(sprintf(__('%s has still been pinged'),$url));
80          }
81         
82          $ping_parts = explode('|',$url);
83         
84          # Let's walk by the trackback way
85          if (count($ping_parts) < 2) {
86               $data = array(
87                    'title' => $post_title,
88                    'excerpt' => $post_excerpt,
89                    'url' => $post_url,
90                    'blog_name' => trim(html::escapeHTML(html::clean($this->core->blog->name)))
91                    //,'__debug' => false
92               );
93               
94               # Ping
95               try
96               {
97                    $http = self::initHttp($url,$path);
98                    $http->post($path,$data,'UTF-8');
99                    $res = $http->getContent();
100               }
101               catch (Exception $e)
102               {
103                    throw new Exception(__('Unable to ping URL'));
104               }
105               
106               $pattern =
107               '|<response>.*<error>(.*)</error>(.*)'.
108               '(<message>(.*)</message>(.*))?'.
109               '</response>|msU';
110               
111               if (!preg_match($pattern,$res,$match))
112               {
113                    throw new Exception(sprintf(__('%s is not a ping URL'),$url));
114               }
115               
116               $ping_error = trim($match[1]);
117               $ping_msg = (!empty($match[4])) ? $match[4] : '';
118          }
119          # Damnit ! Let's play pingback
120          else {
121               try {
122                    $xmlrpc = new xmlrpcClient($ping_parts[0]);
123                    $res = $xmlrpc->query('pingback.ping', $post_url, $ping_parts[1]);
124                    $ping_error = '0';
125               }
126               catch (xmlrpcException $e) {
127                    $ping_error = $e->getCode();
128                    $ping_msg = $e->getMessage(); 
129               }
130               catch (Exception $e) {
131                    throw new Exception(__('Unable to ping URL'));
132               }
133          }
134         
135          if ($ping_error != '0') {
136               throw new Exception(sprintf(__('%s, ping error:'),$url).' '.$ping_msg);
137          } else {
138               # Notify ping result in database
139               $cur = $this->con->openCursor($this->table);
140               $cur->post_id = $post_id;
141               $cur->ping_url = $url;
142               $cur->ping_dt = date('Y-m-d H:i:s');
143               
144               $cur->insert();
145          }
146     }
147     //@}
148     
149     /// @name Receive trackbacks
150     //@{
151     /**
152     Receives a trackback and insert it as a comment of given post.
153     
154     @param    post_id        <b>integer</b>      Post ID
155     */
156     public function receive($post_id)
157     {
158          header('Content-Type: text/xml; charset=UTF-8');
159          if (empty($_POST)) {
160               http::head(405,'Method Not Allowed');
161               echo
162               '<?xml version="1.0" encoding="utf-8"?>'."\n".
163               "<response>\n".
164               "  <error>1</error>\n".
165               "  <message>POST request needed</message>\n".
166               "</response>";
167               return;
168          }
169         
170          $post_id = (integer) $post_id;
171         
172          $title = !empty($_POST['title']) ? $_POST['title'] : '';
173          $excerpt = !empty($_POST['excerpt']) ? $_POST['excerpt'] : '';
174          $url = !empty($_POST['url']) ? $_POST['url'] : '';
175          $blog_name = !empty($_POST['blog_name']) ? $_POST['blog_name'] : '';
176          $charset = '';
177          $comment = '';
178         
179          $err = false;
180          $msg = '';
181         
182          if ($this->core->blog === null)
183          {
184               $err = true;
185               $msg = 'No blog.';
186          }
187          elseif ($url == '')
188          {
189               $err = true;
190               $msg = 'URL parameter is required.';
191          }
192          elseif ($blog_name == '') {
193               $err = true;
194               $msg = 'Blog name is required.';
195          }
196         
197          if (!$err)
198          {
199               $post = $this->core->blog->getPosts(array('post_id'=>$post_id,'post_type'=>''));
200               
201               if ($post->isEmpty())
202               {
203                    $err = true;
204                    $msg = 'No such post.';
205               }
206               elseif (!$post->trackbacksActive())
207               {
208                    $err = true;
209                    $msg = 'Trackbacks are not allowed for this post or weblog.';
210               }
211          }
212         
213          if (!$err)
214          {
215               $charset = self::getCharsetFromRequest();
216               
217               if (!$charset) {
218                    $charset = mb_detect_encoding($title.' '.$excerpt.' '.$blog_name,
219                    'UTF-8,ISO-8859-1,ISO-8859-2,ISO-8859-3,'.
220                    'ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,'.
221                    'ISO-8859-9,ISO-8859-10,ISO-8859-13,ISO-8859-14,ISO-8859-15');
222               }
223               
224               if (strtolower($charset) != 'utf-8') {
225                    $title = iconv($charset,'UTF-8',$title);
226                    $excerpt = iconv($charset,'UTF-8',$excerpt);
227                    $blog_name = iconv($charset,'UTF-8',$blog_name);
228               }
229               
230               $title = trim(html::clean($title));
231               $title = html::decodeEntities($title);
232               $title = html::escapeHTML($title);
233               $title = text::cutString($title,60);
234               
235               $excerpt = trim(html::clean($excerpt));
236               $excerpt = html::decodeEntities($excerpt);
237               $excerpt = preg_replace('/\s+/ms',' ',$excerpt);
238               $excerpt = text::cutString($excerpt,252); 
239               $excerpt = html::escapeHTML($excerpt).'...';
240               
241               $blog_name = trim(html::clean($blog_name));
242               $blog_name = html::decodeEntities($blog_name);
243               $blog_name = html::escapeHTML($blog_name);
244               $blog_name = text::cutString($blog_name,60);
245               
246               $url = trim(html::clean($url));
247               
248               if (!$blog_name) {
249                    $blog_name = 'Anonymous blog';
250               }
251               
252               $comment =
253               "<!-- TB -->\n".
254               '<p><strong>'.($title ? $title : $blog_name)."</strong></p>\n".
255               '<p>'.$excerpt.'</p>';
256               
257               $cur = $this->core->con->openCursor($this->core->prefix.'comment');
258               $cur->comment_author = (string) $blog_name;
259               $cur->comment_site = (string) $url;
260               $cur->comment_content = (string) $comment;
261               $cur->post_id = $post_id;
262               $cur->comment_trackback = 1;
263               $cur->comment_status = $this->core->blog->settings->system->trackbacks_pub ? 1 : -1;
264               $cur->comment_ip = http::realIP();
265               
266               try
267               {
268                    # --BEHAVIOR-- publicBeforeTrackbackCreate
269                    $this->core->callBehavior('publicBeforeTrackbackCreate',$cur);
270                    if ($cur->post_id) {
271                         $comment_id = $this->core->blog->addComment($cur);
272                         
273                         # --BEHAVIOR-- publicAfterTrackbackCreate
274                         $this->core->callBehavior('publicAfterTrackbackCreate',$cur,$comment_id);
275                    }
276               }
277               catch (Exception $e)
278               {
279                    $err = 1;
280                    $msg = 'Something went wrong : '.$e->getMessage();
281               }
282          }
283         
284         
285          $debug_trace =
286          "  <debug>\n".
287          '    <title>'.$title."</title>\n".
288          '    <excerpt>'.$excerpt."</excerpt>\n".
289          '    <url>'.$url."</url>\n".
290          '    <blog_name>'.$blog_name."</blog_name>\n".
291          '    <charset>'.$charset."</charset>\n".
292          '    <comment>'.$comment."</comment>\n".
293          "  </debug>\n";
294         
295          $resp =
296          '<?xml version="1.0" encoding="utf-8"?>'."\n".
297          "<response>\n".
298          '  <error>'.(integer) $err."</error>\n";
299         
300          if ($msg) {
301               $resp .= '  <message>'.$msg."</message>\n";
302          }
303         
304          if (!empty($_POST['__debug'])) {
305               $resp .= $debug_trace;
306          }
307         
308          echo $resp."</response>";
309     }
310     //@}
311
312     /// @name Receive pingbacks
313     //@{
314     /**
315     Receives a pingback and insert it as a comment of given post.
316     
317     @param    from_url       <b>string</b>       Source URL
318     @param    to_url              <b>string</b>       Target URL
319     */
320     public function receive_pb($from_url, $to_url)
321     {
322          $reg = '!^'.preg_quote($this->core->blog->url).'(.*)!';
323          $type = $args = $next = '';
324         
325          # Are you dumb?
326          if (!preg_match($reg, $to_url, $m)) {
327               throw new Exception(__('Any chance you ping one of my contents? No? Really?'), 0);
328          }
329         
330          # Does the targeted URL look like a registered post type?
331          $url_part = $m[1];
332          $p_type = '';
333          $post_types = $this->core->getPostTypes();
334          foreach ($post_types as $k => $v) {
335               $reg = '!^'.preg_quote(str_replace('%s', '', $v['public_url'])).'(.*)!';
336               if (preg_match($reg, $url_part, $n)) {
337                    $p_type = $k;
338                    $post_url = $n[1];
339                    break;
340               }
341          }
342         
343          if (empty($p_type)) {
344               throw new Exception(__('Sorry but you can not ping this type of content.'), 33);
345          }
346
347          # Time to see if we've got a winner...
348          $params = array(
349               'post_type' => $p_type,
350               'post_url' => $post_url,
351          );
352          $posts = $this->core->blog->getPosts($params);
353         
354          # Missed!
355          if ($posts->isEmpty()) {
356               throw new Exception(__('Oops. Kinda "not found" stuff. Please check the target URL twice.'), 33);
357          }
358         
359          # Nice try. But, sorry, no.
360          if (!$posts->trackbacksActive()) {
361               throw new Exception(__('Sorry, dude. This entry does not accept pingback at the moment.'), 33);
362          }
363
364          # OK. We've found our champion. Time to check the remote part.
365          try {
366               $http = self::initHttp($from_url, $from_path);
367               
368               # First round : just to be sure the ping comes from an acceptable resource type.
369               $http->setHeadersOnly(true);
370               $http->get($from_path);
371               $c_type = explode(';', $http->getHeader('content-type'));
372
373               # Bad luck. Bye, bye...
374               if (!in_array($c_type[0],array('text/html', 'application/xhtml+xml'))) {
375                    throw new Exception(__('Your source URL does not look like a supported content type. Sorry. Bye, bye!'), 0);
376               }
377               
378               # Second round : let's go fetch and parse the remote content
379               $http->setHeadersOnly(false);
380               $http->get($from_path);
381               $remote_content = $http->getContent();
382
383               $charset = mb_detect_encoding($remote_content,
384                    'UTF-8,ISO-8859-1,ISO-8859-2,ISO-8859-3,'.
385                    'ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,'.
386                    'ISO-8859-9,ISO-8859-10,ISO-8859-13,ISO-8859-14,ISO-8859-15');
387
388               if (strtolower($charset) != 'utf-8') {
389                    $remote_content = iconv($charset,'UTF-8',$remote_content);
390               }
391               
392               # We want a title...
393               if (!preg_match('!<title>([^<].*?)</title>!mis', $remote_content, $m)) {
394                    throw new Exception(__('Where\'s your title?'), 0);
395               }
396               $title = trim(html::clean($m[1]));
397               $title = html::decodeEntities($title);
398               $title = html::escapeHTML($title);
399               $title = text::cutString($title,60);
400               
401               preg_match('!<body[^>]*?>(.*)?</body>!msi', $remote_content, $m);
402               $source = $m[1];
403               $source = preg_replace('![\r\n\s]+!ms',' ',$source);
404               $source = preg_replace( "/<\/*(h\d|p|th|td|li|dt|dd|pre|caption|input|textarea|button)[^>]*>/", "\n\n", $source );
405               $source = strip_tags($source, '<a>');
406               $source = explode("\n\n",$source);
407               
408               $excerpt = '';
409               foreach ($source as $line) {
410                    if (strpos($line, $to_url) !== false) {
411                         if (preg_match("!<a[^>]+?".$to_url."[^>]*>([^>]+?)</a>!", $line, $m)) {
412                              $excerpt = strip_tags($line);
413                              break;
414                         }
415                    }
416               }
417               if ($excerpt) {
418                    $excerpt = '(&#8230;) '.text::cutString(html::escapeHTML($excerpt),255).' (&#8230;)';
419               }
420               else {
421                    $excerpt = '(??)';
422               }
423
424               $comment =
425               "<!-- TB -->\n".
426               '<p><strong>'.$title."</strong></p>\n".
427               '<p>'.$excerpt.'</p>';
428               
429               $cur = $this->core->con->openCursor($this->core->prefix.'comment');
430               $cur->comment_author = 'Anonymous blog';
431               $cur->comment_site = (string) $from_url;
432               $cur->comment_content = (string) $comment;
433               $cur->post_id = $posts->post_id;
434               $cur->comment_trackback = 1;
435               $cur->comment_status = $this->core->blog->settings->system->trackbacks_pub ? 1 : -1;
436               $cur->comment_ip = http::realIP();
437               
438               # --BEHAVIOR-- publicBeforeTrackbackCreate
439               $this->core->callBehavior('publicBeforeTrackbackCreate',$cur);
440               if ($cur->post_id) {
441                    $comment_id = $this->core->blog->addComment($cur);
442                   
443                    # --BEHAVIOR-- publicAfterTrackbackCreate
444                    $this->core->callBehavior('publicAfterTrackbackCreate',$cur,$comment_id);
445               }
446          }
447          catch (Exception $e) {
448               throw new Exception(__('Sorry, an internal problem has occured.'), 0);
449          }
450         
451          return __('Thanks, mate. It was a pleasure.');
452     }
453     //@}
454     
455     private static function initHttp($url,&$path)
456     {
457          $client = netHttp::initClient($url,$path);
458          $client->setTimeout(5);
459          $client->setUserAgent('Dotclear - http://www.dotclear.org/');
460          $client->useGzip(false);
461          $client->setPersistReferers(false);
462         
463          return $client;
464     }
465     
466     private static function getCharsetFromRequest()
467     {
468          if (isset($_SERVER['CONTENT_TYPE']))
469          {
470               if (preg_match('|charset=([a-zA-Z0-9-]+)|',$_SERVER['CONTENT_TYPE'],$m)) {
471                    return $m[1];
472               }
473          }
474         
475          return null;
476     }
477     
478     /// @name Trackbacks auto discovery
479     //@{
480     /**
481     Returns an array containing all discovered trackbacks URLs in
482     <var>$text</var>.
483     
484     @param    text      <b>string</b>       Input text
485     @return   <b>array</b>
486     */
487     public function discover($text)
488     {
489          $res = array();
490         
491          foreach ($this->getTextLinks($text) as $link)
492          {
493               if (($url = $this->getPingURL($link)) !== null) {
494                    $res[] = $url;
495               }
496          }
497         
498          return $res;
499     }
500     //@}
501     
502     private function getTextLinks($text)
503     {
504          $res = array();
505         
506          # href attribute on "a" tags
507          if (preg_match_all('/<a ([^>]+)>/ms', $text, $match, PREG_SET_ORDER))
508          {
509               for ($i = 0; $i<count($match); $i++)
510               {
511                    if (preg_match('/href="((https?:\/)?\/[^"]+)"/ms', $match[$i][1], $matches)) {
512                         $res[$matches[1]] = 1;
513                    }
514               }
515          }
516          unset($match);
517         
518          # cite attributes on "blockquote" and "q" tags
519          if (preg_match_all('/<(blockquote|q) ([^>]+)>/ms', $text, $match, PREG_SET_ORDER))
520          {
521               for ($i = 0; $i<count($match); $i++)
522               {
523                    if (preg_match('/cite="((https?:\/)?\/[^"]+)"/ms', $match[$i][2], $matches)) {
524                         $res[$matches[1]] = 1;
525                    }
526               }
527          }
528         
529          return array_keys($res);
530     }
531     
532     private function getPingURL($url)
533     {
534          if (strpos($url,'/') === 0) {
535               $url = http::getHost().$url;
536          }
537         
538          try
539          {
540               $http = self::initHttp($url,$path);
541               $http->get($path);
542               $page_content = $http->getContent();
543               $pb_url = $http->getHeader('x-pingback');
544          }
545          catch (Exception $e)
546          {
547               return false;
548          }
549         
550          # If we've got a X-Pingback header and it's a valid URL, it will be enough
551          if ($pb_url && filter_var($pb_url,FILTER_VALIDATE_URL) && preg_match('!^https?:!',$pb_url)) {
552               return $pb_url.'|'.$url;
553          }
554         
555          # No X-Pingback header. A link rel=pingback, maybe ?
556          $pattern_pingback = '!<link rel="pingback" href="(.*?)"( /)?>!msi';
557         
558          if (preg_match($pattern_pingback,$page_content,$m)) {
559               $pb_url = $m[1];
560               if (filter_var($pb_url,FILTER_VALIDATE_URL) && preg_match('!^https?:!',$pb_url)) {
561                    return $pb_url.'|'.$url;
562               }
563          }
564
565          # No pingback ? OK, let's check for a trackback data chunk...
566          $pattern_rdf =
567          '/<rdf:RDF.*?>.*?'.
568          '<rdf:Description\s+(.*?)\/>'.
569          '.*?<\/rdf:RDF>'.
570          '/msi';
571         
572          preg_match_all($pattern_rdf,$page_content,$rdf_all,PREG_SET_ORDER);
573         
574          $url_path = parse_url($url, PHP_URL_PATH);
575          $sanitized_url = str_replace($url_path, html::sanitizeURL($url_path), $url);
576         
577          for ($i=0; $i<count($rdf_all); $i++)
578          {
579               $rdf = $rdf_all[$i][1];
580               if (preg_match('/dc:identifier="'.preg_quote($url,'/').'"/msi',$rdf) ||
581                    preg_match('/dc:identifier="'.preg_quote($sanitized_url,'/').'"/msi',$rdf)) {
582                    if (preg_match('/trackback:ping="(.*?)"/msi',$rdf,$tb_link)) {
583                         return $tb_link[1];
584                    }
585               }
586          }
587         
588          return null;
589     }
590}
591?>
Note: See TracBrowser for help on using the repository browser.

Sites map