source: trunk/include/functions_comment.inc.php @ 27867

Last change on this file since 27867 was 26916, checked in by mistic100, 10 years ago

bug 3029: XSS on website_url comment form

  • Property svn:eol-style set to LF
File size: 14.4 KB
RevLine 
[1849]1<?php
2// +-----------------------------------------------------------------------+
[8728]3// | Piwigo - a PHP based photo gallery                                    |
[2297]4// +-----------------------------------------------------------------------+
[26461]5// | Copyright(C) 2008-2014 Piwigo Team                  http://piwigo.org |
[2297]6// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
7// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
8// +-----------------------------------------------------------------------+
9// | This program is free software; you can redistribute it and/or modify  |
10// | it under the terms of the GNU General Public License as published by  |
11// | the Free Software Foundation                                          |
12// |                                                                       |
13// | This program is distributed in the hope that it will be useful, but   |
14// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
15// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
16// | General Public License for more details.                              |
17// |                                                                       |
18// | You should have received a copy of the GNU General Public License     |
19// | along with this program; if not, write to the Free Software           |
20// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
21// | USA.                                                                  |
22// +-----------------------------------------------------------------------+
[1849]23
[25548]24/**
25 * @package functions\comment
26 */
27 
28
29add_event_handler('user_comment_check', 'user_comment_check',
30  EVENT_HANDLER_PRIORITY_NEUTRAL, 2);
31
32/**
33 * Does basic check on comment and returns action to perform.
34 * This method is called by a trigger_event()
35 *
36 * @param string $action before check
37 * @param array $comment
38 * @return string validate, moderate, reject
39 */
[1849]40function user_comment_check($action, $comment)
41{
42  global $conf,$user;
43
44  if ($action=='reject')
45    return $action;
46
47  $my_action = $conf['comment_spam_reject'] ? 'reject':'moderate';
48
49  if ($action==$my_action)
50    return $action;
51
52  // we do here only BASIC spam check (plugins can do more)
[2029]53  if ( !is_a_guest() )
[1849]54    return $action;
55
56  $link_count = preg_match_all( '/https?:\/\//',
57    $comment['content'], $matches);
58
59  if ( strpos($comment['author'], 'http://')!==false )
60  {
61    $link_count++;
62  }
[2155]63
[1849]64  if ( $link_count>$conf['comment_spam_max_links'] )
[13800]65  {
66    $_POST['cr'][] = 'links';
[1849]67    return $my_action;
[13800]68  }
[1849]69  return $action;
70}
71
72/**
[25548]73 * Tries to insert a user comment and returns action to perform.
74 *
[25658]75 * @param array &$comm
[25548]76 * @param string $key secret key sent back to the browser
[25658]77 * @param array &$infos output array of error messages
[25548]78 * @return string validate, moderate, reject
[1849]79 */
[25548]80function insert_user_comment(&$comm, $key, &$infos)
[1849]81{
82  global $conf, $user;
[2155]83
84  $comm = array_merge( $comm,
[1849]85    array(
86      'ip' => $_SERVER['REMOTE_ADDR'],
87      'agent' => $_SERVER['HTTP_USER_AGENT']
88    )
89   );
90
91  $infos = array();
92  if (!$conf['comments_validation'] or is_admin())
93  {
94    $comment_action='validate'; //one of validate, moderate, reject
95  }
96  else
97  {
98    $comment_action='moderate'; //one of validate, moderate, reject
99  }
100
[2029]101  // display author field if the user status is guest or generic
102  if (!is_classic_user())
[1849]103  {
104    if ( empty($comm['author']) )
105    {
[18164]106      if ($conf['comments_author_mandatory'])
107      {
[25018]108        $infos[] = l10n('Username is mandatory');
[18164]109        $comment_action='reject';
110      }
[1849]111      $comm['author'] = 'guest';
112    }
[3450]113    $comm['author_id'] = $conf['guest_id'];
[1849]114    // if a guest try to use the name of an already existing user, he must be
115    // rejected
116    if ( $comm['author'] != 'guest' )
117    {
118      $query = '
119SELECT COUNT(*) AS user_exists
120  FROM '.USERS_TABLE.'
[4304]121  WHERE '.$conf['user_fields']['username']." = '".addslashes($comm['author'])."'";
[4325]122      $row = pwg_db_fetch_assoc( pwg_query( $query ) );
[1849]123      if ( $row['user_exists'] == 1 )
124      {
[25018]125        $infos[] = l10n('This login is already used by another user');
[1849]126        $comment_action='reject';
127      }
128    }
129  }
130  else
131  {
[3600]132    $comm['author'] = addslashes($user['username']);
[3450]133    $comm['author_id'] = $user['id'];
[1849]134  }
[3450]135
[1849]136  if ( empty($comm['content']) )
137  { // empty comment content
138    $comment_action='reject';
139  }
140
[7495]141  if ( !verify_ephemeral_key(@$key, $comm['image_id']) )
[1849]142  {
143    $comment_action='reject';
[13800]144    $_POST['cr'][] = 'key'; // rvelices: I use this outside to see how spam robots work
[1849]145  }
[15983]146 
[17351]147  // website
[18164]148  if (!empty($comm['website_url']))
[17351]149  {
[26916]150    $comm['website_url'] = strip_tags($comm['website_url']);
[18164]151    if (!preg_match('/^https?/i', $comm['website_url']))
152    {
153      $comm['website_url'] = 'http://'.$comm['website_url'];
154    }
155    if (!url_check_format($comm['website_url']))
156    {
[25018]157      $infos[] = l10n('Your website URL is invalid');
[18164]158      $comment_action='reject';
159    }
[17351]160  }
[18164]161 
162  // email
163  if (empty($comm['email']))
[17351]164  {
[18164]165    if (!empty($user['email']))
166    {
167      $comm['email'] = $user['email'];
168    }
169    else if ($conf['comments_email_mandatory'])
170    {
[25018]171      $infos[] = l10n('Email address is missing. Please specify an email address.');
[18164]172      $comment_action='reject';
173    }
174  }
175  else if (!email_check_format($comm['email']))
176  {
[25018]177    $infos[] = l10n('mail address must be like xxx@yyy.eee (example : jack@altern.org)');
[17351]178    $comment_action='reject';
179  }
180 
[15983]181  // anonymous id = ip address
182  $ip_components = explode('.', $comm['ip']);
183  if (count($ip_components) > 3)
184  {
185    array_pop($ip_components);
186  }
187  $comm['anonymous_id'] = implode('.', $ip_components);
[2155]188
[7784]189  if ($comment_action!='reject' and $conf['anti-flood_time']>0 and !is_admin())
[1849]190  { // anti-flood system
[6604]191    $reference_date = pwg_db_get_flood_period_expression($conf['anti-flood_time']);
192
[1849]193    $query = '
[6604]194SELECT count(1) FROM '.COMMENTS_TABLE.'
195  WHERE date > '.$reference_date.'
[3450]196    AND author_id = '.$comm['author_id'];
[15983]197    if (!is_classic_user())
198    {
199      $query.= '
200      AND anonymous_id = "'.$comm['anonymous_id'].'"';
201    }
202    $query.= '
203;';
204
[6604]205    list($counter) = pwg_db_fetch_row(pwg_query($query));
206    if ( $counter > 0 )
[1849]207    {
[25018]208      $infos[] = l10n('Anti-flood system : please wait for a moment before trying to post another comment');
[1849]209      $comment_action='reject';
210    }
211  }
212
213  // perform more spam check
214  $comment_action = trigger_event('user_comment_check',
215      $comment_action, $comm
216    );
217
218  if ( $comment_action!='reject' )
219  {
220    $query = '
221INSERT INTO '.COMMENTS_TABLE.'
[18164]222  (author, author_id, anonymous_id, content, date, validated, validation_date, image_id, website_url, email)
[1849]223  VALUES (
[6589]224    \''.$comm['author'].'\',
[3450]225    '.$comm['author_id'].',
[15983]226    \''.$comm['anonymous_id'].'\',
[6589]227    \''.$comm['content'].'\',
[1849]228    NOW(),
[6589]229    \''.($comment_action=='validate' ? 'true':'false').'\',
[1849]230    '.($comment_action=='validate' ? 'NOW()':'NULL').',
[17351]231    '.$comm['image_id'].',
[18164]232    '.(!empty($comm['website_url']) ? '\''.$comm['website_url'].'\'' : 'NULL').',
233    '.(!empty($comm['email']) ? '\''.$comm['email'].'\'' : 'NULL').'
[1849]234  )
235';
236    pwg_query($query);
[4892]237    $comm['id'] = pwg_db_insert_id(COMMENTS_TABLE);
[1849]238
[21817]239    invalidate_user_cache_nb_comments();
240
[13800]241    if ( ($conf['email_admin_on_comment'] && 'validate' == $comment_action)
[5195]242        or ($conf['email_admin_on_comment_validation'] and 'moderate' == $comment_action))
[1849]243    {
244      include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
245
[5195]246      $comment_url = get_absolute_root_url().'comments.php?comment_id='.$comm['id'];
[1849]247
[25360]248      $keyargs_content = array(
249        get_l10n_args('Author: %s', stripslashes($comm['author']) ),
250        get_l10n_args('Email: %s', stripslashes($comm['email']) ),
251        get_l10n_args('Comment: %s', stripslashes($comm['content']) ),
252        get_l10n_args(''),
253        get_l10n_args('Manage this user comment: %s', $comment_url),
[1908]254      );
[1849]255
[5195]256      if ('moderate' == $comment_action)
[1849]257      {
[25360]258        $keyargs_content[] = get_l10n_args('(!) This comment requires validation');
[1849]259      }
260
[25357]261      pwg_mail_notification_admins(
[25360]262        get_l10n_args('Comment by %s', stripslashes($comm['author']) ),
263        $keyargs_content
[1849]264      );
265    }
266  }
[25548]267
[1849]268  return $comment_action;
269}
270
[3445]271/**
[25548]272 * Tries to delete a (or more) user comment.
273 *    only admin can delete all comments
274 *    other users can delete their own comments
[3445]275 *
[25548]276 * @param int|int[] $comment_id
277 * @return bool false if nothing deleted
[3445]278 */
[12596]279function delete_user_comment($comment_id)
280{
[3445]281  $user_where_clause = '';
282  if (!is_admin())
283  {
[3450]284    $user_where_clause = '   AND author_id = \''.$GLOBALS['user']['id'].'\'';
[3445]285  }
[12596]286 
287  if (is_array($comment_id))
288    $where_clause = 'id IN('.implode(',', $comment_id).')';
289  else
290    $where_clause = 'id = '.$comment_id;
291   
[3445]292  $query = '
293DELETE FROM '.COMMENTS_TABLE.'
[12596]294  WHERE '.$where_clause.
[3445]295$user_where_clause.'
296;';
[12596]297 
[21817]298  if ( pwg_db_changes(pwg_query($query)) )
[12596]299  {
[21817]300    invalidate_user_cache_nb_comments();
301
[5707]302    email_admin('delete', 
303                array('author' => $GLOBALS['user']['username'],
304                      'comment_id' => $comment_id
305                  ));
[21817]306    trigger_action('user_comment_deletion', $comment_id);
[25548]307
308    return true;
[3445]309  }
[25548]310
311  return false;
[3445]312}
313
314/**
[25548]315 * Tries to update a user comment
316 *    only admin can update all comments
317 *    users can edit their own comments if admin allow them
[3445]318 *
[25548]319 * @param array $comment
320 * @param string $post_key secret key sent back to the browser
321 * @return string validate, moderate, reject
[3445]322 */
323
[3488]324function update_user_comment($comment, $post_key)
325{
[18995]326  global $conf, $page;
[3445]327
328  $comment_action = 'validate';
329
[7495]330  if ( !verify_ephemeral_key($post_key, $comment['image_id']) )
[3445]331  {
332    $comment_action='reject';
333  }
[11253]334  elseif (!$conf['comments_validation'] or is_admin()) // should the updated comment must be validated
335  {
336    $comment_action='validate'; //one of validate, moderate, reject
337  }
338  else
339  {
340    $comment_action='moderate'; //one of validate, moderate, reject
341  }
[3445]342
343  // perform more spam check
[3488]344  $comment_action =
[3445]345    trigger_event('user_comment_check',
[3488]346                  $comment_action,
347                  array_merge($comment,
[3445]348                              array('author' => $GLOBALS['user']['username'])
349                              )
350                  );
351
[18995]352  // website
353  if (!empty($comment['website_url']))
354  {
[26916]355    $comm['website_url'] = strip_tags($comm['website_url']);
[18995]356    if (!preg_match('/^https?/i', $comment['website_url']))
357    {
358      $comment['website_url'] = 'http://'.$comment['website_url'];
359    }
360    if (!url_check_format($comment['website_url']))
361    {
[21817]362      $page['errors'][] = l10n('Your website URL is invalid');
[18995]363      $comment_action='reject';
364    }
365  }
366
[3445]367  if ( $comment_action!='reject' )
368  {
369    $user_where_clause = '';
370    if (!is_admin())
371    {
[3450]372      $user_where_clause = '   AND author_id = \''.
373        $GLOBALS['user']['id'].'\'';
[3445]374    }
[10097]375
[3445]376    $query = '
377UPDATE '.COMMENTS_TABLE.'
378  SET content = \''.$comment['content'].'\',
[18995]379      website_url = '.(!empty($comment['website_url']) ? '\''.$comment['website_url'].'\'' : 'NULL').',
[10097]380      validated = \''.($comment_action=='validate' ? 'true':'false').'\',
381      validation_date = '.($comment_action=='validate' ? 'NOW()':'NULL').'
[3445]382  WHERE id = '.$comment['comment_id'].
383$user_where_clause.'
384;';
385    $result = pwg_query($query);
[10097]386   
387    // mail admin and ask to validate the comment
388    if ($result and $conf['email_admin_on_comment_validation'] and 'moderate' == $comment_action) 
389    {
390      include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
391
392      $comment_url = get_absolute_root_url().'comments.php?comment_id='.$comment['comment_id'];
393
[25360]394      $keyargs_content = array(
395        get_l10n_args('Author: %s', stripslashes($GLOBALS['user']['username']) ),
396        get_l10n_args('Comment: %s', stripslashes($comment['content']) ),
397        get_l10n_args(''),
398        get_l10n_args('Manage this user comment: %s', $comment_url),
399        get_l10n_args('(!) This comment requires validation'),
[10097]400      );
401
[25357]402      pwg_mail_notification_admins(
[25360]403        get_l10n_args('Comment by %s', stripslashes($GLOBALS['user']['username']) ),
404        $keyargs_content
[10097]405      );
406    }
407    // just mail admin
[21817]408    elseif ($result)
[10097]409    {
[3445]410      email_admin('edit', array('author' => $GLOBALS['user']['username'],
[3488]411                                'content' => stripslashes($comment['content'])) );
[3445]412    }
413  }
[10097]414 
415  return $comment_action;
[3445]416}
417
[25548]418/**
419 * Notifies admins about updated or deleted comment.
420 * Only used when no validation is needed, otherwise pwg_mail_notification_admins() is used.
421 *
422 * @param string $action edit, delete
423 * @param array $comment
424 */
[3488]425function email_admin($action, $comment)
426{
[3445]427  global $conf;
428
429  if (!in_array($action, array('edit', 'delete'))
430      or (($action=='edit') and !$conf['email_admin_on_comment_edition'])
431      or (($action=='delete') and !$conf['email_admin_on_comment_deletion']))
432  {
433    return;
434  }
435
436  include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
[3488]437
[25360]438  $keyargs_content = array(
439    get_l10n_args('Author: %s', $comment['author']),
[25357]440    );
441
[3488]442  if ($action=='delete')
[3445]443  {
[25360]444    $keyargs_content[] = get_l10n_args('This author removed the comment with id %d', $comment['comment_id']);
[3445]445  }
446  else
447  {
[25360]448    $keyargs_content[] = get_l10n_args('This author modified following comment:');
449    $keyargs_content[] = get_l10n_args('Comment: %s', $comment['content']);
[3445]450  }
[3488]451
[25357]452  pwg_mail_notification_admins(
[25360]453    get_l10n_args('Comment by %s', $comment['author']),
454    $keyargs_content
455    );
[3445]456}
[5195]457
[25548]458/**
459 * Returns the author id of a comment
460 *
461 * @param int $comment_id
462 * @param bool $die_on_error
463 * @return int
464 */
[5195]465function get_comment_author_id($comment_id, $die_on_error=true)
466{
467  $query = '
468SELECT
469    author_id
470  FROM '.COMMENTS_TABLE.'
471  WHERE id = '.$comment_id.'
472;';
473  $result = pwg_query($query);
474  if (pwg_db_num_rows($result) == 0)
475  {
476    if ($die_on_error)
477    {
478      fatal_error('Unknown comment identifier');
479    }
480    else
481    {
482      return false;
483    }
484  }
485 
486  list($author_id) = pwg_db_fetch_row($result);
487
488  return $author_id;
489}
490
[12596]491/**
[25548]492 * Tries to validate a user comment.
493 *
494 * @param int|int[] $comment_id
[12596]495 */
[5195]496function validate_user_comment($comment_id)
497{
[12596]498  if (is_array($comment_id))
499    $where_clause = 'id IN('.implode(',', $comment_id).')';
500  else
501    $where_clause = 'id = '.$comment_id;
502   
[5195]503  $query = '
504UPDATE '.COMMENTS_TABLE.'
[6589]505  SET validated = \'true\'
[5195]506    , validation_date = NOW()
[12596]507  WHERE '.$where_clause.'
[5195]508;';
509  pwg_query($query);
[12556]510 
[21817]511  invalidate_user_cache_nb_comments();
[12556]512  trigger_action('user_comment_validation', $comment_id);
[5195]513}
[21817]514
[25548]515/**
516 * Clears cache of nb comments for all users
517 */
[21817]518function invalidate_user_cache_nb_comments()
519{
520  global $user;
[25548]521
[21817]522  unset($user['nb_available_comments']);
[25548]523
[21817]524  $query = '
525UPDATE '.USER_CACHE_TABLE.'
[25548]526  SET nb_available_comments = NULL
527;';
[21817]528  pwg_query($query);
529}
530
[1849]531?>
Note: See TracBrowser for help on using the repository browser.