source: trunk/admin/notification_by_mail.php @ 1112

Last change on this file since 1112 was 1112, checked in by rub, 18 years ago

[NBM] Step 5: Change notification queries in order to try to optimize treatment duration.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 17.8 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | PhpWebGallery - a PHP based picture gallery                           |
4// | Copyright (C) 2002-2003 Pierrick LE GALL - pierrick@phpwebgallery.net |
5// | Copyright (C) 2003-2006 PhpWebGallery Team - http://phpwebgallery.net |
6// | Copyright (C) 2006 Ruben ARNAUD - team@phpwebgallery.net              |
7// +-----------------------------------------------------------------------+
8// | branch        : BSF (Best So Far)
9// | file          : $RCSfile$
10// | last update   : $Date: 2006-03-28 22:33:29 +0000 (Tue, 28 Mar 2006) $
11// | last modifier : $Author: rub $
12// | revision      : $Revision: 1112 $
13// +-----------------------------------------------------------------------+
14// | This program is free software; you can redistribute it and/or modify  |
15// | it under the terms of the GNU General Public License as published by  |
16// | the Free Software Foundation                                          |
17// |                                                                       |
18// | This program is distributed in the hope that it will be useful, but   |
19// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
20// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
21// | General Public License for more details.                              |
22// |                                                                       |
23// | You should have received a copy of the GNU General Public License     |
24// | along with this program; if not, write to the Free Software           |
25// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
26// | USA.                                                                  |
27// +-----------------------------------------------------------------------+
28
29// +-----------------------------------------------------------------------+
30// | include                                                               |
31// +-----------------------------------------------------------------------+
32
33if (!defined('PHPWG_ROOT_PATH'))
34{
35  die ("Hacking attempt!");
36}
37
38include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
39include_once(PHPWG_ROOT_PATH.'admin/include/functions_notification_by_mail.inc.php');
40include_once(PHPWG_ROOT_PATH.'include/common.inc.php');
41include_once(PHPWG_ROOT_PATH.'include/functions_notification.inc.php');
42include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
43
44// +-----------------------------------------------------------------------+
45// | Check Access and exit when user status is not ok                      |
46// +-----------------------------------------------------------------------+
47check_status(ACCESS_ADMINISTRATOR);
48
49// +-----------------------------------------------------------------------+
50// | functions                                                             |
51// +-----------------------------------------------------------------------+
52
53/*
54 * Get the authorized_status for each tab
55 * return corresponding status
56*/
57function get_tab_status($mode)
58{
59  $result = ACCESS_WEBMASTER;
60  switch ($mode)
61  {
62    case 'param':
63    case 'subscribe' :
64      $result = ACCESS_WEBMASTER;
65      break;
66    case 'send' :
67      $result = ACCESS_ADMINISTRATOR;
68      break;
69    default:
70      $result = ACCESS_WEBMASTER;
71      break;
72  }
73  return $result;
74}
75
76/*
77 * Inserting News users
78 */
79function insert_new_data_user_mail_notification()
80{
81  global $conf, $page;
82
83  // Set null mail_address empty
84  $query = '
85update
86  '.USERS_TABLE.'
87set
88  mail_address = null
89where
90  trim(mail_address) = \'\';';
91  pwg_query($query);
92
93  // null mail_address are not selected in the list
94  $query = '
95select
96  u.id user_id, u.username, u.mail_address
97from
98  '.USERS_TABLE.' as u left join '.USER_MAIL_NOTIFICATION_TABLE.' as m on u.id = m.user_id
99where
100  u.mail_address is not null and
101  m.user_id is null
102order by
103  id;';
104
105  $result = pwg_query($query);
106
107  if (mysql_num_rows($result) > 0)
108  {
109    $inserts = array();
110    $check_key_list = array();
111
112    while ($row = mysql_fetch_array($result))
113    {
114      // Calculate key
115      $row['check_key'] = find_available_check_key();
116
117      // Save key
118      array_push($check_key_list, $row['check_key']);
119
120      // Insert new rows
121      array_push
122      (
123        $inserts, 
124        array
125        (
126          'user_id' => $row['user_id'],
127          'check_key' => $row['check_key'],
128          'enabled' => 'false' // By default if false, set to true with specific functions
129        )
130      );
131
132      array_push($page['infos'], sprintf(l10n('nbm_User %s [%s] added.'), $row['username'], $row['mail_address']));
133    }
134
135    // Insert new rows
136    mass_inserts(USER_MAIL_NOTIFICATION_TABLE, array('user_id', 'check_key', 'enabled'), $inserts);
137    // Update field enabled with specific function
138    do_subscribe_unsubcribe_notification_by_mail
139    (
140      ($conf['default_value_user_mail_notification_enabled'] == true ? true : false),
141      $check_key_list
142    );
143  }
144}
145
146/*
147 * Send mail for notification to all users
148 * Return list of "treated/selected" users
149 */
150function do_action_send_mail_notification($action = 'prepare', $check_key_list = array(), $customize_mail_content = '')
151{
152  global $conf, $page, $user, $lang_info, $lang;
153  list($dbnow) = mysql_fetch_row(pwg_query('SELECT NOW();'));
154  $return_list = array();
155  $is_action_send = ($action == 'send');
156
157  $quoted_check_key_list = quote_check_key_list($check_key_list);
158  if (count($quoted_check_key_list) != 0 )
159  {
160    $query_and_check_key = ' and
161  check_key in ('.implode(",", $quoted_check_key_list).') ';
162  }
163  else
164  {
165    $query_and_check_key = '';
166  }
167
168  if (isset($customize_mail_content))
169  {
170    $customize_mail_content = $conf['nbm_complementary_mail_content'];
171  }
172
173  // disabled and null mail_address are not selected in the list
174  $query = '
175select
176  N.user_id, N.check_key, U.username, U.mail_address, N.last_send
177from
178  '.USER_MAIL_NOTIFICATION_TABLE.' as N,
179  '.USERS_TABLE.' as U
180where
181  N.user_id =  U.id and
182  N.enabled = \'true\' and
183  U.mail_address is not null'.$query_and_check_key.'
184order by
185  username;';
186
187  $result = pwg_query($query);
188
189  if (mysql_num_rows($result) > 0)
190  {
191    $error_on_mail_count = 0;
192    $sent_mail_count = 0;
193    $datas = array();
194    // Save $user, $lang_info and $lang arrays (include/user.inc.php has been executed)
195    $sav_mailtousers_user = $user;
196    $sav_mailtousers_lang_info = $lang_info;
197    $sav_mailtousers_lang = $lang;
198    // Save message info and error in the original language
199    $msg_info = l10n('nbm_Mail sent to %s [%s].');
200    $msg_error = l10n('nbm_Error when sending email to %s [%s].');
201    // Last Language
202    $last_mailtousers_language = $user['language'];
203
204    if ($is_action_send)
205    {
206      // Init mail configuration
207      $send_as_name = ((isset($conf['nbm_send_mail_as']) and !empty($conf['nbm_send_mail_as'])) ? $conf['nbm_send_mail_as'] : $conf['gallery_title']);
208      $send_as_mail_address = get_webmaster_mail_address();
209      $send_as_mail_formated = format_email($send_as_name, $send_as_mail_address);
210    }
211
212    while ($row = mysql_fetch_array($result))
213    {
214      $user = array();
215      $user['id'] = $row['user_id'];
216      $user = array_merge($user, getuserdata($user['id'], true));
217
218      if ($last_mailtousers_language != $user['language'])
219      {
220        $last_mailtousers_language = $user['language'];
221
222        // Re-Init language arrays
223        $lang_info = array();
224        $lang  = array();
225
226        // language files
227        include(get_language_filepath('common.lang.php'));
228        // No test admin because script is checked admin (user selected no)
229        // Translations are in admin file too
230        include(get_language_filepath('admin.lang.php'));
231      }
232
233      if ($is_action_send)
234      {
235        $message = '';
236        $news = news($row['last_send'], $dbnow);
237        if (count($news) > 0)
238        {
239          array_push($return_list, $row);
240
241          $subject = '['.$conf['gallery_title'].']: '.l10n('nbm_ContentObject');
242          $message .= sprintf(l10n('nbm_ContentHello'), $row['username']).",\n\n";
243
244          if (!is_null($row['last_send']))
245            $message .= sprintf(l10n('nbm_ContentNewElementsBetween'), $row['last_send'], $dbnow);
246          else
247            $message .= sprintf(l10n('nbm_ContentNewElements'), $dbnow);
248
249          if ($conf['nbm_send_detailed_content'])
250          {
251            $message .= ":\n";
252
253            foreach ($news as $line)
254            {
255              $message .= '  o '.$line."\n";
256            }
257            $message .= "\n";
258          }
259          else
260          {
261            $message .= ".\n";
262          }
263
264          $message .= sprintf(l10n('nbm_ContentGoTo'), $conf['gallery_title'], $conf['gallery_url'])."\n\n";
265          $message .= $customize_mail_content."\n\n";
266          $message .= l10n('nbm_ContentByeBye')."\n   ".$send_as_name."\n\n";
267          $message .= "\n".sprintf(l10n('nbm_ContentUnsubscribe'), $send_as_mail_address)."\n\n";
268
269          if (pwg_mail(format_email($row['username'], $row['mail_address']), $send_as_mail_formated, $subject, $message))
270          {
271            $sent_mail_count += 1;
272            array_push($page['infos'], sprintf($msg_info, $row['username'], $row['mail_address']));
273            $data = array('user_id' => $row['user_id'],
274                          'last_send' => $dbnow);
275            array_push($datas, $data);
276          }
277          else
278          {
279            $error_on_mail_count += 1;
280            array_push($page['errors'], sprintf($msg_error, $row['username'], $row['mail_address']));
281          }
282        }
283      }
284      else
285      {
286        if (news_exists($row['last_send'], $dbnow))
287        {
288          array_push($return_list, $row);
289        }
290      }
291    }
292
293    // Restore $user, $lang_info and $lang arrays (include/user.inc.php has been executed)
294    $user = $sav_mailtousers_user;
295    $lang_info = $sav_mailtousers_lang_info;
296    $lang = $sav_mailtousers_lang;
297
298    if ($is_action_send)
299    {
300      mass_updates(
301        USER_MAIL_NOTIFICATION_TABLE,
302        array(
303          'primary' => array('user_id'),
304          'update' => array('last_send')
305         ),
306         $datas
307         );
308
309      if ($error_on_mail_count != 0)
310      {
311        array_push($page['errors'], sprintf(l10n('nbm_%d mails were not sent.'), $error_on_mail_count));
312      }
313      else
314      {
315        if ($sent_mail_count == 0)
316          array_push($page['infos'], l10n('nbm_No mail to send.'));
317        else
318          array_push($page['infos'], sprintf(l10n('nbm_%d mails were sent.'), $sent_mail_count));
319      }
320    }
321  }
322  else
323  {
324    if ($is_action_send)
325    {
326      array_push($page['errors'], l10n('nbm_No user to send notifications by mail.'));
327    }
328  }
329  return $return_list;
330}
331
332// +-----------------------------------------------------------------------+
333// | Main                                                                  |
334// +-----------------------------------------------------------------------+
335if (!isset($_GET['mode']))
336{
337  $page['mode'] = 'send';
338}
339else
340{
341  $page['mode'] = $_GET['mode'];
342}
343
344// +-----------------------------------------------------------------------+
345// | Check Access and exit when user status is not ok                      |
346// +-----------------------------------------------------------------------+
347check_status(get_tab_status($page['mode']));
348
349// +-----------------------------------------------------------------------+
350// | Insert new users with mails                                           |
351// +-----------------------------------------------------------------------+
352if (!isset($_POST) or (count($_POST) ==0))
353{
354  // No insert data in post mode
355  insert_new_data_user_mail_notification();
356}
357
358// +-----------------------------------------------------------------------+
359// | Treatment of tab post                                                 |
360// +-----------------------------------------------------------------------+
361switch ($page['mode'])
362{
363  case 'param' :
364  {
365    $updated_param_count = 0;
366    // Update param
367    $result = pwg_query('select param, value from '.CONFIG_TABLE.' where param like \'nbm\\_%\'');
368    while ($row = mysql_fetch_array($result))
369    {
370      if (isset($_POST['param_submit']))
371      {
372        if (isset($_POST[$row['param']]))
373        {
374          $value = $_POST[$row['param']];
375
376          $query = '
377update
378  '.CONFIG_TABLE.'
379set
380  value = \''. str_replace("\'", "''", $value).'\'
381where
382  param = \''.$row['param'].'\';';
383          pwg_query($query);
384          $updated_param_count += 1;
385        }
386      }
387
388      $conf[$row['param']] = $row['value'];
389
390      // if the parameter is present in $_POST array (if a form is submited), we
391      // override it with the submited value
392      if (isset($_POST[$row['param']]))
393      {
394        $conf[$row['param']] = stripslashes($_POST[$row['param']]);
395      }
396
397      // If the field is true or false, the variable is transformed into a
398      // boolean value.
399      if ($conf[$row['param']] == 'true' or $conf[$row['param']] == 'false')
400      {
401        $conf[$row['param']] = get_boolean($conf[$row['param']]);
402      }
403    }
404   
405    if ($updated_param_count != 0)
406    {
407      array_push($page['infos'], sprintf(l10n('nbm_updated_param_count'), $updated_param_count));
408    }
409  }
410  case 'subscribe' :
411  {
412    if (isset($_POST['falsify']) and isset($_POST['cat_true']))
413    {
414      unsubcribe_notification_by_mail($_POST['cat_true']);
415    }
416    else
417    if (isset($_POST['trueify']) and isset($_POST['cat_false']))
418    {
419      subcribe_notification_by_mail($_POST['cat_false']);
420    }
421    break;
422  }
423
424  case 'send' :
425  {
426    if (isset($_POST['send_submit']) and isset($_POST['send_selection']) and isset($_POST['send_customize_mail_content']))
427    {
428      do_action_send_mail_notification('send', $_POST['send_selection'], $_POST['send_customize_mail_content']);
429    }
430  }
431}
432
433// +-----------------------------------------------------------------------+
434// | template initialization                                               |
435// +-----------------------------------------------------------------------+
436$template->set_filenames
437(
438  array
439  (
440    'double_select' => 'admin/double_select.tpl',
441    'notification_by_mail'=>'admin/notification_by_mail.tpl'
442  )
443);
444
445$base_url = get_root_url().'admin.php';
446
447$template->assign_vars
448(
449  array
450  (
451    'U_TABSHEET_TITLE' => l10n('nbm_'.$page['mode'].'_mode'),
452    'U_HELP' => add_url_params(get_root_url().'/popuphelp.php', array('page' => 'notification_by_mail')),
453    'F_ACTION'=> $base_url.get_query_string_diff(array())
454  )
455);
456
457if (is_autorize_status(ACCESS_WEBMASTER))
458{
459  $template->assign_block_vars
460  (
461    'header_link',
462    array
463    (
464      'PARAM_MODE' => add_url_params($base_url.get_query_string_diff(array('mode', 'select')), array('mode' => 'param')),
465      'SUBSCRIBE_MODE' => add_url_params($base_url.get_query_string_diff(array('mode', 'select')), array('mode' => 'subscribe')),
466      'SEND_MODE' => add_url_params($base_url.get_query_string_diff(array('mode', 'select')), array('mode' => 'send'))
467    )
468  );
469}
470
471switch ($page['mode'])
472{
473  case 'param' :
474  {
475    $template->assign_block_vars(
476      $page['mode'],
477      array(
478        'SEND_MAIL_AS' => $conf['nbm_send_mail_as'],
479        'SEND_DETAILED_CONTENT_YES' => ($conf['nbm_send_detailed_content'] ? 'checked="checked"' : ''),
480        'SEND_DETAILED_CONTENT_NO' => (!$conf['nbm_send_detailed_content'] ? 'checked="checked"' : ''),
481        'COMPLEMENTARY_MAIL_CONTENT' => $conf['nbm_complementary_mail_content']
482        ));
483    break;
484  }
485
486  case 'subscribe' :
487  {
488    $template->assign_block_vars(
489      $page['mode'],
490      array(
491        ));
492
493    $template->assign_vars(
494      array(
495        'L_CAT_OPTIONS_TRUE' => l10n('nbm_subscribe_col'),
496        'L_CAT_OPTIONS_FALSE' => l10n('nbm_unsubscribe_col')
497        )
498      );
499
500    $query = '
501select
502  N.check_key, N.enabled, U.username, U.mail_address
503from
504  '.USER_MAIL_NOTIFICATION_TABLE.' as N,
505  '.USERS_TABLE.' as U
506where
507  N.user_id =  U.id
508order by
509  username;';
510
511    $result = pwg_query($query);
512    if (!empty($result))
513    {
514      while ($row = mysql_fetch_array($result))
515      {
516        $template->assign_block_vars(
517          (get_boolean($row['enabled']) ? 'category_option_true' : 'category_option_false'),
518          array('SELECTED' => '',
519                'VALUE' => $row['check_key'],
520                'OPTION' => $row['username'].'['.$row['mail_address'].']'
521            ));
522      }
523    }
524
525    break;
526  }
527
528  case 'send' :
529  {
530    $template->assign_block_vars($page['mode'], array());
531
532    $data_rows = do_action_send_mail_notification('prepare');
533
534    if  (count($data_rows) == 0)
535    {
536      $template->assign_block_vars($page['mode'].'.send_empty', array());
537    }
538    else
539    {
540      $template->assign_block_vars(
541        $page['mode'].'.send_data',
542        array(
543  //        'URL_CHECK_ALL' => add_url_params($base_url.get_query_string_diff(array('select')), array('select' => 'all')),
544  //        'URL_UNCHECK_ALL' => add_url_params($base_url.get_query_string_diff(array('select')), array('select' => 'none')),
545          'CUSTOMIZE_MAIL_CONTENT' => isset($_POST['send_customize_mail_content']) ? $_POST['send_customize_mail_content'] : $conf['nbm_complementary_mail_content']
546          ));
547
548      foreach ($data_rows as $num => $local_user)
549          $template->assign_block_vars(
550            $page['mode'].'.send_data.user_send_mail',
551            array(
552              'CLASS' => ($num % 2 == 1) ? 'row2' : 'row1',
553              'ID' => $local_user['check_key'],
554              'CHECKED' => isset($_POST['send_uncheck_all']) ? '' : 'checked="checked"',
555              'USERNAME'=> $local_user['username'],
556              'EMAIL' => $local_user['mail_address'],
557              'LAST_SEND'=> $local_user['last_send']
558              ));
559    }
560
561    break;
562  }
563}
564
565// +-----------------------------------------------------------------------+
566// | Sending html code                                                     |
567// +-----------------------------------------------------------------------+
568$template->assign_var_from_handle('DOUBLE_SELECT', 'double_select');
569$template->assign_var_from_handle('ADMIN_CONTENT', 'notification_by_mail');
570
571?>
Note: See TracBrowser for help on using the repository browser.