OSDN Git Service

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