summaryrefslogtreecommitdiffstats
path: root/privatemsg.module
blob: 5d6df95d3ec9b2fa2482adf5e00a458933fa74d1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
<?php

function privatemsg_system($field){
  $system["description"] = t("Allows private messages between users.");
  return $system[$field];
}

function privatemsg_link($type) {
  global $user;
  
  if ($type == "menu.view" && user_access("access private messages")) {
    $links[] = l(t("view inbox"), "privatemsg") . " (". (int)_privatemsg_get_new_messages($user->uid) .")";
  }

  return $links ? $links : array();
}

function privatemsg_user($type, $edit, &$user) {
  if (user_access("access private messages")) {
    switch ($type) {
      case "view_public":
        return form_item(t("Private message"), l(t("send private message"), "privatemsg/msgto/$user->uid"));
        break;
      case "edit_form":
        return form_item(t("Private message"), form_checkbox(t("Get daily mail if you have new messages."), "privatemsg_mailalert", 1, $user->privatemsg_mailalert, t("If you check this box you'll get a mail (no more than once per day) if you any unread messages.")));
        break;
      case "edit_validate":
        if (!$edit["privatemsg_mailalert"]) {
          $edit["privatemsg_mailalert"] = 0;
        }
        return $edit;
        break;
    }
  }
}

function privatemsg_conf_options() {
  $rate = array(5 => format_interval(5), 10 => format_interval(10), 15 => format_interval(15), 20 => format_interval(20), 30 => format_interval(30), 60 => format_interval(60)); 
  $output .= form_select(t("Private messaging max rate"), "privatemsg_max_rate", variable_get("privatemsg_max_rate", 15), $rate, t("Max submit rate for private messaging. To prevent abuse."));
  $output .= form_select(t("Sent message status"), "privatemsg_sent_status", variable_get("privatemsg_sent_status", 1), array("Disabled", "Enabled"), t("If enabled users can see whether a message has been read or not."));
  $number = array(5 => 5, 10 => 10, 15 => 15, 20 => 20, 25 => 25, 30 => 30, 35 => 35, 40 => 40, 50 => 50, 60 => 60, 80 => 80, 100 => 100);
  $output .= form_select(t("Messages per page"), "privatemsg_per_page", variable_get("privatemsg_per_page", 10), $number, t("The maximum number of messages displayed per page; links to browse messages automatically appear."));
  
  return $output;
}

function privatemsg_perm() {
  return array("access private messages");
}

function privatemsg_cron() {
  // perform these actions just once per day
  if (variable_get("privatemsg_last_cron", 0) < (time() - 3600*24)) {
    _privatemsg_prune();
    _privatemsg_mailalert();
    variable_set("privatemsg_last_cron", time());
  }
}

function _privatemsg_prune() {
  // move deleted message older than 1 month to archive table, and optimize table
  $result = db_query("SELECT * FROM privatemsg WHERE author_del = 1 AND recipient_del = 1 AND timestamp < '%d'", (time() - 3600*24*30));
  while ($message = db_fetch_object($result)) {
    db_query("INSERT INTO privatemsg_archive (id, author, recipient, subject, message, timestamp, hostname, folder)  VALUES ('%d', '%d', '%d', '%s', '%s', '%d', '%s', '%d')", $message->id, $message->author, $message->recipient, $message->subject, $message->message, $message->timestamp, $message->hostname, $message->folder);
    db_query("DELETE FROM privatemsg WHERE id = '%d'", $message->id);
  }
  
  // this is MySQL-specific
  db_query("OPTIMIZE TABLE privatemsg");
}

