source: trunk/admin/notification_by_mail.php @ 25489

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

feature 2995: New email template
restore get_l10n_args removed at r25357
apply changes to NBM

  • Property svn:eol-style set to LF
File size: 22.9 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// | include                                                               |
26// +-----------------------------------------------------------------------+
27
28if (!defined('PHPWG_ROOT_PATH'))
29{
30  die ("Hacking attempt!");
31}
32
33include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
34include_once(PHPWG_ROOT_PATH.'admin/include/functions_notification_by_mail.inc.php');
35include_once(PHPWG_ROOT_PATH.'admin/include/tabsheet.class.php');
36include_once(PHPWG_ROOT_PATH.'include/common.inc.php');
37include_once(PHPWG_ROOT_PATH.'include/functions_notification.inc.php');
38include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
39
40// +-----------------------------------------------------------------------+
41// | Check Access and exit when user status is not ok                      |
42// +-----------------------------------------------------------------------+
43check_status(ACCESS_ADMINISTRATOR);
44
45// +-----------------------------------------------------------------------+
46// | Initialization                                                        |
47// +-----------------------------------------------------------------------+
48$base_url = get_root_url().'admin.php';
49$must_repost = false;
50
51// +-----------------------------------------------------------------------+
52// | functions                                                             |
53// +-----------------------------------------------------------------------+
54
55/*
56 * Do timeout treatment in order to finish to send mails
57 *
58 * @param $post_keyname: key of check_key post array
59 * @param check_key_treated: array of check_key treated
60 * @return none
61 */
62function do_timeout_treatment($post_keyname, $check_key_treated = array())
63{
64  global $env_nbm, $base_url, $page, $must_repost;
65
66  if ($env_nbm['is_sendmail_timeout'])
67  {
68    if (isset($_POST[$post_keyname]))
69    {
70      $post_count = count($_POST[$post_keyname]);
71      $treated_count = count($check_key_treated);
72      if ($treated_count != 0)
73      {
74        $time_refresh = ceil((get_moment() - $env_nbm['start_time']) * $post_count / $treated_count);
75      }
76      else
77      {
78        $time_refresh = 0;
79      }
80      $_POST[$post_keyname] = array_diff($_POST[$post_keyname], $check_key_treated);
81
82      $must_repost = true;
83      $page['errors'][] = l10n_dec(
84        'Execution time is out, treatment must be continue [Estimated time: %d second].',
85        'Execution time is out, treatment must be continue [Estimated time: %d seconds].',
86        $time_refresh
87        );
88    }
89  }
90
91}
92
93/*
94 * Get the authorized_status for each tab
95 * return corresponding status
96 */
97function get_tab_status($mode)
98{
99  $result = ACCESS_WEBMASTER;
100  switch ($mode)
101  {
102    case 'param':
103    case 'subscribe':
104      $result = ACCESS_WEBMASTER;
105      break;
106    case 'send':
107      $result = ACCESS_ADMINISTRATOR;
108      break;
109    default:
110      $result = ACCESS_WEBMASTER;
111      break;
112  }
113  return $result;
114}
115
116/*
117 * Inserting News users
118 */
119function insert_new_data_user_mail_notification()
120{
121  global $conf, $page, $env_nbm;
122
123  // Set null mail_address empty
124  $query = '
125update
126  '.USERS_TABLE.'
127set
128  '.$conf['user_fields']['email'].' = null
129where
130  trim('.$conf['user_fields']['email'].') = \'\';';
131  pwg_query($query);
132
133  // null mail_address are not selected in the list
134  $query = '
135select
136  u.'.$conf['user_fields']['id'].' as user_id,
137  u.'.$conf['user_fields']['username'].' as username,
138  u.'.$conf['user_fields']['email'].' as mail_address
139from
140  '.USERS_TABLE.' as u left join '.USER_MAIL_NOTIFICATION_TABLE.' as m on u.'.$conf['user_fields']['id'].' = m.user_id
141where
142  u.'.$conf['user_fields']['email'].' is not null and
143  m.user_id is null
144order by
145  user_id;';
146
147  $result = pwg_query($query);
148
149  if (pwg_db_num_rows($result) > 0)
150  {
151    $inserts = array();
152    $check_key_list = array();
153
154    while ($nbm_user = pwg_db_fetch_assoc($result))
155    {
156      // Calculate key
157      $nbm_user['check_key'] = find_available_check_key();
158
159      // Save key
160      $check_key_list[] = $nbm_user['check_key'];
161
162      // Insert new nbm_users
163      $inserts[] = array(
164        'user_id' => $nbm_user['user_id'],
165        'check_key' => $nbm_user['check_key'],
166        'enabled' => 'false' // By default if false, set to true with specific functions
167        );
168
169      $page['infos'][] = l10n(
170        'User %s [%s] added.',
171        stripslashes($nbm_user['username']),
172        get_email_address_as_display_text($nbm_user['mail_address'])
173        );
174    }
175
176    // Insert new nbm_users
177    mass_inserts(USER_MAIL_NOTIFICATION_TABLE, array('user_id', 'check_key', 'enabled'), $inserts);
178    // Update field enabled with specific function
179    $check_key_treated = do_subscribe_unsubscribe_notification_by_mail
180    (
181      true,
182      $conf['nbm_default_value_user_enabled'],
183      $check_key_list
184    );
185
186     // On timeout simulate like tabsheet send
187    if ($env_nbm['is_sendmail_timeout'])
188    {
189      $quoted_check_key_list = quote_check_key_list(array_diff($check_key_list, $check_key_treated));
190      if (count($quoted_check_key_list) != 0 )
191      {
192        $query = 'delete from '.USER_MAIL_NOTIFICATION_TABLE.' where check_key in ('.implode(",", $quoted_check_key_list).');';
193        $result = pwg_query($query);
194
195        redirect($base_url.get_query_string_diff(array(), false), l10n('Operation in progress')."\n".l10n('Please wait...'));
196      }
197    }
198  }
199}
200
201/*
202 * Apply global functions to mail content
203 * return customize mail content rendered
204 */
205function render_global_customize_mail_content($customize_mail_content)
206{
207  global $conf;
208
209  if ($conf['nbm_send_html_mail'] and !(strpos($customize_mail_content, '<') === 0))
210  {
211    // On HTML mail, detects if the content are HTML format.
212    // If it's plain text format, convert content to readable HTML
213    return nl2br(htmlspecialchars($customize_mail_content));
214  }
215  else
216  {
217    return $customize_mail_content;
218  }
219}
220
221/*
222 * Send mail for notification to all users
223 * Return list of "selected" users for 'list_to_send'
224 * Return list of "treated" check_key for 'send'
225 */
226function do_action_send_mail_notification($action = 'list_to_send', $check_key_list = array(), $customize_mail_content = '')
227{
228  global $conf, $page, $user, $lang_info, $lang, $env_nbm;
229  $return_list = array();
230
231  if (in_array($action, array('list_to_send', 'send')))
232  {
233    list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
234
235    $is_action_send = ($action == 'send');
236
237    // disabled and null mail_address are not selected in the list
238    $data_users = get_user_notifications('send', $check_key_list);
239
240    // List all if it's define on options or on timeout
241    $is_list_all_without_test = ($env_nbm['is_sendmail_timeout'] or $conf['nbm_list_all_enabled_users_to_send']);
242
243    // Check if exist news to list user or send mails
244    if ((!$is_list_all_without_test) or ($is_action_send))
245    {
246      if (count($data_users) > 0)
247      {
248        $datas = array();
249
250        if (!isset($customize_mail_content))
251        {
252          $customize_mail_content = $conf['nbm_complementary_mail_content'];
253        }
254
255        $customize_mail_content = 
256          trigger_event('nbm_render_global_customize_mail_content', $customize_mail_content);
257
258
259        // Prepare message after change language
260        if ($is_action_send)
261        {
262          $msg_break_timeout = l10n('Time to send mail is limited. Others mails are skipped.');
263        }
264        else
265        {
266          $msg_break_timeout = l10n('Prepared time for list of users to send mail is limited. Others users are not listed.');
267        }
268
269        // Begin nbm users environment
270        begin_users_env_nbm($is_action_send);
271
272        foreach ($data_users as $nbm_user)
273        {
274          if ((!$is_action_send) and check_sendmail_timeout())
275          {
276            // Stop fill list on 'list_to_send', if the quota is override
277            $page['infos'][] = $msg_break_timeout;
278            break;
279          }
280          if (($is_action_send) and check_sendmail_timeout())
281          {
282            // Stop fill list on 'send', if the quota is override
283            $page['errors'][] = $msg_break_timeout;
284            break;
285          }
286
287          // set env nbm user
288          set_user_on_env_nbm($nbm_user, $is_action_send);
289
290          if ($is_action_send)
291          {
292            set_make_full_url();
293            // Fill return list of "treated" check_key for 'send'
294            $return_list[] = $nbm_user['check_key'];
295
296            if ($conf['nbm_send_detailed_content'])
297            {
298               $news = news($nbm_user['last_send'], $dbnow, false, $conf['nbm_send_html_mail']);
299               $exist_data = count($news) > 0;
300            }
301            else
302            {
303              $exist_data = news_exists($nbm_user['last_send'], $dbnow);
304            }
305
306            if ($exist_data)
307            {
308              $subject = '['.$conf['gallery_title'].'] '.l10n('New photos added');
309
310              // Assign current var for nbm mail
311              assign_vars_nbm_mail_content($nbm_user);
312
313              if (!is_null($nbm_user['last_send']))
314              {
315                $env_nbm['mail_template']->assign
316                (
317                  'content_new_elements_between',
318                  array
319                  (
320                    'DATE_BETWEEN_1' => $nbm_user['last_send'],
321                    'DATE_BETWEEN_2' => $dbnow,
322                  )
323                );
324              }
325              else
326              {
327                $env_nbm['mail_template']->assign
328                (
329                  'content_new_elements_single',
330                  array
331                  (
332                    'DATE_SINGLE' => $dbnow,
333                  )
334                );
335              }
336
337              if ($conf['nbm_send_detailed_content'])
338              {
339                $env_nbm['mail_template']->assign('global_new_lines', $news);
340              }
341
342              $nbm_user_customize_mail_content = 
343                trigger_event('nbm_render_user_customize_mail_content',
344                  $customize_mail_content, $nbm_user);
345              if (!empty($nbm_user_customize_mail_content))
346              {
347                $env_nbm['mail_template']->assign
348                (
349                  'custom_mail_content', $nbm_user_customize_mail_content
350                );
351              }
352
353              if ($conf['nbm_send_html_mail'] and $conf['nbm_send_recent_post_dates'])
354              {
355                $recent_post_dates = get_recent_post_dates_array(
356                  $conf['recent_post_dates']['NBM']);
357                foreach ($recent_post_dates as $date_detail)
358                {
359                  $env_nbm['mail_template']->append
360                  (
361                    'recent_posts',
362                    array
363                    (
364                      'TITLE' => get_title_recent_post_date($date_detail),
365                      'HTML_DATA' => get_html_description_recent_post_date($date_detail)
366                    )
367                  );
368                }
369              }
370
371              $env_nbm['mail_template']->assign
372              (
373                array
374                (
375                  'GOTO_GALLERY_TITLE' => $conf['gallery_title'],
376                  'GOTO_GALLERY_URL' => get_gallery_home_url(),
377                  'SEND_AS_NAME'      => $env_nbm['send_as_name'],
378                )
379              );
380             
381              $ret = pwg_mail(
382                array(
383                  'name' => stripslashes($nbm_user['username']),
384                  'email' => $nbm_user['mail_address'],
385                  ),
386                array(
387                  'from' => $env_nbm['send_as_mail_formated'],
388                  'subject' => $subject,
389                  'email_format' => $env_nbm['email_format'],
390                  'content' => $env_nbm['mail_template']->parse('notification_by_mail', true),
391                  'content_format' => $env_nbm['email_format'],
392                  )
393                );
394
395              if ($ret)
396              {
397                inc_mail_sent_success($nbm_user);
398
399                $datas[] = array(
400                  'user_id' => $nbm_user['user_id'],
401                  'last_send' => $dbnow
402                  );
403              }
404              else
405              {
406                inc_mail_sent_failed($nbm_user);
407              }
408
409              unset_make_full_url();
410            }
411          }
412          else
413          {
414            if (news_exists($nbm_user['last_send'], $dbnow))
415            {
416              // Fill return list of "selected" users for 'list_to_send'
417              $return_list[] = $nbm_user;
418            }
419          }
420
421          // unset env nbm user
422          unset_user_on_env_nbm();
423        }
424
425        // Restore nbm environment
426        end_users_env_nbm();
427
428        if ($is_action_send)
429        {
430          mass_updates(
431            USER_MAIL_NOTIFICATION_TABLE,
432            array(
433              'primary' => array('user_id'),
434              'update' => array('last_send')
435             ),
436             $datas
437             );
438
439          display_counter_info();
440        }
441      }
442      else
443      {
444        if ($is_action_send)
445        {
446          $page['errors'][] = l10n('No user to send notifications by mail.');
447        }
448      }
449    }
450    else
451    {
452      // Quick List, don't check news
453      // Fill return list of "selected" users for 'list_to_send'
454      $return_list = $data_users;
455    }
456  }
457
458  // Return list of "selected" users for 'list_to_send'
459  // Return list of "treated" check_key for 'send'
460  return $return_list;
461}
462
463// +-----------------------------------------------------------------------+
464// | Main                                                                  |
465// +-----------------------------------------------------------------------+
466if (!isset($_GET['mode']))
467{
468  $page['mode'] = 'send';
469}
470else
471{
472  $page['mode'] = $_GET['mode'];
473}
474
475// +-----------------------------------------------------------------------+
476// | Check Access and exit when user status is not ok                      |
477// +-----------------------------------------------------------------------+
478check_status(get_tab_status($page['mode']));
479
480
481// +-----------------------------------------------------------------------+
482// | Add event handler                                                     |
483// +-----------------------------------------------------------------------+
484add_event_handler('nbm_render_global_customize_mail_content', 'render_global_customize_mail_content');
485trigger_action('nbm_event_handler_added');
486
487
488// +-----------------------------------------------------------------------+
489// | Insert new users with mails                                           |
490// +-----------------------------------------------------------------------+
491if (!isset($_POST) or (count($_POST) ==0))
492{
493  // No insert data in post mode
494  insert_new_data_user_mail_notification();
495}
496
497// +-----------------------------------------------------------------------+
498// | Treatment of tab post                                                 |
499// +-----------------------------------------------------------------------+
500switch ($page['mode'])
501{
502  case 'param' :
503  {
504    if (isset($_POST['param_submit']))
505    {
506      $updated_param_count = 0;
507      // Update param
508      $result = pwg_query('select param, value from '.CONFIG_TABLE.' where param like \'nbm\\_%\'');
509      while ($nbm_user = pwg_db_fetch_assoc($result))
510      {
511        if (isset($_POST[$nbm_user['param']]))
512        {
513          $value = $_POST[$nbm_user['param']];
514
515          $query = '
516update
517'.CONFIG_TABLE.'
518set
519  value = \''. str_replace("\'", "''", $value).'\'
520where
521  param = \''.$nbm_user['param'].'\';';
522          pwg_query($query);
523          $updated_param_count += 1;
524        }
525      }
526
527      $page['infos'][] = l10n_dec(
528        '%d parameter was updated.', '%d parameters were updated.',
529        $updated_param_count
530        );
531
532      // Reload conf with new values
533      load_conf_from_db('param like \'nbm\\_%\'');
534    }
535  }
536  case 'subscribe' :
537  {
538    if (isset($_POST['falsify']) and isset($_POST['cat_true']))
539    {
540      $check_key_treated = unsubscribe_notification_by_mail(true, $_POST['cat_true']);
541      do_timeout_treatment('cat_true', $check_key_treated);
542    }
543    else
544    if (isset($_POST['trueify']) and isset($_POST['cat_false']))
545    {
546      $check_key_treated = subscribe_notification_by_mail(true, $_POST['cat_false']);
547      do_timeout_treatment('cat_false', $check_key_treated);
548    }
549    break;
550  }
551
552  case 'send' :
553  {
554    if (isset($_POST['send_submit']) and isset($_POST['send_selection']) and isset($_POST['send_customize_mail_content']))
555    {
556      $check_key_treated = do_action_send_mail_notification('send', $_POST['send_selection'], stripslashes($_POST['send_customize_mail_content']));
557      do_timeout_treatment('send_selection', $check_key_treated);
558    }
559  }
560}
561
562// +-----------------------------------------------------------------------+
563// | template initialization                                               |
564// +-----------------------------------------------------------------------+
565$template->set_filenames
566(
567  array
568  (
569    'double_select' => 'double_select.tpl',
570    'notification_by_mail'=>'notification_by_mail.tpl'
571  )
572);
573
574$template->assign
575(
576  array
577  (
578    'U_HELP' => get_root_url().'admin/popuphelp.php?page=notification_by_mail',
579    'F_ACTION'=> $base_url.get_query_string_diff(array())
580  )
581);
582
583if (is_autorize_status(ACCESS_WEBMASTER))
584{
585  // TabSheet
586  $tabsheet = new tabsheet();
587  $tabsheet->set_id('nbm');
588  $tabsheet->select($page['mode']);
589  $tabsheet->assign();
590}
591
592if ($must_repost)
593{
594  // Get name of submit button
595  $repost_submit_name = '';
596  if (isset($_POST['falsify']))
597  {
598    $repost_submit_name = 'falsify';
599  }
600  elseif (isset($_POST['trueify']))
601  {
602    $repost_submit_name = 'trueify';
603  }
604  elseif (isset($_POST['send_submit']))
605  {
606    $repost_submit_name = 'send_submit';
607  }
608
609  $template->assign('REPOST_SUBMIT_NAME', $repost_submit_name);
610}
611
612switch ($page['mode'])
613{
614  case 'param' :
615  {
616    $template->assign(
617      $page['mode'],
618      array(
619        'SEND_HTML_MAIL' => $conf['nbm_send_html_mail'],
620        'SEND_MAIL_AS' => $conf['nbm_send_mail_as'],
621        'SEND_DETAILED_CONTENT' => $conf['nbm_send_detailed_content'],
622        'COMPLEMENTARY_MAIL_CONTENT' => $conf['nbm_complementary_mail_content'],
623        'SEND_RECENT_POST_DATES' => $conf['nbm_send_recent_post_dates'],
624        ));
625    break;
626  }
627
628  case 'subscribe' :
629  {
630    $template->assign( $page['mode'], true );
631
632    $template->assign(
633      array(
634        'L_CAT_OPTIONS_TRUE' => l10n('Subscribed'),
635        'L_CAT_OPTIONS_FALSE' => l10n('Unsubscribed')
636        )
637      );
638
639    $data_users = get_user_notifications('subscribe');
640   
641    $opt_true = array();
642    $opt_true_selected = array();
643    $opt_false = array();
644    $opt_false_selected = array();
645    foreach ($data_users as $nbm_user)
646    {
647      if (get_boolean($nbm_user['enabled']))
648      {
649        $opt_true[ $nbm_user['check_key'] ] = stripslashes($nbm_user['username']).'['.get_email_address_as_display_text($nbm_user['mail_address']).']';
650        if ((isset($_POST['falsify']) and isset($_POST['cat_true']) and in_array($nbm_user['check_key'], $_POST['cat_true'])))
651        {
652          $opt_true_selected[] = $nbm_user['check_key'];
653        }
654      }
655      else
656      {
657        $opt_false[ $nbm_user['check_key'] ] = stripslashes($nbm_user['username']).'['.get_email_address_as_display_text($nbm_user['mail_address']).']';
658        if (isset($_POST['trueify']) and isset($_POST['cat_false']) and in_array($nbm_user['check_key'], $_POST['cat_false']))
659        {
660          $opt_false_selected[] = $nbm_user['check_key'];
661        }
662      }
663    }
664    $template->assign( array(
665        'category_option_true'          => $opt_true,
666        'category_option_true_selected' => $opt_true_selected,
667        'category_option_false'         => $opt_false,
668        'category_option_false_selected' => $opt_false_selected,
669        )
670    );
671    $template->assign_var_from_handle('DOUBLE_SELECT', 'double_select');
672    break;
673  }
674
675  case 'send' :
676  {
677    $tpl_var = array('users'=> array() );
678
679    $data_users = do_action_send_mail_notification('list_to_send');
680
681    $tpl_var['CUSTOMIZE_MAIL_CONTENT'] = 
682      isset($_POST['send_customize_mail_content']) 
683        ? stripslashes($_POST['send_customize_mail_content']) 
684        : $conf['nbm_complementary_mail_content'];
685
686    if  (count($data_users))
687    {
688      foreach ($data_users as $nbm_user)
689      {
690        if (
691            (!$must_repost) or // Not timeout, normal treatment
692            (($must_repost) and in_array($nbm_user['check_key'], $_POST['send_selection']))  // Must be repost, show only user to send
693            )
694        {
695          $tpl_var['users'][] = 
696            array(
697              'ID' => $nbm_user['check_key'],
698              'CHECKED' =>  ( // not check if not selected,  on init select<all
699                              isset($_POST['send_selection']) and // not init
700                              !in_array($nbm_user['check_key'], $_POST['send_selection']) // not selected
701                            )   ? '' : 'checked="checked"',
702              'USERNAME'=> stripslashes($nbm_user['username']),
703              'EMAIL' => get_email_address_as_display_text($nbm_user['mail_address']),
704              'LAST_SEND'=> $nbm_user['last_send']
705              );
706        }
707      }
708    }
709    $template->assign($page['mode'], $tpl_var);
710    break;
711  }
712}
713
714// +-----------------------------------------------------------------------+
715// | Sending html code                                                     |
716// +-----------------------------------------------------------------------+
717$template->assign_var_from_handle('ADMIN_CONTENT', 'notification_by_mail');
718
719?>
Note: See TracBrowser for help on using the repository browser.