aboutsummaryrefslogtreecommitdiffstats
path: root/include/functions_comment.inc.php
blob: 344a56335f3c43bdc62ba908cfd488d65daa8148 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
<?php
// +-----------------------------------------------------------------------+
// | Piwigo - a PHP based photo gallery                                    |
// +-----------------------------------------------------------------------+
// | Copyright(C) 2008-2013 Piwigo Team                  http://piwigo.org |
// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
// +-----------------------------------------------------------------------+
// | This program is free software; you can redistribute it and/or modify  |
// | it under the terms of the GNU General Public License as published by  |
// | the Free Software Foundation                                          |
// |                                                                       |
// | This program is distributed in the hope that it will be useful, but   |
// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
// | General Public License for more details.                              |
// |                                                                       |
// | You should have received a copy of the GNU General Public License     |
// | along with this program; if not, write to the Free Software           |
// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
// | USA.                                                                  |
// +-----------------------------------------------------------------------+

//returns string action to perform on a new comment: validate, moderate, reject
function user_comment_check($action, $comment)
{
  global $conf,$user;

  if ($action=='reject')
    return $action;

  $my_action = $conf['comment_spam_reject'] ? 'reject':'moderate';

  if ($action==$my_action)
    return $action;

  // we do here only BASIC spam check (plugins can do more)
  if ( !is_a_guest() )
    return $action;

  $link_count = preg_match_all( '/https?:\/\//',
    $comment['content'], $matches);

  if ( strpos($comment['author'], 'http://')!==false )
  {
    $link_count++;
  }

  if ( $link_count>$conf['comment_spam_max_links'] )
  {
    $_POST['cr'][] = 'links';
    return $my_action;
  }
  return $action;
}


add_event_handler('user_comment_check', 'user_comment_check',
  EVENT_HANDLER_PRIORITY_NEUTRAL, 2);

/**
 * Tries to insert a user comment in the database and returns one of :
 * validate, moderate, reject
 * @param array comm contains author, content, image_id
 * @param string key secret key sent back to the browser
 * @param array infos out array of messages
 */
function insert_user_comment( &$comm, $key, &$infos )
{
  global $conf, $user;

  $comm = array_merge( $comm,
    array(
      'ip' => $_SERVER['REMOTE_ADDR'],
      'agent' => $_SERVER['HTTP_USER_AGENT']
    )
   );

  $infos = array();
  if (!$conf['comments_validation'] or is_admin())
  {
    $comment_action='validate'; //one of validate, moderate, reject
  }
  else
  {
    $comment_action='moderate'; //one of validate, moderate, reject
  }

  // display author field if the user status is guest or generic
  if (!is_classic_user())
  {
    if ( empty($comm['author']) )
    {
      if ($conf['comments_author_mandatory'])
      {
        $infos[] = l10n('Username is mandatory');
        $comment_action='reject';
      }
      $comm['author'] = 'guest';
    }
    $comm['author_id'] = $conf['guest_id'];
    // if a guest try to use the name of an already existing user, he must be
    // rejected
    if ( $comm['author'] != 'guest' )
    {
      $query = '
SELECT COUNT(*) AS user_exists
  FROM '.USERS_TABLE.'
  WHERE '.$conf['user_fields']['username']." = '".addslashes($comm['author'])."'";
      $row = pwg_db_fetch_assoc( pwg_query( $query ) );
      if ( $row['user_exists'] == 1 )
      {
        $infos[] = l10n('This login is already used by another user');
        $comment_action='reject';
      }
    }
  }
  else
  {
    $comm['author'] = addslashes($user['username']);
    $comm['author_id'] = $user['id'];
  }

  if ( empty($comm['content']) )
  { // empty comment content
    $comment_action='reject';
  }

  if ( !verify_ephemeral_key(@$key, $comm['image_id']) )
  {
    $comment_action='reject';
    $_POST['cr'][] = 'key'; // rvelices: I use this outside to see how spam robots work
  }
  
  // website
  if (!empty($comm['website_url']))
  {
    if (!preg_match('/^https?/i', $comm['website_url']))
    {
      $comm['website_url'] = 'http://'.$comm['website_url'];
    }
    if (!url_check_format($comm['website_url']))
    {
      $infos[] = l10n('Your website URL is invalid');
      $comment_action='reject';
    }
  }
  
  // email
  if (empty($comm['email']))
  {
    if (!empty($user['email']))
    {
      $comm['email'] = $user['email'];
    }
    else if ($conf['comments_email_mandatory'])
    {
      $infos[] = l10n('Email address is missing. Please specify an email address.');
      $comment_action='reject';
    }
  }
  else if (!email_check_format($comm['email']))
  {
    $infos[] = l10n('mail address must be like xxx@yyy.eee (example : jack@altern.org)');
    $comment_action='reject';
  }
  
  // anonymous id = ip address
  $ip_components = explode('.', $comm['ip']);
  if (count($ip_components) > 3)
  {
    array_pop($ip_components);
  }
  $comm['anonymous_id'] = implode('.', $ip_components);

  if ($comment_action!='reject' and $conf['anti-flood_time']>0 and !is_admin())
  { // anti-flood system
    $reference_date = pwg_db_get_flood_period_expression($conf['anti-flood_time']);

    $query = '
SELECT count(1) FROM '.COMMENTS_TABLE.'
  WHERE date > '.$reference_date.'
    AND author_id = '.$comm['author_id'];
    if (!is_classic_user())
    {
      $query.= '
      AND anonymous_id = "'.$comm['anonymous_id'].'"';
    }
    $query.= '
;';

    list($counter) = pwg_db_fetch_row(pwg_query($query));
    if ( $counter > 0 )
    {
      $infos[] = l10n('Anti-flood system : please wait for a moment before trying to post another comment');
      $comment_action='reject';
    }
  }

  // perform more spam check
  $comment_action = trigger_event('user_comment_check',
      $comment_action, $comm
    );

  if ( $comment_action!='reject' )
  {
    $query = '
INSERT INTO '.COMMENTS_TABLE.'
  (author, author_id, anonymous_id, content, date, validated, validation_date, image_id, website_url, email)
  VALUES (
    \''.$comm['author'].'\',
    '.$comm['author_id'].',
    \''.$comm['anonymous_id'].'\',
    \''.$comm['content'].'\',
    NOW(),
    \''.($comment_action=='validate' ? 'true':'false').'\',
    '.($comment_action=='validate' ? 'NOW()':'NULL').',
    '.$comm['image_id'].',
    '.(!empty($comm['website_url']) ? '\''.$comm['website_url'].'\'' : 'NULL').',
    '.(!empty($comm['email']) ? '\''.$comm['email'].'\'' : 'NULL').'
  )
