source: trunk/admin/notification_by_mail.php @ 25018

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

remove all array_push (50% slower than []) + some changes missing for feature:2978

  • 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              if (pwg_mail
382                  (
383                    format_email(stripslashes($nbm_user['username']), $nbm_user['mail_address']),
384                    array
385                    (
386                      'from' => $env_nbm['send_as_mail_formated'],
387                      'subject' => $subject,
388                      'email_format' => $env_nbm['email_format'],
389                      'content' => $env_nbm['mail_template']->parse('notification_by_mail', true),
390                      'content_format' => $env_nbm['email_format'],
391                      'theme' => $nbm_user['theme']
392                    )
393                  ))
394              {
395                inc_mail_sent_success($nbm_user);
396
397                $datas[] = array(
398                  'user_id' => $nbm_user['user_id'],
399                  'last_send' => $dbnow
400                  );
401              }
402              else
403              {
404                inc_mail_sent_failed($nbm_user);
405              }
406
407              unset_make_full_url();
408            }
409          }
410          else
411          {
412            if (news_exists($nbm_user['last_send'], $dbnow))
413            {
414              // Fill return list of "selected" users for 'list_to_send'
415              $return_list[] = $nbm_user;
416            }
417          }
418
419          // unset env nbm user
420          unset_user_on_env_nbm();
421        }
422
423        // Restore nbm environment
424        end_users_env_nbm();
425
426        if ($is_action_send)
427        {
428          mass_updates(
429            USER_MAIL_NOTIFICATION_TABLE,
430            array(
431              'primary' => array('user_id'),
432              'update' => array('last_send')
433             ),
434             $datas
435             );
436
437          display_counter_info();
438        }
439      }
440      else
441      {
442        if ($is_action_send)
443        {
444          $page['errors'][] = l10n('No user to send notifications by mail.');
445        }
446      }
447    }
448    else
449    {
450      // Quick List, don't check news
451      // Fill return list of "selected" users for 'list_to_send'
452      $return_list = $data_users;
453    }
454  }
455
456  // Return list of "selected" users for 'list_to_send'
457  // Return list of "treated" check_key for 'send'
458  return $return_list;
459}
460
461// +-----------------------------------------------------------------------+
462// | Main                                                                  |
463// +-----------------------------------------------------------------------+
464if (!isset($_GET['mode']))
465{
466  $page['mode'] = 'send';
467}
468else
469{
470  $page['mode'] = $_GET['mode'];
471}
472
473// +-----------------------------------------------------------------------+
474// | Check Access and exit when user status is not ok                      |
475// +-----------------------------------------------------------------------+
476check_status(get_tab_status($page['mode']));
477
478
479// +-----------------------------------------------------------------------+
480// | Add event handler                                                     |
481// +-----------------------------------------------------------------------+
482add_event_handler('nbm_render_global_customize_mail_content', 'render_global_customize_mail_content');
483trigger_action('nbm_event_handler_added');
484
485
486// +-----------------------------------------------------------------------+
487// | Insert new users with mails                                           |
488// +-----------------------------------------------------------------------+
489if (!isset($_POST) or (count($_POST) ==0))
490{
491  // No insert data in post mode
492  insert_new_data_user_mail_notification();
493}
494
495// +-----------------------------------------------------------------------+
496// | Treatment of tab post                                                 |
497// +-----------------------------------------------------------------------+
498switch ($page['mode'])
499{
500  case 'param' :
501  {
502    if (isset($_POST['param_submit']))
503    {
504      $updated_param_count = 0;
505      // Update param
506      $result = pwg_query('select param, value from '.CONFIG_TABLE.' where param like \'nbm\\_%\'');
507      while ($nbm_user = pwg_db_fetch_assoc($result))
508      {
509        if (isset($_POST[$nbm_user['param']]))
510        {
511          $value = $_POST[$nbm_user['param']];
512
513          $query = '
514update
515'.CONFIG_TABLE.'
516set
517  value = \''. str_replace("\'", "''", $value).'\'
518where
519  param = \''.$nbm_user['param'].'\';';
520          pwg_query($query);
521          $updated_param_count += 1;
522        }
523      }
524
525      $page['infos'][] = l10n_dec(
526        '%d parameter was updated.', '%d parameters were updated.',
527        $updated_param_count
528        );
529
530      // Reload conf with new values
531      load_conf_from_db('param like \'nbm\\_%\'');
532    }
533  }
534  case 'subscribe' :
535  {
536    if (isset($_POST['falsify']) and isset($_POST['cat_true']))
537    {
538      $check_key_treated = unsubscribe_notification_by_mail(true, $_POST['cat_true']);
539      do_timeout_treatment('cat_true', $check_key_treated);
540    }
541    else
542    if (isset($_POST['trueify']) and isset($_POST['cat_false']))
543    {
544      $check_key_treated = subscribe_notification_by_mail(true, $_POST['cat_false']);
545      do_timeout_treatment('cat_false', $check_key_treated);
546    }
547    break;
548  }
549
550  case 'send' :
551  {
552    if (isset($_POST['send_submit']) and isset($_POST['send_selection']) and isset($_POST['send_customize_mail_content']))
553    {
554      $check_key_treated = do_action_send_mail_notification('send', $_POST['send_selection'], stripslashes($_POST['send_customize_mail_content']));
555      do_timeout_treatment('send_selection', $check_key_treated);
556    }
557  }
558}
559
560// +-----------------------------------------------------------------------+
561// | template initialization                                               |
562// +-----------------------------------------------------------------------+
563$template->set_filenames
564(
565  array
566  (
567    'double_select' => 'double_select.tpl',
568    'notification_by_mail'=>'notification_by_mail.tpl'
569  )
570);
571
572$template->assign
573(
574  array
575  (
576    'U_HELP' => get_root_url().'admin/popuphelp.php?page=notification_by_mail',
577    'F_ACTION'=> $base_url.get_query_string_diff(array())
578  )
579);
580
581if (is_autorize_status(ACCESS_WEBMASTER))
582{
583  // TabSheet
584  $tabsheet = new tabsheet();
585  $tabsheet->set_id('nbm');
586  $tabsheet->select($page['mode']);
587  $tabsheet->assign();
588}
589
590if ($must_repost)
591{
592  // Get name of submit button
593  $repost_submit_name = '';
594  if (isset($_POST['falsify']))
595  {
596    $repost_submit_name = 'falsify';
597  }
598  elseif (isset($_POST['trueify']))
599  {
600    $repost_submit_name = 'trueify';
601  }
602  elseif (isset($_POST['send_submit']))
603  {
604    $repost_submit_name = 'send_submit';
605  }
606
607  $template->assign('REPOST_SUBMIT_NAME', $repost_submit_name);
608}
609
610switch ($page['mode'])
611{
612  case 'param' :
613  {
614    $template->assign(
615      $page['mode'],
616      array(
617        'SEND_HTML_MAIL' => $conf['nbm_send_html_mail'],
618        'SEND_MAIL_AS' => $conf['nbm_send_mail_as'],
619        'SEND_DETAILED_CONTENT' => $conf['nbm_send_detailed_content'],
620        'COMPLEMENTARY_MAIL_CONTENT' => $conf['nbm_complementary_mail_content'],
621        'SEND_RECENT_POST_DATES' => $conf['nbm_send_recent_post_dates'],
622        ));
623    break;
624  }
625
626  case 'subscribe' :
627  {
628    $template->assign( $page['mode'], true );
629
630    $template->assign(
631      array(
632        'L_CAT_OPTIONS_TRUE' => l10n('Subscribed'),
633        'L_CAT_OPTIONS_FALSE' => l10n('Unsubscribed')
634        )
635      );
636
637    $data_users = get_user_notifications('subscribe');
638   
639    $opt_true = array();
640    $opt_true_selected = array();
641    $opt_false = array();
642    $opt_false_selected = array();
643    foreach ($data_users as $nbm_user)
644    {
645      if (get_boolean($nbm_user['enabled']))
646      {
647        $opt_true[ $nbm_user['check_key'] ] = stripslashes($nbm_user['username']).'['.get_email_address_as_display_text($nbm_user['mail_address']).']';
648        if ((isset($_POST['falsify']) and isset($_POST['cat_true']) and in_array($nbm_user['check_key'], $_POST['cat_true'])))
649        {
650          $opt_true_selected[] = $nbm_user['check_key'];
651        }
652      }
653      else
654      {
655        $opt_false[ $nbm_user['check_key'] ] = stripslashes($nbm_user['username']).'['.get_email_address_as_display_text($nbm_user['mail_address']).']';
656        if (isset($_POST['trueify']) and isset($_POST['cat_false']) and in_array($nbm_user['check_key'], $_POST['cat_false']))
657        {
658          $opt_false_selected[] = $nbm_user['check_key'];
659        }
660      }
661    }
662    $template->assign( array(
663        'category_option_true'          => $opt_true,
664        'category_option_true_selected' => $opt_true_selected,
665        'category_option_false'         => $opt_false,
666        'category_option_false_selected' => $opt_false_selected,
667        )
668    );
669    $template->assign_var_from_handle('DOUBLE_SELECT', 'double_select');
670    break;
671  }
672
673  case 'send' :
674  {
675    $tpl_var = array('users'=> array() );
676
677    $data_users = do_action_send_mail_notification('list_to_send');
678
679    $tpl_var['CUSTOMIZE_MAIL_CONTENT'] = 
680      isset($_POST['send_customize_mail_content']) 
681        ? stripslashes($_POST['send_customize_mail_content']) 
682        : $conf['nbm_complementary_mail_content'];
683
684    if  (count($data_users))
685    {
686      foreach ($data_users as $nbm_user)
687      {
688        if (
689            (!$must_repost) or // Not timeout, normal treatment
690            (($must_repost) and in_array($nbm_user['check_key'], $_POST['send_selection']))  // Must be repost, show only user to send
691            )
692        {
693          $tpl_var['users'][] = 
694            array(
695              'ID' => $nbm_user['check_key'],
696              'CHECKED' =>  ( // not check if not selected,  on init select<all
697                              isset($_POST['send_selection']) and // not init
698                              !in_array($nbm_user['check_key'], $_POST['send_selection']) // not selected
699                            )   ? '' : 'checked="checked"',
700              'USERNAME'=> stripslashes($nbm_user['username']),
701              'EMAIL' => get_email_address_as_display_text($nbm_user['mail_address']),
702              'LAST_SEND'=> $nbm_user['last_send']
703              );
704        }
705      }
706    }
707    $template->assign($page['mode'], $tpl_var);
708    break;
709  }
710}
711
712// +-----------------------------------------------------------------------+
713// | Sending html code                                                     |
714// +-----------------------------------------------------------------------+
715$template->assign_var_from_handle('ADMIN_CONTENT', 'notification_by_mail');
716
717?>
Note: See TracBrowser for help on using the repository browser.