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

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

change layout of form (use colorbox for standalone) + cleaning of subscriptions page

File size: 14.3 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_change('render_comment_author', $comm['author']);
96  $comm['content'] = trigger_change('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']).'] '.l10n('New comment on %s', $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    pwg_mail_notification_admins(
286      get_l10n_args('New subscription on %s', strip_tags($element['on'])),
287      array(
288        get_l10n_args('%s has subscribed to comments on %s.', array($email, $element['on'])),
289        )
290      );
291  }
292
293  unset_make_full_url();
294
295  return true;
296}
297
298
299/**
300 * remove an email from subscribers list
301 * @param: string email
302 * @param: int subscription id
303 * @return: bool
304 */
305function un_subscribe_to_comments($email, $ids)
306{
307  if (!empty($email) and !email_check_format($email))
308  {
309    trigger_error('un_subscribe_to_comment: bad email', E_USER_WARNING);
310    return false;
311  }
312  if (empty($ids))
313  {
314    trigger_error('un_subscribe_to_comment: bad id', E_USER_WARNING);
315    return false;
316  }
317
318  global $user;
319
320  // check email
321  if ( (is_a_guest() or empty($user['email'])) and empty($email) )
322  {
323    return false;
324  }
325  else if (!is_a_guest() and empty($email))
326  {
327    $email = $user['email'];
328  }
329
330  if (!is_array($ids))
331  {
332    $ids = array($ids);
333  }
334  $ids = array_map('intval', $ids);
335
336  // delete subscription
337  $query = '
338DELETE FROM '.SUBSCRIBE_TO_TABLE.'
339  WHERE
340    email = "'.pwg_db_real_escape_string($email).'"
341    AND id IN('. implode(',', $ids) .')
342;';
343  pwg_query($query);
344
345  return (pwg_db_changes() != 0);
346}
347
348
349/**
350 * validate a subscription
351 * @param: string email
352 * @param: int subscription id
353 * @return: bool
354 */
355function validate_subscriptions($email, $ids)
356{
357  if (!email_check_format($email))
358  {
359    trigger_error('validate_subscriptions: bad email', E_USER_WARNING);
360    return false;
361  }
362  if (empty($ids))
363  {
364    trigger_error('validate_subscriptions: bad id', E_USER_WARNING);
365    return false;
366  }
367
368  if (!is_array($ids))
369  {
370    $ids = array($ids);
371  }
372  $ids = array_map('intval', $ids);
373
374  $query = '
375UPDATE '.SUBSCRIBE_TO_TABLE.'
376  SET validated = "true"
377  WHERE
378    email = "'.pwg_db_real_escape_string($email).'"
379    AND id IN('. implode(',', $ids) .')
380;';
381  pwg_query($query);
382
383  return (pwg_db_changes() != 0);
384}
385
386
387/**
388 * create absolute url to subscriptions section
389 * @param: string action
390 * @param: string email
391 * @param: int optional
392 * @return: string
393 */
394function make_stc_url($action, $email, $id=null)
395{
396  if (empty($action) or empty($email))
397  {
398    trigger_error('make_stc_url: missing action and/or mail', E_USER_WARNING);
399    return null;
400  }
401
402  global $conf;
403  set_make_full_url();
404
405  $url_params = compact('action', 'email');
406  if (!empty($id))
407  {
408    $url_params['id'] = $id;
409  }
410
411  $url_params['key'] = crypt_value(
412    $action.$email.$id,
413    $conf['secret_key']
414    );
415
416  $url = add_url_params(
417    make_index_url(array('section' => 'subscriptions')),
418    $url_params
419    );
420
421  unset_make_full_url();
422  return $url;
423}
424
425
426/**
427 * get name, url and thumbnail of a picture
428 * @param: int image_id
429 * @param: bool return thumbnail
430 * @return: array (id, name, url, thumbnail)
431 */
432function get_picture_infos($image_id, $with_thumb=true)
433{
434  if (empty($image_id))
435  {
436    return array();
437  }
438
439  $query = '
440SELECT
441    id,
442    file,
443    name,
444    path
445  FROM '.IMAGES_TABLE.'
446  WHERE id = '.$image_id.'
447;';
448  $element = pwg_db_fetch_assoc(pwg_query($query));
449
450  if (empty($element['name']))
451  {
452    $element['name'] = get_name_from_file($element['file']);
453  }
454  $element['name'] = trigger_change('render_element_name', $element['name']);
455
456  $element['url'] = make_picture_url(array(
457    'image_id'=>$element['id']
458    ));
459
460  if ($with_thumb)
461  {
462    $element['thumbnail'] = DerivativeImage::thumb_url($element);
463  }
464
465  return $element;
466}
467
468/**
469 * get name, url and thumbnail of a category
470 * @param: int cat_id
471 * @param: int return thumbnail
472 * @return: array (id, name, url, thumbnail)
473 */
474function get_category_infos($cat_id, $with_thumb=true, $user_id=null)
475{
476  global $conf;
477
478  if ($user_id===null)
479  {
480    $user_id = $conf['guest_id'];
481  }
482
483  $query = '
484SELECT
485    cat.id,
486    cat.name,
487    cat.permalink,
488    ucc.count_images,
489    cat.uppercats,
490    img.id AS image_id,
491    img.path
492  FROM '.CATEGORIES_TABLE.' AS cat
493    LEFT JOIN '.USER_CACHE_CATEGORIES_TABLE.' AS ucc
494      ON ucc.cat_id = cat.id AND ucc.user_id = '.$user_id.'
495    LEFT JOIN '.IMAGES_TABLE.' AS img
496      ON img.id = ucc.user_representative_picture_id
497  WHERE cat.id = '.$cat_id.'
498;';
499  $element = pwg_db_fetch_assoc(pwg_query($query));
500
501  $element['url'] = make_index_url(array(
502    'section'=>'categories',
503    'category'=>$element,
504    ));
505
506  $element['name'] = trigger_change('render_category_name', $element['name']);
507
508  if ($with_thumb)
509  {
510    if (empty($element['image_id']) and $conf['allow_random_representative'])
511    {
512      $image = get_picture_infos(get_random_image_in_category($element));
513      $element['thumbnail'] = $image['thumbnail'];
514    }
515    else
516    {
517      $element['thumbnail'] = DerivativeImage::thumb_url(array(
518        'id'=>$element['image_id'],
519        'path'=>$element['path'],
520        ));
521    }
522  }
523
524  return $element;
525}
526
527
528/**
529 * check if the given user can view the category/image
530 * @param: int user_id
531 * @param: int element_id
532 * @param: string type (image|category)
533 * @return: bool
534 */
535function user_can_view_element($user_id, $element_id, $type)
536{
537  global $conf;
538
539  $old_conf = $conf['external_authentification'];
540  $conf['external_authentification'] = false;
541  $user = getuserdata($user_id, true);
542  $conf['external_authentification'] = $old_conf;
543
544  if ($type == 'image')
545  {
546    return !in_array($element_id, explode(',', $user['image_access_list']));
547  }
548  else if ($type == 'category')
549  {
550    return !in_array($element_id, explode(',', $user['forbidden_categories']));
551  }
552  else
553  {
554    return false;
555  }
556}
557
558
559/**
560 * crypt a string using mcrypt extension or
561 * http://stackoverflow.com/questions/800922/how-to-encrypt-string-without-mcrypt-library-in-php/802957#802957
562 * @param: string value to crypt
563 * @param: string key
564 * @return: string
565 */
566function crypt_value($value, $key)
567{
568  if (extension_loaded('mcrypt'))
569  {
570    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
571    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
572    $result = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $value, MCRYPT_MODE_ECB, $iv);
573  }
574  else
575  {
576    $result = null;
577    for($i = 0; $i < strlen($value); $i++)
578    {
579      $char = substr($value, $i, 1);
580      $keychar = substr($key, ($i % strlen($key))-1, 1);
581      $char = chr(ord($char) + ord($keychar));
582      $result .= $char;
583    }
584  }
585
586  $result = base64url_encode($result);
587  return trim($result);
588}
589
590/**
591 * decrypt a string crypted with previous function
592 * @param: string value to decrypt
593 * @param: string key
594 * @return: string
595 */
596function decrypt_value($value, $key)
597{
598  $value = base64url_decode($value);
599
600  if (extension_loaded('mcrypt'))
601  {
602    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
603    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
604    $result = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $value, MCRYPT_MODE_ECB, $iv);
605  }
606  else
607  {
608    $result = null;
609    for($i = 0; $i < strlen($value); $i++)
610    {
611      $char = substr($value, $i, 1);
612      $keychar = substr($key, ($i % strlen($key))-1, 1);
613      $char = chr(ord($char) - ord($keychar));
614      $result .= $char;
615    }
616  }
617
618  return trim($result);
619}
620
621/**
622 * variant of base64 functions usable into url
623 * http://php.net/manual/en/function.base64-encode.php#103849
624 */
625if (!function_exists('base64url_encode'))
626{
627  function base64url_encode($data)
628  {
629    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
630  }
631  function base64url_decode($data)
632  {
633    return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT));
634  }
635}
Note: See TracBrowser for help on using the repository browser.