function _privatemsg_mailalert() {
  global $base_url;
  
  $result = db_query("SELECT COUNT(*) AS c, recipient FROM privatemsg WHERE new = 1 AND recipient_del = 0 GROUP BY recipient");
    
  while ($alert = db_fetch_object($result)) {
    $user = user_load(array("uid" => $alert->recipient));
    if ($user->privatemsg_mailalert) {
      user_mail($user->mail,
                t("You have unread messages"),
                t("Hi %name,\nthis is an automatic reminder from the site %site. You have %new unread private messages.\n\nTo read your messages, follow this link:\n%link1\n\nIf you don't want to receive these email again, change your preferences here:\n%link2\n\n",
                  array("%name" => $user->name, "%site" => variable_get("site_name", $base_url), "%link1" => "$base_url/privatemsg", "%link2" => "$base_url/user/edit")),
                t("New private messages at %site.", array("%site" => variable_get("site_name", $base_url))));
    }
  }
}

function privatemsg_page() {
  global $user;

  $op = $_POST["op"];
  $edit = $_POST["edit"];
  $recipient = $_POST["recipient"];
  $msg = $_POST["msg"];
  
  if (empty($op)) {
    $op = arg(1);
  }
  $arg = arg(2);
  
  if (user_access("access private messages")) {
    switch($op) {
      case "list";
        _privatemsg_list($arg);
        break;
      case "view";
        _privatemsg_view($arg);
        break;
      case t("Write a new message"):
        $arg = "";
      case "form";
      case "reply";
        _privatemsg_form($arg);
        break;
      case "msgto";
        $msg->name = db_result(db_query("SELECT name FROM users WHERE uid = '%d'", $arg));
        _privatemsg_form($msg);
        break;
      case "send";
      case t("Send private message"):
        if (!$edit["recipient"]) {
          $edit["recipient"] = $recipient;
        }
        _privatemsg_edit($edit);
        break;
      case t("Move to folder"):
        if ($edit["folder"] == 0 || db_result(db_query("SELECT fid FROM privatemsg_folder WHERE fid = '%d' AND uid = '%d'", $edit["folder"], $user->uid))) {
          // this folder belongs to him
          echo "entro";
          if ($msg) {
            foreach ($msg as $mid) {
              _privatemsg_move($mid, $edit["folder"]);
            }
            _privatemsg_list($edit["folder"]);
            break;
          }
        }

        _privatemsg_list(0);
        break;
      case t("Delete messages"):
        if ($msg) {
          foreach ($msg as $id) {
            _privatemsg_delete($id);
          }
        }
        _privatemsg_list(0);
        break;
      case "delete";
        _privatemsg_delete($arg);
        _privatemsg_list(0);
        break;
      case t("New folder"):
      case t("Add folder"):
        if (_privatemsg_new_folder($edit)) {
          _privatemsg_list(0);
        }
        break;
      case t("Delete folder");
        // check ownership
        if (db_result(db_query("SELECT fid FROM privatemsg_folder WHERE fid = '%d' AND uid = '%d'", $edit["current_folder"], $user->uid))) {
          db_query("DELETE FROM privatemsg_folder WHERE fid = '%d'", $edit["current_folder"]);
          db_query("UPDATE privatemsg SET recipient_del = 1 WHERE folder = '%d'", $edit["current_folder"]);
        }

        _privatemsg_list(0);
        break;
      case t("Empty folder");
        $fid = $edit["current_folder"];
        
        if ($fid == 1) {
          db_query("UPDATE privatemsg SET author_del = 1 WHERE author = '%d'", $user->uid);
        }
        else if ($fid == 0 || db_result(db_query("SELECT fid FROM privatemsg_folder WHERE fid = '%d' AND uid = '%d'", $fid, $user->uid))) {
          // check ownership
          db_query("UPDATE privatemsg SET recipient_del = 1 WHERE folder = '%d'", $edit["current_folder"]);
        }

        _privatemsg_list(0);
        break;
      default;
        _privatemsg_list(0);
        break;
    }
  }
  else {
    theme("header");
    
    if ($user->uid) {
      $theme->box(t("Private messages"), t("You don't have access to private messages."));
    }
    else {
      $theme->box(t("Private messages"), t("You must login below or <a href=\"%url\">create a new account</a> before accessing private messages.", array ("%url" => drupal_url(array ("mod" => "user", "op" => "register"), "module"))));
    }
    
    theme("footer");
  }
  
}

