source: extensions/Subscribe_to_comments/include/functions.inc.php @ 26139

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

update for 2.6

File size: 16.0 KB
Line 
1<?php
2defined('SUBSCRIBE_TO_PATH') or die('Hacking attempt!');
3
4/**
5 * Send comment to subscribers
6 * @param: array comment (author, content, image_id|category_id)
7 */
8function send_comment_to_subscribers($comm)
9{
10  if (empty($comm) or !is_array($comm))
11  {
12    trigger_error('send_comment_to_subscribers: undefined comm', E_USER_WARNING);
13    return false;
14  }
15
16  global $conf, $page, $user, $template;
17
18  // create search clauses
19  $where_clauses = array();
20  if (isset($comm['image_id']))
21  {
22    $element_id = $comm['image_id'];
23    $element_type = 'image';
24
25    $where_clauses[] = '(type = "image" AND element_id = '.$element_id.')';
26    $where_clauses[] = 'type = "all-images"';
27    if (!empty($page['category']['id']))
28    {
29      $where_clauses[] = '(type = "album-images" AND element_id = '.$page['category']['id'].')';
30    }
31  }
32  else if (isset($comm['category_id']))
33  {
34    $element_id = $comm['category_id'];
35    $element_type = 'category';
36
37    $where_clauses[] = '(type = "album" AND element_id = '.$element_id.')';
38    $where_clauses[] = 'type = "all-albums"';
39  }
40  else
41  {
42    return;
43  }
44
45  // exclude current user
46  $exclude = null;
47  if (!empty($_POST['stc_mail']))
48  {
49    $exclude = pwg_db_real_escape_string($_POST['stc_mail']);
50  }
51  else if (!is_a_guest())
52  {
53    $exclude = $user['email'];
54  }
55
56  // get subscribers datas
57  $query = '
58SELECT
59    id,
60    email,
61    language
62  FROM '.SUBSCRIBE_TO_TABLE.'
63  WHERE (
64      '.implode("\n      OR ", $where_clauses).'
65    )
66    AND validated = true
67    AND email != "'.$exclude.'"
68  GROUP BY email
69';
70  $subscriptions = query2array($query);
71
72  if (count($subscriptions)==0)
73  {
74    return;
75  }
76
77  set_make_full_url();
78
79  // get element infos
80  if ($element_type == 'image')
81  {
82    $element = get_picture_infos($comm['image_id']);
83  }
84  else
85  {
86    $element = get_category_infos($comm['category_id']);
87  }
88
89  // format comment
90  if ($comm['author'] == 'guest')
91  {
92    $comm['author'] = l10n('guest');
93  }
94
95  $comm['author'] = trigger_event('render_comment_author', $comm['author']);
96  $comm['content'] = trigger_event('render_comment_content', $comm['content']);
97
98  include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
99
100  foreach ($subscriptions as $row)
101  {
102    // get subscriber id
103    if ( ($uid = get_userid_by_email($row['email'])) !== false )
104    {
105      $row['user_id'] = $uid;
106    }
107    else
108    {
109      $row['user_id'] = $conf['guest_id'];
110    }
111
112    // check permissions
113    if (!user_can_view_element($row['user_id'], $element_id, $element_type))
114    {
115      continue;
116    }
117
118    switch_lang_to($language);
119
120    $comm['date'] = format_date(date('Y-m-d H:i:s'));
121
122    pwg_mail(
123      $row['email'],
124      array(
125        'subject' => '['.strip_tags($conf['gallery_title']).'] Re:'.$element['name'],
126        ),
127      array(
128        'filename' => 'notification',
129        'dirname' => SUBSCRIBE_TO_PATH . 'template',
130        'assign' => array(
131          'ELEMENT' => $element,
132          'COMMENT' => $comm,
133          'UNSUB_URL' => make_stc_url('unsubscribe', $row['email'], $row['id']),
134          'MANAGE_URL' => make_stc_url('manage', $row['email']),
135          ),
136        )
137      );
138
139    switch_lang_back();
140  }
141
142  load_language('plugin.lang', SUBSCRIBE_TO_PATH);
143  unset_make_full_url();
144}
145
146
147/**
148 * add an email to subscribers list
149 * @param: string email
150 * @param: string type (image|album-images|all-images|album|all-albums)
151 * @param: int element_id
152 * @return: bool
153 */
154function subscribe_to_comments($email, $type, $element_id='NULL')
155{
156  if (empty($type))
157  {
158    trigger_error('subscribe_to_comment: missing type', E_USER_WARNING);
159    return false;
160  }
161
162  if (!in_array($type, array('all-images','all-albums')) and $element_id == 'NULL')
163  {
164    trigger_error('subscribe_to_comment: missing element_id', E_USER_WARNING);
165    return false;
166  }
167
168  global $page, $conf, $user, $template, $picture;
169
170  // check email
171  if (!empty($email) and !email_check_format($email))
172  {
173    $page['errors'][] = l10n('mail address must be like xxx@yyy.eee (example : jack@altern.org)');
174    return false;
175  }
176  if ( (is_a_guest() or empty($user['email'])) and empty($email) )
177  {
178    $page['errors'][] = l10n('Invalid email address, your are not subscribed to comments.');
179    return false;
180  }
181  else if (!is_a_guest() and empty($email))
182  {
183    $email = $user['email'];
184  }
185
186  // search if already registered
187  $query = '
188SELECT id
189  FROM '.SUBSCRIBE_TO_TABLE.'
190  WHERE
191    type = "'.$type.'"
192    AND element_id = '.$element_id.'
193    AND email = "'.pwg_db_real_escape_string($email).'"
194;';
195  $result = pwg_query($query);
196
197  if (pwg_db_num_rows($result))
198  {
199    return false;
200  }
201
202  $query = '
203INSERT INTO '.SUBSCRIBE_TO_TABLE.'(
204    type,
205    element_id,
206    language,
207    email,
208    registration_date,
209    validated
210  )
211  VALUES(
212    "'.$type.'",
213    '.$element_id.',
214    "'.$user['language'].'",
215    "'.pwg_db_real_escape_string($email).'",
216    NOW(),
217    "'.(is_a_guest() ? "false" : "true").'"
218  )
219;';
220  pwg_query($query);
221
222  $stc_id = pwg_db_insert_id();
223
224  include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
225
226  set_make_full_url();
227
228  if (!is_a_guest() or $conf['Subscribe_to_Comments']['notify_admin_on_subscribe'])
229  {
230    switch ($type)
231    {
232      case 'image':
233        $element = get_picture_infos($element_id);
234        $element['on'] = l10n('the picture <a href="%s">%s</a>', $element['url'], $element['name']);
235        break;
236      case 'album-images':
237        $element = get_category_infos($element_id);
238        $element['on'] = l10n('all pictures of the album <a href="%s">%s</a>', $element['url'], $element['name']);
239        break;
240      case 'all-images':
241        $element['thumbnail'] = null;
242        $element['on'] = l10n('all pictures of the gallery');
243        break;
244      case 'album':
245        $element = get_category_infos($element_id);
246        $element['on'] = l10n('the album <a href="%s">%s</a>', $element['url'], $element['name']);
247        break;
248      case 'all-albums':
249        $element['thumbnail'] = null;
250        $element['on'] = l10n('all albums of the gallery');
251        break;
252    }
253  }
254
255  // send validation mail
256  if (is_a_guest())
257  {
258    pwg_mail(
259      $email,
260      array(
261        'subject' => '['.strip_tags($conf['gallery_title']).'] '.l10n('Confirm your subscription to comments'),
262        ),
263      array(
264        'filename' => 'confirm',
265        'dirname' => SUBSCRIBE_TO_PATH . 'template',
266        'assign' => array(
267          'ELEMENT' => $element,
268          'VALIDATE_URL' => make_stc_url('validate', $email, $stc_id),
269          'MANAGE_URL' => make_stc_url('manage', $email),
270          ),
271        )
272      );
273
274    $page['infos'][] = l10n('Please check your email in-box to confirm your subscription.');
275  }
276  // just display confirmation message
277  else
278  {
279    $page['infos'][] = l10n('You have been added to the list of subscribers.');
280  }
281
282  // notify admins
283  if ($conf['Subscribe_to_Comments']['notify_admin_on_subscribe'])
284  {
285    $keyargs_content = array(
286      get_l10n_args('Hi administrators,'),
287      get_l10n_args(''),
288      get_l10n_args('%s has subscribed to comments on %s.', array($email, $element['on'])),
289      get_l10n_args('', ''),
290      get_l10n_args('Connected user: %s', stripslashes($user['username'])),
291      get_l10n_args('IP: %s', $_SERVER['REMOTE_ADDR']),
292      get_l10n_args('Browser: %s', $_SERVER['HTTP_USER_AGENT']),
293      );
294
295    pwg_mail_notification_admins(
296      get_l10n_args('%s has subscribed to comments on %s.', array($email, '')),
297      $keyargs_content
298      );
299  }
300
301  unset_make_full_url();
302
303  return true;
304}
305
306
307/**
308 * remove an email from subscribers list
309 * @param: string email
310 * @param: int subscription id
311 * @return: bool
312 */
313function un_subscribe_to_comments($email, $ids)
314{
315  if (!empty($email) and !email_check_format($email))
316  {
317    trigger_error('un_subscribe_to_comment: bad email', E_USER_WARNING);
318    return false;
319  }
320  if (empty($ids))
321  {
322    trigger_error('un_subscribe_to_comment: bad id', E_USER_WARNING);
323    return false;
324  }
325
326  global $user;
327
328  // check email
329  if ( (is_a_guest() or empty($user['email'])) and empty($email) )
330  {
331    return false;
332  }
333  else if (!is_a_guest() and empty($email))
334  {
335    $email = $user['email'];
336  }
337
338  if (!is_array($ids))
339  {
340    $ids = array($ids);
341  }
342  $ids = array_map('intval', $ids);
343
344  // delete subscription
345  $query = '
346DELETE FROM '.SUBSCRIBE_TO_TABLE.'
347  WHERE
348    email = "'.pwg_db_real_escape_string($email).'"
349    AND id IN('. implode(',', $ids) .')
350;';
351  pwg_query($query);
352
353  return (pwg_db_changes() != 0);
354}
355
356
357/**
358 * validate a subscription
359 * @param: string email
360 * @param: int subscription id
361 * @return: bool
362 */
363function validate_subscriptions($email, $ids)
364{
365  if (!email_check_format($email))
366  {
367    trigger_error('validate_subscriptions: bad email', E_USER_WARNING);
368    return false;
369  }
370  if (empty($ids))
371  {
372    trigger_error('validate_subscriptions: bad id', E_USER_WARNING);
373    return false;
374  }
375
376  if (!is_array($ids))
377  {
378    $ids = array($ids);
379  }
380  $ids = array_map('intval', $ids);
381
382  $query = '
383UPDATE '.SUBSCRIBE_TO_TABLE.'
384  SET validated = "true"
385  WHERE
386    email = "'.pwg_db_real_escape_string($email).'"
387    AND id IN('. implode(',', $ids) .')
388;';
389  pwg_query($query);
390
391  return (pwg_db_changes() != 0);
392}
393
394
395/**
396 * create absolute url to subscriptions section
397 * @param: string action
398 * @param: string email
399 * @param: int optional
400 * @return: string
401 */
402function make_stc_url($action, $email, $id=null)
403{
404  if (empty($action) or empty($email))
405  {
406    trigger_error('make_stc_url: missing action and/or mail', E_USER_WARNING);
407    return null;
408  }
409
410  global $conf;
411  set_make_full_url();
412
413  $url_params = compact('action', 'email');
414  if (!empty($id))
415  {
416    $url_params['id'] = $id;
417  }
418
419  $url_params['key'] = crypt_value(
420    $action.$email.$id,
421    $conf['secret_key']
422    );
423
424  $url = add_url_params(
425    make_index_url(array('section' => 'subscriptions')),
426    $url_params
427    );
428
429  unset_make_full_url();
430  return $url;
431}
432
433
434/**
435 * get name, url and thumbnail of a picture
436 * @param: int image_id
437 * @param: bool return thumbnail
438 * @return: array (id, name, url, thumbnail)
439 */
440function get_picture_infos($image_id, $with_thumb=true)
441{
442  if (empty($image_id))
443  {
444    return array();
445  }
446
447  $query = '
448SELECT
449    id,
450    file,
451    name,
452    path
453  FROM '.IMAGES_TABLE.'
454  WHERE id = '.$image_id.'
455;';
456  $element = pwg_db_fetch_assoc(pwg_query($query));
457
458  if (empty($element['name']))
459  {
460    $element['name'] = get_name_from_file($element['file']);
461  }
462  $element['name'] = trigger_event('render_element_name', $element['name']);
463
464  $element['url'] = make_picture_url(array(
465    'image_id'=>$element['id']
466    ));
467
468  if ($with_thumb)
469  {
470    $element['thumbnail'] = DerivativeImage::thumb_url($element);
471  }
472
473  return $element;
474}
475
476/**
477 * get name, url and thumbnail of a category
478 * @param: int cat_id
479 * @param: int return thumbnail
480 * @return: array (id, name, url, thumbnail)
481 */
482function get_category_infos($cat_id, $with_thumb=true, $user_id=null)
483{
484  global $conf;
485
486  if ($user_id===null)
487  {
488    $user_id = $conf['guest_id'];
489  }
490
491  $query = '
492SELECT
493    cat.id,
494    cat.name,
495    cat.permalink,
496    ucc.count_images,
497    cat.uppercats,
498    img.id AS image_id,
499    img.path
500  FROM '.CATEGORIES_TABLE.' AS cat
501    LEFT JOIN '.USER_CACHE_CATEGORIES_TABLE.' AS ucc
502      ON ucc.cat_id = cat.id AND ucc.user_id = '.$user_id.'
503    LEFT JOIN '.IMAGES_TABLE.' AS img
504      ON img.id = ucc.user_representative_picture_id
505  WHERE cat.id = '.$cat_id.'
506;';
507  $element = pwg_db_fetch_assoc(pwg_query($query));
508
509  $element['url'] = make_index_url(array(
510    'section'=>'categories',
511    'category'=>$element,
512    ));
513
514  $element['name'] = trigger_event('render_category_name', $element['name']);
515
516  if ($with_thumb)
517  {
518    if (empty($element['image_id']) and $conf['allow_random_representative'])
519    {
520      $image = get_picture_infos(get_random_image_in_category($element));
521      $element['thumbnail'] = $image['thumbnail'];
522    }
523    else
524    {
525      $element['thumbnail'] = DerivativeImage::thumb_url(array(
526        'id'=>$element['image_id'],
527        'path'=>$element['path'],
528        ));
529    }
530  }
531
532  return $element;
533}
534
535/**
536 * get list of admins email
537 * @return: string
538 */
539function get_admins_email()
540{
541  global $conf, $user;
542
543  $admins = array();
544
545  $query = '
546SELECT
547    u.'.$conf['user_fields']['username'].' AS username,
548    u.'.$conf['user_fields']['email'].' AS email
549  FROM '.USERS_TABLE.' AS u
550    JOIN '.USER_INFOS_TABLE.' AS i
551      ON i.user_id =  u.'.$conf['user_fields']['id'].'
552  WHERE i.status IN ("webmaster", "admin")
553    AND '.$conf['user_fields']['email'].' IS NOT NULL
554    AND i.user_id != '.$user['id'].'
555  ORDER BY username
556;';
557
558  $datas = pwg_query($query);
559  if (!empty($datas))
560  {
561    while ($admin = pwg_db_fetch_assoc($datas))
562    {
563      array_push($admins, format_email($admin['username'], $admin['email']));
564    }
565  }
566
567  return implode(',', $admins);
568}
569
570
571/**
572 * check if the given user can view the category/image
573 * @param: int user_id
574 * @param: int element_id
575 * @param: string type (image|category)
576 * @return: bool
577 */
578function user_can_view_element($user_id, $element_id, $type)
579{
580  global $conf;
581
582  $old_conf = $conf['external_authentification'];
583  $conf['external_authentification'] = false;
584  $user = getuserdata($user_id, true);
585  $conf['external_authentification'] = $old_conf;
586
587  if ($type == 'image')
588  {
589    return !in_array($element_id, explode(',', $user['image_access_list']));
590  }
591  else if ($type == 'category')
592  {
593    return !in_array($element_id, explode(',', $user['forbidden_categories']));
594  }
595  else
596  {
597    return false;
598  }
599}
600
601
602/**
603 * crypt a string using mcrypt extension or
604 * http://stackoverflow.com/questions/800922/how-to-encrypt-string-without-mcrypt-library-in-php/802957#802957
605 * @param: string value to crypt
606 * @param: string key
607 * @return: string
608 */
609function crypt_value($value, $key)
610{
611  if (extension_loaded('mcrypt'))
612  {
613    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
614    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
615    $result = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $value, MCRYPT_MODE_ECB, $iv);
616  }
617  else
618  {
619    $result = null;
620    for($i = 0; $i < strlen($value); $i++)
621    {
622      $char = substr($value, $i, 1);
623      $keychar = substr($key, ($i % strlen($key))-1, 1);
624      $char = chr(ord($char) + ord($keychar));
625      $result .= $char;
626    }
627  }
628
629  $result = base64url_encode($result);
630  return trim($result);
631}
632
633/**
634 * decrypt a string crypted with previous function
635 * @param: string value to decrypt
636 * @param: string key
637 * @return: string
638 */
639function decrypt_value($value, $key)
640{
641  $value = base64url_decode($value);
642
643  if (extension_loaded('mcrypt'))
644  {
645    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
646    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
647    $result = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $value, MCRYPT_MODE_ECB, $iv);
648  }
649  else
650  {
651    $result = null;
652    for($i = 0; $i < strlen($value); $i++)
653    {
654      $char = substr($value, $i, 1);
655      $keychar = substr($key, ($i % strlen($key))-1, 1);
656      $char = chr(ord($char) - ord($keychar));
657      $result .= $char;
658    }
659  }
660
661  return trim($result);
662}
663
664/**
665 * variant of base64 functions usable into url
666 * http://php.net/manual/en/function.base64-encode.php#103849
667 */
668if (!function_exists('base64url_encode'))
669{
670  function base64url_encode($data)
671  {
672    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
673  }
674  function base64url_decode($data)
675  {
676    return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT));
677  }
678}
Note: See TracBrowser for help on using the repository browser.