';
    pwg_query($query);
    $comm['id'] = pwg_db_insert_id(COMMENTS_TABLE);

    invalidate_user_cache_nb_comments();

    if ( ($conf['email_admin_on_comment'] && 'validate' == $comment_action)
        or ($conf['email_admin_on_comment_validation'] and 'moderate' == $comment_action))
    {
      include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');

      $comment_url = get_absolute_root_url().'comments.php?comment_id='.$comm['id'];

      $content = array(
        l10n('Author: %s', stripslashes($comm['author']) ),
        l10n('Email: %s', stripslashes($comm['email']) ),
        l10n('Comment: %s', stripslashes($comm['content']) ),
        '',
        l10n('Manage this user comment: %s', $comment_url),
      );

      if ('moderate' == $comment_action)
      {
        $content[] = l10n('(!) This comment requires validation');
      }

      pwg_mail_notification_admins(
        l10n('Comment by %s', stripslashes($comm['author']) ),
        implode("\n", $content)
      );
    }
  }
  return $comment_action;
}

/**
 * Tries to delete a user comment in the database
 * only admin can delete all comments
 * other users can delete their own comments
 * so to avoid a new sql request we add author in where clause
 *
 * @param int or array of int comment_id
 */
function delete_user_comment($comment_id)
{
  $user_where_clause = '';
  if (!is_admin())
  {
    $user_where_clause = '   AND author_id = \''.$GLOBALS['user']['id'].'\'';
  }
  
  if (is_array($comment_id))
    $where_clause = 'id IN('.implode(',', $comment_id).')';
  else
    $where_clause = 'id = '.$comment_id;
    
  $query = '
DELETE FROM '.COMMENTS_TABLE.'
  WHERE '.$where_clause.
$user_where_clause.'
;';
  
  if ( pwg_db_changes(pwg_query($query)) )
  {
    invalidate_user_cache_nb_comments();

    email_admin('delete', 
                array('author' => $GLOBALS['user']['username'],
                      'comment_id' => $comment_id
                  ));
    trigger_action('user_comment_deletion', $comment_id);
  }
}

/**
 * Tries to update a user comment in the database
 * only admin can update all comments
 * users can edit their own comments if admin allow them
 * so to avoid a new sql request we add author in where clause
 *
 * @param comment_id
 * @param post_key
 * @param content
 */

