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

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

keep old trigger functions (PHP 5.2 issue)

File size: 14.5 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']).'] '.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, $spam_check=true)
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 !isset($element_id))
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  // spam check
187  if ($spam_check)
188  {
189    if (!trigger_event('loc_before_subscribe_to_comments', true, $email, $type, $element_id))
190    {
191      return false;
192    }
193  }
194
195  // search if already registered
196  $query = '
197SELECT id
198  FROM '.SUBSCRIBE_TO_TABLE.'
199  WHERE
200    type = "'.$type.'"
201    AND element_id = '. (isset($element_id) ? $element_id : 'NULL') .'
202    AND email = "'.pwg_db_real_escape_string($email).'"
203;';
204  $result = pwg_query($query);
205
206  if (pwg_db_num_rows($result))
207  {
208    return false;
209  }
210
211  $query = '
212INSERT INTO '.SUBSCRIBE_TO_TABLE.'(
213    type,
214    element_id,
215    language,
216    email,
217    registration_date,
218    validated
219  )
220  VALUES(
221    "'.$type.'",
222    '. (isset($element_id) ? $element_id : 'NULL') .',
223    "'.$user['language'].'",
224    "'.pwg_db_real_escape_string($email).'",
225    NOW(),
226    "'.(is_a_guest() ? "false" : "true").'"
227  )
228;';
229  pwg_query($query);
230
231  $stc_id = pwg_db_insert_id();
232
233  include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
234
235  set_make_full_url();
236
237  if (!is_a_guest() or $conf['Subscribe_to_Comments']['notify_admin_on_subscribe'])
238  {
239    switch ($type)
240    {
241      case 'image':
242        $element = get_picture_infos($element_id);
243        $element['on'] = l10n('the picture <a href="%s">%s</a>', $element['url'], $element['name']);
244        break;
245      case 'album-images':
246        $element = get_category_infos($element_id);
247        $element['on'] = l10n('all pictures of the album <a href="%s">%s</a>', $element['url'], $element['name']);
248        break;
249      case 'all-images':
250        $element['thumbnail'] = null;
251        $element['on'] = l10n('all pictures of the gallery');
252        break;
253      case 'album':
254        $element = get_category_infos($element_id);
255        $element['on'] = l10n('the album <a href="%s">%s</a>', $element['url'], $element['name']);
256        break;
257      case 'all-albums':
258        $element['thumbnail'] = null;
259        $element['on'] = l10n('all albums of the gallery');
260        break;
261    }
262  }
263
264  // send validation mail
265  if (is_a_guest())
266  {
267    pwg_mail(
268      $email,
269      array(
270        'subject' => '['.strip_tags($conf['gallery_title']).'] '.l10n('Confirm your subscription to comments'),
271        ),
272      array(
273        'filename' => 'confirm',
274        'dirname' => SUBSCRIBE_TO_PATH . 'template',
275        'assign' => array(
276          'ELEMENT' => $element,
277          'VALIDATE_URL' => make_stc_url('validate', $email, $stc_id),
278          'MANAGE_URL' => make_stc_url('manage', $email),
279          ),
280        )
281      );
282
283    $page['infos'][] = l10n('Please check your email in-box to confirm your subscription.');
284  }
285  // just display confirmation message
286  else
287  {
288    $page['infos'][] = l10n('You have been added to the list of subscribers.');
289  }
290
291  // notify admins
292  if ($conf['Subscribe_to_Comments']['notify_admin_on_subscribe'])
293  {
294    pwg_mail_notification_admins(
295      get_l10n_args('New subscription on %s', strip_tags($element['on'])),
296      array(
297        get_l10n_args('%s has subscribed to comments on %s.', array($email, $element['on'])),
298        )
299      );
300  }
301
302  unset_make_full_url();
303
304  return true;
305}
306
307
308/**
309 * remove an email from subscribers list
310 * @param: string email
311 * @param: int subscription id
312 * @return: bool
313 */
314function un_subscribe_to_comments($email, $ids)
315{
316  if (!empty($email) and !email_check_format($email))
317  {
318    trigger_error('un_subscribe_to_comment: bad email', E_USER_WARNING);
319    return false;
320  }
321  if (empty($ids))
322  {
323    trigger_error('un_subscribe_to_comment: bad id', E_USER_WARNING);
324    return false;
325  }
326
327  global $user;
328
329  // check email
330  if ( (is_a_guest() or empty($user['email'])) and empty($email) )
331  {
332    return false;
333  }
334  else if (!is_a_guest() and empty($email))
335  {
336    $email = $user['email'];
337  }
338
339  if (!is_array($ids))
340  {
341    $ids = array($ids);
342  }
343  $ids = array_map('intval', $ids);
344
345  // delete subscription
346  $query = '
347DELETE FROM '.SUBSCRIBE_TO_TABLE.'
348  WHERE
349    email = "'.pwg_db_real_escape_string($email).'"
350    AND id IN('. implode(',', $ids) .')
351;';
352  pwg_query($query);
353
354  return (pwg_db_changes() != 0);
355}
356
357
358/**
359 * validate a subscription
360 * @param: string email
361 * @param: int subscription id
362 * @return: bool
363 */
364function validate_subscriptions($email, $ids)
365{
366  if (!email_check_format($email))
367  {
368    trigger_error('validate_subscriptions: bad email', E_USER_WARNING);
369    return false;
370  }
371  if (empty($ids))
372  {
373    trigger_error('validate_subscriptions: bad id', E_USER_WARNING);
374    return false;
375  }
376
377  if (!is_array($ids))
378  {
379    $ids = array($ids);
380  }
381  $ids = array_map('intval', $ids);
382
383  $query = '
384UPDATE '.SUBSCRIBE_TO_TABLE.'
385  SET validated = "true"
386  WHERE
387    email = "'.pwg_db_real_escape_string($email).'"
388    AND id IN('. implode(',', $ids) .')
389;';
390  pwg_query($query);
391
392  return (pwg_db_changes() != 0);
393}
394
395
396/**
397 * create absolute url to subscriptions section
398 * @param: string action
399 * @param: string email
400 * @param: int optional
401 * @return: string
402 */
403function make_stc_url($action, $email, $id=null)
404{
405  if (empty($action) or empty($email))
406  {
407    trigger_error('make_stc_url: missing action and/or mail', E_USER_WARNING);
408    return null;
409  }
410
411  global $conf;
412  set_make_full_url();
413
414  $url_params = compact('action', 'email');
415  if (!empty($id))
416  {
417    $url_params['id'] = $id;
418  }
419
420  $url_params['key'] = crypt_value(
421    $action.$email.$id,
422    $conf['secret_key']
423    );
424
425  $url = add_url_params(
426    make_index_url(array('section' => 'subscriptions')),
427    $url_params
428    );
429
430  unset_make_full_url();
431  return $url;
432}
433
434
435/**
436 * get name, url and thumbnail of a picture
437 * @param: int image_id
438 * @param: bool return thumbnail
439 * @return: array (id, name, url, thumbnail)
440 */
441function get_picture_infos($image_id, $with_thumb=true)
442{
443  if (empty($image_id))
444  {
445    return array();
446  }
447
448  $query = '
449SELECT
450    id,
451    file,
452    name,
453    path
454  FROM '.IMAGES_TABLE.'
455  WHERE id = '.$image_id.'
456;';
457  $element = pwg_db_fetch_assoc(pwg_query($query));
458
459  if (empty($element['name']))
460  {
461    $element['name'] = get_name_from_file($element['file']);
462  }
463  $element['name'] = trigger_event('render_element_name', $element['name']);
464
465  $element['url'] = make_picture_url(array(
466    'image_id'=>$element['id']
467    ));
468
469  if ($with_thumb)
470  {
471    $element['thumbnail'] = DerivativeImage::thumb_url($element);
472  }
473
474  return $element;
475}
476
477/**
478 * get name, url and thumbnail of a category
479 * @param: int cat_id
480 * @param: int return thumbnail
481 * @return: array (id, name, url, thumbnail)
482 */
483function get_category_infos($cat_id, $with_thumb=true, $user_id=null)
484{
485  global $conf;
486
487  if ($user_id===null)
488  {
489    $user_id = $conf['guest_id'];
490  }
491
492  $query = '
493SELECT
494    cat.id,
495    cat.name,
496    cat.permalink,
497    ucc.count_images,
498    cat.uppercats,
499    img.id AS image_id,
500    img.path
501  FROM '.CATEGORIES_TABLE.' AS cat
502    LEFT JOIN '.USER_CACHE_CATEGORIES_TABLE.' AS ucc
503      ON ucc.cat_id = cat.id AND ucc.user_id = '.$user_id.'
504    LEFT JOIN '.IMAGES_TABLE.' AS img
505      ON img.id = ucc.user_representative_picture_id
506  WHERE cat.id = '.$cat_id.'
507;';
508  $element = pwg_db_fetch_assoc(pwg_query($query));
509
510  $element['url'] = make_index_url(array(
511    'section'=>'categories',
512    'category'=>$element,
513    ));
514
515  $element['name'] = trigger_event('render_category_name', $element['name']);
516
517  if ($with_thumb)
518  {
519    if (empty($element['image_id']) and $conf['allow_random_representative'])
520    {
521      $image = get_picture_infos(get_random_image_in_category($element));
522      $element['thumbnail'] = $image['thumbnail'];
523    }
524    else
525    {
526      $element['thumbnail'] = DerivativeImage::thumb_url(array(
527        'id'=>$element['image_id'],
528        'path'=>$element['path'],
529        ));
530    }
531  }
532
533  return $element;
534}
535
536
537/**
538 * check if the given user can view the category/image
539 * @param: int user_id
540 * @param: int element_id
541 * @param: string type (image|category)
542 * @return: bool
543 */
544function user_can_view_element($user_id, $element_id, $type)
545{
546  global $conf;
547
548  $old_conf = $conf['external_authentification'];
549  $conf['external_authentification'] = false;
550  $user = getuserdata($user_id, true);
551  $conf['external_authentification'] = $old_conf;
552
553  if ($type == 'image')
554  {
555    return !in_array($element_id, explode(',', $user['image_access_list']));
556  }
557  else if ($type == 'category')
558  {
559    return !in_array($element_id, explode(',', $user['forbidden_categories']));
560  }
561  else
562  {
563    return false;
564  }
565}
566
567
568/**
569 * crypt a string using mcrypt extension or
570 * http://stackoverflow.com/questions/800922/how-to-encrypt-string-without-mcrypt-library-in-php/802957#802957
571 * @param: string value to crypt
572 * @param: string key
573 * @return: string
574 */
575function crypt_value($value, $key)
576{
577  if (extension_loaded('mcrypt'))
578  {
579    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
580    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
581    $result = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $value, MCRYPT_MODE_ECB, $iv);
582  }
583  else
584  {
585    $result = null;
586    for($i = 0; $i < strlen($value); $i++)
587    {
588      $char = substr($value, $i, 1);
589      $keychar = substr($key, ($i % strlen($key))-1, 1);
590      $char = chr(ord($char) + ord($keychar));
591      $result .= $char;
592    }
593  }
594
595  $result = base64url_encode($result);
596  return trim($result);
597}
598
599/**
600 * decrypt a string crypted with previous function
601 * @param: string value to decrypt
602 * @param: string key
603 * @return: string
604 */
605function decrypt_value($value, $key)
606{
607  $value = base64url_decode($value);
608
609  if (extension_loaded('mcrypt'))
610  {
611    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
612    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
613    $result = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $value, MCRYPT_MODE_ECB, $iv);
614  }
615  else
616  {
617    $result = null;
618    for($i = 0; $i < strlen($value); $i++)
619    {
620      $char = substr($value, $i, 1);
621      $keychar = substr($key, ($i % strlen($key))-1, 1);
622      $char = chr(ord($char) - ord($keychar));
623      $result .= $char;
624    }
625  }
626
627  return trim($result);
628}
629
630/**
631 * variant of base64 functions usable into url
632 * http://php.net/manual/en/function.base64-encode.php#103849
633 */
634if (!function_exists('base64url_encode'))
635{
636  function base64url_encode($data)
637  {
638    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
639  }
640  function base64url_decode($data)
641  {
642    return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT));
643  }
644}
Note: See TracBrowser for help on using the repository browser.