function _privatemsg_list($current_folder = 0, $status_message = "") {
  global $user, $theme;
  
  theme("header");
  
  if ($current_folder != 1) {
    $result = pager_query("SELECT id, subject, p.timestamp, u.uid, u.name, new FROM privatemsg p, users u WHERE p.author = u.uid AND p.recipient = $user->uid AND folder = '".addslashes($current_folder)."' AND p.recipient_del = 0 ORDER BY p.timestamp DESC", variable_get("privatemsg_per_page", 10));
    
    if ($current_folder > 0) {
      $folder_name = db_result(db_query("SELECT name FROM privatemsg_folder WHERE fid = '%d' AND uid = '$user->uid'", $current_folder));
    }
    else {
      $folder_name = t("Inbox");
    }
  }
  else {
    // sent messages
    $result = pager_query("SELECT id, subject, p.timestamp, u.uid, u.name, new FROM privatemsg p, users u WHERE p.recipient = u.uid AND p.author = $user->uid AND p.author_del = 0 ORDER BY p.timestamp DESC", variable_get("privatemsg_per_page", 10));
    
    $folder_name = t("Sent messages");
  }
  
  $messages = array();
  while ($message = db_fetch_object($result)) {
    $messages[] = $message;
  }
  
  $folders[] = array(0, t("Inbox"));
  $result = db_query("SELECT fid, name FROM privatemsg_folder WHERE uid = '$user->uid'");
  while ($folder = db_fetch_object($result)) {
    $folders[] = array($folder->fid, $folder->name);
  }
  $folders[] = array(1, t("Sent messages"));
  
  theme("privatemsg_list", $current_folder, $status_message, $messages, $folders);
  theme("footer");
}

function privatemsg_list($current_folder, $status_message, $messages, $folders) {
  foreach ($messages as $message) {
    $msg .= "<tr>";
    $msg .= "<td width=\"2%\"><input type=\"checkbox\" name=\"msg[]\" value=\"$message->id\"></td>";
    if ($current_folder != 1) {
      $new = $message->new;
    }
    else {
      if (variable_get("privatemsg_sent_status", 1)) {
        $new = $message->new;
      }
      else {
        $new = 0;
      }
    }
    $msg .= "<td width=\"3%\">".($new ? "<b>".t("new")."</b>" : "")."</td>";
    $msg .= "<td width=\"20%\">".format_date($message->timestamp, "small")."</td>";
    #$msg .= "<td width=\"30%\">".format_name($message)."</a></td>";
    $msg .= "<td width=\"30%\">".l(check_output($message->name), "privatemsg/view/$message->id")."</a></td>";
    $msg .= "<td width=\"55%\">".l(check_output($message->subject), "privatemsg/view/$message->id")."</td>";
    
    $msg .= "</tr>\n";
  }
  
  if (!$msg)
    $msg = "<tr><td colspan=\"5\" align=\"center\">".t("No messages")."</td></tr>";
  else
    $msg = '
          <tr>
            <td width="2%">&nbsp;</td>
            <td width="3%">&nbsp;</td>
            <td width="20%"><b>'.t("date").'</b></td>
            <td width="30%"><b>'.($current_folder == 1 ? t("to") : t("from")).'</b></td>
            <td width="55%"><b>'.t("subject").'</b></td>
          </tr>
          '.$msg;
  
  $out = "<table width=\"100%\">";

  if ($status_message) {
    $out .= "<tr><td colspan=\"5\" align=\"center\">$status_message</td></tr>";
  }
  
  $extra_folders = array();
  foreach ($folders as $folder) {
    $folder_list[] = _privatemsg_format_folder($current_folder, $folder[0], $folder[1]);
    if ($folder[0] != 1 && $folder[0] != $current_folder) {
      $extra_folders[$folder[0]] = $folder[1];
    }
  }
  
  $out .= "<tr><td colspan=\"5\" align=\"center\">".implode(" - ", $folder_list)."</td></tr>\n";
    
  $out .= $msg;
  $out .= "<tr><td colspan=\"5\" align=\"center\">".theme("pager_display", NULL, ($user->nodes ? $user->nodes : variable_get("default_nodes_main", 10)))."</td></tr>";
  $out .= "<tr><td colspan=\"5\" align=\"center\"><br><hr>".form_submit(t("Write a new message"))._form_submit(t("Delete messages"), "onClick=\"return confirm('".t("Are you sure you want to delete these messages?")."')\"")."</td></tr>";
  
  // folder management
  $out .= "<tr><td colspan=\"5\" align=\"center\">";
  if (count($extra_folders) > 0 && $current_folder != 1) {
    $out .= '<select name="edit[folder]">';
    foreach ($extra_folders as $fid => $folder_name) {
      $out .= "<option value='$fid'>$folder_name</option>";
    }
    $out .= '</select>';
    
    $out .= form_submit(t("Move to folder"));
  }
  
  if ($current_folder > 1) {
    // you can't delete Inbox
    $out .= _form_submit(t("Delete folder"), "onClick=\"return confirm('".t("Are you sure you want to delete this folder and all its messages?")."')\"");
  }
  
  $out .= _form_submit(t("Empty folder"), "onClick=\"return confirm('".t("Are you sure you want to delete every message in this folder?")."')\"");
  $out .= form_hidden("current_folder", $current_folder);
  $out .= form_submit(t("New folder"))."</td></tr>";
  
  $out .= "</table>";
  
  theme("box", t("Private messages"), form($out));
}

