source: trunk/admin/include/functions_notification_by_mail.inc.php @ 17210

Last change on this file since 17210 was 13106, checked in by plg, 13 years ago

merge r13105 from branch 2.3 to trunk

bug 2551 fixed: force the use of $confgallery_url (thanks to the
get_gallery_home_url function) to build subscribe/unsubscribe links
in NBM emails.

  • Property svn:eol-style set to LF
File size: 14.3 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based photo gallery                                    |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008-2012 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/* nbm_global_var */
25$env_nbm = array
26          (
27            'start_time' => get_moment(),
28            'sendmail_timeout' => (intval(ini_get('max_execution_time')) * $conf['nbm_max_treatment_timeout_percent']),
29            'is_sendmail_timeout' => false
30          );
31
32if
33  (
34    (!isset($env_nbm['sendmail_timeout'])) or
35    (!is_numeric($env_nbm['sendmail_timeout'])) or
36    ($env_nbm['sendmail_timeout'] <= 0)
37  )
38{
39  $env_nbm['sendmail_timeout'] = $conf['nbm_treatment_timeout_default'];
40}
41
42/*
43 * Search an available check_key
44 *
45 * It's a copy of function find_available_feed_id
46 *
47 * @return string nbm identifier
48 */
49function find_available_check_key()
50{
51  while (true)
52  {
53    $key = generate_key(16);
54    $query = '
55select
56  count(*)
57from
58  '.USER_MAIL_NOTIFICATION_TABLE.'
59where
60  check_key = \''.$key.'\';';
61
62    list($count) = pwg_db_fetch_row(pwg_query($query));
63    if ($count == 0)
64    {
65      return $key;
66    }
67  }
68}
69
70/*
71 * Check sendmail timeout state
72 *
73 * @return true, if it's timeout
74 */
75function check_sendmail_timeout()
76{
77  global $env_nbm;
78
79  $env_nbm['is_sendmail_timeout'] = ((get_moment() - $env_nbm['start_time']) > $env_nbm['sendmail_timeout']);
80
81  return $env_nbm['is_sendmail_timeout'];
82}
83
84
85/*
86 * Add quote to all elements of check_key_list
87 *
88 * @return quoted check key list
89 */
90function quote_check_key_list($check_key_list = array())
91{
92  return array_map(create_function('$s', 'return \'\\\'\'.$s.\'\\\'\';'), $check_key_list);
93}
94
95/*
96 * Execute all main queries to get list of user
97 *
98 * Type are the type of list 'subscribe', 'send'
99 *
100 * return array of users
101 */
102function get_user_notifications($action, $check_key_list = array(), $enabled_filter_value = '')
103{
104  global $conf;
105
106  $data_users = array();
107
108  if (in_array($action, array('subscribe', 'send')))
109  {
110    $quoted_check_key_list = quote_check_key_list($check_key_list);
111    if (count($quoted_check_key_list) != 0 )
112    {
113      $query_and_check_key = ' and
114    check_key in ('.implode(",", $quoted_check_key_list).') ';
115    }
116    else
117    {
118      $query_and_check_key = '';
119    }
120
121    $query = '
122select
123  N.user_id,
124  N.check_key,
125  U.'.$conf['user_fields']['username'].' as username,
126  U.'.$conf['user_fields']['email'].' as mail_address,
127  N.enabled,
128  N.last_send
129from
130  '.USER_MAIL_NOTIFICATION_TABLE.' as N,
131  '.USERS_TABLE.' as U
132where
133  N.user_id =  U.'.$conf['user_fields']['id'];
134
135    if ($action == 'send')
136    {
137      // No mail empty and all users enabled
138      $query .= ' and
139  N.enabled = \'true\' and
140  U.'.$conf['user_fields']['email'].' is not null';
141    }
142
143    $query .= $query_and_check_key;
144
145    if (isset($enabled_filter_value) and ($enabled_filter_value != ''))
146    {
147      $query .= ' and
148        N.enabled = \''.boolean_to_string($enabled_filter_value).'\'';
149    }
150
151    $query .= '
152order by';
153
154    if ($action == 'send')
155    {
156      $query .= '
157  last_send, username;';
158    }
159    else
160    {
161      $query .= '
162  username;';
163    }
164
165    $query .= ';';
166
167    $result = pwg_query($query);
168    if (!empty($result))
169    {
170      while ($nbm_user = pwg_db_fetch_assoc($result))
171      {
172        array_push($data_users, $nbm_user);
173      }
174    }
175  }
176  return $data_users;
177}
178
179/*
180 * Begin of use nbm environment
181 * Prepare and save current environment and initialize data in order to send mail
182 *
183 * Return none
184 */
185function begin_users_env_nbm($is_to_send_mail = false)
186{
187  global $user, $lang, $lang_info, $conf, $env_nbm;
188
189  // Save $user, $lang_info and $lang arrays (include/user.inc.php has been executed)
190  $env_nbm['save_user'] = $user;
191  // Save current language to stack, necessary because $user change during NBM
192  switch_lang_to($user['language']);
193
194  $env_nbm['is_to_send_mail'] = $is_to_send_mail;
195
196  if ($is_to_send_mail)
197  {
198    // Init mail configuration
199    $env_nbm['email_format'] = get_str_email_format($conf['nbm_send_html_mail']);
200    $env_nbm['send_as_name'] = ((isset($conf['nbm_send_mail_as']) and !empty($conf['nbm_send_mail_as'])) ? $conf['nbm_send_mail_as'] : get_mail_sender_name());
201    $env_nbm['send_as_mail_address'] = get_webmaster_mail_address();
202    $env_nbm['send_as_mail_formated'] = format_email($env_nbm['send_as_name'], $env_nbm['send_as_mail_address']);
203    // Init mail counter
204    $env_nbm['error_on_mail_count'] = 0;
205    $env_nbm['sent_mail_count'] = 0;
206    // Save sendmail message info and error in the original language
207    $env_nbm['msg_info'] = l10n('Mail sent to %s [%s].');
208    $env_nbm['msg_error'] = l10n('Error when sending email to %s [%s].');
209  }
210}
211
212/*
213 * End of use nbm environment
214 * Restore environment
215 *
216 * Return none
217 */
218function end_users_env_nbm()
219{
220  global $user, $lang, $lang_info, $env_nbm;
221
222  // Restore $user, $lang_info and $lang arrays (include/user.inc.php has been executed)
223  $user = $env_nbm['save_user'];
224  // Restore current language to stack, necessary because $user change during NBM
225  switch_lang_back();
226
227  if ($env_nbm['is_to_send_mail'])
228  {
229    unset($env_nbm['email_format']);
230    unset($env_nbm['send_as_name']);
231    unset($env_nbm['send_as_mail_address']);
232    unset($env_nbm['send_as_mail_formated']);
233    // Don t unset counter
234    //unset($env_nbm['error_on_mail_count']);
235    //unset($env_nbm['sent_mail_count']);
236    unset($env_nbm['msg_info']);
237    unset($env_nbm['msg_error']);
238  }
239
240  unset($env_nbm['save_user']);
241  unset($env_nbm['is_to_send_mail']);
242}
243
244/*
245 * Set user on nbm enviromnent
246 *
247 * Return none
248 */
249function set_user_on_env_nbm(&$nbm_user, $is_action_send)
250{
251  global $user, $lang, $lang_info, $env_nbm;
252
253  $user = build_user( $nbm_user['user_id'], true );
254
255  switch_lang_to($user['language']);
256
257  if ($is_action_send)
258  {
259    $nbm_user['theme'] = $user['theme'];
260    $env_nbm['mail_template'] = get_mail_template($env_nbm['email_format'], $nbm_user['theme']);
261    $env_nbm['mail_template']->set_filename('notification_by_mail', 'notification_by_mail.tpl');
262  }
263}
264
265/*
266 * Unset user on nbm enviromnent
267 *
268 * Return none
269 */
270function unset_user_on_env_nbm()
271{
272  global $env_nbm;
273
274  switch_lang_back();
275  unset($env_nbm['mail_template']);
276}
277
278/*
279 * Inc Counter success
280 *
281 * Return none
282 */
283function inc_mail_sent_success($nbm_user)
284{
285  global $page, $env_nbm;
286
287  $env_nbm['sent_mail_count'] += 1;
288  array_push($page['infos'], sprintf($env_nbm['msg_info'], stripslashes($nbm_user['username']), $nbm_user['mail_address']));
289}
290
291/*
292 * Inc Counter failed
293 *
294 * Return none
295 */
296function inc_mail_sent_failed($nbm_user)
297{
298  global $page, $env_nbm;
299
300  $env_nbm['error_on_mail_count'] += 1;
301  array_push($page['errors'], sprintf($env_nbm['msg_error'], stripslashes($nbm_user['username']), $nbm_user['mail_address']));
302}
303
304/*
305 * Display Counter Info
306 *
307 * Return none
308 */
309function display_counter_info()
310{
311  global $page, $env_nbm;
312
313  if ($env_nbm['error_on_mail_count'] != 0)
314  {
315    array_push($page['errors'], l10n_dec('%d mail was not sent.', '%d mails were not sent.', $env_nbm['error_on_mail_count']));
316    if ($env_nbm['sent_mail_count'] != 0)
317      array_push($page['infos'], l10n_dec('%d mail was sent.', '%d mails were sent.', $env_nbm['sent_mail_count']));
318  }
319  else
320  {
321    if ($env_nbm['sent_mail_count'] == 0)
322      array_push($page['infos'], l10n('No mail to send.'));
323    else
324      array_push($page['infos'], l10n_dec('%d mail was sent.', '%d mails were sent.', $env_nbm['sent_mail_count']));
325  }
326}
327
328function assign_vars_nbm_mail_content($nbm_user)
329{
330  global $env_nbm;
331
332  set_make_full_url();
333
334  $env_nbm['mail_template']->assign
335  (
336    array
337    (
338      'USERNAME' => stripslashes($nbm_user['username']),
339
340      'SEND_AS_NAME' => $env_nbm['send_as_name'],
341
342      'UNSUBSCRIBE_LINK' => add_url_params(get_gallery_home_url().'/nbm.php', array('unsubscribe' => $nbm_user['check_key'])),
343      'SUBSCRIBE_LINK' => add_url_params(get_gallery_home_url().'/nbm.php', array('subscribe' => $nbm_user['check_key'])),
344      'CONTACT_EMAIL' => $env_nbm['send_as_mail_address']
345    )
346  );
347
348  unset_make_full_url();
349}
350
351/*
352 * Subscribe or unsubscribe notification by mail
353 *
354 * is_subscribe define if action=subscribe or unsubscribe
355 * check_key list where action will be done
356 *
357 * @return check_key list treated
358 */
359function do_subscribe_unsubscribe_notification_by_mail($is_admin_request, $is_subscribe = false, $check_key_list = array())
360{
361  global $conf, $page, $env_nbm, $conf;
362
363  set_make_full_url();
364
365  $check_key_treated = array();
366  $updated_data_count = 0;
367  $error_on_updated_data_count = 0;
368
369  if ($is_subscribe)
370  {
371    $msg_info = l10n('User %s [%s] was added to the subscription list.');
372    $msg_error = l10n('User %s [%s] was not added to the subscription list.');
373  }
374  else
375  {
376    $msg_info = l10n('User %s [%s] was removed from the subscription list.');
377    $msg_error = l10n('User %s [%s] was not removed from the subscription list.');
378  }
379
380  if (count($check_key_list) != 0)
381  {
382    $updates = array();
383    $enabled_value = boolean_to_string($is_subscribe);
384    $data_users = get_user_notifications('subscribe', $check_key_list, !$is_subscribe);
385
386    // Prepare message after change language
387    $msg_break_timeout = l10n('Time to send mail is limited. Others mails are skipped.');
388
389    // Begin nbm users environment
390    begin_users_env_nbm(true);
391
392    foreach ($data_users as $nbm_user)
393    {
394      if (check_sendmail_timeout())
395      {
396        // Stop fill list on 'send', if the quota is override
397        array_push($page['errors'], $msg_break_timeout);
398        break;
399      }
400
401      // Fill return list
402      array_push($check_key_treated, $nbm_user['check_key']);
403
404      $do_update = true;
405      if ($nbm_user['mail_address'] != '')
406      {
407        // set env nbm user
408        set_user_on_env_nbm($nbm_user, true);
409
410        $subject = '['.$conf['gallery_title'].']: '.($is_subscribe ? l10n('Subscribe to notification by mail'): l10n('Unsubscribe from notification by mail'));
411
412        // Assign current var for nbm mail
413        assign_vars_nbm_mail_content($nbm_user);
414
415        $section_action_by = ($is_subscribe ? 'subscribe_by_' : 'unsubscribe_by_');
416        $section_action_by .= ($is_admin_request ? 'admin' : 'himself');
417        $env_nbm['mail_template']->assign
418        (
419          array
420          (
421            $section_action_by => true,
422            'GOTO_GALLERY_TITLE' => $conf['gallery_title'],
423            'GOTO_GALLERY_URL' => get_gallery_home_url(),
424          )
425        );
426
427        if (pwg_mail
428            (
429              format_email(stripslashes($nbm_user['username']), $nbm_user['mail_address']),
430              array
431              (
432                'from' => $env_nbm['send_as_mail_formated'],
433                'subject' => $subject,
434                'email_format' => $env_nbm['email_format'],
435                'content' => $env_nbm['mail_template']->parse('notification_by_mail', true),
436                'content_format' => $env_nbm['email_format'],
437                'theme' => $nbm_user['theme']
438              )
439            ))
440        {
441          inc_mail_sent_success($nbm_user);
442        }
443        else
444        {
445          inc_mail_sent_failed($nbm_user);
446          $do_update = false;
447        }
448
449        // unset env nbm user
450        unset_user_on_env_nbm();
451
452      }
453
454      if ($do_update)
455      {
456        array_push
457        (
458          $updates,
459          array
460          (
461            'check_key' => $nbm_user['check_key'],
462            'enabled' => $enabled_value
463          )
464        );
465        $updated_data_count += 1;
466        array_push($page['infos'], sprintf($msg_info, stripslashes($nbm_user['username']), $nbm_user['mail_address']));
467      }
468      else
469      {
470        $error_on_updated_data_count += 1;
471        array_push($page['errors'], sprintf($msg_error, stripslashes($nbm_user['username']), $nbm_user['mail_address']));
472      }
473
474    }
475
476    // Restore nbm environment
477    end_users_env_nbm();
478
479    display_counter_info();
480
481    mass_updates(
482      USER_MAIL_NOTIFICATION_TABLE,
483      array(
484        'primary' => array('check_key'),
485        'update' => array('enabled')
486      ),
487      $updates
488    );
489
490  }
491
492  array_push($page['infos'], l10n_dec('%d user was updated.', '%d users were updated.', $updated_data_count));
493  if ($error_on_updated_data_count != 0)
494  {
495    array_push($page['errors'],
496      l10n_dec('%d user was not updated.',
497               '%d users were not updated.',
498               $error_on_updated_data_count));
499  }
500
501  unset_make_full_url();
502
503  return $check_key_treated;
504}
505
506/*
507 * Unsubscribe notification by mail
508 *
509 * check_key list where action will be done
510 *
511 * @return check_key list treated
512 */
513function unsubscribe_notification_by_mail($is_admin_request, $check_key_list = array())
514{
515  return do_subscribe_unsubscribe_notification_by_mail($is_admin_request, false, $check_key_list);
516}
517
518/*
519 * Subscribe notification by mail
520 *
521 * check_key list where action will be done
522 *
523 * @return check_key list treated
524 */
525function subscribe_notification_by_mail($is_admin_request, $check_key_list = array())
526{
527  return do_subscribe_unsubscribe_notification_by_mail($is_admin_request, true, $check_key_list);
528}
529
530?>
Note: See TracBrowser for help on using the repository browser.