source: trunk/admin/notification_by_mail.php @ 1115

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

[NBM] Step 6: Undo svn:1114 (Lost functionalities)
Re-adapt idea of svn:1114 and optimize treatment:

o check/uncheck all completely done by Javascript
o add function get_user_notifications
o reduce queries for not detailed content mail

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 19.3 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-30 22:49:49 +0000 (Thu, 30 Mar 2006) $
11// | last modifier : $Author: rub $
12// | revision      : $Revision: 1115 $
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 * Execute all main queries to get list of user
78 *
79 * Type are the type of list 'subscribe', 'send'
80 *
81 * return array of users
82 */
83function get_user_notifications($action, $check_key_list = array())
84{
85  global $conf;
86
87  $data_users = array();
88
89  if (in_array($action, array('subscribe', 'send')))
90  {
91    $quoted_check_key_list = quote_check_key_list($check_key_list);
92    if (count($quoted_check_key_list) != 0 )
93    {
94      $query_and_check_key = ' and
95    check_key in ('.implode(",", $quoted_check_key_list).') ';
96    }
97    else
98    {
99      $query_and_check_key = '';
100    }
101
102    $query = '
103select
104  N.user_id,
105  N.check_key,
106  U.'.$conf['user_fields']['username'].' as username,
107  U.'.$conf['user_fields']['email'].' as mail_address,
108  N.enabled,
109  N.last_send
110from
111  '.USER_MAIL_NOTIFICATION_TABLE.' as N,
112  '.USERS_TABLE.' as U
113where
114  N.user_id =  U.'.$conf['user_fields']['id'];
115 
116    if ($action == 'send')
117    {
118      $query .= ' and
119  N.enabled = \'true\' and
120  U.'.$conf['user_fields']['email'].' is not null'.$query_and_check_key;
121    }
122
123    $query .= '
124order by
125  username;';
126
127    $result = pwg_query($query);
128    if (!empty($result))
129    {
130      while ($nbm_user = mysql_fetch_array($result))
131      {
132        array_push($data_users, $nbm_user);
133      }
134    }
135  }
136  return $data_users;
137}
138
139/*
140 * Inserting News users
141 */
142function insert_new_data_user_mail_notification()
143{
144  global $conf, $page;
145
146  // Set null mail_address empty
147  $query = '
148update
149  '.USERS_TABLE.'
150set
151  '.$conf['user_fields']['email'].' = null
152where
153  trim('.$conf['user_fields']['email'].') = \'\';';
154  pwg_query($query);
155
156  // null mail_address are not selected in the list
157  $query = '
158select
159  u.'.$conf['user_fields']['id'].' as user_id,
160  u.'.$conf['user_fields']['username'].' as username,
161  u.'.$conf['user_fields']['email'].' as mail_address
162from
163  '.USERS_TABLE.' as u left join '.USER_MAIL_NOTIFICATION_TABLE.' as m on u.'.$conf['user_fields']['id'].' = m.user_id
164where
165  u.'.$conf['user_fields']['email'].' is not null and
166  m.user_id is null
167order by
168  user_id;';
169
170  $result = pwg_query($query);
171
172  if (mysql_num_rows($result) > 0)
173  {
174    $inserts = array();
175    $check_key_list = array();
176
177    while ($nbm_user = mysql_fetch_array($result))
178    {
179      // Calculate key
180      $nbm_user['check_key'] = find_available_check_key();
181
182      // Save key
183      array_push($check_key_list, $nbm_user['check_key']);
184
185      // Insert new nbm_users
186      array_push
187      (
188        $inserts, 
189        array
190        (
191          'user_id' => $nbm_user['user_id'],
192          'check_key' => $nbm_user['check_key'],
193          'enabled' => 'false' // By default if false, set to true with specific functions
194        )
195      );
196
197      array_push($page['infos'], sprintf(l10n('nbm_User %s [%s] added.'), $nbm_user['username'], $nbm_user['mail_address']));
198    }
199
200    // Insert new nbm_users
201    mass_inserts(USER_MAIL_NOTIFICATION_TABLE, array('user_id', 'check_key', 'enabled'), $inserts);
202    // Update field enabled with specific function
203    do_subscribe_unsubcribe_notification_by_mail
204    (
205      ($conf['default_value_user_mail_notification_enabled'] == true ? true : false),
206      $check_key_list
207    );
208  }
209}
210
211/*
212 * Send mail for notification to all users
213 * Return list of "treated/selected" users
214 */
215function do_action_send_mail_notification($action = 'list', $check_key_list = array(), $customize_mail_content = '')
216{
217  global $conf, $page, $user, $lang_info, $lang;
218  $return_list = array();
219 
220  if (in_array($action, array('list', 'send')))
221  {
222    list($dbnow) = mysql_fetch_row(pwg_query('SELECT NOW();'));
223
224    $is_action_send = ($action == 'send');
225
226    if (isset($customize_mail_content))
227    {
228      $customize_mail_content = $conf['nbm_complementary_mail_content'];
229    }
230
231    // disabled and null mail_address are not selected in the list
232    $data_users = get_user_notifications('send', $check_key_list);
233
234    if (count($data_users) > 0)
235    {
236      $error_on_mail_count = 0;
237      $sent_mail_count = 0;
238      // Save $user, $lang_info and $lang arrays (include/user.inc.php has been executed)
239      $sav_mailtousers_user = $user;
240      $sav_mailtousers_lang_info = $lang_info;
241      $sav_mailtousers_lang = $lang;
242      // Save message info and error in the original language
243      $msg_info = l10n('nbm_Mail sent to %s [%s].');
244      $msg_error = l10n('nbm_Error when sending email to %s [%s].');
245      // Last Language
246      $last_mailtousers_language = $user['language'];
247
248      if ($is_action_send)
249      {
250        // Init mail configuration
251        $send_as_name = ((isset($conf['nbm_send_mail_as']) and !empty($conf['nbm_send_mail_as'])) ? $conf['nbm_send_mail_as'] : $conf['gallery_title']);
252        $send_as_mail_address = get_webmaster_mail_address();
253        $send_as_mail_formated = format_email($send_as_name, $send_as_mail_address);
254      }
255
256      foreach ($data_users as $nbm_user)
257      {
258        $user = array();
259        $user['id'] = $nbm_user['user_id'];
260        $user = array_merge($user, getuserdata($user['id'], true));
261
262        if ($last_mailtousers_language != $user['language'])
263        {
264          $last_mailtousers_language = $user['language'];
265
266          // Re-Init language arrays
267          $lang_info = array();
268          $lang  = array();
269
270          // language files
271          include(get_language_filepath('common.lang.php'));
272          // No test admin because script is checked admin (user selected no)
273          // Translations are in admin file too
274          include(get_language_filepath('admin.lang.php'));
275        }
276
277        if ($is_action_send)
278        {
279          $message = '';
280
281          if ($conf['nbm_send_detailed_content'])
282          {
283             $news = news($nbm_user['last_send'], $dbnow);
284             $exist_data = count($news) > 0;
285          }
286          else
287          {
288            $exist_data = news_exists($nbm_user['last_send'], $dbnow);
289          }
290
291          if ($exist_data)
292          {
293            array_push($return_list, $nbm_user);
294
295            $subject = '['.$conf['gallery_title'].']: '.l10n('nbm_ContentObject');
296            $message .= sprintf(l10n('nbm_ContentHello'), $nbm_user['username']).",\n\n";
297
298            if (!is_null($nbm_user['last_send']))
299              $message .= sprintf(l10n('nbm_ContentNewElementsBetween'), $nbm_user['last_send'], $dbnow);
300            else
301              $message .= sprintf(l10n('nbm_ContentNewElements'), $dbnow);
302
303            if ($conf['nbm_send_detailed_content'])
304            {
305              $message .= ":\n";
306
307              foreach ($news as $line)
308              {
309                $message .= '  o '.$line."\n";
310              }
311              $message .= "\n";
312            }
313            else
314            {
315              $message .= ".\n";
316            }
317
318            $message .= sprintf(l10n('nbm_ContentGoTo'), $conf['gallery_title'], $conf['gallery_url'])."\n\n";
319            $message .= $customize_mail_content."\n\n";
320            $message .= l10n('nbm_ContentByeBye')."\n   ".$send_as_name."\n\n";
321            $message .= "\n".sprintf(l10n('nbm_ContentUnsubscribe'), $send_as_mail_address)."\n\n";
322
323            if (pwg_mail(format_email($nbm_user['username'], $nbm_user['mail_address']), $send_as_mail_formated, $subject, $message))
324            {
325              $sent_mail_count += 1;
326              array_push($page['infos'], sprintf($msg_info, $nbm_user['username'], $nbm_user['mail_address']));
327
328              $data = array('user_id' => $user_notification['user_id'],
329                            'last_send' => $dbnow);
330              array_push($datas, $data);
331            }
332            else
333            {
334              $error_on_mail_count += 1;
335              array_push($page['errors'], sprintf($msg_error, $nbm_user['username'], $nbm_user['mail_address']));
336            }
337          }
338        }
339        else
340        {
341          if (news_exists($nbm_user['last_send'], $dbnow))
342          {
343            array_push($return_list, $nbm_user);
344          }
345        }
346      }
347
348      // Restore $user, $lang_info and $lang arrays (include/user.inc.php has been executed)
349      $user = $sav_mailtousers_user;
350      $lang_info = $sav_mailtousers_lang_info;
351      $lang = $sav_mailtousers_lang;
352
353      if ($is_action_send)
354      {
355        mass_updates(
356          USER_MAIL_NOTIFICATION_TABLE,
357          array(
358            'primary' => array('user_id'),
359            'update' => array('last_send')
360           ),
361           $datas
362           );
363
364
365        if ($error_on_mail_count != 0)
366        {
367          array_push($page['errors'], sprintf(l10n('nbm_%d mails were not sent.'), $error_on_mail_count));
368        }
369        else
370        {
371          if ($sent_mail_count == 0)
372            array_push($page['infos'], l10n('nbm_No mail to send.'));
373          else
374            array_push($page['infos'], sprintf(l10n('nbm_%d mails were sent.'), $sent_mail_count));
375        }
376      }
377    }
378    else
379    {
380      if ($is_action_send)
381      {
382        array_push($page['errors'], l10n('nbm_No user to send notifications by mail.'));
383      }
384    }
385  }
386  return $return_list;
387}
388
389// +-----------------------------------------------------------------------+
390// | Main                                                                  |
391// +-----------------------------------------------------------------------+
392if (!isset($_GET['mode']))
393{
394  $page['mode'] = 'send';
395}
396else
397{
398  $page['mode'] = $_GET['mode'];
399}
400
401// +-----------------------------------------------------------------------+
402// | Check Access and exit when user status is not ok                      |
403// +-----------------------------------------------------------------------+
404check_status(get_tab_status($page['mode']));
405
406// +-----------------------------------------------------------------------+
407// | Insert new users with mails                                           |
408// +-----------------------------------------------------------------------+
409if (!isset($_POST) or (count($_POST) ==0))
410{
411  // No insert data in post mode
412  insert_new_data_user_mail_notification();
413}
414
415// +-----------------------------------------------------------------------+
416// | Treatment of tab post                                                 |
417// +-----------------------------------------------------------------------+
418switch ($page['mode'])
419{
420  case 'param' :
421  {
422    $updated_param_count = 0;
423    // Update param
424    $result = pwg_query('select param, value from '.CONFIG_TABLE.' where param like \'nbm\\_%\'');
425    while ($nbm_user = mysql_fetch_array($result))
426    {
427      if (isset($_POST['param_submit']))
428      {
429        if (isset($_POST[$nbm_user['param']]))
430        {
431          $value = $_POST[$nbm_user['param']];
432
433          $query = '
434update
435  '.CONFIG_TABLE.'
436set
437  value = \''. str_replace("\'", "''", $value).'\'
438where
439  param = \''.$nbm_user['param'].'\';';
440          pwg_query($query);
441          $updated_param_count += 1;
442        }
443      }
444
445      $conf[$nbm_user['param']] = $nbm_user['value'];
446
447      // if the parameter is present in $_POST array (if a form is submited), we
448      // override it with the submited value
449      if (isset($_POST[$nbm_user['param']]))
450      {
451        $conf[$nbm_user['param']] = stripslashes($_POST[$nbm_user['param']]);
452      }
453
454      // If the field is true or false, the variable is transformed into a
455      // boolean value.
456      if ($conf[$nbm_user['param']] == 'true' or $conf[$nbm_user['param']] == 'false')
457      {
458        $conf[$nbm_user['param']] = get_boolean($conf[$nbm_user['param']]);
459      }
460    }
461   
462    if ($updated_param_count != 0)
463    {
464      array_push($page['infos'], sprintf(l10n('nbm_updated_param_count'), $updated_param_count));
465    }
466  }
467  case 'subscribe' :
468  {
469    if (isset($_POST['falsify']) and isset($_POST['cat_true']))
470    {
471      unsubcribe_notification_by_mail($_POST['cat_true']);
472    }
473    else
474    if (isset($_POST['trueify']) and isset($_POST['cat_false']))
475    {
476      subcribe_notification_by_mail($_POST['cat_false']);
477    }
478    break;
479  }
480
481  case 'send' :
482  {
483    if (isset($_POST['send_submit']) and isset($_POST['send_selection']) and isset($_POST['send_customize_mail_content']))
484    {
485      do_action_send_mail_notification('send', $_POST['send_selection'], $_POST['send_customize_mail_content']);
486    }
487  }
488}
489
490// +-----------------------------------------------------------------------+
491// | template initialization                                               |
492// +-----------------------------------------------------------------------+
493$template->set_filenames
494(
495  array
496  (
497    'double_select' => 'admin/double_select.tpl',
498    'notification_by_mail'=>'admin/notification_by_mail.tpl'
499  )
500);
501
502$base_url = get_root_url().'admin.php';
503
504$template->assign_vars
505(
506  array
507  (
508    'U_TABSHEET_TITLE' => l10n('nbm_'.$page['mode'].'_mode'),
509    'U_HELP' => add_url_params(get_root_url().'/popuphelp.php', array('page' => 'notification_by_mail')),
510    'F_ACTION'=> $base_url.get_query_string_diff(array())
511  )
512);
513
514if (is_autorize_status(ACCESS_WEBMASTER))
515{
516  $template->assign_block_vars
517  (
518    'header_link',
519    array
520    (
521      'PARAM_MODE' => add_url_params($base_url.get_query_string_diff(array('mode', 'select')), array('mode' => 'param')),
522      'SUBSCRIBE_MODE' => add_url_params($base_url.get_query_string_diff(array('mode', 'select')), array('mode' => 'subscribe')),
523      'SEND_MODE' => add_url_params($base_url.get_query_string_diff(array('mode', 'select')), array('mode' => 'send'))
524    )
525  );
526}
527
528switch ($page['mode'])
529{
530  case 'param' :
531  {
532    $template->assign_block_vars(
533      $page['mode'],
534      array(
535        'SEND_MAIL_AS' => $conf['nbm_send_mail_as'],
536        'SEND_DETAILED_CONTENT_YES' => ($conf['nbm_send_detailed_content'] ? 'checked="checked"' : ''),
537        'SEND_DETAILED_CONTENT_NO' => (!$conf['nbm_send_detailed_content'] ? 'checked="checked"' : ''),
538        'COMPLEMENTARY_MAIL_CONTENT' => $conf['nbm_complementary_mail_content']
539        ));
540    break;
541  }
542
543  case 'subscribe' :
544  {
545    $template->assign_block_vars(
546      $page['mode'],
547      array(
548        ));
549
550    $template->assign_vars(
551      array(
552        'L_CAT_OPTIONS_TRUE' => l10n('nbm_subscribe_col'),
553        'L_CAT_OPTIONS_FALSE' => l10n('nbm_unsubscribe_col')
554        )
555      );
556
557    $data_users = get_user_notifications('subscribe');
558    foreach ($data_users as $nbm_user)
559    {
560      $template->assign_block_vars(
561        (get_boolean($nbm_user['enabled']) ? 'category_option_true' : 'category_option_false'),
562        array('SELECTED' => '',
563              'VALUE' => $nbm_user['check_key'],
564              'OPTION' => $nbm_user['username'].'['.$nbm_user['mail_address'].']'
565          ));
566    }
567
568    break;
569  }
570
571  case 'send' :
572  {
573    $template->assign_block_vars($page['mode'], array());
574
575    $data_users = do_action_send_mail_notification('list');
576
577    if  (count($data_users) == 0)
578    {
579      $template->assign_block_vars($page['mode'].'.send_empty', array());
580    }
581    else
582    {
583      $template->assign_block_vars(
584        $page['mode'].'.send_data',
585        array(
586          'CUSTOMIZE_MAIL_CONTENT' => isset($_POST['send_customize_mail_content']) ? $_POST['send_customize_mail_content'] : $conf['nbm_complementary_mail_content']
587          ));
588
589      foreach ($data_users as $num => $nbm_user)
590          $template->assign_block_vars(
591            $page['mode'].'.send_data.user_send_mail',
592            array(
593              'CLASS' => ($num % 2 == 1) ? 'nbm_user2' : 'nbm_user1',
594              'ID' => $nbm_user['check_key'],
595              'CHECKED' =>  ( // not check if not selected,  on init select<all
596                              isset($_POST['send_selection']) and // not init
597                              !in_array($nbm_user['check_key'],  $_POST['send_selection']) // not selected
598                            )   ? '' : 'checked="checked"',
599              'USERNAME'=> $nbm_user['username'],
600              'EMAIL' => $nbm_user['mail_address'],
601              'LAST_SEND'=> $nbm_user['last_send']
602              ));
603    }
604
605    break;
606  }
607}
608
609// +-----------------------------------------------------------------------+
610// | Sending html code                                                     |
611// +-----------------------------------------------------------------------+
612$template->assign_var_from_handle('DOUBLE_SELECT', 'double_select');
613$template->assign_var_from_handle('ADMIN_CONTENT', 'notification_by_mail');
614
615?>
Note: See TracBrowser for help on using the repository browser.