function _privatemsg_format_folder($current, $fid, $name) {
  if ($current == $fid) {
    return "<b>$name</b>";
  }
  else {
    return l($name, "privatemsg/list/$fid");
  }
}

function _privatemsg_form($message = 0, $error = "") {
  global $user;

  if ($message) {
    if (!is_object($message)) {
      $message = db_fetch_object(db_query("SELECT subject, message, u.name FROM privatemsg p, users u WHERE u.uid = p.author AND id = '%d' AND recipient = '%d'", $message, $user->uid));

      if (!stristr($message->subject, "re:")) {
        $message->subject = "re: ".$message->subject;
      }
      
      # quoting
      $message->message = "\n".str_replace ("\n", "\n> ", "\n".$message->message);
    }
  }
  
  $to .= "<input type='text' name='recipient' value='".htmlentities($message->name, ENT_QUOTES)."' maxlength='64' size='50'>";
  
  if (!$message->name) {
    $to .= ' <select name="quick" onChange="recipient.value=quick.value"><option value="--'.t("contacts").'--" selected="selected">--'.t("contacts").'--</option>';
    $result = db_query("SELECT DISTINCT(name) AS name FROM privatemsg p, users u WHERE p.author = u.uid AND recipient = '%d' AND p.timestamp > (UNIX_TIMESTAMP(NOW()) - (3600 * 24 * 30)) ORDER BY name", $user->uid);
    while ($name = db_fetch_object($result)) {
      $name = htmlentities($name->name);
      $to .= "<option value='$name'>$name</option>";
    }
    $to .= '</select>';
  }
  
  $form .= form_item(t("To"), $to);

  $form .= form_textfield(t("Subject"), "subject", $message->subject, 50, 64);
  $form .= form_textarea(t("Message"), "message", $message->message, 80, 5);
  $form .= form_submit(t("Send private message"));  
  
  theme("header");
  theme("box", t("Write a new message"), "<br /><p align=\"center\"><b><i>$error</i></b></p>".form($form));
  theme("footer");
}

