OSDN Git Service

(none)
[nucleus-jp/nucleus-plugins.git] / trunk / NP_TrackBack / NP_TrackBack.php
1 <?php
2 // vim: tabstop=2:shiftwidth=2 
3
4    /* ==========================================================================================
5         * Trackback 2.0 for Nucleus CMS 
6         * ==========================================================================================
7         * This program is free software and open source software; you can redistribute
8         * it and/or modify it under the terms of the GNU General Public License as
9         * published by the Free Software Foundation; either version 2 of the License,
10         * or (at your option) any later version.
11         *
12         * This program is distributed in the hope that it will be useful, but WITHOUT
13         * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14         * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
15         * more details.
16         *
17         * You should have received a copy of the GNU General Public License along
18         * with this program; if not, write to the Free Software Foundation, Inc.,
19         * 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA  or visit
20         * http://www.gnu.org/licenses/gpl.html
21         * ==========================================================================================
22         */
23
24         // Compatiblity with Nucleus < = 2.0
25         if (!function_exists('sql_table')) { function sql_table($name) { return 'nucleus_' . $name; } }
26
27         
28         class NP_TrackBack extends NucleusPlugin {
29
30                 var $useCurl = 1; // use curl? 2:precheck+read by curl, 1: read by curl 0: fread
31
32 //modify start+++++++++
33                 function _createItemLink($itemid, $b){
34                         global $CONF, $manager;
35                         $blogurl = $b->getURL();
36                 
37                         if (!$blogurl) {
38                                 if($blog) {
39                                         $b_tmp =& $manager->getBlog($CONF['DefaultBlog']);
40                                         $blogurl = $b_tmp->getURL();
41                                 }
42                                 if (!$blogurl) {
43                                         $blogurl = $CONF['IndexURL'];
44                                         if ($CONF['URLMode'] != 'pathinfo'){
45                                                 $blogurl = $CONF['Self'];
46                                         }
47                                 }
48                         }
49                         if ($CONF['URLMode'] == 'pathinfo'){
50                                 if(substr($blogurl, -1) == '/')  $blogurl = substr($blogurl,0,-1);
51                         }
52                         
53                         $itemUrlOrg = $CONF['ItemURL'];
54                         $CONF['ItemURL'] = $blogurl;
55                         $itemLink = createItemLink($itemid,'');
56                         $CONF['ItemURL'] = $itemUrlOrg;
57                         
58                         return $itemLink;
59                 }
60 //modify end+++++++++
61
62         /**************************************************************************************
63          * SKIN VARS, TEMPLATE VARS AND ACTIONS
64                  */
65
66                 /*
67                  * TrackBack data can be inserted using skinvars (or templatevars)
68                  */
69                 function doSkinVar($skinType, $what = '', $tb_id = '', $amount = 'limit-1') {
70
71                         global $itemid, $manager, $CONF;
72
73 //modify start+++++++++
74                         if(eregi('limit', $tb_id)){
75                                 $amount = $tb_id;
76                                 $tb_id = '';
77                         }
78                         $amount = eregi_replace("limit", "", $amount);
79                         $amount = intval($amount);
80 //modify end+++++++++
81
82                         if ($tb_id == '') $tb_id = intval($itemid);
83         
84 //mod by cles
85                         $isAcceptPing = $this->isAcceptTrackBack($tb_id);
86
87                         //if( $skinType == 'template' && (! $isAcceptPing ) ){
88                         //      return;
89                         //}
90 //mod by cles end
91                         switch ($what) {
92                         
93                                 // Insert Auto-discovery RDF code
94                                 case 'tbcode':
95                                 case 'code':
96 //mod by cles
97 //                                      if($skinType == 'item')
98
99                                         $spamcheck = array (
100                                                 'type'          => 'tbcode',
101                                                 'id'            => -1,
102                                                 'title'         => '',
103                                                 'excerpt'       => '',
104                                                 'blogname'      => '',
105                                                 'url'           => '',
106                                                 'return'        => true,
107                                                 'live'          => true,
108                                                 
109                                                 /* Backwards compatibility with SpamCheck API 1*/
110                                                 'data'          => '',
111                                                 'ipblock'   => true,
112                                         );
113                                         global $manager;
114                                         //$manager->notify('SpamCheck', array ('spamcheck' => & $spamcheck));
115                                         $spam = false;
116                                         if (isset($spamcheck['result']) && $spamcheck['result'] == true){
117                                                 $spam = true;
118                                         }
119
120                                         if( ($skinType == 'item') && (!$spam) && $isAcceptPing  )
121 //mod by cles end
122                                                 $this->insertCode($tb_id);
123                                         break;
124                                         
125                                 // Insert TrackBack URL
126                                 case 'tburl':
127                                 case 'url':
128 //mod by cles
129 //                                      echo $this->getTrackBackUrl($tb_id);
130                                         if($isAcceptPing)
131                                                 echo $this->getTrackBackUrl($tb_id);
132                                         else
133                                                 echo 'Sorry, no trackback pings are accepted.';
134 //mod by cles end
135                                         break;
136                                 
137                                 // Insert manual ping URL
138                                 case 'form':
139                                 case 'manualpingformlink':
140                                         echo $this->getManualPingUrl($tb_id);
141                                         break;
142                                 
143                                 case 'sendpinglink':
144                                         echo $manager->addTicketToUrl($CONF['PluginURL'] . 'trackback/index.php?action=ping&amp;id=' . intval($tb_id));
145                                         break;
146         
147                                 // Insert TrackBack count
148                                 case 'count':
149                                         $count = $this->getTrackBackCount($tb_id);
150                                         switch ($count) {
151                                                 case 0:         echo TEMPLATE::fill($this->getOption('tplTbNone'), array('number' => $count)); break;
152                                                 case 1:         echo TEMPLATE::fill($this->getOption('tplTbOne'),  array('number' => $count)); break;
153                                                 default:        echo TEMPLATE::fill($this->getOption('tplTbMore'), array('number' => $count)); break;
154                                         }
155                                         break;
156
157                                 // Shows the TrackBack list
158                                 case 'list':
159                                 case '':
160 //modify start+++++++++
161 //                                      $this->showList($tb_id);
162                                         $this->showList($tb_id, $amount);
163 //modify end+++++++++
164                                         break;
165 //mod by cles
166                                 // show requred URL
167                                 case 'required':
168                                         echo  $this->getRequiredURL($tb_id);
169                                         break;
170                                         
171                                 // shows the Local list
172                                 case 'locallist':
173                                         $this->showLocalList($tb_id);
174                                         break;                                  
175 //mod by cles end
176                                         
177                                 default:
178                                         return;
179                         }
180                 }
181         
182                 /*
183                  * When used in templates, the tb_id will be determined by the itemid there
184                  */
185                 function doTemplateVar(&$item, $what = '') {
186                         $this->doSkinVar('template', $what, $item->itemid);
187                 }
188                 
189                 /*
190                 * A trackback ping is to be received on the URL
191                 * http://yourdomain.com/item/1234.trackback
192                 * Extra variables to be passed along are url, title, excerpt, blog_name
193                 */
194                 function event_InitSkinParse(&$data) {
195                         global $CONF, $itemid;
196                         $format = requestVar('format');
197                         
198                         if ($CONF['URLMode'] == 'pathinfo') {
199                                 if (preg_match('/(\/|\.)(trackback)(\/|$)/', serverVar('PATH_INFO'), $matches)) {
200                                         $format = $matches[2];
201                                 }
202                         }
203                         
204                         if ($format == 'trackback' && $data['type'] == 'item')
205                         {
206                                 $errorMsg = $this->handlePing(intval($itemid));
207                                 
208                                 if ($errorMsg != '')
209                                 $this->xmlResponse($errorMsg);
210                                 else
211                                 $this->xmlResponse();
212                                 
213                                 exit;
214                         }
215                 }
216
217                 /*
218                  * A trackback ping is to be received on the URL
219                  * http://yourdomain.com/action.php?action=plugin&name=TrackBack&tb_id=1234
220                  * Extra variables to be passed along are url, title, excerpt, blog_name
221                  */
222                 function doAction($type)
223                 {
224                         global $CONF,$manager;
225                         $aActionsNotToCheck = array(
226                                 '',
227                                 'ping',
228                                 'form',
229                                 'redirect',
230                                 'left',
231                         );
232                         if (!in_array($type, $aActionsNotToCheck)) {
233                                 if (!$manager->checkTicket()) return _ERROR_BADTICKET;
234                         }
235                         
236                         switch ($type) {
237         
238                                 // When no action type is given, assume it's a ping
239                                 case '':
240                                         $errorMsg = $this->handlePing();
241                                         
242                                         if ($errorMsg != '')
243                                                 $this->xmlResponse($errorMsg);
244                                         else
245                                                 $this->xmlResponse();
246                                         break; 
247                                         
248                                 // Manual ping
249                                 case 'ping':
250                                         $errorMsg = $this->handlePing();
251                                         if ($errorMsg != '')
252                                                 $this->showManualPingError(intRequestVar('tb_id'), $errorMsg);
253                                         else
254                                                 $this->showManualPingSuccess(intRequestVar('tb_id'));
255                                         break; 
256         
257                                 // Show manual ping form
258                                 case 'form':
259 //mod by cles
260 //                                      $this->showManualPingForm(intRequestVar('tb_id'));
261                                         $tb_id = intRequestVar('tb_id');
262                                         $isAcceptPing = $this->isAcceptTrackBack($tb_id);
263                                         
264                                         if( $isAcceptPing )     
265                                                 $this->showManualPingForm($tb_id);
266                                         else
267                                                 echo 'Sorry, no trackback pings are accepted.';
268 //mod by cles end
269                                         break;
270         
271                                 // Detect trackback
272                                 case 'detect':
273                                         list($url, $title) = 
274                                                 $this->getURIfromLink(html_entity_decode(requestVar('tb_link')));
275
276                                         $url = addslashes($url);
277                                         $url = $this->_utf8_to_javascript($url);
278
279                                         $title = addslashes($title);
280                                         $title = $this->_utf8_to_javascript($title);
281                                 
282                                         echo "tbDone('" . requestVar('tb_link') . "', '" . $url . "', '" . $title . "');";
283
284                                         break;
285 //mod by cles
286                                 // redirect 
287                                 case 'redirect':
288                                         return $this->redirect(intRequestVar('tb_id'), requestVar('urlHash'));
289                                         break;
290 //mod by cles end
291                                 case 'left':
292                                         echo $this->showLeftList(intRequestVar('tb_id'), intRequestVar('amount'));
293                                         break;
294                                 
295                                 // delete a trackback(local)
296                                 case 'deletelc':
297                                         $err = $this->deleteLocal(intRequestVar('tb_id'), intRequestVar('from_id'));
298                                         if( $err )
299                                                 return $err;
300                                         header('Location: ' . serverVar('HTTP_REFERER'));
301                                         break;
302                         } 
303
304                         exit;
305                 }
306                 
307                 function doIf($key = '', $value = '')
308                 {
309                         global $itemid;
310                         //echo "key: $key, value: $value";
311                         
312                         switch( strtolower($key) ){
313                                 case '':
314                                 case 'accept':
315                                         if( $value == '' ) $value = 'yes';
316                                         $value = ( $value == 'no' || (! $value) ) ? false : true;
317                                 
318                                         $ret = false;
319                                         if( $itemid )
320                                                 $ret = $this->isAcceptTrackBack($itemid);
321                                         else
322                                                 $ret = $this->isAcceptTrackBack();
323                                         return ( $value == false ) ? (! $ret) : $ret;
324                                         
325                                 case 'required':
326                                         if( $value == '' ) $value = 'yes';
327                                         $value = ( $value == 'no' || (! $value) ) ? false : true;
328                                         
329                                         $ret = false;
330                                         if( $itemid )
331                                                 $ret = $this->isEnableLinkCheck($itemid);
332                                         
333                                         return ( $value == false ) ? (! $ret) : $ret;
334                                         
335                                 default:
336                                         return false;
337                         }
338                 }
339
340         /**************************************************************************************
341          * OUTPUT
342                  */
343
344                 /*
345                  * Show a list of left trackbacks for this ID
346                  */
347                 function showLeftList($tb_id, $offset = 0, $amount = 99999999) {
348                         global $manager, $blog, $CONF;
349
350                         $out = array();
351                         $query = '
352                                 SELECT 
353                                         url, 
354                                         md5(url) as urlHash,
355                                         blog_name, 
356                                         excerpt, 
357                                         title, 
358                                         UNIX_TIMESTAMP(timestamp) AS timestamp 
359                                 FROM 
360                                         '.sql_table('plugin_tb').' 
361                                 WHERE 
362                                         tb_id = '.intval($tb_id).' AND
363                                         block = 0
364                                 ORDER BY 
365                                         timestamp DESC
366                         ';
367                         if($offset)
368                                 $query .= ' LIMIT '.intval($offset).', ' .intval($amount);
369                         $res = mysql_query($query);
370                         while ($row = mysql_fetch_array($res))
371                         {
372
373                                 $row['blog_name']       = htmlspecialchars($row['blog_name'], ENT_QUOTES);
374                                 $row['title']           = htmlspecialchars($row['title'], ENT_QUOTES);
375                                 $row['excerpt']         = htmlspecialchars($row['excerpt'], ENT_QUOTES);
376                                 if (_CHARSET != 'UTF-8') {
377 //modify start+++++++++
378                                         $row['blog_name']       = $this->_restore_to_utf8($row['blog_name']);
379                                         $row['title']           = $this->_restore_to_utf8($row['title']);
380                                         $row['excerpt']         = $this->_restore_to_utf8($row['excerpt']);
381 //modify end+++++++++
382                                         $row['blog_name']       = $this->_utf8_to_entities($row['blog_name']);
383                                         $row['title']           = $this->_utf8_to_entities($row['title']);
384                                         $row['excerpt']         = $this->_utf8_to_entities($row['excerpt']);
385                                 }                               
386                                 $iVars = array(
387                                         'action'        => $this->getTrackBackUrl($tb_id),
388                                         'form'          => $this->getManualPingUrl($tb_id),
389                                         'name'          => $row['blog_name'],
390                                         'title'         => $row['title'],
391                                         'excerpt'       => $this->_cut_string($row['excerpt'], 400),
392                                         'url'           => htmlspecialchars($row['url'], ENT_QUOTES),
393                                         'date'          => htmlspecialchars(strftime($this->getOption('dateFormat'), $row['timestamp']), ENT_QUOTES)
394                                 );
395
396 //mod by cles
397                                 if( $this->getOption('HideUrl') == 'yes' )
398                                         $iVars['url'] = $CONF['ActionURL'] . '?action=plugin&amp;name=TrackBack&amp;type=redirect&amp;tb_id=' . $tb_id . '&amp;urlHash=' . $row['urlHash'];
399                                 else
400                                         $iVars['url'] = $row['url'];
401 //mod by cles end
402
403                                 $out[] = TEMPLATE::fill($this->getOption('tplItem'), $iVars);
404                         }
405                         mysql_free_result($res);
406                         
407                         return @join("\n",$out);
408                 }
409
410                 /*
411                  * Show a list of all trackbacks for this ID
412                  */
413                 function showList($tb_id, $amount = 0) {
414                         $tb_id = intval($tb_id);
415                         global $manager, $blog, $CONF, $member;
416 //mod by cles
417                         $enableHideurl = true;
418                         // for TB LinkLookup
419                         if( 
420                                    strstr(serverVar('HTTP_USER_AGENT'),'Hatena Diary Track Forward Agent')
421                                 || strstr(serverVar('HTTP_USER_AGENT'),'NP_TrackBack')
422                                 || strstr(serverVar('HTTP_USER_AGENT'),'TBPingLinkLookup')
423                                 || strstr(serverVar('HTTP_USER_AGENT'),'MT::Plugin::BanNoReferTb')
424                                 || strstr(serverVar('HTTP_USER_AGENT'),'livedoorBlog')
425                         ){
426                                 $enableHideurl = false;
427                                 $amount = '-1';
428                         }
429 //mod by cles end
430
431 /*
432                         $res = mysql_query('
433                                 SELECT 
434                                         url, 
435                                         md5(url) as urlHash,
436                                         blog_name, 
437                                         excerpt, 
438                                         title, 
439                                         UNIX_TIMESTAMP(timestamp) AS timestamp 
440                                 FROM 
441                                         '.sql_table('plugin_tb').' 
442                                 WHERE 
443                                         tb_id = '.$tb_id .' AND
444                                         block = 0
445                                 ORDER BY 
446                                         timestamp ASC
447                         ');
448 */
449                         $query = '
450                                 SELECT 
451                                         url, 
452                                         md5(url) as urlHash,
453                                         blog_name, 
454                                         excerpt, 
455                                         title, 
456                                         UNIX_TIMESTAMP(timestamp) AS timestamp 
457                                 FROM 
458                                         '.sql_table('plugin_tb').' 
459                                 WHERE 
460                                         tb_id = '.intval($tb_id) .' AND
461                                         block = 0
462                                 ORDER BY 
463                                         timestamp DESC
464                         ';
465                         if( $amount == '-1' )
466                                 $query .= ' LIMIT 9999999';
467                         elseif( $amount )
468                                 $query .= ' LIMIT '.intval($amount);
469                         
470                         if( $amount != 0)
471                                 $res = mysql_query($query);
472
473                         $gVars = array(
474                                 'action' => $this->getTrackBackUrl(intval($tb_id)),
475                                 'form'   => $this->getManualPingUrl(intval($tb_id)),
476                                 'required' => $this->getRequiredURL(intval($tb_id)),
477                         );
478                         
479                         if ($member->isLoggedIn() && $member->isAdmin()){
480                                 $adminurl = htmlspecialchars($manager->addTicketToUrl($CONF['PluginURL'] . 'trackback/index.php?action=list&id=' . intval($tb_id)), ENT_QUOTES);
481                                 $pingformurl = htmlspecialchars($manager->addTicketToUrl($CONF['PluginURL'] . 'trackback/index.php?action=ping&id=' . intval($tb_id)), ENT_QUOTES);
482                                 $gVars['admin'] = '<a href="' . $adminurl . '" target="_blank">[admin]</a>';
483                                 $gVars['pingform'] = '<a href="' . $pingformurl . '" target="_blank">[pingform]</a>';
484                         }
485
486                         echo TEMPLATE::fill($this->getOption('tplHeader'), $gVars);
487
488
489                         while ($amount != 0 && $row = mysql_fetch_array($res))
490                         {
491
492                                 $row['blog_name']       = htmlspecialchars($row['blog_name'], ENT_QUOTES);
493                                 $row['title']           = htmlspecialchars($row['title'], ENT_QUOTES);
494                                 $row['excerpt']         = htmlspecialchars($row['excerpt'], ENT_QUOTES);
495
496 /*
497 */
498                                 if (_CHARSET != 'UTF-8') {
499 //modify start+++++++++
500 /*
501                                         $row['blog_name']       = $this->_utf8_to_entities($row['blog_name']);
502                                         $row['title']           = $this->_utf8_to_entities($row['title']);
503                                         $row['excerpt']         = $this->_utf8_to_entities($row['excerpt']);
504 */
505                                         $row['blog_name']       = $this->_restore_to_utf8($row['blog_name']);
506                                         $row['title']           = $this->_restore_to_utf8($row['title']);
507                                         $row['excerpt']         = $this->_restore_to_utf8($row['excerpt']);
508
509                                         $row['blog_name']       = mb_convert_encoding($row['blog_name'], _CHARSET, 'UTF-8');
510                                         $row['title']           = mb_convert_encoding($row['title'], _CHARSET, 'UTF-8');
511                                         $row['excerpt']         = mb_convert_encoding($row['excerpt'], _CHARSET, 'UTF-8');
512 //modify end+++++++++
513                                 }                               
514
515 //modify start+++++++++
516 /*
517                                 $iVars = array(
518                                         'action'        => $this->getTrackBackUrl($tb_id),
519                                         'form'          => $this->getManualPingUrl($tb_id),
520                                         'name'          => $row['blog_name'],
521                                         'title'         => $row['title'],
522                                         'excerpt'       => $row['excerpt'],
523                                         'url'           => htmlspecialchars($row['url'], ENT_QUOTES),
524                                         'date'          => htmlspecialchars(strftime($this->getOption('dateFormat'), $row['timestamp'] + ($blog->getTimeOffset() * 3600)), ENT_QUOTES)
525                                 );
526 */
527                                 $iVars = array(
528                                         'action'        => $this->getTrackBackUrl($tb_id),
529                                         'form'          => $this->getManualPingUrl($tb_id),
530                                         'name'          => htmlspecialchars($row['blog_name'], ENT_QUOTES),
531                                         'title'         => htmlspecialchars($row['title'], ENT_QUOTES),
532                                         'excerpt'       => htmlspecialchars($this->_cut_string($row['excerpt'], 400), ENT_QUOTES),
533                                         'url'           => htmlspecialchars($row['url'], ENT_QUOTES),
534                                         'date'          => htmlspecialchars(strftime($this->getOption('dateFormat'), $row['timestamp']), ENT_QUOTES)
535                                 );
536
537 //mod by cles
538                                 if( $enableHideurl && $this->getOption('HideUrl') == 'yes' )
539                                         $iVars['url'] = $CONF['ActionURL'] . '?action=plugin&amp;name=TrackBack&amp;type=redirect&amp;tb_id=' . intval($tb_id) . '&amp;urlHash=' . $row['urlHash'];
540                                 else
541                                         $iVars['url'] = $row['url'];
542 //mod by cles end
543
544 //modify end+++++++++
545                                 echo TEMPLATE::fill($this->getOption('tplItem'), $iVars);
546                                 
547                         }
548
549 //modify start+++++++++
550                         $q = '
551                                 SELECT 
552                                         count(*) 
553                                 FROM 
554                                         '.sql_table('plugin_tb').' 
555                                 WHERE 
556                                         tb_id = '.intval($tb_id) .' AND
557                                         block = 0
558                                 ORDER BY 
559                                         timestamp DESC
560                         ';
561                         $result = mysql_query($q);
562                         $total = mysql_result($result,0,0);
563
564                         if($amount != -1 && $total > $amount){
565                                 $leftcount = $total - $amount;
566
567                                 echo '<script type="text/javascript" src="' . $this->getAdminURL() . 'detectlist.php?tb_id='.intval($tb_id).'&amp;amount='.intval($amount).'"></script>';
568
569 ?>
570
571 <a name="restoftrackback" id="restoftrackback"></a>
572 <div id="tbshownavi"><a href="#restoftrackback" onclick="resttbStart(); return false;" id="tbshow">Show left <?php echo $leftcount;?> Trackbacks</a></div>
573 <div id="tbhidenavi" style="display: none;"><a href="#restoftrackback" onclick="hideresttb(); return false;">Hide <?php echo $leftcount;?> Trackbacks</a></div>
574 <div id="resttb"></div>
575
576 <?php
577                         }
578 //modify end+++++++++
579
580                         if (mysql_num_rows($res) == 0) 
581                         {
582                                 echo TEMPLATE::fill($this->getOption('tplEmpty'), $gVars);
583                         }
584                         mysql_free_result($res);
585                         
586                         echo TEMPLATE::fill($this->getOption('tplFooter'), $gVars);
587
588                 }
589                         
590                 /*
591                  * Returns the TrackBack count for a TrackBack item
592                  */
593                 function getTrackBackCount($tb_id) {
594                         return quickQuery('SELECT COUNT(*) as result FROM ' . sql_table('plugin_tb') . ' WHERE tb_id='.intval($tb_id).' AND block = 0');
595                 }
596                 
597                 /**
598                   * Returns the manual ping URL
599                   */
600                 function getManualPingUrl($itemid) {
601                         global $CONF;
602                         return $CONF['ActionURL'] . '?action=plugin&amp;name=TrackBack&amp;type=form&amp;tb_id='.$itemid;
603                 }
604
605                 /**
606                   * Show the manual ping form
607                   */
608                 function showManualPingError($itemid, $status = '') {
609                         global $CONF;
610
611                         $form = true; $error = true; $success = false;
612                         sendContentType('text/html', 'admin-trackback', _CHARSET);      
613 //modify start+++++++++
614 //                      include ($this->getDirectory() . '/templates/form.html');
615                         require_once($this->getDirectory() . '/template.php');
616                         $mTemplate = new Trackback_Template(null, $this->getDirectory());
617                         $mTemplate->set ('CONF', $CONF);
618                         $mTemplate->set ('itemid', $itemid);
619                         $mTemplate->set ('form', $form);
620                         $mTemplate->set ('error', $error);
621                         $mTemplate->set ('success', $success);
622                         $mTemplate->set ('status', $status);
623                         $mTemplate->template('templates/form.html');
624                         echo $mTemplate->fetch();
625 //modify end+++++++++
626                 }
627                 
628                 function showManualPingSuccess($itemid, $status = '') {
629                         global $CONF;
630
631                         $form = false; $error = false; $success = true;
632                         sendContentType('text/html', 'admin-trackback', _CHARSET);      
633 //modify start+++++++++
634                         //include ($this->getDirectory() . '/templates/form.html');
635                         require_once($this->getDirectory() . '/template.php');
636                         $mTemplate = new Trackback_Template(null, $this->getDirectory());
637                         $mTemplate->set ('CONF', $CONF);
638                         $mTemplate->set ('itemid', $itemid);
639                         $mTemplate->set ('form', $form);
640                         $mTemplate->set ('error', $error);
641                         $mTemplate->set ('success', $success);
642                         $mTemplate->set ('status', $status);
643                         $mTemplate->template('templates/form.html');
644                         echo $mTemplate->fetch();
645 //modify end+++++++++
646                 }
647                 
648                 function showManualPingForm($itemid, $text = '') {
649                         global $CONF;
650
651                         $form = true; $error = false; $success = false;
652
653                         // Check if we are allowed to accept pings
654                         if ( !$this->isAcceptTrackBack($itemid) ) {
655                                 $text = 'Sorry, no trackback pings are accepted';
656                                 $form = false; $error = true;
657                         }
658                         
659                         sendContentType('text/html', 'admin-trackback', _CHARSET);      
660 //modify start+++++++++
661                         //include ($this->getDirectory() . '/templates/form.html');
662                         require_once($this->getDirectory() . '/template.php');
663                         $mTemplate = new Trackback_Template(null, $this->getDirectory());
664                         $mTemplate->set ('CONF', $CONF);
665                         $mTemplate->set ('itemid', $itemid);
666                         $mTemplate->set ('form', $form);
667                         $mTemplate->set ('error', $error);
668                         $mTemplate->set ('success', $success);
669                         $mTemplate->set ('status', $status);
670                         $mTemplate->template('templates/form.html');
671                         echo $mTemplate->fetch();
672 //modify end+++++++++
673                 }
674         
675                 /**
676                   * Returns the trackback URL
677                   */
678                 function getTrackBackUrl($itemid) {
679                         global $CONF, $manager;
680                         return $CONF['ActionURL'] . '?action=plugin&amp;name=TrackBack&amp;tb_id='.$itemid;
681                 }               
682
683                 /*
684                  * Insert RDF code for item
685                  */
686                 function insertCode($itemid) {
687                         $itemid = intval($itemid);
688                         global $manager, $CONF;
689
690                         $item = & $manager->getItem($itemid, 0, 0);
691                         $blog = & $manager->getBlog(getBlogIDFromItemID($item['itemid']));
692                                 
693 /*
694                         $CONF['ItemURL'] = preg_replace('/\/$/', '', $blog->getURL());   
695                         $uri    = createItemLink($item['itemid'],'');   
696 */
697                         $uri    = $this->_createItemLink($item['itemid'],$blog);        
698                                         
699                         $title  = strip_tags($item['title']);
700                         $desc   = strip_tags($item['body']);
701                         $desc   = $this->_cut_string($desc, 200);
702                         $desc   = htmlspecialchars($desc, ENT_QUOTES);
703                         
704                         ?>
705                         <!--
706                         <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
707                                          xmlns:dc="http://purl.org/dc/elements/1.1/"
708                                          xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">
709                         <rdf:Description
710                                          rdf:about="<?php echo $uri; ?>"
711                                          dc:identifier="<?php echo $uri; ?>"
712                                          dc:title="<?php echo $title; ?>"
713                                          dc:description="<?php echo $desc; ?>"
714                                          trackback:ping="<?php echo $this->getTrackBackUrl($itemid)?>"
715                                          dc:date="<?php echo strftime('%Y-%m-%dT%H:%M:%S')?>" />
716                         </rdf:RDF>
717                         -->
718                         <?php
719                 }
720
721                 /**
722                  * Retrieving TrackBack Pings (when __mode=rss)
723                  */
724                 function rssResponse($tb_id) {
725                         $itemid = intval($itemid);
726                         global $manager, $CONF;
727                         $item =& $manager->getItem($tb_id, 0, 0);
728         
729                         if($item)
730                         {
731                                 $blog =& $manager->getBlog(getBlogIDFromItemID($item['itemid']));
732                                 
733                                 $blog_name  = $blog->getName();
734                                 $title      = $item['title'];
735                                 $excerpt    = $item['body'];
736
737 //modify start+++++++++
738 /*
739                                 if (_CHARSET != 'UTF-8')
740                                 {
741                                         $title          = $this->_convert_to_utf8($title, $encoding);
742                                         $excerpt    = $this->_convert_to_utf8($excerpt, $encoding);
743                                         $blog_name  = $this->_convert_to_utf8($blog_name, $encoding);
744                                 }
745
746                                 $title      = $this->_decode_entities(strip_tags($title));
747                                 $excerpt    = $this->_decode_entities(strip_tags($excerpt));
748                                 $blog_name  = $this->_decode_entities(strip_tags($blog_name));
749 */
750
751                                 $title      = $this->_restore_to_utf8($title);
752                                 $excerpt    = $this->_restore_to_utf8($excerpt);
753                                 $blog_name  = $this->_restore_to_utf8($blog_name);
754 //modify end+++++++++
755
756                                 $excerpt    = $this->_cut_string($excerpt, 200);
757
758                                 
759 //modify start+++++++++
760 /*
761                                 $CONF['ItemURL'] = preg_replace('/\/$/', '', $blog->getURL());   
762                                 $url    = createItemLink($item['itemid'],'');   
763 */
764                                 $url    = $this->_createItemLink($item['itemid'],$blog);        
765 //modify end+++++++++
766         
767                                 // Use UTF-8 charset for output
768                                 header('Content-Type: text/xml');
769                                 echo "<","?xml version='1.0' encoding='UTF-8'?",">\n";
770                                 
771                                 echo "<response>\n";
772                                 echo "\t<error>0</error>\n";
773                                 echo "\t<rss version='0.91'>\n";
774                                 echo "\t\t<channel>\n";
775                                 echo "\t\t\t<title>".htmlspecialchars($title, ENT_QUOTES)."</title>\n";
776                                 echo "\t\t\t<link>".htmlspecialchars($url, ENT_QUOTES)."</link>\n";
777                                 echo "\t\t\t<description>".htmlspecialchars($excerpt, ENT_QUOTES)."</description>\n";
778         
779                                 $query = 'SELECT url, blog_name, excerpt, title, UNIX_TIMESTAMP(timestamp) as timestamp FROM '.sql_table('plugin_tb').' WHERE tb_id='.intval($tb_id).' AND block = 0 ORDER BY timestamp DESC';
780                                 $res = mysql_query($query);
781                                 while ($o = mysql_fetch_object($res)) 
782                                 {
783                                         // No need to do conversion, because it is already UTF-8
784                                         $data = array (
785                                                 'url'           => htmlspecialchars($o->url, ENT_QUOTES),
786                                                 'blogname'      => htmlspecialchars($this->_restore_to_utf8($o->blog_name), ENT_QUOTES),
787                                                 'timestamp' => strftime('%Y-%m-%d',$o->timestamp),
788                                                 'title'         => htmlspecialchars($this->_restore_to_utf8($o->title), ENT_QUOTES),
789                                                 'excerpt'       => htmlspecialchars($this->_restore_to_utf8($o->excerpt), ENT_QUOTES),
790                                                 'tburl'         => $this->getTrackBackUrl($tb_id)
791                                         );
792                                         
793                                         echo "\n";
794                                         echo "\t\t\t<item>\n";
795                                         echo "\t\t\t\t<title>".$data['title']."</title>\n";
796                                         echo "\t\t\t\t<link>".$data['url']."</link>\n";
797                                         echo "\t\t\t\t<description>".$data['excerpt']."</description>\n";
798                                         echo "\t\t\t</item>\n";
799                                 }
800                                 echo "\t\t</channel>\n";
801                                 echo "\t</rss>\n";
802                                 echo "</response>";
803                                 exit;
804                         }
805                         else
806                         {
807                                 $this->xmlResponse(_ERROR_NOSUCHITEM);
808                         }
809         
810                 }
811
812
813
814         /**************************************************************************************
815          * SENDING AND RECEIVING TRACKBACK PINGS
816                  */
817
818                 /* 
819                  *  Send a Trackback ping to another website
820                  */
821                 function sendPing($itemid, $title, $url, $excerpt, $blog_name, $ping_url, $utf8flag=0) 
822                 {
823                         $tempEncording = ($utf8flag)? 'UTF-8': _CHARSET;
824                         
825                         // 1. Check some basic things
826                         if (!$this->canSendPing()) {
827                                 return 'You\'re not allowed to send pings';
828                         }
829                         
830                         if ($this->getOption('SendPings') == 'no') {
831                                 return 'Sending trackback pings is disabled';
832                         }
833                         
834                         if ($ping_url == '') {
835                                 return 'No ping URL';
836                         }
837         
838                         // 2. Check if protocol is correct http URL
839                         $parsed_url = parse_url($ping_url);
840
841                         if ($parsed_url['scheme'] != 'http' || $parsed_url['host'] == '')
842                                 return 'Bad ping URL';
843         
844                         $port = ($parsed_url['port']) ? $parsed_url['port'] : 80;
845         
846                         // 3. Create contents
847                         if($tempEncording != _CHARSET){
848                                 $title = mb_convert_encoding($title, $tempEncording, _CHARSET);
849                                 $excerpt = mb_convert_encoding($excerpt, $tempEncording, _CHARSET);
850                                 $blog_name = mb_convert_encoding($blog_name, $tempEncording, _CHARSET);
851                         }
852                         
853                         
854                         $content  = 'title=' .  urlencode( $title );
855                         $content .= '&url=' .           urlencode( $url );
856                         $content .= '&excerpt=' .       urlencode( $excerpt );
857                         $content .= '&blog_name=' . urlencode( $blog_name );
858         
859 #                       $user_agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)';
860                         $user_agent = 'NP_TrackBack/'. $this->getVersion();
861         
862                         // 4. Prepare HTTP request
863                         $request  = 'POST ' . $parsed_url['path'];
864
865                         if ($parsed_url['query'] != '')
866                                 $request .= '?' . $parsed_url['query'];
867                                 
868                         $request .= " HTTP/1.1\r\n";
869                         $request .= "Accept: */*\r\n";
870                         $request .= "User-Agent: " . $user_agent . "\r\n";
871                         $request .= ( $port == 80 )?
872                                                                         "Host: " . $parsed_url['host'] . "\r\n":
873                                                                         "Host: " . $parsed_url['host'] . ":" . $port . "\r\n";
874                         $request .= "Connection: Keep-Alive\r\n";
875                         $request .= "Cache-Control: no-cache\r\n";
876                         $request .= "Connection: Close\r\n";
877                         $request .= "Content-Length: " . strlen( $content ) . "\r\n";
878                         $request .= ($utf8flag)? 
879                                 "Content-Type: application/x-www-form-urlencoded; charset=UTF-8\r\n":
880                                 "Content-Type: application/x-www-form-urlencoded; charset="._CHARSET."\r\n";
881                         $request .= "\r\n";
882                         $request .= $content;
883         
884                         $socket = fsockopen( $parsed_url['host'], $port, $errno, $errstr );
885                         if ( ! $socket )
886                                 return 'Could not send ping: '.$errstr.' ('.$errno.')';
887         
888                         // 5. Execute HTTP request
889                         fputs($socket, $request);
890         
891                         // 6. Receive response
892                         $result = '';
893                         while (!feof($socket)) {
894                                 $result .= fgets($socket, 4096);
895                         }
896                         
897                         fclose($socket);
898         
899                         // instead of parsing the XML, just check for the error string
900                         // [TODO] extract real error message and return that
901 //modify start+++++++++
902
903                         $DATA = split("\r\n\r\n", $result, 2);
904                         preg_match("/HTTP\/1\.[0-1] ([0-9]+) ([^\r\n]*)\r?\n/",$DATA[0],$httpresp);
905                         $respCd = $httpresp[1];
906                         $respMsg = $httpresp[2];
907
908                         if( $respCd != 200 ){
909                                 return 'An error occurred: HTTP Error: [' . $respCd . '] ' . $respMsg;
910                         }
911                         if ( strstr($DATA[1],'<error>0</error>') === false ){
912                                 preg_match("/<message>(.*?)<\/message>/",$DATA[1],$error_message);
913                                 if( $error_message[1] )
914                                         return 'An error occurred: '.htmlspecialchars($error_message[1], ENT_QUOTES);
915                                 else
916                                         return 'An error occurred: fatal error.';
917                         }
918                 } 
919 //modify end+++++++++
920
921                 /* 
922                  *  Handle a Trackback ping sent to this website
923                  */
924                 function handlePing($tb_id = 0) {
925                         global $manager;
926                         
927                         // Defaults
928                         $spam       = false;
929                         $link       = false;
930 //modify start+++++++++
931 //                      $block      = true;
932                         $block      = false;
933 //modify end+++++++++
934                         if ($tb_id == 0)
935                         $tb_id          = intRequestVar('tb_id');
936                         
937                         $rss            = requestVar('__mode') == 'rss'; 
938 //mod by cles
939                         $enableLinkCheck = $this->isEnableLinkCheck($tb_id);
940                         $block = ( $enableLinkCheck ) ? true : false ;
941 //mod by cles end
942
943                         if (!$tb_id) {
944                                 return 'TrackBack ID is missing (tb_id)';
945                         }
946                         
947                         if ((!$manager->existsItem($tb_id,0,0)) && ($this->getOption('CheckIDs') == 'yes')) {
948                                 return _ERROR_NOSUCHITEM;
949                         }
950
951                         // 0. Check if we need to output the list as rss
952                         if ($rss) {
953                                 $this->rssResponse($tb_id);
954                                 return;
955                         }
956 //mod by cles
957                         // check: accept pings.
958                         $blogId = getBlogIDFromItemID($tb_id);
959                         $isAcceptPing = $this->isAcceptTrackBack($tb_id);
960                                 
961                         if (! $isAcceptPing)
962                                 return 'Sorry, no trackback pings are accepted.';
963 //mod by cles end
964
965                         // 1. Get attributes
966 //modify start+++++++++
967                         $b =& $manager->getBlog($blogId);
968 //modify end+++++++++
969                         $url            = requestVar('url');
970                         $title          = requestVar('title');
971                         $excerpt        = requestVar('excerpt');
972                         $blog_name      = requestVar('blog_name');
973                         
974                         if( $url && preg_match('/https?:\/\/([^\/]+)/', $url, $matches) ){
975                                 if( gethostbynamel($matches[1]) === FALSE )
976                                         return 'URL is invalid (url)';
977                         } else {
978                                 return 'URL is missing or invalid (url)';
979                         }
980
981                         // 2. Conversion of encoding...
982 //modify start+++++++++
983 /*                      if (preg_match ("/;\s*charset=([^\n]+)/is", $_SERVER["CONTENT_TYPE"], $regs))
984                                 $encoding = strtoupper(trim($regs[1]));
985                         else
986                                 $encoding = $this->_detect_encoding($excerpt);
987 */
988                         $encoding = $this->_detect_encoding($excerpt);
989 //modify end+++++++++
990                         
991 //modify start+++++++++
992                         if (_CHARSET != 'UTF-8'){
993                                 $title = $this->_strip_controlchar(strip_tags(mb_convert_encoding($title, _CHARSET, $encoding)));
994                                 $excerpt = $this->_strip_controlchar(strip_tags(mb_convert_encoding($excerpt, _CHARSET, $encoding)));
995                                 $blog_name = $this->_strip_controlchar(strip_tags(mb_convert_encoding($blog_name, _CHARSET, $encoding)));
996                         }else{
997                                 $title      = $this->_strip_controlchar($this->_convert_to_utf8($title, $encoding));
998                                 $excerpt    = $this->_strip_controlchar($this->_convert_to_utf8($excerpt, $encoding));
999                                 $blog_name  = $this->_strip_controlchar($this->_convert_to_utf8($blog_name, $encoding));
1000
1001                                 $title      = $this->_decode_entities(strip_tags($title));
1002                                 $excerpt    = $this->_decode_entities(strip_tags($excerpt));
1003                                 $blog_name  = $this->_decode_entities(strip_tags($blog_name));
1004                         }
1005 //modify end+++++++++
1006
1007                         // 4. Save data in the DB
1008                         $res = @mysql_query('
1009                                 SELECT 
1010                                         tb_id, block, spam
1011                                 FROM 
1012                                         '.sql_table('plugin_tb').' 
1013                                 WHERE 
1014                                         url   = \''.mysql_real_escape_string($url).'\' AND 
1015                                         tb_id = \''.intval($tb_id).'\'
1016                         ');
1017                         
1018                         if (mysql_num_rows($res) != 0) 
1019                         {
1020                                 // Existing TB, update it
1021 /*
1022                                 $res = @mysql_query('
1023                                         UPDATE
1024                                                 '.sql_table('plugin_tb').'
1025                                         SET 
1026                                                 title     = "'.mysql_real_escape_string($title).'", 
1027                                                 excerpt   = "'.mysql_real_escape_string($excerpt).'", 
1028                                                 blog_name = "'.mysql_real_escape_string($blog_name).'", 
1029                                                 timestamp = '.mysqldate(time()).'
1030                                         WHERE 
1031                                                 url       = "'.mysql_real_escape_string($url).'" AND 
1032                                                 tb_id     = "'.$tb_id.'"
1033                                 ');
1034 */
1035 //modify start+++++++++
1036                                 $rows = mysql_fetch_assoc($res);
1037                                 $spam = ( $rows['block'] || $rows['spam'] ) ? true : false;
1038                                 $res = @mysql_query('
1039                                         UPDATE
1040                                                 '.sql_table('plugin_tb').'
1041                                         SET 
1042                                                 title     = \''.mysql_real_escape_string($title).'\', 
1043                                                 excerpt   = \''.mysql_real_escape_string($excerpt).'\', 
1044                                                 blog_name = \''.mysql_real_escape_string($blog_name).'\', 
1045                                                 timestamp = '.mysqldate($b->getCorrectTime()).'
1046                                         WHERE 
1047                                                 url       = \''.mysql_real_escape_string($url).'\' AND 
1048                                                 tb_id     = \''.mysql_real_escape_string(intval($tb_id)).'\'
1049                                 ');
1050 //modify end+++++++++
1051
1052                                 if (!$res) {
1053                                         return 'Could not update trackback data: '.mysql_error();
1054                                 }
1055                         } 
1056                         else 
1057                         {
1058                                 // 4. SPAM check (for SpamCheck API 2 /w compat. API 1)
1059                                 $spamcheck = array (
1060                                         'type'          => 'trackback',
1061                                         'id'            => $tb_id,
1062                                         'title'         => $title,
1063                                         'excerpt'       => $excerpt,
1064                                         'blogname'      => $blog_name,
1065                                         'url'           => $url,
1066                                         'return'        => true,
1067                                         'live'          => true,
1068                                         
1069                                         /* Backwards compatibility with SpamCheck API 1*/
1070                                         'data'          => $url . "\n" . $title . "\n" . $excerpt . "\n" . $blog_name . "\n" . serverVar('HTTP_USER_AGENT'),
1071                                         'ipblock'   => true,
1072                                 );
1073                                 
1074                                 $manager->notify('SpamCheck', array ('spamcheck' => & $spamcheck));
1075                                 
1076                                 if (isset($spamcheck['result']) && $spamcheck['result'] == true) 
1077                                 {
1078                                         $spam = true;
1079                                 }
1080                                 
1081                                 // 5. Content check (TO DO)
1082                                 if($spam == false || $enableLinkCheck == 'ignore' )     //modify
1083                                 {
1084 //mod by cles
1085 //                                      $contents = $this->retrieveUrl ($url);
1086 //                              
1087 //                                      if (preg_match("/(".preg_quote($_SERVER["REQUEST_URI"], '/').")|(".preg_quote($_SERVER["SERVER_NAME"], '/').")/i", $contents)) {        
1088 //                                              $link = true;
1089 //                                      }
1090                                         if( $enableLinkCheck ){
1091                                                 $contents = $this->retrieveUrl($url);
1092                                                 
1093                                                 $linkArray = $this->getPermaLinksFromText($contents);
1094                                                 $itemLink = $this->_createItemLink($tb_id, $b);
1095                                                 $itemLinkPat = '{^' . preg_quote($itemLink) .'}i';
1096                                                 $itemLinkPat = str_replace('&','&(amp;)?', $itemLinkPat);
1097                                                 
1098                                                 foreach($linkArray as $l) {
1099                                                         if(preg_match($itemLinkPat, $l)){
1100                                                                 ACTIONLOG :: add(INFO, "Trackback: LinkCheck OK. (link: $l pat: $itemLinkPat )");
1101                                                                 $link = true;
1102                                                                 break;
1103                                                         }
1104                                                 }
1105                                                 if( ! $link ){
1106                                                         $cnt = @count($linkArray);
1107                                                         if( $enableLinkCheck == 'ignore' ){
1108                                                                 ACTIONLOG :: add(INFO, "Trackback: LinkCheck NG. [ignore] (itemid:$tb_id from: $url cnt: $cnt pat: $itemLinkPat)");
1109                                                                 return 'Sorry, trackback ping is not accepted.';
1110                                                         } else {
1111                                                                 ACTIONLOG :: add(INFO, "Trackback: LinkCheck NG. [block] (itemid:$tb_id from: $url cnt: $cnt pat: $itemLinkPat");
1112                                                         }
1113                                                 }
1114                                         }
1115 //mod by cles end
1116                                 }
1117
1118                                 // 6. Determine if Trackback is safe...
1119 //modify start+++++++++
1120 //                              $block = $spam == true || $link == false;
1121 //                              $block = $spam == true ;
1122 //modify end+++++++++
1123 //mod by cles
1124                                 if ( $enableLinkCheck )
1125                                         $block = ($spam == true || $link == false);
1126                                 else
1127                                         $block = $spam == true ;
1128 //mod by cles end
1129                                 // New TB, insert it
1130 /*
1131                                 $query = '
1132                                         INSERT INTO 
1133                                                 '.sql_table('plugin_tb').' 
1134                                         SET
1135                                                 tb_id     = "'.$tb_id.'",
1136                                                 block     = "'.($block ? '1' : '0').'",
1137                                                 spam      = "'.($spam ? '1' : '0').'",
1138                                                 link      = "'.($link ? '1' : '0').'",
1139                                                 url       = "'.mysql_real_escape_string($url).'",
1140                                                 title     = "'.mysql_real_escape_string($title).'",
1141                                                 excerpt   = "'.mysql_real_escape_string($excerpt).'",
1142                                                 blog_name = "'.mysql_real_escape_string($blog_name).'",
1143                                                 timestamp = '.mysqldate(time()).'
1144                                 ';
1145 */
1146 //modify start+++++++++
1147                                 $query = '
1148                                         INSERT INTO 
1149                                                 '.sql_table('plugin_tb').' 
1150                                         SET
1151                                                 tb_id     = \''.mysql_real_escape_string(intval($tb_id)).'\',
1152                                                 block     = \''.($block ? '1' : '0').'\',
1153                                                 spam      = \''.($spam ? '1' : '0').'\',
1154                                                 link      = \''.($link ? '1' : '0').'\',
1155                                                 url       = \''.mysql_real_escape_string($url).'\',
1156                                                 title     = \''.mysql_real_escape_string($title).'\',
1157                                                 excerpt   = \''.mysql_real_escape_string($excerpt).'\',
1158                                                 blog_name = \''.mysql_real_escape_string($blog_name).'\',
1159                                                 timestamp = '.mysqldate($b->getCorrectTime()).'
1160                                 ';
1161 //modify end+++++++++
1162                                 
1163                                 $res = @mysql_query($query);
1164
1165                                 if (!$res) {
1166                                         return 'Could not save trackback data, possibly because of a double entry: ' . mysql_error() . $query;
1167                                 }
1168                         }
1169         
1170                         // 7. Send notification e-mail if needed
1171                         $notifyAddrs = $this->getOption('NotifyEmail');
1172                         $notifyAddrs = ( $notifyAddrs ? $notifyAddrs . ';' : '') 
1173                                                         . $this->getBlogOption($blogId ,'NotifyEmailBlog');
1174                                                 
1175                         if ($notifyAddrs && $spam == false) 
1176                         {
1177                                 
1178                                 $vars = array (
1179                                         'tb_id'    => $tb_id,
1180                                         'url'      => $url,
1181                                         'title'    => $title,
1182                                         'excerpt'  => $excerpt,
1183                                         'blogname' => $blog_name
1184                                 );
1185                                 
1186 //modify start+++++++++
1187 /*
1188                                 $vars = array (
1189                                         'tb_id'    => $tb_id,
1190                                         'url'      => $url,
1191                                         'title'    => mb_convert_encoding($title, 'ISO-2022-JP', _CHARSET),
1192                                         'excerpt'  => mb_convert_encoding($excerpt, 'ISO-2022-JP', _CHARSET),
1193                                         'blogname' => mb_convert_encoding($blog_name, 'ISO-2022-JP', _CHARSET)
1194                                 );
1195 */                              
1196 //maybe not needed because japanese version has "mb_send_mail" in function notify
1197 //modify end+++++++++
1198                                 
1199                                 $mailto_title = TEMPLATE::fill($this->notificationMailTitle, $vars);
1200                                 $mailto_msg   = TEMPLATE::fill($this->notificationMail, $vars);
1201         
1202                                 global $CONF, $DIR_LIBS;
1203                                 
1204                                 // make sure notification class is loaded
1205                                 if (!class_exists('notification'))
1206                                         include($DIR_LIBS . 'NOTIFICATION.php');
1207                                 
1208                                 $notify = new NOTIFICATION($notifyAddrs);
1209                                 $notify->notify($mailto_title, $mailto_msg , $CONF['AdminEmail']);
1210                                 
1211 //mod by cles+++++++++++        
1212                                 if ($manager->pluginInstalled('NP_Cache')){
1213                                         $p =& $manager->getPlugin('NP_Cache');
1214                                         $p->setCurrentBlog($tb_id);
1215                                         $p->cleanItem($tb_id);
1216                                         $p->cleanArray(array('index'));
1217                                 }
1218 //mod by cles end +++++++++++   
1219                         }
1220
1221                         if( $block )
1222                                 return 'Sorry, trackback ping is not accepted.';
1223                         return '';
1224                 }       
1225
1226                 function xmlResponse($errorMessage = '') 
1227                 {
1228                         header('Content-Type: text/xml');
1229
1230                         echo "<","?xml version='1.0' encoding='UTF-8'?",">\n";
1231                         echo "<response>\n";
1232
1233                         if ($errorMessage) 
1234                                 echo "\t<error>1</error>\n\t<message>",htmlspecialchars($errorMessage, ENT_QUOTES),"</message>\n";
1235                         else
1236                                 echo "\t<error>0</error>\n";
1237
1238                         echo "</response>";
1239                         exit;
1240                 }
1241                 
1242                 /*
1243                  * Check if member may send ping (check if logged in)
1244                  */
1245                 function canSendPing() {
1246                         global $member;
1247                         return $member->isLoggedIn() || $this->xmlrpc;
1248                 }
1249
1250
1251 //mod by cles
1252                 function redirect($tb_id, $urlHash){
1253                         global $CONF;
1254                         $query = 'SELECT url FROM '.sql_table('plugin_tb').' WHERE tb_id='.intval($tb_id).' and md5(url)="'.$urlHash.'"';
1255                         $res = mysql_query($query);
1256                         
1257                         $url = $CONF['SiteURL'];
1258                         
1259                         if ($o = mysql_fetch_object($res)) {
1260                                 $url = htmlspecialchars($o->url, ENT_QUOTES);
1261                         }
1262                         
1263                         $url = stripslashes($url);
1264                         $url = str_replace('&amp;','&',$url);
1265                         $url = str_replace('&lt;','<',$url);
1266                         $url = str_replace('&gt;','>',$url);
1267                         $url = str_replace('&quot;','"',$url);
1268                         
1269                         header('Location: '.$url);
1270                 }
1271                                 
1272                 function getRequiredURL($itemid){
1273                         global $manager;
1274                         $blog = & $manager->getBlog(getBlogIDFromItemID($item['itemid']));
1275                         if( $this->isEnableLinkCheck($itemid) )
1276                                 return $this->_createItemLink($itemid, $blog);
1277                         return null;
1278                 }
1279                 
1280                 function isEnableLinkCheck($itemid){
1281                         $blogid = getBlogIDFromItemID($itemid);
1282                         
1283                         switch( $this->getItemOption($itemid, 'isAcceptW/OLink') ){
1284                                 case 'default':
1285                                         $def = $this->getBlogOption($blogid, 'isAcceptW/OLinkDef');
1286                                         if($def == 'yes')
1287                                                 return false;
1288                                         else
1289                                                 return $def; // block or ignore
1290                                 case 'yes':
1291                                         return false;
1292                                 case 'no':
1293                                         return true;
1294                                 default :
1295                                         ACTIONLOG :: add(INFO, "Trackback: Unknown Option (itemid:$itemid, value:$val)");
1296                                         return false;
1297                         }
1298                 }
1299                 
1300                 var $acceptTrackbacks = array();
1301                 function isAcceptTrackBack($itemid = null){
1302                         if( $itemid && isset($acceptTrackbacks[$itemid]) )
1303                                 return $acceptTrackbacks[$itemid] === true;
1304                         
1305                         $ret = false;
1306                         if( $this->getOption('AcceptPing') == 'yes' ){
1307                                 $bid = null;
1308                                 if($itemid){
1309                                         $bid = getBlogIDFromItemID(intval($itemid));
1310                                 } else {
1311                                         global $blog;
1312                                         $bid = $blog->getID();
1313                                 }
1314                                 
1315                                 if( $this->getBlogOption($bid, "AllowTrackBack") == 'yes' ){
1316                                         if( ! $itemid ){
1317                                                 $ret = ( $this->getItemOption(intval($itemid), 'ItemAcceptPing') == 'yes' ) ? true : false ;
1318                                         } else {
1319                                                 $ret = true;
1320                                         }
1321                                 } else {
1322                                         $ret = false;
1323                                 }
1324                         }
1325                         if($itemid)
1326                                 $acceptTrackbacks[$itemid] = $ret;
1327                         return $ret === true;
1328                 }
1329                 
1330 //mod by cles end
1331
1332         /**************************************************************************************
1333          * EVENTS
1334                  */
1335
1336                 function event_SendTrackback($data) {
1337                         global $manager;
1338                         
1339                         // Enable sending trackbacks for the XML-RPC API, otherwise we would 
1340                         // get an error because the current user is not exactly logged in.
1341                         $this->xmlrpc = true;
1342                         
1343                         $itemid = $data['tb_id'];
1344                         $item = &$manager->getItem($itemid, 0, 0);
1345                         if (!$item) return; // don't ping for draft & future
1346                         if ($item['draft']) return;   // don't ping on draft items
1347                         
1348                         // gather some more information, needed to send the ping (blog name, etc)      
1349                         $blog =& $manager->getBlog(getBlogIDFromItemID($itemid));
1350                         $blog_name      = $blog->getName();
1351                         
1352                         $title      = $data['title'] != '' ? $data['title'] : $item['title'];
1353                         $title          = strip_tags($title);
1354                         
1355                         $excerpt    = $data['body'] != '' ? $data['body'] : $item['body'];
1356                         $excerpt        = strip_tags($excerpt);
1357                         $excerpt    = $this->_cut_string($excerpt, 200);
1358                         
1359                         $CONF['ItemURL'] = preg_replace('/\/$/', '', $blog->getURL());
1360                         //$url = createItemLink($itemid);
1361                         $url = $this->_createItemLink($itemid, $blog);
1362                         
1363                         while (list(,$url) = each($data['urls'])) {
1364                                 $res = $this->sendPing($itemid, $title, $url, $excerpt, $blog_name, $url);
1365                                 if ($res) ACTIONLOG::add(WARNING, 'TrackBack Error:' . $res . ' (' . $url . ')');
1366                         }
1367                 }
1368                 
1369                 function event_RetrieveTrackback($data) {
1370                         
1371                         $res = mysql_query('
1372                         SELECT 
1373                         url, 
1374                         title, 
1375                         UNIX_TIMESTAMP(timestamp) AS timestamp 
1376                         FROM 
1377                         '.sql_table('plugin_tb').' 
1378                         WHERE 
1379                         tb_id = '.intval($data['tb_id']).' AND
1380                         block = 0
1381                         ORDER BY 
1382                         timestamp ASC
1383                         ');
1384                         
1385                         while ($row = mysql_fetch_array($res)) {
1386                                 
1387                                 $trackback = array(
1388                                 'title' => $row['title'],
1389                                 'url'   => $row['url'],
1390                                 'ip'    => ''
1391                                 );
1392                                 
1393                                 $data['trackbacks'][] = $trackback;
1394                         }
1395                 }
1396 /*
1397                 function event_BookmarkletExtraHead($data) {
1398                         global $NP_TB_URL;
1399                         list ($NP_TB_URL,) = $this->getURIfromLink(requestVar('loglink'));
1400                 } 
1401 */
1402                 function event_PrepareItemForEdit($data) {
1403 //                      if (!$this->getOption('AutoXMLHttp'))
1404                         if ($this->getOption('AutoXMLHttp') == 'no')
1405                         {
1406                                 // The space between body and more is to make sure we didn't join 2 words accidently....
1407                                 $this->larray = $this->autoDiscovery($data['item']['body'].' '.$data['item']['more']);
1408                         }
1409                 } 
1410
1411                 /*
1412                  * After an item has been added to the database, send out a ping if requested
1413                  * (trackback_ping_url variable in request)
1414                  */
1415                 function event_PostAddItem($data) {
1416                         $this->pingTrackback($data);
1417                 }
1418         
1419                 function event_PreUpdateItem($data) {
1420                         $this->pingTrackback($data);
1421                 }
1422
1423                 /**
1424                  * Add trackback options to add item form/bookmarklet
1425                  */
1426                 function event_AddItemFormExtras($data) {
1427                 
1428 //                      global $NP_TB_URL;
1429                         
1430                         ?>
1431                                 <h3>TrackBack</h3>
1432                                 <p>
1433 <!--modify start+++++++++-->
1434 <!--                                    <label for="plug_tb_url">TrackBack Ping URL:</label>
1435                                         <input type="text" value="<?php if (isSet($NP_TB_URL)) {echo $NP_TB_URL;} ?>" id="plug_tb_url" name="trackback_ping_url" size="60" />
1436 -->
1437 <!--modify end+++++++++-->
1438                                         <label for="plug_tb_url">TrackBack URL:</label><br />
1439                                         <textarea id="plug_tb_url" name="trackback_ping_url" cols="60" rows="5" style="font:normal xx-small Tahoma, Arial, verdana ;"></textarea>
1440 <input type="button" name="btnAdd" value="<?php echo _TB_LIST_IT?>" onClick="AddStart()" />
1441
1442                 <br />
1443         
1444                         <?php
1445 //                              if ($this->getOption('AutoXMLHttp'))
1446                                 if ($this->getOption('AutoXMLHttp') == 'yes')
1447                                 {
1448                         ?>
1449                                         <div id="tb_auto">
1450 <input type="button" name="discoverit" value="Auto Discover" onclick="tbSetup();" />
1451                                                 <img id='tb_busy' src='<?php echo $this->getAdminURL(); ?>busy.gif' style="display:none;" /><br />
1452                                         <div id="tb_auto_title"></div>
1453                                                 <table border="1"><tbody id="tb_ping_list"></tbody></table>
1454                                                 <input type="hidden" id="tb_url_amount" name="tb_url_amount" value="0" /> 
1455                                         </div>
1456                                         
1457                         <?php
1458                                         $this->jsautodiscovery();
1459                                 }
1460                         ?>
1461                                 </p>
1462                         <?php
1463                 }
1464
1465                 /**
1466                  * Add trackback options to edit item form/bookmarklet
1467                  */
1468                 function event_EditItemFormExtras($data) {
1469                         global $CONF;
1470                         ?>
1471 <!--                                    <input type="text" value="" id="plug_tb_url" name="trackback_ping_url" size="60" /><br />-->
1472                                 <h3>TrackBack</h3>
1473                                 <p>
1474                                         <label for="plug_tb_url">TrackBack URL:</label><br />
1475                                         <textarea id="plug_tb_url" name="trackback_ping_url" cols="60" rows="5" style="font:normal xx-small Tahoma, Arial, verdana ;"></textarea>
1476 <input type="button" name="btnAdd" value="<?php echo _TB_LIST_IT?>" onClick="AddStart()" />
1477         
1478                         <?php
1479 //                              if ($this->getOption('AutoXMLHttp'))
1480                                 if ($this->getOption('AutoXMLHttp') == 'yes')
1481                                 {
1482                         ?>
1483
1484
1485                                         <div id="tb_auto">
1486 <input type="button" name="discoverit" value="Auto Discover" onclick="tbSetup();" />
1487                                                 <img id='tb_busy' src='<?php echo $this->getAdminURL(); ?>busy.gif' style="display:none;" /><br />
1488                                         <div id="tb_auto_title"></div>
1489                                                 <table border="1"><tbody id="tb_ping_list"></tbody></table>
1490                                                 <input type="hidden" id="tb_url_amount" name="tb_url_amount" value="0" /> 
1491                                         </div>
1492
1493                         <?php
1494                                         $this->jsautodiscovery();
1495                                 }
1496                                 else
1497                                 {
1498                                         if (count($this->larray) > 0) 
1499                                         {
1500                         ?>
1501                                         Auto Discovered Ping URL's:<br />
1502                         <?php
1503                                                 echo '<input type="hidden" name="tb_url_amount" value="'.count($this->larray).'" />';
1504         
1505                                                 $i = 0;
1506                                                 
1507                                                 while (list($url, $title) = each ($this->larray))
1508                                                 {
1509 //modify start+++++++++
1510                                                         if (_CHARSET != 'UTF-8') {
1511                                                                 $title = $this->_utf8_to_entities($title);
1512                                                                 $title = mb_convert_encoding($title, _CHARSET, 'UTF-8');
1513                                                         }
1514 //modify end+++++++++
1515
1516                                                         echo '<input type="checkbox" name="tb_url_'.$i.
1517                                                                  '" value="'.$url.'" id="tb_url_'.$i.
1518                                                                  '" /><label for="tb_url_'.$i.'" title="'.$url.'">'.$title.'</label><br />';
1519                                                         
1520                                                         $i++;
1521                                                 }
1522                                         }
1523                                 }               
1524                         ?>
1525                                 </p>
1526                         <?php
1527                 }
1528
1529                 /**
1530                  * Insert Javascript AutoDiscovery routines
1531                  */
1532                 function jsautodiscovery() 
1533                 {
1534                         global $CONF;
1535                 
1536                         ?>
1537                                 <script type='text/javascript' src='<?php echo $this->getAdminURL(); ?>autodetect.php'></script>        
1538                         <?php
1539                 }
1540
1541                 /**
1542                  * Ping all URLs
1543                  */
1544                 function pingTrackback($data) {
1545                         global $manager, $CONF;
1546                         
1547                         $ping_urls_count = 0;
1548                         $ping_urls = array();
1549                         $utf8flag = array();
1550                         $localflag = array();
1551                         
1552                         $ping_url = requestVar('trackback_ping_url');
1553 //modify start+++++++++
1554 /*
1555                         if ($ping_url) {
1556                                 $ping_urls[0] = $ping_url;
1557                                 $ping_urls_count++;
1558                         }
1559 */
1560                         if (trim($ping_url)) {
1561                                 $ping_urlsTemp = array();
1562                                 $ping_urlsTemp = preg_split("/[\s,]+/", trim($ping_url));
1563                                 for($i=0;$i<count($ping_urlsTemp);$i++){
1564                                         $ping_urls[] = trim($ping_urlsTemp[$i]);
1565                                         $ping_urls_count++;
1566                                 }
1567                         }
1568 //modify end+++++++++
1569         
1570                         $tb_url_amount = requestVar('tb_url_amount');
1571                         for ($i=0;$i<$tb_url_amount;$i++) {
1572                                 $tb_temp_url = requestVar('tb_url_'.$i);
1573                                 if ($tb_temp_url) {
1574                                         $ping_urls[$ping_urls_count] = $tb_temp_url;
1575                                         $utf8flag[$ping_urls_count] = (requestVar('tb_url_'.$i.'_utf8') == 'on')? 1: 0;
1576                                         $localflag[$ping_urls_count] = (requestVar('tb_url_'.$i.'_local') == 'on')? 1: 0;
1577                                         $ping_urls_count++;
1578                                 }
1579                         }
1580         
1581                         if ($ping_urls_count <= 0) {
1582                                 return;
1583                         }
1584         
1585                         $itemid = $data['itemid'];
1586                         $item = &$manager->getItem($itemid, 0, 0);
1587                         if (!$item) return; // don't ping for draft & future
1588                         if ($item['draft']) return;   // don't ping on draft items
1589         
1590                         // gather some more information, needed to send the ping (blog name, etc)      
1591                         $blog =& $manager->getBlog(getBlogIDFromItemID($itemid));
1592                         $blog_name      = $blog->getName();
1593
1594                         $title      = $data['title'] != '' ? $data['title'] : $item['title'];
1595                         $title          = strip_tags($title);
1596
1597                         $excerpt    = $data['body'] != '' ? $data['body'] : $item['body'];
1598                         $excerpt        = strip_tags($excerpt);
1599                         $excerpt    = $this->_cut_string($excerpt, 200);
1600         
1601 /*
1602                         $CONF['ItemURL'] = preg_replace('/\/$/', '', $blog->getURL());   
1603                         $url = createItemLink($itemid);
1604 */
1605                         $url    = $this->_createItemLink($item['itemid'],$blog);        
1606         
1607                         // send the ping(s) (add errors to actionlog)
1608                         for ($i=0; $i<count($ping_urls); $i++) {
1609                                 if( ! $localflag[$i] )
1610                                         $res = $this->sendPing($itemid, $title, $url, $excerpt, $blog_name, $ping_urls[$i], $utf8flag[$i]);
1611                                 else
1612                                         $res = $this->handleLocalPing($itemid, $title, $excerpt, $blog_name, $ping_urls[$i]);
1613                                 if ($res) ACTIONLOG::add(WARNING, 'TrackBack Error:' . $res . ' (' . $ping_urls[$i] . ')');
1614                         }
1615                 }
1616
1617         
1618         
1619         
1620         /**************************************************************************************
1621          * AUTO-DISCOVERY
1622                  */
1623
1624                 /*
1625                  * Auto-Discovery of TrackBack Ping URLs based on HTML story
1626                  */
1627                 function autoDiscovery($text) 
1628                 {
1629                         $links  = $this->getPermaLinksFromText($text);
1630                         $result = array();
1631         
1632                         for ($i = 0; $i < count($links); $i++)
1633                         {
1634                                 list ($url, $title) = $this->getURIfromLink($links[$i]);
1635                                 
1636                                 if ($url != '')
1637                                         $result[$url] = $title;
1638                         }
1639                         
1640                         return $result;
1641                 }
1642                 
1643                 /*
1644                  * Auto-Discovery of TrackBack Ping URLs based on single link
1645                  */
1646                 function getURIfromLink($link) 
1647                 {
1648                         
1649                         // Check to see if the cache contains this link
1650                         $res = mysql_query('SELECT url, title FROM '.sql_table('plugin_tb_lookup').' WHERE link=\''.mysql_real_escape_string($link).'\'');
1651
1652                         if ($row = mysql_fetch_array($res)) 
1653                         {
1654                                 if ($row['title'] != '')
1655                                 {
1656 //modify start+++++++++
1657                                         if (_CHARSET != 'UTF-8'){
1658                                                 $row['title'] = mb_convert_encoding($row['title'], 'UTF-8', _CHARSET);
1659                                                 $row['title'] = $this->_decode_entities($row['title']);
1660                                         }
1661 //modify end+++++++++
1662                                         return array (
1663                                                 $row['url'], $row['title']
1664                                         );
1665                                 }
1666                                 else
1667                                 {
1668                                         return array (
1669                                                 $row['url'], $row['url']
1670                                         );
1671                                 }
1672                         }
1673                         
1674                         // Retrieve RDF
1675                         if (($rdf = $this->getRDFFromLink($link)) !== false) 
1676                         {
1677                                 // Get PING attribute
1678                                 if (($uri = $this->getAttributeFromRDF($rdf, 'trackback:ping')) !== false) 
1679                                 {
1680                                         // Get TITLE attribute
1681                                         if (($title = $this->getAttributeFromRDF($rdf, 'dc:title')) !== false) 
1682                                         {
1683                                                 // Get CREATOR attribute
1684                                                 if (($author = $this->getAttributeFromRDF($rdf, 'dc:creator')) !== false) 
1685                                                 {
1686                                                         $title = $author. ": " . $title;
1687                                                 }
1688         
1689                                                 $uri   = $this->_decode_entities($uri);
1690 //modify start+++++++++
1691                                                 if (_CHARSET != 'UTF-8')
1692                                                         $convertedTitle = mb_convert_encoding($title, _CHARSET, 'UTF-8');
1693                                                 else
1694                                                         $convertedTitle = $title;
1695 /*
1696                                                 // Store in cache
1697                                                 $res = mysql_query("INSERT INTO ".sql_table('plugin_tb_lookup')." (link, url, title) VALUES ('".mysql_real_escape_string($link)."','".mysql_real_escape_string($uri)."','".mysql_real_escape_string($title)."')");
1698 */
1699                                                 // Store in cache
1700                                                 $res = mysql_query("INSERT INTO ".sql_table('plugin_tb_lookup')." (link, url, title) VALUES ('".mysql_real_escape_string($link)."','".mysql_real_escape_string($uri)."','".mysql_real_escape_string($convertedTitle)."')");
1701 //modify end+++++++++
1702                                                 $title = $this->_decode_entities($title);
1703
1704                                                 return array (
1705                                                         $uri, $title
1706                                                 );
1707                                         }
1708                                         else
1709                                         {
1710                                                 $uri = html_entity_decode($uri, ENT_COMPAT);
1711         
1712                                                 // Store in cache
1713                                                 $res = mysql_query("INSERT INTO ".sql_table('plugin_tb_lookup')." (link, url, title) VALUES ('".mysql_real_escape_string($link)."','".mysql_real_escape_string($uri)."','')");
1714         
1715                                                 return array (
1716                                                         $uri, $uri
1717                                                 );
1718                                         }
1719                                 }
1720                         }
1721                         
1722                         // Store in cache
1723                         $res = mysql_query("INSERT INTO ".sql_table('plugin_tb_lookup')." (link, url, title) VALUES ('".mysql_real_escape_string($link)."','','')");
1724         
1725                         return array ('', '');
1726                 }
1727         
1728                 /*
1729                  * Detect links used in HTML code
1730                  */
1731                 function getPermaLinksFromText($text)
1732                 {
1733                         $links = array();
1734                         
1735                         if (preg_match_all('/<[aA] +([^>]+)>/', $text, $array, PREG_SET_ORDER))
1736                         {
1737                                 for ($i = 0; $i < count($array); $i++)
1738                                 {
1739                                         //if( preg_match('/s?https?:\/\/[-_.!~*\'()a-zA-Z0-9;\/?:@&=+$,%#]+/', $array[$i][1], $matches) )
1740                                         if( preg_match('/s?https?:\/\/[-_.!~*\'()a-zA-Z0-9;\/:@&=+$,%]+/', $array[$i][1], $matches) )
1741                                                 $links[$matches[0]] = 1;
1742                                 }
1743                         }
1744                         
1745                         return array_keys($links);
1746                 }
1747         
1748                 /*
1749                  * Retrieve RDF code from external link
1750                  */
1751                 function getRDFFromLink($link) 
1752                 {
1753                         if ($content = $this->getContents($link))
1754                         {
1755                                 preg_match_all('/(<rdf:RDF.*?<\/rdf:RDF>)/sm', $content, $rdfs, PREG_SET_ORDER);
1756                                 
1757                                 if (count($rdfs) > 1)
1758                                 {
1759                                         for ($i = 0; $i < count($rdfs); $i++)
1760                                         {
1761                                                 if (preg_match('|dc:identifier="'.preg_quote($link).'"|ms',$rdfs[$i][1])) 
1762                                                 {
1763                                                         return $rdfs[$i][1];
1764                                                 }
1765                                         }
1766                                 }
1767                                 else
1768                                 {
1769                                         // No need to check the identifier
1770                                         return $rdfs[0][1];
1771                                 }
1772                         }
1773                         
1774                         return false;
1775                 }
1776         
1777                 /**
1778                  * Retrieve the contents of an external (X)HTML document
1779                  */
1780                 function getContents($link) {
1781                 
1782                         // Use cURL extention if available
1783                         if (function_exists("curl_init") && $this->useCurl == 2)
1784                         {
1785                                 // Make HEAD request
1786                                 $ch = curl_init();
1787                                 @curl_setopt($ch, CURLOPT_URL, $link);
1788                                 @curl_setopt($ch, CURLOPT_HEADER, true);
1789                                 @curl_setopt($ch, CURLOPT_NOBODY, true);
1790                                 @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1791                                 @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
1792                                 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1793                                 @curl_setopt($ch, CURLOPT_TIMEOUT, 20);
1794                                 @curl_setopt($ch, CURLOPT_USERAGENT, 'NP_TrackBack/'. $this->getVersion());
1795
1796                                 $headers = curl_exec($ch);
1797                                 curl_close($ch);
1798                                 
1799                                 // Check if the link points to a (X)HTML document
1800                                 if (preg_match('/Content-Type: (text\/html|application\/xhtml+xml)/i', $headers))
1801                                 {
1802                                         return $this->retrieveUrl ($link);
1803                                 }
1804                                 
1805                                 return false;
1806                         }
1807                         else
1808                         {
1809                                 return $this->retrieveUrl ($link);
1810                         }
1811                 }
1812         
1813                 /*
1814                  * Get a single attribute from RDF
1815                  */
1816                 function getAttributeFromRDF($rdf, $attribute)
1817                 {
1818                         if (preg_match('/'.$attribute.'="([^"]+)"/', $rdf, $matches)) 
1819                         {
1820                                 return $matches[1];
1821                         }
1822                         
1823                         return false;
1824                 }
1825
1826
1827
1828
1829
1830
1831                 /**************************************************************************************/
1832                 /* Internal helper functions for dealing with external file retrieval                 */
1833         
1834                 function retrieveUrl ($url) {
1835 //mod by cles
1836                         $ua = ini_set('user_agent', 'NP_TrackBack/'. $this->getVersion());
1837 //mod by cles end
1838                         if (function_exists('curl_init') && $this->useCurl > 0)
1839                         {
1840                                 // Set options
1841                                 $ch = curl_init();
1842                                 @curl_setopt($ch, CURLOPT_URL, $url);
1843                                 @curl_setopt($ch, CURLOPT_HEADER, 1);
1844                                 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1845                                 @curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
1846                                 @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
1847                                 @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
1848                                 @curl_setopt($ch, CURLOPT_TIMEOUT, 20);
1849                                 @curl_setopt($ch, CURLOPT_USERAGENT, 'NP_TrackBack/'. $this->getVersion());
1850                 
1851                                 // Retrieve response
1852                                 $raw  = curl_exec($ch);
1853                                 $info = curl_getinfo($ch);
1854                         
1855                                 // Split into headers and contents
1856                                 $headers  = substr($raw, 0, $info['header_size']);
1857                                 $contents = substr($raw, $info['header_size']);
1858
1859                                 curl_close($ch);
1860                         }
1861                         elseif ($fp = @fopen ($url, "r"))
1862                         {
1863 //mod by cles
1864 //                              $contents = fread($fp, 8192);
1865                                 $contents = '';
1866                                 while (!feof($fp)) {
1867                                         $contents .= fread($fp, 8192);
1868                                 }
1869 //mod by cles end
1870                                 $headers  = '';
1871                                 
1872                                 fclose($fp);
1873                         }               
1874 //mod by cles
1875                         ini_set('user_agent', $ua);
1876 //mod by cles end
1877                         
1878                         // Next normalize the encoding to UTF8...
1879                         $contents = $this->_convert_to_utf8_auto($contents, $headers);
1880         
1881                         return $contents;
1882                 }
1883                 
1884
1885                 /**************************************************************************************/
1886                 /* Internal helper functions for dealing with encodings and entities                  */
1887         
1888                 var $entities_cp1251 = array (
1889                         '&#128;'                => '&#8364;',
1890                         '&#130;'                => '&#8218;',
1891                         '&#131;'                => '&#402;',    
1892                         '&#132;'                => '&#8222;',   
1893                         '&#133;'                => '&#8230;',   
1894                         '&#134;'                => '&#8224;',   
1895                         '&#135;'                => '&#8225;',   
1896                         '&#136;'                => '&#710;',    
1897                         '&#137;'                => '&#8240;',   
1898                         '&#138;'                => '&#352;',    
1899                         '&#139;'                => '&#8249;',   
1900                         '&#140;'                => '&#338;',    
1901                         '&#142;'                => '&#381;',    
1902                         '&#145;'                => '&#8216;',   
1903                         '&#146;'                => '&#8217;',   
1904                         '&#147;'                => '&#8220;',   
1905                         '&#148;'                => '&#8221;',   
1906                         '&#149;'                => '&#8226;',   
1907                         '&#150;'                => '&#8211;',   
1908                         '&#151;'                => '&#8212;',   
1909                         '&#152;'                => '&#732;',    
1910                         '&#153;'                => '&#8482;',   
1911                         '&#154;'                => '&#353;',    
1912                         '&#155;'                => '&#8250;',   
1913                         '&#156;'                => '&#339;',    
1914                         '&#158;'                => '&#382;',    
1915                         '&#159;'                => '&#376;',    
1916                 );
1917         
1918                 var $entities_default = array (
1919                         '&quot;'                => '&#34;',             
1920                         '&amp;'                 => '&#38;',             
1921                         '&apos;'                => '&#39;',             
1922                         '&lt;'                  => '&#60;',             
1923                         '&gt;'                  => '&#62;',             
1924                 );
1925         
1926                 var $entities_latin = array (
1927                         '&nbsp;'                => '&#160;',    
1928                         '&iexcl;'               => '&#161;',    
1929                         '&cent;'                => '&#162;',    
1930                         '&pound;'               => '&#163;',    
1931                         '&curren;'              => '&#164;',    
1932                         '&yen;'                 => '&#165;',    
1933                         '&brvbar;'              => '&#166;',    
1934                         '&sect;'                => '&#167;',    
1935                         '&uml;'                 => '&#168;',    
1936                         '&copy;'                => '&#169;',    
1937                         '&ordf;'                => '&#170;',    
1938                         '&laquo;'               => '&#171;',    
1939                         '&not;'                 => '&#172;',    
1940                         '&shy;'                 => '&#173;',    
1941                         '&reg;'                 => '&#174;',    
1942                         '&macr;'                => '&#175;',    
1943                         '&deg;'                 => '&#176;',    
1944                         '&plusmn;'              => '&#177;',    
1945                         '&sup2;'                => '&#178;',    
1946                         '&sup3;'                => '&#179;',    
1947                         '&acute;'               => '&#180;',    
1948                         '&micro;'               => '&#181;',    
1949                         '&para;'                => '&#182;',    
1950                         '&middot;'              => '&#183;',    
1951                         '&cedil;'               => '&#184;',    
1952                         '&sup1;'                => '&#185;',    
1953                         '&ordm;'                => '&#186;',    
1954                         '&raquo;'               => '&#187;',    
1955                         '&frac14;'              => '&#188;',    
1956                         '&frac12;'              => '&#189;',    
1957                         '&frac34;'              => '&#190;',    
1958                         '&iquest;'              => '&#191;',    
1959                         '&Agrave;'              => '&#192;',    
1960                         '&Aacute;'              => '&#193;',    
1961                         '&Acirc;'               => '&#194;',    
1962                         '&Atilde;'              => '&#195;',    
1963                         '&Auml;'                => '&#196;',    
1964                         '&Aring;'               => '&#197;',    
1965                         '&AElig;'               => '&#198;',    
1966                         '&Ccedil;'              => '&#199;',    
1967                         '&Egrave;'              => '&#200;',    
1968                         '&Eacute;'              => '&#201;',    
1969                         '&Ecirc;'               => '&#202;',    
1970                         '&Euml;'                => '&#203;',    
1971                         '&Igrave;'              => '&#204;',    
1972                         '&Iacute;'              => '&#205;',    
1973                         '&Icirc;'               => '&#206;',    
1974                         '&Iuml;'                => '&#207;',    
1975                         '&ETH;'                 => '&#208;',    
1976                         '&Ntilde;'              => '&#209;',    
1977                         '&Ograve;'              => '&#210;',    
1978                         '&Oacute;'              => '&#211;',    
1979                         '&Ocirc;'               => '&#212;',    
1980                         '&Otilde;'              => '&#213;',    
1981                         '&Ouml;'                => '&#214;',    
1982                         '&times;'               => '&#215;',    
1983                         '&Oslash;'              => '&#216;',    
1984                         '&Ugrave;'              => '&#217;',    
1985                         '&Uacute;'              => '&#218;',    
1986                         '&Ucirc;'               => '&#219;',    
1987                         '&Uuml;'                => '&#220;',    
1988                         '&Yacute;'              => '&#221;',    
1989                         '&THORN;'               => '&#222;',    
1990                         '&szlig;'               => '&#223;',    
1991                         '&agrave;'              => '&#224;',    
1992                         '&aacute;'              => '&#225;',    
1993                         '&acirc;'               => '&#226;',    
1994                         '&atilde;'              => '&#227;',    
1995                         '&auml;'                => '&#228;',    
1996                         '&aring;'               => '&#229;',    
1997                         '&aelig;'               => '&#230;',    
1998                         '&ccedil;'              => '&#231;',    
1999                         '&egrave;'              => '&#232;',    
2000                         '&eacute;'              => '&#233;',    
2001                         '&ecirc;'               => '&#234;',    
2002                         '&euml;'                => '&#235;',    
2003                         '&igrave;'              => '&#236;',    
2004                         '&iacute;'              => '&#237;',    
2005                         '&icirc;'               => '&#238;',    
2006                         '&iuml;'                => '&#239;',    
2007                         '&eth;'                 => '&#240;',    
2008                         '&ntilde;'              => '&#241;',    
2009                         '&ograve;'              => '&#242;',    
2010                         '&oacute;'              => '&#243;',    
2011                         '&ocirc;'               => '&#244;',    
2012                         '&otilde;'              => '&#245;',    
2013                         '&ouml;'                => '&#246;',    
2014                         '&divide;'              => '&#247;',    
2015                         '&oslash;'              => '&#248;',    
2016                         '&ugrave;'              => '&#249;',    
2017                         '&uacute;'              => '&#250;',    
2018                         '&ucirc;'               => '&#251;',    
2019                         '&uuml;'                => '&#252;',    
2020                         '&yacute;'              => '&#253;',    
2021                         '&thorn;'               => '&#254;',    
2022                         '&yuml;'                => '&#255;',    
2023                 );      
2024         
2025                 var $entities_extended = array (
2026                         '&OElig;'               => '&#338;',    
2027                         '&oelig;'               => '&#229;',    
2028                         '&Scaron;'              => '&#352;',    
2029                         '&scaron;'              => '&#353;',    
2030                         '&Yuml;'                => '&#376;',    
2031                         '&circ;'                => '&#710;',    
2032                         '&tilde;'               => '&#732;',    
2033                         '&esnp;'                => '&#8194;',   
2034                         '&emsp;'                => '&#8195;',   
2035                         '&thinsp;'              => '&#8201;',   
2036                         '&zwnj;'                => '&#8204;',   
2037                         '&zwj;'                 => '&#8205;',   
2038                         '&lrm;'                 => '&#8206;',   
2039                         '&rlm;'                 => '&#8207;',   
2040                         '&ndash;'               => '&#8211;',   
2041                         '&mdash;'               => '&#8212;',   
2042                         '&lsquo;'               => '&#8216;',   
2043                         '&rsquo;'               => '&#8217;',   
2044                         '&sbquo;'               => '&#8218;',   
2045                         '&ldquo;'               => '&#8220;',   
2046                         '&rdquo;'               => '&#8221;',   
2047                         '&bdquo;'               => '&#8222;',   
2048                         '&dagger;'              => '&#8224;',   
2049                         '&Dagger;'              => '&#8225;',   
2050                         '&permil;'              => '&#8240;',   
2051                         '&lsaquo;'              => '&#8249;',
2052                         '&rsaquo;'              => '&#8250;',
2053                         '&euro;'                => '&#8364;',
2054                         '&fnof;'                => '&#402;',    
2055                         '&Alpha;'               => '&#913;',    
2056                         '&Beta;'                => '&#914;',    
2057                         '&Gamma;'               => '&#915;',    
2058                         '&Delta;'               => '&#916;',    
2059                         '&Epsilon;'             => '&#917;',    
2060                         '&Zeta;'                => '&#918;',    
2061                         '&Eta;'                 => '&#919;',    
2062                         '&Theta;'               => '&#920;',    
2063                         '&Iota;'                => '&#921;',    
2064                         '&Kappa;'               => '&#922;',    
2065                         '&Lambda;'              => '&#923;',    
2066                         '&Mu;'                  => '&#924;',    
2067                         '&Nu;'                  => '&#925;',    
2068                         '&Xi;'                  => '&#926;',    
2069                         '&Omicron;'             => '&#927;',    
2070                         '&Pi;'                  => '&#928;',    
2071                         '&Rho;'                 => '&#929;',    
2072                         '&Sigma;'               => '&#931;',    
2073                         '&Tau;'                 => '&#932;',    
2074                         '&Upsilon;'             => '&#933;',    
2075                         '&Phi;'                 => '&#934;',    
2076                         '&Chi;'                 => '&#935;',    
2077                         '&Psi;'                 => '&#936;',    
2078                         '&Omega;'               => '&#937;',    
2079                         '&alpha;'               => '&#945;',    
2080                         '&beta;'                => '&#946;',    
2081                         '&gamma;'               => '&#947;',    
2082                         '&delta;'               => '&#948;',    
2083                         '&epsilon;'             => '&#949;',    
2084                         '&zeta;'                => '&#950;',    
2085                         '&eta;'                 => '&#951;',    
2086                         '&theta;'               => '&#952;',    
2087                         '&iota;'                => '&#953;',    
2088                         '&kappa;'               => '&#954;',    
2089                         '&lambda;'              => '&#955;',    
2090                         '&mu;'                  => '&#956;',    
2091                         '&nu;'                  => '&#957;',    
2092                         '&xi;'                  => '&#958;',    
2093                         '&omicron;'             => '&#959;',    
2094                         '&pi;'                  => '&#960;',    
2095                         '&rho;'                 => '&#961;',    
2096                         '&sigmaf;'              => '&#962;',    
2097                         '&sigma;'               => '&#963;',    
2098                         '&tau;'                 => '&#964;',    
2099                         '&upsilon;'             => '&#965;',    
2100                         '&phi;'                 => '&#966;',    
2101                         '&chi;'                 => '&#967;',    
2102                         '&psi;'                 => '&#968;',    
2103                         '&omega;'               => '&#969;',    
2104                         '&thetasym;'    => '&#977;',    
2105                         '&upsih;'               => '&#978;',    
2106                         '&piv;'                 => '&#982;',    
2107                         '&bull;'                => '&#8226;',   
2108                         '&hellip;'              => '&#8230;',   
2109                         '&prime;'               => '&#8242;',   
2110                         '&Prime;'               => '&#8243;',   
2111                         '&oline;'               => '&#8254;',   
2112                         '&frasl;'               => '&#8260;',   
2113                         '&weierp;'              => '&#8472;',   
2114                         '&image;'               => '&#8465;',   
2115                         '&real;'                => '&#8476;',   
2116                         '&trade;'               => '&#8482;',   
2117                         '&alefsym;'     => '&#8501;',   
2118                         '&larr;'                => '&#8592;',   
2119                         '&uarr;'                => '&#8593;',   
2120                         '&rarr;'                => '&#8594;',   
2121                         '&darr;'                => '&#8595;',   
2122                         '&harr;'                => '&#8596;',   
2123                         '&crarr;'               => '&#8629;',   
2124                         '&lArr;'                => '&#8656;',   
2125                         '&uArr;'                => '&#8657;',   
2126                         '&rArr;'                => '&#8658;',   
2127                         '&dArr;'                => '&#8659;',   
2128                         '&hArr;'                => '&#8660;',   
2129                         '&forall;'              => '&#8704;',   
2130                         '&part;'                => '&#8706;',   
2131                         '&exist;'               => '&#8707;',   
2132                         '&empty;'               => '&#8709;',   
2133                         '&nabla;'               => '&#8711;',   
2134                         '&isin;'                => '&#8712;',   
2135                         '&notin;'               => '&#8713;',   
2136                         '&ni;'                  => '&#8715;',   
2137                         '&prod;'                => '&#8719;',   
2138                         '&sum;'                 => '&#8721;',   
2139                         '&minus;'               => '&#8722;',   
2140                         '&lowast;'              => '&#8727;',   
2141                         '&radic;'               => '&#8730;',   
2142                         '&prop;'                => '&#8733;',   
2143                         '&infin;'               => '&#8734;',   
2144                         '&ang;'                 => '&#8736;',   
2145                         '&and;'                 => '&#8743;',   
2146                         '&or;'                  => '&#8744;',   
2147                         '&cap;'                 => '&#8745;',   
2148                         '&cup;'                 => '&#8746;',   
2149                         '&int;'                 => '&#8747;',   
2150                         '&there4;'              => '&#8756;',   
2151                         '&sim;'                 => '&#8764;',   
2152                         '&cong;'                => '&#8773;',   
2153                         '&asymp;'               => '&#8776;',   
2154                         '&ne;'                  => '&#8800;',   
2155                         '&equiv;'               => '&#8801;',   
2156                         '&le;'                  => '&#8804;',   
2157                         '&ge;'                  => '&#8805;',   
2158                         '&sub;'                 => '&#8834;',   
2159                         '&sup;'                 => '&#8835;',   
2160                         '&nsub;'                => '&#8836;',   
2161                         '&sube;'                => '&#8838;',   
2162                         '&supe;'                => '&#8839;',   
2163                         '&oplus;'               => '&#8853;',   
2164                         '&otimes;'      => '&#8855;',   
2165                         '&perp;'                => '&#8869;',   
2166                         '&sdot;'                => '&#8901;',   
2167                         '&lceil;'               => '&#8968;',   
2168                         '&rceil;'               => '&#8969;',   
2169                         '&lfloor;'              => '&#8970;',   
2170                         '&rfloor;'              => '&#8971;',   
2171                         '&lang;'                => '&#9001;',   
2172                         '&rang;'                => '&#9002;',   
2173                         '&loz;'                 => '&#9674;',   
2174                         '&spades;'              => '&#9824;',   
2175                         '&clubs;'               => '&#9827;',   
2176                         '&hearts;'              => '&#9829;',   
2177                         '&diams;'               => '&#9830;',   
2178                 );
2179         
2180         
2181 //modify start+++++++++
2182                 function _restore_to_utf8($contents)
2183                 {
2184                         if (_CHARSET != 'UTF-8')
2185                         {
2186                                 $contents = mb_convert_encoding($contents, 'UTF-8', _CHARSET);
2187                         }
2188                         $contents = $this->_decode_entities(strip_tags($contents));
2189                         return $contents;
2190                 }
2191 //modify end+++++++++
2192                 function _detect_encoding($string)
2193                 {
2194 //modify start+++++++++
2195                         if (function_exists('mb_convert_encoding')) {
2196                                 $encoding = (preg_match ("/;\s*charset=([^\n]+)/is", serverVar("CONTENT_TYPE"), $regs))? 
2197                                         strtoupper(trim($regs[1])):
2198                                         '';
2199
2200                                 if ( ($encoding !="") && ((mb_http_input("P") == "") || ( strtolower( ini_get("mbstring.http_input") ) == "pass")) ) {
2201                                         return $encoding;
2202                                 } else { 
2203                                         $encoding = mb_detect_encoding($string, 'UTF-8,EUC-JP,SJIS,ISO-8859-1,ASCII,JIS');
2204                                 }
2205                                 return ( $encoding ) ? $encoding : 'ISO-8859-1';
2206                         }
2207 //modify end+++++++++
2208                         if (!ereg("[\x80-\xFF]", $string) && !ereg("\x1B", $string))
2209                         return 'US-ASCII';
2210                         
2211                         if (!ereg("[\x80-\xFF]", $string) && ereg("\x1B", $string))
2212                         return 'ISO-2022-JP';
2213                         
2214                         if (preg_match("/^([\x01-\x7F]|[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF][\x80-\xBF])+$/", $string) == 1)
2215                         return 'UTF-8';
2216                         
2217                         if (preg_match("/^([\x01-\x7F]|\x8E[\xA0-\xDF]|\x8F[xA1-\xFE][\xA1-\xFE]|[\xA1-\xFE][\xA1-\xFE])+$/", $string) == 1)
2218                         return 'EUC-JP';
2219                         
2220                         if (preg_match("/^([\x01-\x7F]|[\xA0-\xDF]|[\x81-\xFC][\x40-\xFC])+$/", $string) == 1)
2221                         return 'Shift_JIS';
2222                         
2223                         return 'ISO-8859-1';
2224                 }
2225
2226                 function _convert_to_utf8($contents, $encoding)
2227                 {
2228                         $done = false;
2229                         
2230 //modify start+++++++++
2231 //                      if (!$done && function_exists('iconv'))  
2232 //                      {
2233 //                      
2234 //                              $result = @iconv($encoding, 'UTF-8//IGNORE', $contents);
2235 //      
2236 //                              if ($result) 
2237 //                              {
2238 //                                      $contents = $result;
2239 //                                      $done = true;
2240 //                              }
2241 //                      }
2242                         
2243                         if(!$done && function_exists('mb_convert_encoding')) 
2244                         {
2245                                 
2246                                 if( function_exists('mb_substitute_character') ){
2247                                         @mb_substitute_character('none');
2248                                 }
2249                                 $result = @mb_convert_encoding($contents, 'UTF-8', $encoding );
2250         
2251                                 if ($result) 
2252                                 {
2253                                         $contents = $result;
2254                                         $done = true;
2255                                 }
2256                         }
2257
2258                         if (!$done && function_exists('iconv'))  
2259                         {
2260                         
2261                                 $result = @iconv($encoding, 'UTF-8//IGNORE', $contents);
2262         
2263                                 if ($result) 
2264                                 {
2265                                         $contents = $result;
2266                                         $done = true;
2267                                 }
2268                         }
2269 //modify end+++++++++
2270                         return $contents;
2271                 }
2272                 
2273                 function _convert_to_utf8_auto($contents, $headers = '')
2274                 {
2275                         /* IN:  string in unknown encoding, headers received during transfer
2276                          * OUT: string in UTF-8 encoding
2277                          */
2278         
2279                         $str = substr($contents, 0, 4096);
2280                         $len = strlen($str);
2281                         $pos = 0;
2282                         $out = '';
2283                         
2284                         while ($pos < $len)
2285                         {
2286                                 $ord = ord($str[$pos]);
2287                                 
2288                                 if ($ord > 32 && $ord < 128)
2289                                         $out .= $str[$pos];
2290                                         
2291                                 $pos++;
2292                         }
2293         
2294                         // Detection of encoding, check headers
2295                         if (preg_match ("/;\s*charset=([^\n]+)/is", $headers, $regs))
2296                                 $encoding = strtoupper(trim($regs[1]));
2297         
2298                         // Then check meta inside document
2299                         if (preg_match ("/;\s*charset=([^\"']+)/is", $out, $regs))
2300                                 $encoding = strtoupper(trim($regs[1]));
2301                                 
2302                         // Then check xml declaration
2303                         if (preg_match("/<\?xml.+encoding\s*=\s*[\"|']([^\"']+)[\"|']\s*\?>/i", $out, $regs))
2304                                 $encoding = strtoupper(trim($regs[1]));         
2305         
2306                         // Converts
2307                         return $this->_convert_to_utf8($contents, $encoding);
2308                 }
2309                 
2310                 function _decode_entities($string)
2311                 {
2312                         /* IN:  string in UTF-8 containing entities
2313                          * OUT: string in UTF-8 without entities
2314                          */
2315                          
2316                         /// Convert all hexadecimal entities to decimal entities
2317                         $string = preg_replace('/&#[Xx]([0-9A-Fa-f]+);/e', "'&#'.hexdec('\\1').';'", $string);          
2318
2319                         // Deal with invalid cp1251 numeric entities
2320                         $string = strtr($string, $this->entities_cp1251);
2321
2322                         // Convert all named entities to numeric entities
2323                         $string = strtr($string, $this->entities_default);
2324                         $string = strtr($string, $this->entities_latin);
2325                         $string = strtr($string, $this->entities_extended);
2326
2327                         // Convert all numeric entities to UTF-8
2328                         $string = preg_replace('/&#([0-9]+);/e', "'&#x'.dechex('\\1').';'", $string);
2329                         $string = preg_replace('/&#[Xx]([0-9A-Fa-f]+);/e', "NP_TrackBack::_hex_to_utf8('\\1')", $string);               
2330
2331                         return $string;
2332                 }
2333         
2334                 function _hex_to_utf8($s)
2335                 {
2336                         /* IN:  string containing one hexadecimal Unicode character
2337                          * OUT: string containing one binary UTF-8 character
2338                          */
2339                          
2340                         $c = hexdec($s);
2341                 
2342                         if ($c < 0x80) {
2343                                 $str = chr($c);
2344                         }
2345                         else if ($c < 0x800) {
2346                                 $str = chr(0xC0 | $c>>6) . chr(0x80 | $c & 0x3F);
2347                         }
2348                         else if ($c < 0x10000) {
2349                                 $str = chr(0xE0 | $c>>12) . chr(0x80 | $c>>6 & 0x3F) . chr(0x80 | $c & 0x3F);
2350                         }
2351                         else if ($c < 0x200000) {
2352                                 $str = chr(0xF0 | $c>>18) . chr(0x80 | $c>>12 & 0x3F) . chr(0x80 | $c>>6 & 0x3F) . chr(0x80 | $c & 0x3F);
2353                         }
2354                         
2355                         return $str;
2356                 }               
2357
2358                 function _utf8_to_entities($string)
2359                 {
2360                         /* IN:  string in UTF-8 encoding
2361                          * OUT: string consisting of only characters ranging from 0x00 to 0x7f, 
2362                          *      using numeric entities to represent the other characters 
2363                          */
2364                          
2365                         $len = strlen ($string);
2366                         $pos = 0;
2367                         $out = '';
2368                                 
2369                         while ($pos < $len) 
2370                         {
2371                                 $ascii = ord (substr ($string, $pos, 1));
2372                                 
2373                                 if ($ascii >= 0xF0) 
2374                                 {
2375                                         $byte[1] = ord(substr ($string, $pos, 1)) - 0xF0;
2376                                         $byte[2] = ord(substr ($string, $pos + 1, 1)) - 0x80;
2377                                         $byte[3] = ord(substr ($string, $pos + 2, 1)) - 0x80;
2378                                         $byte[4] = ord(substr ($string, $pos + 3, 1)) - 0x80;
2379         
2380                                         $char_code = ($byte[1] << 18) + ($byte[2] << 12) + ($byte[3] << 6) + $byte[4];
2381                                         $pos += 4;
2382                                 }
2383                                 elseif (($ascii >= 0xE0) && ($ascii < 0xF0)) 
2384                                 {
2385                                         $byte[1] = ord(substr ($string, $pos, 1)) - 0xE0;
2386                                         $byte[2] = ord(substr ($string, $pos + 1, 1)) - 0x80;
2387                                         $byte[3] = ord(substr ($string, $pos + 2, 1)) - 0x80;
2388         
2389                                         $char_code = ($byte[1] << 12) + ($byte[2] << 6) + $byte[3];
2390                                         $pos += 3;
2391                                 }
2392                                 elseif (($ascii >= 0xC0) && ($ascii < 0xE0)) 
2393                                 {
2394                                         $byte[1] = ord(substr ($string, $pos, 1)) - 0xC0;
2395                                         $byte[2] = ord(substr ($string, $pos + 1, 1)) - 0x80;
2396         
2397                                         $char_code = ($byte[1] << 6) + $byte[2];
2398                                         $pos += 2;
2399                                 }
2400                                 else 
2401                                 {
2402                                         $char_code = ord(substr ($string, $pos, 1));
2403                                         $pos += 1;
2404                                 }
2405         
2406                                 if ($char_code < 0x80)
2407                                         $out .= chr($char_code);
2408                                 else
2409                                         $out .=  '&#'. str_pad($char_code, 5, '0', STR_PAD_LEFT) . ';';
2410                         }
2411         
2412                         return $out;    
2413                 }                       
2414
2415                 function _utf8_to_javascript($string)
2416                 {
2417                         /* IN:  string in UTF-8 encoding
2418                          * OUT: string consisting of only characters ranging from 0x00 to 0x7f, 
2419                          *      using javascript escapes to represent the other characters 
2420                          */
2421                          
2422                         $len = strlen ($string);
2423                         $pos = 0;
2424                         $out = '';
2425                                 
2426                         while ($pos < $len) 
2427                         {
2428                                 $ascii = ord (substr ($string, $pos, 1));
2429                                 
2430                                 if ($ascii >= 0xF0) 
2431                                 {
2432                                         $byte[1] = ord(substr ($string, $pos, 1)) - 0xF0;
2433                                         $byte[2] = ord(substr ($string, $pos + 1, 1)) - 0x80;
2434                                         $byte[3] = ord(substr ($string, $pos + 2, 1)) - 0x80;
2435                                         $byte[4] = ord(substr ($string, $pos + 3, 1)) - 0x80;
2436         
2437                                         $char_code = ($byte[1] << 18) + ($byte[2] << 12) + ($byte[3] << 6) + $byte[4];
2438                                         $pos += 4;
2439                                 }
2440                                 elseif (($ascii >= 0xE0) && ($ascii < 0xF0)) 
2441                                 {
2442                                         $byte[1] = ord(substr ($string, $pos, 1)) - 0xE0;
2443                                         $byte[2] = ord(substr ($string, $pos + 1, 1)) - 0x80;
2444                                         $byte[3] = ord(substr ($string, $pos + 2, 1)) - 0x80;
2445         
2446                                         $char_code = ($byte[1] << 12) + ($byte[2] << 6) + $byte[3];
2447                                         $pos += 3;
2448                                 }
2449                                 elseif (($ascii >= 0xC0) && ($ascii < 0xE0)) 
2450                                 {
2451                                         $byte[1] = ord(substr ($string, $pos, 1)) - 0xC0;
2452                                         $byte[2] = ord(substr ($string, $pos + 1, 1)) - 0x80;
2453         
2454                                         $char_code = ($byte[1] << 6) + $byte[2];
2455                                         $pos += 2;
2456                                 }
2457                                 else 
2458                                 {
2459                                         $char_code = ord(substr ($string, $pos, 1));
2460                                         $pos += 1;
2461                                 }
2462         
2463                                 if ($char_code < 0x80)
2464                                         $out .= chr($char_code);
2465                                 else
2466                                         $out .=  '\\u'. str_pad(dechex($char_code), 4, '0', STR_PAD_LEFT);
2467                         }
2468         
2469                         return $out;    
2470                 }                       
2471 /*              
2472                 function _cut_string($string, $dl = 0) {
2473                 
2474                         $defaultLength = $dl > 0 ? $dl : $this->getOption('defaultLength');
2475                         
2476                         if ($defaultLength < 1)
2477                                 return $string;
2478         
2479                         $border    = 6;
2480                         $count     = 0;
2481                         $lastvalue = 0;
2482         
2483                         for ($i = 0; $i < strlen($string); $i++)
2484                 {
2485                         $value = ord($string[$i]);
2486            
2487                                 if ($value > 127)
2488                         {
2489                                 if ($value >= 192 && $value <= 223)
2490                                 $i++;
2491                                 elseif ($value >= 224 && $value <= 239)
2492                                 $i = $i + 2;
2493                                 elseif ($value >= 240 && $value <= 247)
2494                                 $i = $i + 3;
2495                                         
2496                                         if ($lastvalue <= 223 && $value >= 223 && 
2497                                                 $count >= $defaultLength - $border)
2498                                         {
2499                                                 return substr($string, 0, $i) . '...';
2500                                         }
2501
2502                                         // Chinese and Japanese characters are
2503                                         // wider than Latin characters
2504                                         if ($value >= 224)
2505                                                 $count++;
2506                                         
2507                         }
2508                                 elseif ($string[$i] == '/' || $string[$i] == '?' ||
2509                                                 $string[$i] == '-' || $string[$i] == ':' ||
2510                                                 $string[$i] == ',' || $string[$i] == ';')
2511                                 {
2512                                         if ($count >= $defaultLength - $border)
2513                                                 return substr($string, 0, $i) . '...';
2514                                 }
2515                                 elseif ($string[$i] == ' ')
2516                                 {
2517                                         if ($count >= $defaultLength - $border)
2518                                                 return substr($string, 0, $i) . '...';
2519                                 }
2520                                 
2521                                 if ($count == $defaultLength)
2522                                         return substr($string, 0, $i + 1) . '...';
2523       
2524                                 $lastvalue = $value;
2525                         $count++;
2526                 }
2527
2528                         return $string;
2529                 }
2530 */
2531
2532 function _cut_string($string, $dl = 0) {
2533         $maxLength = $dl > 0 ? $dl : $this->getOption('defaultLength');
2534         
2535         if ($maxLength < 1)
2536                 return $string;
2537         if (strlen($string) > $maxLength)
2538                 $string = mb_strimwidth($string, 0, $maxLength, '...', _CHARSET);
2539
2540         return $string;
2541 }
2542
2543 function _strip_controlchar($string){
2544         $string = preg_replace("/[\x01-\x08\x0b\x0c\x0e-\x1f\x7f]+/","",$string);
2545         $string = str_replace("\0","",$string);
2546         return $string;
2547 }
2548
2549 //modify start+++++++++
2550         function checkTableVersion(){
2551                                 $res = sql_query("SHOW FIELDS from ".sql_table('plugin_tb') );
2552                                 $fieldnames = array();
2553                                 while ($co = mysql_fetch_assoc($res)) {
2554                                         if($co['Field'] == 'block') return true;
2555                                 }
2556                                 return false;
2557         }
2558 //modify end+++++++++
2559
2560 /*---------------------------------------------------------------------------------- */
2561 /*   LOCAL                                                                           */
2562 /*---------------------------------------------------------------------------------- */
2563         /**
2564           * Handle an incoming TrackBack ping and save the data in the database
2565           */
2566         function handleLocalPing($itemid, $title, $excerpt, $blog_name, $ping_url){
2567                 global $manager;
2568                 $ping_url = trim($ping_url);
2569                 
2570                 if( preg_match("/^.+tb_id=([0-9]+)$/",$ping_url,$idnum) ){
2571                         $tb_id = intval($idnum[1]);
2572                 } elseif ( preg_match("/([0-9]+)\.trackback/",$ping_url,$idnum) ){
2573                         $tb_id = intval($idnum[1]);
2574                 } elseif ( preg_match("/itemid=([0-9]+)/",$ping_url,$idnum) ){
2575                         $tb_id = intval($idnum[1]);
2576                 }
2577
2578                 if ((!$manager->existsItem($tb_id,0,0)) && ($this->getOption('CheckIDs') == 'yes'))
2579                         return _ERROR_NOSUCHITEM . "[ $tb_id ]";
2580                         
2581                 // save data in the DB
2582                 $query = 'INSERT INTO ' . sql_table('plugin_tb_lc') . " (tb_id, from_id) VALUES ('".intval($tb_id)."','".intval($itemid)."')";
2583                 $res = @mysql_query($query);
2584                 if (!$res) 
2585                         return 'Could not save trackback data, possibly because of a double entry: ' . mysql_error();
2586         }
2587         
2588         /**
2589           * Show the list of TrackBack pings for a certain Trackback ID
2590           */
2591         function showLocalList($tb_id) {
2592                 global $CONF, $manager;
2593                 
2594                 // create SQL query
2595                 $query = 'SELECT t.from_id as from_id , i.ititle as ititle, i.ibody as ibody, i.itime as itime, i.iblog as iblog FROM '.sql_table('plugin_tb_lc').' as t, '.sql_table('item').' as i WHERE t.tb_id='.intval($tb_id) .' and i.inumber=t.from_id ORDER BY i.itime DESC';
2596                 $res = mysql_query($query);
2597                 
2598                 $vars = array(
2599                         'tburl' => $this->getTrackBackUrl($tb_id)
2600                 );
2601
2602                 // when no TrackBack pings are found
2603                 if (!$res || mysql_num_rows($res) == 0) {
2604                         echo TEMPLATE::fill($this->getOption('tplLocalEmpty'), $vars);
2605                         return;
2606                 }
2607                 
2608                 // when TrackBack pings are found
2609                 echo TEMPLATE::fill($this->getOption('tplLocalHeader'), $vars);
2610                 
2611                 while ($o = mysql_fetch_object($res)) {
2612                         $canDelete = $this->canDelete($tb_id);
2613                         $data = array(
2614                                 'url' => createItemLink($o->from_id),
2615                                 'blogname' => htmlspecialchars(getBlogNameFromID($o->iblog)),
2616                                 'timestamp' => strftime('%Y-%m-%d',strtotime($o->itime)),
2617                                 'title' => htmlspecialchars($o->ititle),
2618                                 'excerpt' => htmlspecialchars(shorten(strip_tags($o->ibody),200,'...')),
2619                                 'delete' => $canDelete?'<a href="'. $manager->addTicketToUrl($CONF['ActionURL'].'?action=plugin&amp;name=TrackBack&amp;type=deletelc&amp;tb_id='.intval($tb_id).'&amp;from_id='.intval($o->from_id)).'">[delete]</a>':'',
2620                                 'tburl' => $this->getTrackBackUrl($tb_id),
2621                                 'commentcount'=> quickQuery('SELECT COUNT(*) as result FROM '.sql_table('comment').' WHERE citem=' . intval($o->from_id))
2622                         );
2623                         echo TEMPLATE::fill($this->getOption('tplLocalItem'), $data);
2624                 }
2625                 echo TEMPLATE::fill($this->getOption('tplLocalFooter'), $vars);
2626         }
2627         
2628         /**
2629           * Delete a TrackBack item, redirect to referer
2630           */
2631         function deleteLocal($tb_id, $from_id) {
2632                 if (!$this->canDelete($tb_id))
2633                         return 'You\'re not allowed to delete this trackback item';
2634                 $query = 'DELETE FROM ' . sql_table('plugin_tb_lc') . " WHERE tb_id='" . intval($tb_id) . "' and from_id='" . intval($from_id) ."'";
2635                 mysql_query($query);
2636                 return '';
2637         }
2638         
2639         function canDelete($tb_id) {
2640                 global $member, $manager;
2641                 
2642                 if ( ! $member->isLoggedIn() ) return 0;
2643                 
2644                 $checkIDs = $this->getOption('CheckIDs');
2645                 $itemExists =& $manager->existsItem($tb_id,0,0);
2646                 
2647                 // if CheckIDs option is set, check if member canEdit($tb_id)
2648                 // if CheckIDs option is not set, and item exists, check if member canEdit($tb_id)
2649                 // if CheckIDs option is not set, and item does not exists, check if member isAdmin()
2650                 
2651                 if (($checkIDs == 'yes') || ($itemExists))
2652                         return $member->canAlterItem($tb_id);
2653                 else
2654                         return $member->isAdmin();
2655         }
2656
2657                 /**************************************************************************************/
2658                 /* Plugin API calls, for installation, configuration and setup                        */
2659         
2660                 function getName()        {             return 'TrackBack';   }
2661                 function getAuthor()      {             return 'rakaz + nakahara21 + hsur'; }
2662                 function getURL()         {             return 'http://blog.cles.jp/np_cles/category/31/subcatid/3'; }
2663                 function getVersion()     {             return '2.0.3 jp9'; }
2664                 function getDescription() {             return _TB_DESCRIPTION; }
2665         
2666 //modify start+++++++++
2667 /*
2668                 function getTableList()   {             return array(sql_table("plugin_tb"), sql_table("plugin_tb_lookup")); }
2669                 function getEventList()   {             return array('QuickMenu','PostAddItem','AddItemFormExtras','EditItemFormExtras','PreUpdateItem','PrepareItemForEdit', 'BookmarkletExtraHead'); }
2670 */
2671                 function getTableList()   {             return array(sql_table("plugin_tb"), sql_table("plugin_tb_lookup"), sql_table('plugin_tb_lc')); }
2672
2673                 function getEventList()   {             return array('QuickMenu','PostAddItem','AddItemFormExtras','EditItemFormExtras','PreUpdateItem','PrepareItemForEdit', 'BookmarkletExtraHead', 'RetrieveTrackback', 'SendTrackback', 'InitSkinParse'); }
2674 //modify end+++++++++
2675                 function getMinNucleusVersion() {       return 200; }
2676         
2677                 function supportsFeature($feature) {
2678                         switch($feature) {
2679                                 case 'SqlTablePrefix':
2680                                         return 1;
2681 //modify start+++++++++
2682 //                              case 'HelpPage':
2683 //                                      return 1;
2684 //modify end+++++++++
2685                                 default:
2686                                         return 0;
2687                         }
2688                 }
2689
2690         
2691                 function hasAdminArea() {                       return 1; }
2692
2693                 function event_QuickMenu(&$data) {
2694                         global $member, $nucleus, $blogid;
2695                         
2696                         // only show to admins
2697                         if (!$member->isLoggedIn() || !$member->isAdmin()) return;
2698
2699                         array_push(
2700                                 $data['options'],
2701                                 array(
2702                                         'title' => 'Trackback',
2703                                         'url' => $this->getAdminURL(),
2704                                         'tooltip' => 'Manage your trackbacks'
2705                                 )
2706                         );
2707                 }
2708                         
2709                 function install() {
2710                         $this->createOption('AcceptPing',  _TB_AcceptPing,'yesno','yes');
2711                         $this->createOption('SendPings',   _TB_SendPings,'yesno','yes');
2712                         $this->createOption('AutoXMLHttp', _TB_AutoXMLHttp, 'yesno', 'yes');
2713                         $this->createOption('CheckIDs',    _TB_CheckIDs,'yesno','yes');
2714
2715                         $this->createOption('tplHeader',   _TB_tplHeader, 'textarea', _TB_tplHeader_VAL);
2716                         $this->createOption('tplEmpty',    _TB_tplEmpty, 'textarea', _TB_tplEmpty_VAL);
2717                         $this->createOption('tplItem',     _TB_tplItem, 'textarea', _TB_tplItem_VAL);
2718                         $this->createOption('tplFooter',   _TB_tplFooter, 'textarea', _TB_tplFooter_VAL);
2719 //mod by cles
2720                         $this->createOption('tplLocalHeader',   _TB_tplLocalHeader, 'textarea', _TB_tplLocalHeader_VAL);
2721                         $this->createOption('tplLocalEmpty',       _TB_tplLocalEmpty, 'textarea', _TB_tplLocalEmpty_VAL);
2722                         $this->createOption('tplLocalItem',        _TB_tplLocalItem, 'textarea', _TB_tplLocalItem_VAL);
2723                         $this->createOption('tplLocalFooter',   _TB_tplLocalFooter, 'textarea', _TB_tplLocalFooter_VAL);
2724 //mod by cles end
2725
2726                         $this->createOption('tplTbNone',   _TB_tplTbNone, 'text', "No Trackbacks");
2727                         $this->createOption('tplTbOne',    _TB_tplTbOne, 'text', "1 Trackback");
2728                         $this->createOption('tplTbMore',   _TB_tplTbMore, 'text', "<%number%> Trackbacks");
2729                         $this->createOption('dateFormat',  _TB_dateFormat, 'text', _TB_dateFormat_VAL);
2730         
2731                         $this->createOption('NotifyEmail', _TB_NotifyEmail,'text','');
2732                         $this->createOption('DropTable',   _TB_DropTable,'yesno','no');
2733 //mod by cles
2734                         $this->createOption('HideUrl',_TB_HideUrl,'yesno','yes');
2735                         $this->createOption('ajaxEnabled',_TB_ajaxEnabled,'yesno','no');
2736
2737                         $this->createItemOption('ItemAcceptPing',_TB_ItemAcceptPing,'yesno','yes');
2738                         $this->createItemOption('isAcceptW/OLink',_TB_isAcceptWOLink,'select','default', _TB_isAcceptWOLink_VAL);
2739
2740                         $this->createBlogOption('NotifyEmailBlog', _TB_NotifyEmailBlog,'text','');      
2741                         $this->createBlogOption('isAcceptW/OLinkDef',_TB_isAcceptWOLinkDef,'select','block', _TB_isAcceptWOLinkDef_VAL);
2742                         $this->createBlogOption('AllowTrackBack',_TB_AllowTrackBack,'yesno','yes');
2743 //mod by cles end
2744
2745                         /* Create tables */
2746                         mysql_query("
2747                                 CREATE TABLE IF NOT EXISTS 
2748                                         ".sql_table('plugin_tb')."
2749                                 (
2750                                         `id`        INT(11)         NOT NULL       AUTO_INCREMENT,
2751                                         `tb_id`     INT(11)         NOT NULL, 
2752                                         `url`       TEXT            NOT NULL, 
2753                                         `block`     TINYINT(4)      NOT NULL, 
2754                                         `spam`      TINYINT(4)      NOT NULL, 
2755                                         `link`      TINYINT(4)      NOT NULL, 
2756                                         `title`     TEXT,       
2757                                         `excerpt`   TEXT, 
2758                                         `blog_name` TEXT, 
2759                                         `timestamp` DATETIME, 
2760                                         
2761                                         PRIMARY KEY (`id`)
2762                                 )
2763                         ");
2764                                                 
2765                         mysql_query("
2766                                 CREATE TABLE IF NOT EXISTS
2767                                         ".sql_table('plugin_tb_lookup')."
2768                                 (
2769                                         `link`      TEXT            NOT NULL, 
2770                                         `url`       TEXT            NOT NULL, 
2771                                         `title`     TEXT, 
2772                                         
2773                                         PRIMARY KEY (`link` (100))
2774                                 )
2775                         ");
2776 //modify start+++++++++
2777                         @mysql_query('ALTER TABLE `' . sql_table('plugin_tb') . '` ADD INDEX `tb_id_block_timestamp_idx` ( `tb_id`, `block`, `timestamp` DESC )');
2778                         @mysql_query('CREATE TABLE IF NOT EXISTS ' . sql_table('plugin_tb_lc'). ' (tb_id int(11) not null, from_id int(11) not null, PRIMARY KEY (tb_id,from_id))');
2779 //modify end+++++++++
2780                 }
2781         
2782                 function uninstall() {
2783                         if ($this->getOption('DropTable') == 'yes') {
2784                                 mysql_query ('DROP TABLE '.sql_table('plugin_tb'));
2785                                 mysql_query ('DROP TABLE '.sql_table('plugin_tb_lookup'));
2786                                 mysql_query ("DROP table ".sql_table('plugin_tb_lc'));
2787                         }
2788                 }
2789
2790                 function init() {
2791       // include language file for this plugin 
2792       $language = ereg_replace( '[\\|/]', '', getLanguageName()); 
2793       if (file_exists($this->getDirectory().'language/'.$language.'.php')) 
2794          include_once($this->getDirectory().'language/'.$language.'.php'); 
2795       else 
2796          include_once($this->getDirectory().'language/'.'english.php'); 
2797                 $this->notificationMail = _TB_NORTIFICATION_MAIL_BODY;
2798                 $this->notificationMailTitle = _TB_NORTIFICATION_MAIL_TITLE;
2799          }
2800         }