Dotclear

source: inc/core/class.dc.trackback.php @ 1684:b7294dd181ee

Revision 1684:b7294dd181ee, 14.8 KB checked in by Florent Cotton <florent.cotton@…>, 11 years ago (diff)

Ré-aménagement de la classe dcTrackback afin de limiter les blocs de code inutilement redondants (closes #1628)

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/Pingbacks sender and server
17
18Sends and receives trackbacks/pingbacks. Also handles trackbacks/pingbacks 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     private function addBacklink($post_id, $url, $blog_name, $title, $excerpt, &$comment)
150     {
151          if (empty($blog_name)) {
152               $blog_name = 'Anonymous blog';
153          }
154         
155          $comment =
156          "<!-- TB -->\n".
157          '<p><strong>'.($title ? $title : $blog_name)."</strong></p>\n".
158          '<p>'.$excerpt.'</p>';
159         
160          $cur = $this->core->con->openCursor($this->core->prefix.'comment');
161          $cur->comment_author = (string) $blog_name;
162          $cur->comment_site = (string) $url;
163          $cur->comment_content = (string) $comment;
164          $cur->post_id = $post_id;
165          $cur->comment_trackback = 1;
166          $cur->comment_status = $this->core->blog->settings->system->trackbacks_pub ? 1 : -1;
167          $cur->comment_ip = http::realIP();
168         
169          # --BEHAVIOR-- publicBeforeTrackbackCreate
170          $this->core->callBehavior('publicBeforeTrackbackCreate',$cur);
171          if ($cur->post_id) {
172               $comment_id = $this->core->blog->addComment($cur);
173               
174               # --BEHAVIOR-- publicAfterTrackbackCreate
175               $this->core->callBehavior('publicAfterTrackbackCreate',$cur,$comment_id);
176          }
177     }
178     
179     /// @name Receive trackbacks
180     //@{
181     /**
182     Receives a trackback and insert it as a comment of given post.
183     
184     @param    post_id        <b>integer</b>      Post ID
185     */
186     public function receive($post_id)
187     {
188          header('Content-Type: text/xml; charset=UTF-8');
189          if (empty($_POST)) {
190               http::head(405,'Method Not Allowed');
191               echo
192               '<?xml version="1.0" encoding="utf-8"?>'."\n".
193               "<response>\n".
194               "  <error>1</error>\n".
195               "  <message>POST request needed</message>\n".
196               "</response>";
197               return;
198          }
199         
200          $post_id = (integer) $post_id;
201         
202          $title = !empty($_POST['title']) ? $_POST['title'] : '';
203          $excerpt = !empty($_POST['excerpt']) ? $_POST['excerpt'] : '';
204          $url = !empty($_POST['url']) ? $_POST['url'] : '';
205          $blog_name = !empty($_POST['blog_name']) ? $_POST['blog_name'] : '';
206          $charset = '';
207          $comment = '';
208         
209          $err = false;
210          $msg = '';
211         
212          if ($this->core->blog === null)
213          {
214               $err = true;
215               $msg = 'No blog.';
216          }
217          elseif ($url == '')
218          {
219               $err = true;
220               $msg = 'URL parameter is required.';
221          }
222          elseif ($blog_name == '') {
223               $err = true;
224               $msg = 'Blog name is required.';
225          }
226         
227          if (!$err)
228          {
229               $post = $this->core->blog->getPosts(array('post_id'=>$post_id,'post_type'=>''));
230               
231               if ($post->isEmpty())
232               {
233                    $err = true;
234                    $msg = 'No such post.';
235               }
236               elseif (!$post->trackbacksActive())
237               {
238                    $err = true;
239                    $msg = 'Trackbacks are not allowed for this post or weblog.';
240               }
241          }
242         
243          if (!$err)
244          {
245               $charset = self::getCharsetFromRequest();
246               
247               if (!$charset) {
248                    $charset = self::detectCharset($title.' '.$excerpt.' '.$blog_name);
249               }
250               
251               if (strtolower($charset) != 'utf-8') {
252                    $title = iconv($charset,'UTF-8',$title);
253                    $excerpt = iconv($charset,'UTF-8',$excerpt);
254                    $blog_name = iconv($charset,'UTF-8',$blog_name);
255               }
256               
257               $title = trim(html::clean($title));
258               $title = html::decodeEntities($title);
259               $title = html::escapeHTML($title);
260               $title = text::cutString($title,60);
261               
262               $excerpt = trim(html::clean($excerpt));
263               $excerpt = html::decodeEntities($excerpt);
264               $excerpt = preg_replace('/\s+/ms',' ',$excerpt);
265               $excerpt = text::cutString($excerpt,252); 
266               $excerpt = html::escapeHTML($excerpt).'...';
267               
268               $blog_name = trim(html::clean($blog_name));
269               $blog_name = html::decodeEntities($blog_name);
270               $blog_name = html::escapeHTML($blog_name);
271               $blog_name = text::cutString($blog_name,60);
272               
273               $url = trim(html::clean($url));
274               
275               try
276               {
277                    $this->addBacklink($post_id, $url, $blog_name, $title, $excerpt, $comment);
278               }
279               catch (Exception $e)
280               {
281                    $err = 1;
282                    $msg = 'Something went wrong : '.$e->getMessage();
283               }
284          }
285         
286          $resp =
287          '<?xml version="1.0" encoding="utf-8"?>'."\n".
288          "<response>\n".
289          '  <error>'.(integer) $err."</error>\n";
290         
291          if ($msg) {
292               $resp .= '  <message>'.$msg."</message>\n";
293          }
294         
295          if (!empty($_POST['__debug'])) {
296               $resp .= 
297               "  <debug>\n".
298               '    <title>'.$title."</title>\n".
299               '    <excerpt>'.$excerpt."</excerpt>\n".
300               '    <url>'.$url."</url>\n".
301               '    <blog_name>'.$blog_name."</blog_name>\n".
302               '    <charset>'.$charset."</charset>\n".
303               '    <comment>'.$comment."</comment>\n".
304               "  </debug>\n";
305          }
306         
307          echo $resp."</response>";
308     }
309     //@}
310
311     /// @name Receive pingbacks
312     //@{
313     /**
314     Receives a pingback and insert it as a comment of given post.
315     
316     @param    from_url       <b>string</b>       Source URL
317     @param    to_url              <b>string</b>       Target URL
318     */
319     public function receive_pb($from_url, $to_url)
320     {
321          $reg = '!^'.preg_quote($this->core->blog->url).'(.*)!';
322          $type = $args = $next = '';
323         
324          # Are you dumb?
325          if (!preg_match($reg, $to_url, $m)) {
326               throw new Exception(__('Any chance you ping one of my contents? No? Really?'), 0);
327          }
328         
329          # Does the targeted URL look like a registered post type?
330          $url_part = $m[1];
331          $p_type = '';
332          $post_types = $this->core->getPostTypes();
333          foreach ($post_types as $k => $v) {
334               $reg = '!^'.preg_quote(str_replace('%s', '', $v['public_url'])).'(.*)!';
335               if (preg_match($reg, $url_part, $n)) {
336                    $p_type = $k;
337                    $post_url = $n[1];
338                    break;
339               }
340          }
341         
342          if (empty($p_type)) {
343               throw new Exception(__('Sorry but you can not ping this type of content.'), 33);
344          }
345
346          # Time to see if we've got a winner...
347          $params = array(
348               'post_type' => $p_type,
349               'post_url' => $post_url,
350          );
351          $posts = $this->core->blog->getPosts($params);
352         
353          # Missed!
354          if ($posts->isEmpty()) {
355               throw new Exception(__('Oops. Kinda "not found" stuff. Please check the target URL twice.'), 33);
356          }
357         
358          # Nice try. But, sorry, no.
359          if (!$posts->trackbacksActive()) {
360               throw new Exception(__('Sorry, dude. This entry does not accept pingback at the moment.'), 33);
361          }
362
363          # OK. We've found our champion. Time to check the remote part.
364          try {
365               $http = self::initHttp($from_url, $from_path);
366               
367               # First round : just to be sure the ping comes from an acceptable resource type.
368               $http->setHeadersOnly(true);
369               $http->get($from_path);
370               $c_type = explode(';', $http->getHeader('content-type'));
371
372               # Bad luck. Bye, bye...
373               if (!in_array($c_type[0],array('text/html', 'application/xhtml+xml'))) {
374                    throw new Exception(__('Your source URL does not look like a supported content type. Sorry. Bye, bye!'), 0);
375               }
376               
377               # Second round : let's go fetch and parse the remote content
378               $http->setHeadersOnly(false);
379               $http->get($from_path);
380               $remote_content = $http->getContent();
381
382               $charset = self::getCharsetFromRequest($http->getHeader('content-type'));
383
384               if (!$charset) {
385                    $charset = self::detectCharset($remote_content);
386               }
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),200).' (&#8230;)';
419               }
420               else {
421                    $excerpt = '(&#8230;)';
422               }
423
424               $this->addBacklink($posts->post_id, $from_url, '', $title, $excerpt, $comment);
425          }
426          catch (Exception $e) {
427               throw new Exception(__('Sorry, an internal problem has occured.'), 0);
428          }
429         
430          return __('Thanks, mate. It was a pleasure.');
431     }
432     //@}
433     
434     private static function initHttp($url,&$path)
435     {
436          $client = netHttp::initClient($url,$path);
437          $client->setTimeout(5);
438          $client->setUserAgent('Dotclear - http://www.dotclear.org/');
439          $client->useGzip(false);
440          $client->setPersistReferers(false);
441         
442          return $client;
443     }
444     
445     private static function getCharsetFromRequest($header = '')
446     {
447          if (!$header && isset($_SERVER['CONTENT_TYPE'])) {
448               $header = $_SERVER['CONTENT_TYPE'];
449          }
450         
451          if ($header) {
452               if (preg_match('|charset=([a-zA-Z0-9-]+)|',$header,$m)) {
453                    return $m[1];
454               }
455          }
456         
457          return null;
458     }
459
460     private static function detectCharset($string)
461     {
462          return mb_detect_encoding($remote_content,
463                    'UTF-8,ISO-8859-1,ISO-8859-2,ISO-8859-3,'.
464                    'ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,'.
465                    'ISO-8859-9,ISO-8859-10,ISO-8859-13,ISO-8859-14,ISO-8859-15');
466     }
467         
468     /// @name Trackbacks auto discovery
469     //@{
470     /**
471     Returns an array containing all discovered trackbacks URLs in
472     <var>$text</var>.
473     
474     @param    text      <b>string</b>       Input text
475     @return   <b>array</b>
476     */
477     public function discover($text)
478     {
479          $res = array();
480         
481          foreach ($this->getTextLinks($text) as $link)
482          {
483               if (($url = $this->getPingURL($link)) !== null) {
484                    $res[] = $url;
485               }
486          }
487         
488          return $res;
489     }
490     //@}
491     
492     private function getTextLinks($text)
493     {
494          $res = array();
495         
496          # href attribute on "a" tags
497          if (preg_match_all('/<a ([^>]+)>/ms', $text, $match, PREG_SET_ORDER))
498          {
499               for ($i = 0; $i<count($match); $i++)
500               {
501                    if (preg_match('/href="((https?:\/)?\/[^"]+)"/ms', $match[$i][1], $matches)) {
502                         $res[$matches[1]] = 1;
503                    }
504               }
505          }
506          unset($match);
507         
508          # cite attributes on "blockquote" and "q" tags
509          if (preg_match_all('/<(blockquote|q) ([^>]+)>/ms', $text, $match, PREG_SET_ORDER))
510          {
511               for ($i = 0; $i<count($match); $i++)
512               {
513                    if (preg_match('/cite="((https?:\/)?\/[^"]+)"/ms', $match[$i][2], $matches)) {
514                         $res[$matches[1]] = 1;
515                    }
516               }
517          }
518         
519          return array_keys($res);
520     }
521     
522     private function getPingURL($url)
523     {
524          if (strpos($url,'/') === 0) {
525               $url = http::getHost().$url;
526          }
527         
528          try
529          {
530               $http = self::initHttp($url,$path);
531               $http->get($path);
532               $page_content = $http->getContent();
533               $pb_url = $http->getHeader('x-pingback');
534          }
535          catch (Exception $e)
536          {
537               return false;
538          }
539         
540          # If we've got a X-Pingback header and it's a valid URL, it will be enough
541          if ($pb_url && filter_var($pb_url,FILTER_VALIDATE_URL) && preg_match('!^https?:!',$pb_url)) {
542               return $pb_url.'|'.$url;
543          }
544         
545          # No X-Pingback header. A link rel=pingback, maybe ?
546          $pattern_pingback = '!<link rel="pingback" href="(.*?)"( /)?>!msi';
547         
548          if (preg_match($pattern_pingback,$page_content,$m)) {
549               $pb_url = $m[1];
550               if (filter_var($pb_url,FILTER_VALIDATE_URL) && preg_match('!^https?:!',$pb_url)) {
551                    return $pb_url.'|'.$url;
552               }
553          }
554
555          # No pingback ? OK, let's check for a trackback data chunk...
556          $pattern_rdf =
557          '/<rdf:RDF.*?>.*?'.
558          '<rdf:Description\s+(.*?)\/>'.
559          '.*?<\/rdf:RDF>'.
560          '/msi';
561         
562          preg_match_all($pattern_rdf,$page_content,$rdf_all,PREG_SET_ORDER);
563         
564          $url_path = parse_url($url, PHP_URL_PATH);
565          $sanitized_url = str_replace($url_path, html::sanitizeURL($url_path), $url);
566         
567          for ($i=0; $i<count($rdf_all); $i++)
568          {
569               $rdf = $rdf_all[$i][1];
570               if (preg_match('/dc:identifier="'.preg_quote($url,'/').'"/msi',$rdf) ||
571                    preg_match('/dc:identifier="'.preg_quote($sanitized_url,'/').'"/msi',$rdf)) {
572                    if (preg_match('/trackback:ping="(.*?)"/msi',$rdf,$tb_link)) {
573                         return $tb_link[1];
574                    }
575               }
576          }
577         
578          return null;
579     }
580}
581?>
Note: See TracBrowser for help on using the repository browser.

Sites map