function _privatemsg_edit($edit) {
  global $user;
  $recipient = db_result(db_query("SELECT uid FROM users WHERE name = '%s'", $edit["recipient"]));
  
  throttle("private message", variable_get(privatemsg_max_rate, 15));
  
  if (!$edit["recipient"] || !$edit["subject"] || !$edit["message"]) {
    _privatemsg_form(array2object($edit), t("Warning: every field required"));
  } elseif ($recipient == $user->uid) {
    _privatemsg_form(array2object($edit), t("A message to yourself?"));
  } else {
    if ($recipient) {            
      $result = db_query("INSERT INTO privatemsg (author, recipient, subject, message, timestamp, new, hostname)
        VALUES ('%d', '%d', '%s', '%s', '%d', '%d', '%s')", $user->uid, $recipient, strip_tags($edit['subject']), strip_tags($edit['message']), time(), 1, getenv("REMOTE_ADDR"));
      _privatemsg_list(0, t("Message sent"));
    } else {
      _privatemsg_form(array2object($edit), t("Warning: user does not exist"));
    }
  }
}

function _privatemsg_view($message_id) {
  global $user;
    
  $result = db_query("
    SELECT id, u.name, author, p.timestamp, subject, message, new, recipient
    FROM privatemsg p, users u
    WHERE (recipient = '%d' OR author = '%d')
    AND author = u.uid
    AND id = '%d'
  ", $user->uid, $user->uid, $message_id);
  
  $message = db_fetch_object($result);
  if (($message->new) && ($user->uid != $message->author)) {
    $result = db_query("
      UPDATE privatemsg
      SET new = 0
      WHERE recipient = '$user->uid'
      AND id = '%d'", $message_id);
  }
  
  theme("header");
  theme("privatemsg_view", $message);
  theme("footer");
}

function privatemsg_view($message) {
  global $user;

  if ($message) {
    $body = "
      <p><b>".t("From").":</b> ".check_output($message->name)."<br />
      <b>".t("Subject").":</b> ".check_output($message->subject)."<br />
      <b>".t("Date").":</b> ".format_date($message->timestamp)."</p>
      ".check_output($message->message, 1)."
      <p align='center'>";
    if ($message->recipient == $user->uid) {
      $body .= l(t("Reply to this message"), "privatemsg/reply/$message->id")." - ";
    }
    if (($message->recipient == $user->uid) || (variable_get("privatemsg_sent_status", 1))) {
      $body .= l(t("Delete this message"), "privatemsg/delete/$message->id", array("onClick" => "return confirm('".t("Are you sure to delete this message?")."')"))." - ";
    }
      
    $body .= l(t("List messages"), "privatemsg")."</p>";
  } else {
    $body = t("Error: you can't read this message");
  }

  theme("box", t("Read message"), $body);
}

function _privatemsg_delete($id) {
  global $user;

  $result = db_query("SELECT author, recipient FROM privatemsg WHERE (recipient = '$user->uid' OR author = '$user->uid') AND id = '%d'", $id);
    
  if ($message = db_fetch_object($result)) {
    if ($message->author == $user->uid) {
      db_query("UPDATE privatemsg SET author_del = 1 WHERE id = '%d'", $id);
    }
    else if ($message->recipient == $user->uid) {
      db_query("UPDATE privatemsg SET recipient_del = 1 WHERE id = '%d'", $id);
    }
    
    return true;
  } else {
    return false;
  }
}

function _privatemsg_get_new_messages($uid) {
  return db_result(db_query("SELECT COUNT(*) FROM privatemsg WHERE recipient = '%d' AND new = 1 AND recipient_del = 0", $uid));
}

function _privatemsg_new_folder($edit) {
  global $user;

  if ($edit["name"]) {
    // check for uniqueness
    if (!db_result(db_query("SELECT name FROM privatemsg_folder WHERE name = '%s' AND uid = '%d'", $edit["name"], $user->uid))) {
      db_query("INSERT INTO privatemsg_folder (uid, name) VALUES ('%d', '%s')", $user->uid, $edit["name"]);
      return 1;
    }
  }
  
  $form .= form_textfield(t("Name"), "name", "", 50, 64);
  $form .= form_submit(t("Add folder"));
  
  theme("header");
  theme("box", t("New folder"), form($form));
  theme("footer");
}

function _privatemsg_move($mid, $fid) {
  global $user;
  db_query("UPDATE privatemsg SET folder = '%d' WHERE id = '%d' AND recipient = '%d'", $fid, $mid, $user->uid);
}

function _form_submit($value, $extra) {
  return "<input type=\"submit\" name=\"op\" value=\"". check_form($value) ."\" $extra />\n";
}

?>