summaryrefslogtreecommitdiff
path: root/src/PhpBB3Impl.php
blob: 06b0427719d26ac1a0cd655edf6e9d2b2fc80da2 (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
<?php

#
# forum-list bridge 
# Copyright (C) 2010 Joel Uckelman
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

require_once(__DIR__ . '/PhpBB3.php');
require_once(__DIR__ . '/Util.php');
require_once(__DIR__ . '/build_post.php');

# phpBB setup
define('IN_PHPBB', true);
$phpEx = substr(strrchr(__FILE__, '.'), 1);
require_once($phpbb_root_path . 'common.' . $phpEx);
require_once($phpbb_root_path . 'includes/functions.' . $phpEx);
require_once($phpbb_root_path . 'includes/functions_posting.' . $phpEx);
require_once($phpbb_root_path . 'includes/functions_user.' . $phpEx);

class PhpBB3Impl implements PhpBB3 {
  public function __construct() {
  }

  public function getUserId($from) {
    throw_if_null($from);

    global $db;

    # NB: There might be multiple user accounts associated with one email
    # address. We can only return one user id, so we decide in favor of
    # the account which was most recently used to visit the forum.
    $sql = 'SELECT u1.user_id FROM ' . USERS_TABLE . ' AS u1 ' .
           'LEFT OUTER JOIN ' . USERS_TABLE . ' AS u2 ON (' .
              'u1.user_email = u2.user_email AND ' .
              'u1.user_lastvisit < u2.user_lastvisit' .
           ') WHERE u1.user_email = "' . $db->sql_escape($from) . '" AND ' .
           'u2.user_email IS NULL';

    $row = $this->get_exactly_one_row($sql);
    return $row ? $row['user_id'] : false;
  }

  public function getUserName($id) {
    throw_if_null($id);

    # NB: user_get_id_name is pass-by-reference; we copy $id to prevent
    # it from being modified, as we might need it for error messages
    $ids = array($id);
    $err = user_get_id_name($ids, $names);
    if ($err) {
      throw new Exception("Could not resolve user id $id: $err");
    }

    if (!isset($names[$id])) {
      throw new Exception("Unknown user id: $id");
    }

    return $names[$id];
  }

  public function getTopicAndForumIds($post_id) {
    throw_if_null($post_id);

    $sql = 'SELECT topic_id, forum_id FROM ' . POSTS_TABLE . ' ' .
           'WHERE post_id = ' . $post_id;

    $row = $this->get_exactly_one_row($sql);
    return $row;
  }

  public function forumExists($forumId) {
    throw_if_null($forumId);

    global $db;

    $sql = 'SELECT 1 FROM ' . FORUMS_TABLE . ' ' .
           'WHERE forum_id = ' . $forumId . ' LIMIT 1';

    $result = $db->sql_query($sql);
  
    $rows = $db->sql_fetchrowset($result);
    $db->sql_freeresult($result);

    switch (count($rows)) {
    case 0:
      return false;
    
    case 1:
      return true;
    
    default:
      # Should be impossible due to LIMIT 1.
      throw new Exception("Too many rows returned: $sql");
    }
  }

  public function getForumName($forumId) {
    throw_if_null($forumId);

    global $db;

    $sql = 'SELECT forum_name FROM ' . FORUMS_TABLE . ' ' .
           'WHERE forum_id = ' . $forumId;

    $row = $this->get_exactly_one_row($sql);
    return $row ? $row['forum_name'] : false;
  }

  public function topicStatus($topicId) {
    throw_if_null($topicId);

    $sql = 'SELECT topic_status FROM ' . TOPICS_TABLE . ' ' .
           'WHERE topic_id = ' . $topicId;

    $row = $this->get_exactly_one_row($sql);
    return $row ? $row['topic_status'] : false;
  }

  public function getPostTime($postId) {
    throw_if_null($postId);

    $sql = 'SELECT post_time FROM ' . POSTS_TABLE . ' ' .
           'WHERE post_id = ' . $postId;

    $row = $this->get_exactly_one_row($sql);
    return $row ? $row['post_time'] : false;
  }

  public function getAttachmentData($attachId) {
    throw_if_null($attachId);

    $sql = 'SELECT physical_filename, real_filename, ' . 
                  'attach_comment, mimetype ' .
           'FROM ' . ATTACHMENTS_TABLE . ' ' .
           'WHERE attach_id = ' . $attachId;

    $row = $this->get_exactly_one_row($sql);
    return $row;
  }

  public function postMessage($postType, $forumId, $topicId, $msg) {
    throw_if_null($msg);

    if ($postType == 'post') {
      # do nothing
    }
    else if ($postType == 'reply') {
      # Check that we're not replying to a locked topic.
      $status = $this->topicStatus($topicId);
      if ($status === false) {
        throw new Exception('topic does not exist: ' . $topicId);
      }

      switch ($this->topicStatus($topicId)) {
      case ITEM_UNLOCKED:
        # normal, ok
        break;
      case ITEM_LOCKED:
        throw new Exception('post to locked topic: ' . $topicId); 
        break;
      case ITEM_MOVED:
        # Should not happen, since the only topics with this status
        # are new shadow topics created after moves.
        throw new Exception('post to moved topic: ' . $topicId);
        break;
      default:
        # Should not happen.
        throw new Exception('bad topic status: ' . $topicId);
        break;
      }
    }
    else {
      # Should not happen.
      throw new Exception('bad post type: ' . $postType);
    }

    if (!$this->forumExists($forumId)) {
      throw new Exception('forum does not exist: ' . $forumId);
    } 

    $userId = $this->getUserId($msg->getFrom());
    if ($userId === false) {
      throw new Exception('unrecognized email address: ' . $msg->getFrom());
    }

    $userName = $this->getUserName($userId);
    if ($userName === false) {
      throw new Exception('unrecognized user id: ' . $userId);
    }

    $subject = $msg->getSubject();
// FIXME: list tag should not be hard-coded
    $listTag = '[messages]';
    $forumName = $this->getForumName($forumId);
    $forumTag = '[' . html_entity_decode($forumName, ENT_QUOTES) . ']';
    $subject = build_post_subject($listTag, $forumTag, $subject, $postType == 'reply');

    list($message, $attachments) = $msg->getFlattenedParts();

# FIXME: extract the footer pattern into a config file?
    # strip the list footer
    $message = strip_list_footer($message, "/^_______________________________________________\\r\\nmessages mailing list\\r\\nmessages@vassalengine.org\\r\\nhttp:\/\/www.vassalengine.org\/mailman\/listinfo\/messages.*/ms");

# TODO: convert > quoting into BBCode

    # handle attachments
    $attachment_data = array();

    foreach ($attachments as $a) {
      $attachment_data[] = $this->addAttachment(
        $userId, $a['filename'], $a['comment'], $a['mimetype'], $a['data']
      );
    } 

    # bring in the PhpBB globals
    global $phpEx, $phpbb_root_path, $user, $auth,
           $template, $cache, $db, $config;

    # authenticate ourselves
    $user->session_create($userId);
    $auth->acl($user->data);

    $subject = utf8_normalize_nfc($subject);
    $message = utf8_normalize_nfc($message);

    $uid = $bitfield = $options = '';

    generate_text_for_storage(
      $subject, $uid, $bitfield, $options, false, false, false
    );

    generate_text_for_storage(
      $message, $uid, $bitfield, $options, true, true, true
    );

    # build the data array for submit_post
    $postId = null;

    $data = array(
      'forum_id'         => $forumId,
      'topic_id'         => &$topicId,
      'post_id'          => &$postId,
      'icon_id'          => false,

      'enable_bbcode'    => true,
      'enable_smilies'   => true,
      'enable_urls'      => true,
      'enable_sig'       => true,

      'message'          => $message,
      'message_md5'      => md5($message),

      'bbcode_bitfield'  => $bitfield,
      'bbcode_uid'       => $uid,

      'post_edit_locked' => 0,
      'topic_title'      => $subject,
      'notify_set'       => false,
      'notify'           => false,
      'post_time'        => 0,
      'forum_name'       => '',
      'enable_indexing'  => true
    );

    if (!empty($attachment_data)) {
      $data['attachment_data'] = $attachment_data;
    }

    $poll = '';

    submit_post($postType, $subject, $userName, POST_NORMAL, $poll, $data);

    return $postId;
  }

  public function addAttachment($userId, $filename, $comment,
                                                    $mimetype, $data) {
    throw_if_null($userId);
    throw_if_null($filename);
    throw_if_null($mimetype);
    throw_if_null($data);

    global $db;

# TODO: check that attachment is a permissible type, size

    # lifted from include/functions_upload.php: filespec::clean_filename()
    $physicalFilename = $userId . '_' . md5(unique_id()); 

    # get extension
    $dot = strrpos($filename, '.');
    $extension = $dot === false ? '' : substr($filename, $dot + 1);

    # put the attachment data into the db
    $sql = 'INSERT INTO ' . ATTACHMENTS_TABLE . ' (' .
             'poster_id, is_orphan, physical_filename, real_filename, ' .
             'attach_comment, extension, mimetype, filesize, filetime' .
           ') VALUES (' .
             $userId . ', ' .
             '1, ' .
             '"' . $physicalFilename           . '", ' .
             '"' . $db->sql_escape($filename)  . '", ' .
             '"' . $db->sql_escape($comment)   . '", ' .
             '"' . $db->sql_escape($extension) . '", ' .
             '"' . $db->sql_escape($mimetype)  . '", ' .
             strlen($data) . ', ' .
             time() .
           ')';

    $db->sql_query($sql);

    if ($db->sql_affectedrows() != 1) {
      throw new Exception("Adding attachment failed: $sql");
    }

    # post the attachment data to our attachment writer shim
    require_once(__DIR__ . '/HTTP_POST_multipart.php');

    $url = 'http://www.vassalengine.org/forum/attachment_writer.php';
    $poster = new HTTP_POST_multipart();
    $poster->addData('password', '5rnudbp7dLkijcwrT@sz');
    $poster->addFile(1, $physicalFilename, $mimetype, null, 'binary', $data);
    $result = $poster->post($url);

    if ($result != 1) {
      throw new Exception('Attachment writer failed: ' . $result);
    } 

    # return the attachment info needed by submit_post
    return array(
      'attach_id'      => $db->sql_nextid(),
      'is_orphan'      => 1,
      'real_filename'  => $realFilename,
      'attach_comment' => $comment,
    );
  }

  protected function get_exactly_one_row($sql) {
    global $db;

    $result = $db->sql_query($sql);
  
    $rows = $db->sql_fetchrowset($result);
    $db->sql_freeresult($result);

    switch (count($rows)) {
    case 0:
      return false;

    case 1:
      return $rows[0];

    default:
      throw new Exception("Too many rows returned: $sql");
    }
  }
}

?>