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

Last change on this file since 26916 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
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based photo gallery                                    |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008-2014 Piwigo Team                  http://piwigo.org |
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// +-----------------------------------------------------------------------+
23
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 */
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)
53  if ( !is_a_guest() )
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  }
63
64  if ( $link_count>$conf['comment_spam_max_links'] )
65  {
66    $_POST['cr'][] = 'links';
67    return $my_action;
68  }
69  return $action;
70}
71
72/**
73 * Tries to insert a user comment and returns action to perform.
74 *
75 * @param array &$comm
76 * @param string $key secret key sent back to the browser
77 * @param array &$infos output array of error messages
78 * @return string validate, moderate, reject
79 */
80function insert_user_comment(&$comm, $key, &$infos)
81{
82  global $conf, $user;
83
84  $comm = array_merge( $comm,
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
101  // display author field if the user status is guest or generic
102  if (!is_classic_user())
103  {
104    if ( empty($comm['author']) )
105    {
106      if ($conf['comments_author_mandatory'])
107      {
108        $infos[] = l10n('Username is mandatory');
109        $comment_action='reject';
110      }
111      $comm['author'] = 'guest';
112    }
113    $comm['author_id'] = $conf['guest_id'];
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.'
121  WHERE '.$conf['user_fields']['username']." = '".addslashes($comm['author'])."'";
122      $row = pwg_db_fetch_assoc( pwg_query( $query ) );
123      if ( $row['user_exists'] == 1 )
124      {
125        $infos[] = l10n('This login is already used by another user');
126        $comment_action='reject';
127      }
128    }
129  }
130  else
131  {
132    $comm['author'] = addslashes($user['username']);
133    $comm['author_id'] = $user['id'];
134  }
135
136  if ( empty($comm['content']) )
137  { // empty comment content
138    $comment_action='reject';
139  }
140
141  if ( !verify_ephemeral_key(@$key, $comm['image_id']) )
142  {
143    $comment_action='reject';
144    $_POST['cr'][] = 'key'; // rvelices: I use this outside to see how spam robots work
145  }
146 
147  // website
148  if (!empty($comm['website_url']))
149  {
150    $comm['website_url'] = strip_tags($comm['website_url']);
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    {
157      $infos[] = l10n('Your website URL is invalid');
158      $comment_action='reject';
159    }
160  }
161 
162  // email
163  if (empty($comm['email']))
164  {
165    if (!empty($user['email']))
166    {
167      $comm['email'] = $user['email'];
168    }
169    else if ($conf['comments_email_mandatory'])
170    {
171      $infos[] = l10n('Email address is missing. Please specify an email address.');
172      $comment_action='reject';
173    }
174  }
175  else if (!email_check_format($comm['email']))
176  {
177    $infos[] = l10n('mail address must be like xxx@yyy.eee (example : jack@altern.org)');
178    $comment_action='reject';
179  }
180 
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);
188
189  if ($comment_action!='reject' and $conf['anti-flood_time']>0 and !is_admin())
190  { // anti-flood system
191    $reference_date = pwg_db_get_flood_period_expression($conf['anti-flood_time']);
192
193    $query = '
194SELECT count(1) FROM '.COMMENTS_TABLE.'
195  WHERE date > '.$reference_date.'
196    AND author_id = '.$comm['author_id'];
197    if (!is_classic_user())
198    {
199      $query.= '
200      AND anonymous_id = "'.$comm['anonymous_id'].'"';
201    }
202    $query.= '
203;';
204
205    list($counter) = pwg_db_fetch_row(pwg_query($query));
206    if ( $counter > 0 )
207    {
208      $infos[] = l10n('Anti-flood system : please wait for a moment before trying to post another comment');
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.'
222  (author, author_id, anonymous_id, content, date, validated, validation_date, image_id, website_url, email)
223  VALUES (
224    \''.$comm['author'].'\',
225    '.$comm['author_id'].',
226    \''.$comm['anonymous_id'].'\',
227    \''.$comm['content'].'\',
228    NOW(),
229    \''.($comment_action=='validate' ? 'true':'false').'\',
230    '.($comment_action=='validate' ? 'NOW()':'NULL').',
231    '.$comm['image_id'].',
232    '.(!empty($comm['website_url']) ? '\''.$comm['website_url'].'\'' : 'NULL').',
233    '.(!empty($comm['email']) ? '\''.$comm['email'].'\'' : 'NULL').'
234  )
235';
236    pwg_query($query);
237    $comm['id'] = pwg_db_insert_id(COMMENTS_TABLE);
238
239    invalidate_user_cache_nb_comments();
240
241    if ( ($conf['email_admin_on_comment'] && 'validate' == $comment_action)
242        or ($conf['email_admin_on_comment_validation'] and 'moderate' == $comment_action))
243    {
244      include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
245
246      $comment_url = get_absolute_root_url().'comments.php?comment_id='.$comm['id'];
247
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),
254      );
255
256      if ('moderate' == $comment_action)
257      {
258        $keyargs_content[] = get_l10n_args('(!) This comment requires validation');
259      }
260
261      pwg_mail_notification_admins(
262        get_l10n_args('Comment by %s', stripslashes($comm['author']) ),
263        $keyargs_content
264      );
265    }
266  }
267
268  return $comment_action;
269}
270
271/**
272 * Tries to delete a (or more) user comment.
273 *    only admin can delete all comments
274 *    other users can delete their own comments
275 *
276 * @param int|int[] $comment_id
277 * @return bool false if nothing deleted
278 */
279function delete_user_comment($comment_id)
280{
281  $user_where_clause = '';
282  if (!is_admin())
283  {
284    $user_where_clause = '   AND author_id = \''.$GLOBALS['user']['id'].'\'';
285  }
286 
287  if (is_array($comment_id))
288    $where_clause = 'id IN('.implode(',', $comment_id).')';
289  else
290    $where_clause = 'id = '.$comment_id;
291   
292  $query = '
293DELETE FROM '.COMMENTS_TABLE.'
294  WHERE '.$where_clause.
295$user_where_clause.'
296;';
297 
298  if ( pwg_db_changes(pwg_query($query)) )
299  {
300    invalidate_user_cache_nb_comments();
301
302    email_admin('delete', 
303                array('author' => $GLOBALS['user']['username'],
304                      'comment_id' => $comment_id
305                  ));
306    trigger_action('user_comment_deletion', $comment_id);
307
308    return true;
309  }
310
311  return false;
312}
313
314/**
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
318 *
319 * @param array $comment
320 * @param string $post_key secret key sent back to the browser
321 * @return string validate, moderate, reject
322 */
323
324function update_user_comment($comment, $post_key)
325{
326  global $conf, $page;
327
328  $comment_action = 'validate';
329
330  if ( !verify_ephemeral_key($post_key, $comment['image_id']) )
331  {
332    $comment_action='reject';
333  }
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  }
342
343  // perform more spam check
344  $comment_action =
345    trigger_event('user_comment_check',
346                  $comment_action,
347                  array_merge($comment,
348                              array('author' => $GLOBALS['user']['username'])
349                              )
350                  );
351
352  // website
353  if (!empty($comment['website_url']))
354  {
355    $comm['website_url'] = strip_tags($comm['website_url']);
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    {
362      $page['errors'][] = l10n('Your website URL is invalid');
363      $comment_action='reject';
364    }
365  }
366
367  if ( $comment_action!='reject' )
368  {
369    $user_where_clause = '';
370    if (!is_admin())
371    {
372      $user_where_clause = '   AND author_id = \''.
373        $GLOBALS['user']['id'].'\'';
374    }
375
376    $query = '
377UPDATE '.COMMENTS_TABLE.'
378  SET content = \''.$comment['content'].'\',
379      website_url = '.(!empty($comment['website_url']) ? '\''.$comment['website_url'].'\'' : 'NULL').',
380      validated = \''.($comment_action=='validate' ? 'true':'false').'\',
381      validation_date = '.($comment_action=='validate' ? 'NOW()':'NULL').'
382  WHERE id = '.$comment['comment_id'].
383$user_where_clause.'
384;';
385    $result = pwg_query($query);
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
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'),
400      );
401
402      pwg_mail_notification_admins(
403        get_l10n_args('Comment by %s', stripslashes($GLOBALS['user']['username']) ),
404        $keyargs_content
405      );
406    }
407    // just mail admin
408    elseif ($result)
409    {
410      email_admin('edit', array('author' => $GLOBALS['user']['username'],
411                                'content' => stripslashes($comment['content'])) );
412    }
413  }
414 
415  return $comment_action;
416}
417
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 */
425function email_admin($action, $comment)
426{
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');
437
438  $keyargs_content = array(
439    get_l10n_args('Author: %s', $comment['author']),
440    );
441
442  if ($action=='delete')
443  {
444    $keyargs_content[] = get_l10n_args('This author removed the comment with id %d', $comment['comment_id']);
445  }
446  else
447  {
448    $keyargs_content[] = get_l10n_args('This author modified following comment:');
449    $keyargs_content[] = get_l10n_args('Comment: %s', $comment['content']);
450  }
451
452  pwg_mail_notification_admins(
453    get_l10n_args('Comment by %s', $comment['author']),
454    $keyargs_content
455    );
456}
457
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 */
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
491/**
492 * Tries to validate a user comment.
493 *
494 * @param int|int[] $comment_id
495 */
496function validate_user_comment($comment_id)
497{
498  if (is_array($comment_id))
499    $where_clause = 'id IN('.implode(',', $comment_id).')';
500  else
501    $where_clause = 'id = '.$comment_id;
502   
503  $query = '
504UPDATE '.COMMENTS_TABLE.'
505  SET validated = \'true\'
506    , validation_date = NOW()
507  WHERE '.$where_clause.'
508;';
509  pwg_query($query);
510 
511  invalidate_user_cache_nb_comments();
512  trigger_action('user_comment_validation', $comment_id);
513}
514
515/**
516 * Clears cache of nb comments for all users
517 */
518function invalidate_user_cache_nb_comments()
519{
520  global $user;
521
522  unset($user['nb_available_comments']);
523
524  $query = '
525UPDATE '.USER_CACHE_TABLE.'
526  SET nb_available_comments = NULL
527;';
528  pwg_query($query);
529}
530
531?>
Note: See TracBrowser for help on using the repository browser.