source: trunk/admin/notification_by_mail.php @ 1114

Last change on this file since 1114 was 1114, checked in by rvelices, 18 years ago

NBM: check/uncheck all completely done by Javascript

NBM: add function make_index_absolute_url

NBM: add function get_user_notifications and simplified code

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