source: trunk/admin/notification_by_mail.php @ 5021

Last change on this file since 5021 was 5021, checked in by nikrou, 14 years ago

Feature 1451 : localization with gettext
Use php-gettext (developpement version rev43, because of php5.3) as fallback
Use native language (english) instead of key for translation
Keep directory en_UK for english customization
Need some refactoring for plurals

Todo : managing plugins in the same way

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