source: trunk/comments.php @ 25751

Last change on this file since 25751 was 25018, checked in by mistic100, 10 years ago

remove all array_push (50% slower than []) + some changes missing for feature:2978

  • Property svn:eol-style set to LF
File size: 17.6 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// +-----------------------------------------------------------------------+
25// |                           initialization                              |
26// +-----------------------------------------------------------------------+
27define('PHPWG_ROOT_PATH','./');
28include_once(PHPWG_ROOT_PATH.'include/common.inc.php');
29include_once(PHPWG_ROOT_PATH.'include/functions_comment.inc.php');
30
31if (!$conf['activate_comments'])
32{
33  page_not_found(null);
34}
35
36// +-----------------------------------------------------------------------+
37// | Check Access and exit when user status is not ok                      |
38// +-----------------------------------------------------------------------+
39check_status(ACCESS_GUEST);
40
41$sort_order = array(
42  'DESC' => l10n('descending'),
43  'ASC'  => l10n('ascending')
44  );
45
46// sort_by : database fields proposed for sorting comments list
47$sort_by = array(
48  'date' => l10n('comment date'),
49  'image_id' => l10n('photo')
50  );
51
52// items_number : list of number of items to display per page
53$items_number = array(5,10,20,50,'all');
54
55// if the default value is not in the expected values, we add it in the $items_number array
56if (!in_array($conf['comments_page_nb_comments'], $items_number))
57{
58  $items_number_new = array();
59
60  $is_inserted = false;
61
62  foreach ($items_number as $number)
63  {
64    if ($number > $conf['comments_page_nb_comments'] or ($number == 'all' and !$is_inserted))
65    {
66      $items_number_new[] = $conf['comments_page_nb_comments'];
67      $is_inserted = true;
68    }
69   
70    $items_number_new[] = $number;
71  }
72
73  $items_number = $items_number_new;
74}
75
76// since when display comments ?
77//
78$since_options = array(
79  1 => array('label' => l10n('today'),
80             'clause' => 'date > '.pwg_db_get_recent_period_expression(1)),
81  2 => array('label' => l10n('last %d days', 7),
82             'clause' => 'date > '.pwg_db_get_recent_period_expression(7)),
83  3 => array('label' => l10n('last %d days', 30),
84             'clause' => 'date > '.pwg_db_get_recent_period_expression(30)),
85  4 => array('label' => l10n('the beginning'),
86             'clause' => '1=1') // stupid but generic
87  );
88 
89trigger_action('loc_begin_comments');
90
91if (!empty($_GET['since']) && is_numeric($_GET['since']))
92{
93  $page['since'] = $_GET['since'];
94}
95else
96{
97  $page['since'] = 4;
98}
99
100// on which field sorting
101//
102$page['sort_by'] = 'date';
103// if the form was submitted, it overloads default behaviour
104if (isset($_GET['sort_by']) and isset($sort_by[$_GET['sort_by']]) )
105{
106  $page['sort_by'] = $_GET['sort_by'];
107}
108
109// order to sort
110//
111$page['sort_order'] = 'DESC';
112// if the form was submitted, it overloads default behaviour
113if (isset($_GET['sort_order']) and isset($sort_order[$_GET['sort_order']]))
114{
115  $page['sort_order'] = $_GET['sort_order'];
116}
117
118// number of items to display
119//
120$page['items_number'] = $conf['comments_page_nb_comments'];
121if (isset($_GET['items_number']))
122{
123  $page['items_number'] = $_GET['items_number'];
124}
125if ( !is_numeric($page['items_number']) and $page['items_number']!='all' )
126{
127  $page['items_number'] = 10;
128}
129
130$page['where_clauses'] = array();
131
132// which category to filter on ?
133if (isset($_GET['cat']) and 0 != $_GET['cat'])
134{
135  check_input_parameter('cat', $_GET, false, PATTERN_ID);
136
137  $category_ids = get_subcat_ids(array($_GET['cat']));
138  if (empty($category_ids))
139  {
140    $category_ids = array(-1);
141  }
142
143  $page['where_clauses'][] =
144    'category_id IN ('.implode(',', $category_ids).')';
145}
146
147// search a particular author
148if (!empty($_GET['author']))
149{
150  $page['where_clauses'][] =
151    '(u.'.$conf['user_fields']['username'].' = \''.$_GET['author'].'\' OR author = \''.$_GET['author'].'\')';
152}
153
154// search a specific comment (if you're coming directly from an admin
155// notification email)
156if (!empty($_GET['comment_id']))
157{
158  check_input_parameter('comment_id', $_GET, false, PATTERN_ID);
159
160  // currently, the $_GET['comment_id'] is only used by admins from email
161  // for management purpose (validate/delete)
162  if (!is_admin())
163  {
164    $login_url =
165      get_root_url().'identification.php?redirect='
166      .urlencode(urlencode($_SERVER['REQUEST_URI']))
167      ;
168    redirect($login_url);
169  }
170
171  $page['where_clauses'][] = 'com.id = '.$_GET['comment_id'];
172}
173
174// search a substring among comments content
175if (!empty($_GET['keyword']))
176{
177  $page['where_clauses'][] =
178    '('.
179    implode(' AND ',
180            array_map(
181              create_function(
182                '$s',
183                'return "content LIKE \'%$s%\'";'
184                ),
185              preg_split('/[\s,;]+/', $_GET['keyword'] )
186              )
187      ).
188    ')';
189}
190
191$page['where_clauses'][] = $since_options[$page['since']]['clause'];
192
193// which status to filter on ?
194if ( !is_admin() )
195{
196  $page['where_clauses'][] = 'validated=\'true\'';
197}
198
199$page['where_clauses'][] = get_sql_condition_FandF
200  (
201    array
202      (
203        'forbidden_categories' => 'category_id',
204        'visible_categories' => 'category_id',
205        'visible_images' => 'ic.image_id'
206      ),
207    '', true
208  );
209
210// +-----------------------------------------------------------------------+
211// |                         comments management                           |
212// +-----------------------------------------------------------------------+
213
214$comment_id = null;
215$action = null;
216
217$actions = array('delete', 'validate', 'edit');
218foreach ($actions as $loop_action)
219{
220  if (isset($_GET[$loop_action]))
221  {
222    $action = $loop_action;
223    check_input_parameter($action, $_GET, false, PATTERN_ID);
224    $comment_id = $_GET[$action];
225    break;
226  }
227}
228
229if (isset($action))
230{
231  $comment_author_id = get_comment_author_id($comment_id);
232
233  if (can_manage_comment($action, $comment_author_id))
234  {
235    $perform_redirect = false;
236
237    if ('delete' == $action)
238    {
239      check_pwg_token();
240      delete_user_comment($comment_id);
241      $perform_redirect = true;
242    }
243
244    if ('validate' == $action)
245    {
246      check_pwg_token();
247      validate_user_comment($comment_id);
248      $perform_redirect = true;
249    }
250
251    if ('edit' == $action)
252    {
253      if (!empty($_POST['content']))
254      {
255        check_pwg_token();
256        $comment_action = update_user_comment(
257          array(
258            'comment_id' => $_GET['edit'],
259            'image_id' => $_POST['image_id'],
260            'content' => $_POST['content'],
261            'website_url' => @$_POST['website_url'],
262            ),
263          $_POST['key']
264          );
265       
266        switch ($comment_action)
267        {
268          case 'moderate':
269            $_SESSION['page_infos'][] = l10n('An administrator must authorize your comment before it is visible.');
270          case 'validate':
271            $_SESSION['page_infos'][] = l10n('Your comment has been registered');
272            $perform_redirect = true;
273            break;
274          case 'reject':
275            $_SESSION['page_errors'][] = l10n('Your comment has NOT been registered because it did not pass the validation rules');
276            break;
277          default:
278            trigger_error('Invalid comment action '.$comment_action, E_USER_WARNING);
279        }
280      }
281     
282      $edit_comment = $_GET['edit'];
283    }
284
285    if ($perform_redirect)
286    {
287      $redirect_url =
288        PHPWG_ROOT_PATH
289        .'comments.php'
290        .get_query_string_diff(array('delete','edit','validate','pwg_token'));
291
292      redirect($redirect_url);
293    }
294  }
295}
296
297// +-----------------------------------------------------------------------+
298// |                       page header and options                         |
299// +-----------------------------------------------------------------------+
300
301$title= l10n('User comments');
302$page['body_id'] = 'theCommentsPage';
303
304$template->set_filenames(array('comments'=>'comments.tpl'));
305$template->assign(
306  array(
307    'F_ACTION'=>PHPWG_ROOT_PATH.'comments.php',
308    'F_KEYWORD'=> @htmlspecialchars(stripslashes($_GET['keyword'], ENT_QUOTES, 'utf-8')),
309    'F_AUTHOR'=> @htmlspecialchars(stripslashes($_GET['author'], ENT_QUOTES, 'utf-8')),
310    )
311  );
312
313// +-----------------------------------------------------------------------+
314// |                          form construction                            |
315// +-----------------------------------------------------------------------+
316
317// Search in a particular category
318$blockname = 'categories';
319
320$query = '
321SELECT id, name, uppercats, global_rank
322  FROM '.CATEGORIES_TABLE.'
323'.get_sql_condition_FandF
324  (
325    array
326      (
327        'forbidden_categories' => 'id',
328        'visible_categories' => 'id'
329      ),
330    'WHERE'
331  ).'
332;';
333display_select_cat_wrapper($query, array(@$_GET['cat']), $blockname, true);
334
335// Filter on recent comments...
336$tpl_var=array();
337foreach ($since_options as $id => $option)
338{
339  $tpl_var[ $id ] = $option['label'];
340}
341$template->assign( 'since_options', $tpl_var);
342$template->assign( 'since_options_selected', $page['since']);
343
344// Sort by
345$template->assign( 'sort_by_options', $sort_by);
346$template->assign( 'sort_by_options_selected', $page['sort_by']);
347
348// Sorting order
349$template->assign( 'sort_order_options', $sort_order);
350$template->assign( 'sort_order_options_selected', $page['sort_order']);
351
352
353// Number of items
354$blockname = 'items_number_option';
355$tpl_var=array();
356foreach ($items_number as $option)
357{
358  $tpl_var[ $option ] = is_numeric($option) ? $option : l10n($option);
359}
360$template->assign( 'item_number_options', $tpl_var);
361$template->assign( 'item_number_options_selected', $page['items_number']);
362
363
364// +-----------------------------------------------------------------------+
365// |                            navigation bar                             |
366// +-----------------------------------------------------------------------+
367
368if (isset($_GET['start']) and is_numeric($_GET['start']))
369{
370  $start = $_GET['start'];
371}
372else
373{
374  $start = 0;
375}
376
377$query = '
378SELECT COUNT(DISTINCT(com.id))
379  FROM '.IMAGE_CATEGORY_TABLE.' AS ic
380    INNER JOIN '.COMMENTS_TABLE.' AS com
381    ON ic.image_id = com.image_id
382    LEFT JOIN '.USERS_TABLE.' As u
383    ON u.'.$conf['user_fields']['id'].' = com.author_id
384  WHERE '.implode('
385    AND ', $page['where_clauses']).'
386;';
387list($counter) = pwg_db_fetch_row(pwg_query($query));
388
389$url = PHPWG_ROOT_PATH
390    .'comments.php'
391  .get_query_string_diff(array('start','delete','validate','pwg_token'));
392
393$navbar = create_navigation_bar($url,
394                                $counter,
395                                $start,
396                                $page['items_number'],
397                                '');
398
399$template->assign('navbar', $navbar);
400
401$url_self = PHPWG_ROOT_PATH
402    .'comments.php'
403  .get_query_string_diff(array('edit','delete','validate','pwg_token'));
404
405// +-----------------------------------------------------------------------+
406// |                        last comments display                          |
407// +-----------------------------------------------------------------------+
408
409$comments = array();
410$element_ids = array();
411$category_ids = array();
412
413$query = '
414SELECT com.id AS comment_id,
415       com.image_id,
416       com.author,
417       com.author_id,
418       u.'.$conf['user_fields']['email'].' AS user_email,
419       com.email,
420       com.date,
421       com.website_url,
422       com.content,
423       com.validated
424  FROM '.IMAGE_CATEGORY_TABLE.' AS ic
425    INNER JOIN '.COMMENTS_TABLE.' AS com
426    ON ic.image_id = com.image_id
427    LEFT JOIN '.USERS_TABLE.' As u
428    ON u.'.$conf['user_fields']['id'].' = com.author_id
429  WHERE '.implode('
430    AND ', $page['where_clauses']).'
431  GROUP BY comment_id,
432       com.image_id,
433       com.author,
434       com.author_id,
435       com.date,
436       com.content,
437       com.validated
438  ORDER BY '.$page['sort_by'].' '.$page['sort_order'];
439if ('all' != $page['items_number'])
440{
441  $query.= '
442  LIMIT '.$page['items_number'].' OFFSET '.$start;
443}
444$query.= '
445;';
446$result = pwg_query($query);
447while ($row = pwg_db_fetch_assoc($result))
448{
449  $comments[] = $row;
450  $element_ids[] = $row['image_id'];
451}
452
453if (count($comments) > 0)
454{
455  // retrieving element informations
456  $elements = array();
457  $query = '
458SELECT *
459  FROM '.IMAGES_TABLE.'
460  WHERE id IN ('.implode(',', $element_ids).')
461;';
462  $result = pwg_query($query);
463  while ($row = pwg_db_fetch_assoc($result))
464  {
465    $elements[$row['id']] = $row;
466  }
467
468  // retrieving category informations
469  $query = '
470SELECT c.id, name, permalink, uppercats, com.id as comment_id
471  FROM '.CATEGORIES_TABLE.' AS c
472  LEFT JOIN '.IMAGE_CATEGORY_TABLE.' AS ic
473  ON c.id=ic.category_id
474  LEFT JOIN '.COMMENTS_TABLE.' AS com
475  ON ic.image_id=com.image_id
476  '.get_sql_condition_FandF
477    (
478      array
479      (
480        'forbidden_categories' => 'c.id',
481        'visible_categories' => 'c.id'
482       ),
483      'WHERE'
484     ).'
485;';
486  $categories = hash_from_query($query, 'comment_id');
487
488  foreach ($comments as $comment)
489  {
490    if (!empty($elements[$comment['image_id']]['name']))
491    {
492      $name=$elements[$comment['image_id']]['name'];
493    }
494    else
495    {
496      $name=get_name_from_file($elements[$comment['image_id']]['file']);
497    }
498
499    // source of the thumbnail picture
500    $src_image = new SrcImage($elements[$comment['image_id']]);
501
502    // link to the full size picture
503    $url = make_picture_url(
504      array(
505        'category' => $categories[ $comment['comment_id'] ],
506        'image_id' => $comment['image_id'],
507        'image_file' => $elements[$comment['image_id']]['file'],
508        )
509      );
510     
511    $email = null;
512    if (!empty($comment['user_email']))
513    {
514      $email = $comment['user_email'];
515    }
516    else if (!empty($comment['email']))
517    {
518      $email = $comment['email'];
519    }
520
521    $tpl_comment = array(
522      'ID' => $comment['comment_id'],
523      'U_PICTURE' => $url,
524      'src_image' => $src_image,
525      'ALT' => $name,
526      'AUTHOR' => trigger_event('render_comment_author', $comment['author']),
527      'WEBSITE_URL' => $comment['website_url'],
528      'DATE'=>format_date($comment['date'], true),
529      'CONTENT'=>trigger_event('render_comment_content',$comment['content']),
530      );
531     
532    if (is_admin())
533    {
534      $tpl_comment['EMAIL'] = $email;
535    }
536
537    if (can_manage_comment('delete', $comment['author_id']))
538    {
539      $url =
540        get_root_url()
541        .'comments.php'
542        .get_query_string_diff(array('delete','validate','edit', 'pwg_token'));
543
544      $tpl_comment['U_DELETE'] = add_url_params(
545        $url,
546        array(
547          'delete' => $comment['comment_id'],
548          'pwg_token' => get_pwg_token(),
549          )
550        );
551    }
552
553    if (can_manage_comment('edit', $comment['author_id']))
554    {
555      $url =
556        get_root_url()
557        .'comments.php'
558        .get_query_string_diff(array('edit', 'delete','validate', 'pwg_token'));
559
560      $tpl_comment['U_EDIT'] = add_url_params(
561        $url,
562        array(
563          'edit' => $comment['comment_id']
564          )
565        );
566
567      if (isset($edit_comment) and ($comment['comment_id'] == $edit_comment))
568      {
569        $tpl_comment['IN_EDIT'] = true;
570        $key = get_ephemeral_key(2, $comment['image_id']);
571        $tpl_comment['KEY'] = $key;
572        $tpl_comment['IMAGE_ID'] = $comment['image_id'];
573        $tpl_comment['CONTENT'] = $comment['content'];
574        $tpl_comment['PWG_TOKEN'] = get_pwg_token();
575        $tpl_comment['U_CANCEL'] = $url_self;
576      }
577    }
578
579    if (can_manage_comment('validate', $comment['author_id']))
580    {
581      if ('true' != $comment['validated'])
582      {
583        $tpl_comment['U_VALIDATE'] = add_url_params(
584          $url,
585          array(
586            'validate'=> $comment['comment_id'],
587            'pwg_token' => get_pwg_token(),
588            )
589          );
590      }
591    }
592    $template->append('comments', $tpl_comment);
593  }
594}
595
596$derivative_params = trigger_event('get_comments_derivative_params', ImageStdParams::get_by_type(IMG_THUMB) );
597$template->assign( 'derivative_params', $derivative_params );
598
599// include menubar
600$themeconf = $template->get_template_vars('themeconf');
601if (!isset($themeconf['hide_menu_on']) OR !in_array('theCommentsPage', $themeconf['hide_menu_on']))
602{
603  include( PHPWG_ROOT_PATH.'include/menubar.inc.php');
604}
605
606// +-----------------------------------------------------------------------+
607// |                           html code display                           |
608// +-----------------------------------------------------------------------+
609include(PHPWG_ROOT_PATH.'include/page_header.php');
610trigger_action('loc_end_comments');
611flush_page_messages();
612$template->pparse('comments');
613include(PHPWG_ROOT_PATH.'include/page_tail.php');
614?>
Note: See TracBrowser for help on using the repository browser.