OSDN Git Service

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