function update_user_comment($comment, $post_key)
{
  global $conf, $page;

  $comment_action = 'validate';

  if ( !verify_ephemeral_key($post_key, $comment['image_id']) )
  {
    $comment_action='reject';
  }
  elseif (!$conf['comments_validation'] or is_admin()) // should the updated comment must be validated
  {
    $comment_action='validate'; //one of validate, moderate, reject
  }
  else
  {
    $comment_action='moderate'; //one of validate, moderate, reject
  }

  // perform more spam check
  $comment_action =
    trigger_event('user_comment_check',
		  $comment_action,
		  array_merge($comment,
			      array('author' => $GLOBALS['user']['username'])
			      )
		  );

  // website
  if (!empty($comment['website_url']))
  {
    if (!preg_match('/^https?/i', $comment['website_url']))
    {
      $comment['website_url'] = 'http://'.$comment['website_url'];
    }
    if (!url_check_format($comment['website_url']))
    {
      $page['errors'][] = l10n('Your website URL is invalid');
      $comment_action='reject';
    }
  }

  if ( $comment_action!='reject' )
  {
    $user_where_clause = '';
    if (!is_admin())
    {
      $user_where_clause = '   AND author_id = \''.
	$GLOBALS['user']['id'].'\'';
    }

    $query = '
UPDATE '.COMMENTS_TABLE.'
  SET content = \''.$comment['content'].'\',
      website_url = '.(!empty($comment['website_url']) ? '\''.$comment['website_url'].'\'' : 'NULL').',
      validated = \''.($comment_action=='validate' ? 'true':'false').'\',
      validation_date = '.($comment_action=='validate' ? 'NOW()':'NULL').'
  WHERE id = '.$comment['comment_id'].
$user_where_clause.'
;';
    $result = pwg_query($query);
    
    // mail admin and ask to validate the comment
    if ($result and $conf['email_admin_on_comment_validation'] and 'moderate' == $comment_action) 
    {
      include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');

      $comment_url = get_absolute_root_url().'comments.php?comment_id='.$comment['comment_id'];

      $content = array(
        l10n('Author: %s', stripslashes($GLOBALS['user']['username']) ),
        l10n('Comment: %s', stripslashes($comment['content']) ),
        '',
        l10n('Manage this user comment: %s', $comment_url),
        l10n('(!) This comment requires validation'),
      );

      pwg_mail_notification_admins(
        l10n('Comment by %s', stripslashes($GLOBALS['user']['username']) ),
        implode("\n", $content)
      );
    }
    // just mail admin
    elseif ($result)
    {
      email_admin('edit', array('author' => $GLOBALS['user']['username'],
				'content' => stripslashes($comment['content'])) );
    }
  }
  
  return $comment_action;
}

function email_admin($action, $comment)
{
  global $conf;

  if (!in_array($action, array('edit', 'delete'))
      or (($action=='edit') and !$conf['email_admin_on_comment_edition'])
      or (($action=='delete') and !$conf['email_admin_on_comment_deletion']))
  {
    return;
  }

  include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');

  $content = array(
    l10n('Author: %s', $comment['author']),
    );

  if ($action=='delete')
  {
    $content[] = l10n('This author removed the comment with id %d', $comment['comment_id']);
  }
  else
  {
    $content[] = l10n('This author modified following comment:');
    $content[] = l10n('Comment: %s', $comment['content']);
  }

  pwg_mail_notification_admins(
    l10n('Comment by %s', $comment['author']),
		implode("\n", $content)
		);
}

function get_comment_author_id($comment_id, $die_on_error=true)
{
  $query = '
SELECT
    author_id
  FROM '.COMMENTS_TABLE.'
  WHERE id = '.$comment_id.'
;';
  $result = pwg_query($query);
  if (pwg_db_num_rows($result) == 0)
  {
    if ($die_on_error)
    {
      fatal_error('Unknown comment identifier');
    }
    else
    {
      return false;
    }
  }
  
  list($author_id) = pwg_db_fetch_row($result);

  return $author_id;
}

/**
 * Tries to validate a user comment in the database
 * @param int or array of int comment_id
 */
function validate_user_comment($comment_id)
{
  if (is_array($comment_id))
    $where_clause = 'id IN('.implode(',', $comment_id).')';
  else
    $where_clause = 'id = '.$comment_id;
    
  $query = '
UPDATE '.COMMENTS_TABLE.'
  SET validated = \'true\'
    , validation_date = NOW()
  WHERE '.$where_clause.'
;';
  pwg_query($query);
  
  invalidate_user_cache_nb_comments();
  trigger_action('user_comment_validation', $comment_id);
}


function invalidate_user_cache_nb_comments()
{
  global $user;
  unset($user['nb_available_comments']);
  $query = '
UPDATE '.USER_CACHE_TABLE.'
  SET nb_available_comments = NULL';
  pwg_query($query);
}

?>