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

Last change on this file since 25360 was 25360, checked in by mistic100, 11 years ago

feature 2995: New email template
restore get_l10n_args removed at r25357
apply changes to NBM

  • Property svn:eol-style set to LF
File size: 13.8 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based photo gallery                                    |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008-2013 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//returns string action to perform on a new comment: validate, moderate, reject
25function user_comment_check($action, $comment)
26{
27  global $conf,$user;
28
29  if ($action=='reject')
30    return $action;
31
32  $my_action = $conf['comment_spam_reject'] ? 'reject':'moderate';
33
34  if ($action==$my_action)
35    return $action;
36
37  // we do here only BASIC spam check (plugins can do more)
38  if ( !is_a_guest() )
39    return $action;
40
41  $link_count = preg_match_all( '/https?:\/\//',
42    $comment['content'], $matches);
43
44  if ( strpos($comment['author'], 'http://')!==false )
45  {
46    $link_count++;
47  }
48
49  if ( $link_count>$conf['comment_spam_max_links'] )
50  {
51    $_POST['cr'][] = 'links';
52    return $my_action;
53  }
54  return $action;
55}
56
57
58add_event_handler('user_comment_check', 'user_comment_check',
59  EVENT_HANDLER_PRIORITY_NEUTRAL, 2);
60
61/**
62 * Tries to insert a user comment in the database and returns one of :
63 * validate, moderate, reject
64 * @param array comm contains author, content, image_id
65 * @param string key secret key sent back to the browser
66 * @param array infos out array of messages
67 */
68function insert_user_comment( &$comm, $key, &$infos )
69{
70  global $conf, $user;
71
72  $comm = array_merge( $comm,
73    array(
74      'ip' => $_SERVER['REMOTE_ADDR'],
75      'agent' => $_SERVER['HTTP_USER_AGENT']
76    )
77   );
78
79  $infos = array();
80  if (!$conf['comments_validation'] or is_admin())
81  {
82    $comment_action='validate'; //one of validate, moderate, reject
83  }
84  else
85  {
86    $comment_action='moderate'; //one of validate, moderate, reject
87  }
88
89  // display author field if the user status is guest or generic
90  if (!is_classic_user())
91  {
92    if ( empty($comm['author']) )
93    {
94      if ($conf['comments_author_mandatory'])
95      {
96        $infos[] = l10n('Username is mandatory');
97        $comment_action='reject';
98      }
99      $comm['author'] = 'guest';
100    }
101    $comm['author_id'] = $conf['guest_id'];
102    // if a guest try to use the name of an already existing user, he must be
103    // rejected
104    if ( $comm['author'] != 'guest' )
105    {
106      $query = '
107SELECT COUNT(*) AS user_exists
108  FROM '.USERS_TABLE.'
109  WHERE '.$conf['user_fields']['username']." = '".addslashes($comm['author'])."'";
110      $row = pwg_db_fetch_assoc( pwg_query( $query ) );
111      if ( $row['user_exists'] == 1 )
112      {
113        $infos[] = l10n('This login is already used by another user');
114        $comment_action='reject';
115      }
116    }
117  }
118  else
119  {
120    $comm['author'] = addslashes($user['username']);
121    $comm['author_id'] = $user['id'];
122  }
123
124  if ( empty($comm['content']) )
125  { // empty comment content
126    $comment_action='reject';
127  }
128
129  if ( !verify_ephemeral_key(@$key, $comm['image_id']) )
130  {
131    $comment_action='reject';
132    $_POST['cr'][] = 'key'; // rvelices: I use this outside to see how spam robots work
133  }
134 
135  // website
136  if (!empty($comm['website_url']))
137  {
138    if (!preg_match('/^https?/i', $comm['website_url']))
139    {
140      $comm['website_url'] = 'http://'.$comm['website_url'];
141    }
142    if (!url_check_format($comm['website_url']))
143    {
144      $infos[] = l10n('Your website URL is invalid');
145      $comment_action='reject';
146    }
147  }
148 
149  // email
150  if (empty($comm['email']))
151  {
152    if (!empty($user['email']))
153    {
154      $comm['email'] = $user['email'];
155    }
156    else if ($conf['comments_email_mandatory'])
157    {
158      $infos[] = l10n('Email address is missing. Please specify an email address.');
159      $comment_action='reject';
160    }
161  }
162  else if (!email_check_format($comm['email']))
163  {
164    $infos[] = l10n('mail address must be like xxx@yyy.eee (example : jack@altern.org)');
165    $comment_action='reject';
166  }
167 
168  // anonymous id = ip address
169  $ip_components = explode('.', $comm['ip']);
170  if (count($ip_components) > 3)
171  {
172    array_pop($ip_components);
173  }
174  $comm['anonymous_id'] = implode('.', $ip_components);
175
176  if ($comment_action!='reject' and $conf['anti-flood_time']>0 and !is_admin())
177  { // anti-flood system
178    $reference_date = pwg_db_get_flood_period_expression($conf['anti-flood_time']);
179
180    $query = '
181SELECT count(1) FROM '.COMMENTS_TABLE.'
182  WHERE date > '.$reference_date.'
183    AND author_id = '.$comm['author_id'];
184    if (!is_classic_user())
185    {
186      $query.= '
187      AND anonymous_id = "'.$comm['anonymous_id'].'"';
188    }
189    $query.= '
190;';
191
192    list($counter) = pwg_db_fetch_row(pwg_query($query));
193    if ( $counter > 0 )
194    {
195      $infos[] = l10n('Anti-flood system : please wait for a moment before trying to post another comment');
196      $comment_action='reject';
197    }
198  }
199
200  // perform more spam check
201  $comment_action = trigger_event('user_comment_check',
202      $comment_action, $comm
203    );
204
205  if ( $comment_action!='reject' )
206  {
207    $query = '
208INSERT INTO '.COMMENTS_TABLE.'
209  (author, author_id, anonymous_id, content, date, validated, validation_date, image_id, website_url, email)
210  VALUES (
211    \''.$comm['author'].'\',
212    '.$comm['author_id'].',
213    \''.$comm['anonymous_id'].'\',
214    \''.$comm['content'].'\',
215    NOW(),
216    \''.($comment_action=='validate' ? 'true':'false').'\',
217    '.($comment_action=='validate' ? 'NOW()':'NULL').',
218    '.$comm['image_id'].',
219    '.(!empty($comm['website_url']) ? '\''.$comm['website_url'].'\'' : 'NULL').',
220    '.(!empty($comm['email']) ? '\''.$comm['email'].'\'' : 'NULL').'
221  )
222';
223    pwg_query($query);
224    $comm['id'] = pwg_db_insert_id(COMMENTS_TABLE);
225
226    invalidate_user_cache_nb_comments();
227
228    if ( ($conf['email_admin_on_comment'] && 'validate' == $comment_action)
229        or ($conf['email_admin_on_comment_validation'] and 'moderate' == $comment_action))
230    {
231      include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
232
233      $comment_url = get_absolute_root_url().'comments.php?comment_id='.$comm['id'];
234
235      $keyargs_content = array(
236        get_l10n_args('Author: %s', stripslashes($comm['author']) ),
237        get_l10n_args('Email: %s', stripslashes($comm['email']) ),
238        get_l10n_args('Comment: %s', stripslashes($comm['content']) ),
239        get_l10n_args(''),
240        get_l10n_args('Manage this user comment: %s', $comment_url),
241      );
242
243      if ('moderate' == $comment_action)
244      {
245        $keyargs_content[] = get_l10n_args('(!) This comment requires validation');
246      }
247
248      pwg_mail_notification_admins(
249        get_l10n_args('Comment by %s', stripslashes($comm['author']) ),
250        $keyargs_content
251      );
252    }
253  }
254  return $comment_action;
255}
256
257/**
258 * Tries to delete a user comment in the database
259 * only admin can delete all comments
260 * other users can delete their own comments
261 * so to avoid a new sql request we add author in where clause
262 *
263 * @param int or array of int comment_id
264 */
265function delete_user_comment($comment_id)
266{
267  $user_where_clause = '';
268  if (!is_admin())
269  {
270    $user_where_clause = '   AND author_id = \''.$GLOBALS['user']['id'].'\'';
271  }
272 
273  if (is_array($comment_id))
274    $where_clause = 'id IN('.implode(',', $comment_id).')';
275  else
276    $where_clause = 'id = '.$comment_id;
277   
278  $query = '
279DELETE FROM '.COMMENTS_TABLE.'
280  WHERE '.$where_clause.
281$user_where_clause.'
282;';
283 
284  if ( pwg_db_changes(pwg_query($query)) )
285  {
286    invalidate_user_cache_nb_comments();
287
288    email_admin('delete', 
289                array('author' => $GLOBALS['user']['username'],
290                      'comment_id' => $comment_id
291                  ));
292    trigger_action('user_comment_deletion', $comment_id);
293  }
294}
295
296/**
297 * Tries to update a user comment in the database
298 * only admin can update all comments
299 * users can edit their own comments if admin allow them
300 * so to avoid a new sql request we add author in where clause
301 *
302 * @param comment_id
303 * @param post_key
304 * @param content
305 */
306
307function update_user_comment($comment, $post_key)
308{
309  global $conf, $page;
310
311  $comment_action = 'validate';
312
313  if ( !verify_ephemeral_key($post_key, $comment['image_id']) )
314  {
315    $comment_action='reject';
316  }
317  elseif (!$conf['comments_validation'] or is_admin()) // should the updated comment must be validated
318  {
319    $comment_action='validate'; //one of validate, moderate, reject
320  }
321  else
322  {
323    $comment_action='moderate'; //one of validate, moderate, reject
324  }
325
326  // perform more spam check
327  $comment_action =
328    trigger_event('user_comment_check',
329                  $comment_action,
330                  array_merge($comment,
331                              array('author' => $GLOBALS['user']['username'])
332                              )
333                  );
334
335  // website
336  if (!empty($comment['website_url']))
337  {
338    if (!preg_match('/^https?/i', $comment['website_url']))
339    {
340      $comment['website_url'] = 'http://'.$comment['website_url'];
341    }
342    if (!url_check_format($comment['website_url']))
343    {
344      $page['errors'][] = l10n('Your website URL is invalid');
345      $comment_action='reject';
346    }
347  }
348
349  if ( $comment_action!='reject' )
350  {
351    $user_where_clause = '';
352    if (!is_admin())
353    {
354      $user_where_clause = '   AND author_id = \''.
355        $GLOBALS['user']['id'].'\'';
356    }
357
358    $query = '
359UPDATE '.COMMENTS_TABLE.'
360  SET content = \''.$comment['content'].'\',
361      website_url = '.(!empty($comment['website_url']) ? '\''.$comment['website_url'].'\'' : 'NULL').',
362      validated = \''.($comment_action=='validate' ? 'true':'false').'\',
363      validation_date = '.($comment_action=='validate' ? 'NOW()':'NULL').'
364  WHERE id = '.$comment['comment_id'].
365$user_where_clause.'
366;';
367    $result = pwg_query($query);
368   
369    // mail admin and ask to validate the comment
370    if ($result and $conf['email_admin_on_comment_validation'] and 'moderate' == $comment_action) 
371    {
372      include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
373
374      $comment_url = get_absolute_root_url().'comments.php?comment_id='.$comment['comment_id'];
375
376      $keyargs_content = array(
377        get_l10n_args('Author: %s', stripslashes($GLOBALS['user']['username']) ),
378        get_l10n_args('Comment: %s', stripslashes($comment['content']) ),
379        get_l10n_args(''),
380        get_l10n_args('Manage this user comment: %s', $comment_url),
381        get_l10n_args('(!) This comment requires validation'),
382      );
383
384      pwg_mail_notification_admins(
385        get_l10n_args('Comment by %s', stripslashes($GLOBALS['user']['username']) ),
386        $keyargs_content
387      );
388    }
389    // just mail admin
390    elseif ($result)
391    {
392      email_admin('edit', array('author' => $GLOBALS['user']['username'],
393                                'content' => stripslashes($comment['content'])) );
394    }
395  }
396 
397  return $comment_action;
398}
399
400function email_admin($action, $comment)
401{
402  global $conf;
403
404  if (!in_array($action, array('edit', 'delete'))
405      or (($action=='edit') and !$conf['email_admin_on_comment_edition'])
406      or (($action=='delete') and !$conf['email_admin_on_comment_deletion']))
407  {
408    return;
409  }
410
411  include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
412
413  $keyargs_content = array(
414    get_l10n_args('Author: %s', $comment['author']),
415    );
416
417  if ($action=='delete')
418  {
419    $keyargs_content[] = get_l10n_args('This author removed the comment with id %d', $comment['comment_id']);
420  }
421  else
422  {
423    $keyargs_content[] = get_l10n_args('This author modified following comment:');
424    $keyargs_content[] = get_l10n_args('Comment: %s', $comment['content']);
425  }
426
427  pwg_mail_notification_admins(
428    get_l10n_args('Comment by %s', $comment['author']),
429    $keyargs_content
430    );
431}
432
433function get_comment_author_id($comment_id, $die_on_error=true)
434{
435  $query = '
436SELECT
437    author_id
438  FROM '.COMMENTS_TABLE.'
439  WHERE id = '.$comment_id.'
440;';
441  $result = pwg_query($query);
442  if (pwg_db_num_rows($result) == 0)
443  {
444    if ($die_on_error)
445    {
446      fatal_error('Unknown comment identifier');
447    }
448    else
449    {
450      return false;
451    }
452  }
453 
454  list($author_id) = pwg_db_fetch_row($result);
455
456  return $author_id;
457}
458
459/**
460 * Tries to validate a user comment in the database
461 * @param int or array of int comment_id
462 */
463function validate_user_comment($comment_id)
464{
465  if (is_array($comment_id))
466    $where_clause = 'id IN('.implode(',', $comment_id).')';
467  else
468    $where_clause = 'id = '.$comment_id;
469   
470  $query = '
471UPDATE '.COMMENTS_TABLE.'
472  SET validated = \'true\'
473    , validation_date = NOW()
474  WHERE '.$where_clause.'
475;';
476  pwg_query($query);
477 
478  invalidate_user_cache_nb_comments();
479  trigger_action('user_comment_validation', $comment_id);
480}
481
482
483function invalidate_user_cache_nb_comments()
484{
485  global $user;
486  unset($user['nb_available_comments']);
487  $query = '
488UPDATE '.USER_CACHE_TABLE.'
489  SET nb_available_comments = NULL';
490  pwg_query($query);
491}
492
493?>
Note: See TracBrowser for help on using the repository browser.