OSDN Git Service

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