annotate forum/Sources/Subs-Post.php @ 87:df86d318892b website

Link to SampleType doc
author Chris Cannam
date Mon, 10 Feb 2014 18:11:48 +0000
parents b31c38a09c41
children
rev   line source
Chris@76 1 <?php
Chris@76 2
Chris@76 3 /**
Chris@76 4 * Simple Machines Forum (SMF)
Chris@76 5 *
Chris@76 6 * @package SMF
Chris@76 7 * @author Simple Machines http://www.simplemachines.org
Chris@76 8 * @copyright 2011 Simple Machines
Chris@76 9 * @license http://www.simplemachines.org/about/smf/license.php BSD
Chris@76 10 *
Chris@76 11 * @version 2.0
Chris@76 12 */
Chris@76 13
Chris@76 14 if (!defined('SMF'))
Chris@76 15 die('Hacking attempt...');
Chris@76 16
Chris@76 17 /* This file contains those functions pertaining to posting, and other such
Chris@76 18 operations, including sending emails, ims, blocking spam, preparsing posts,
Chris@76 19 spell checking, and the post box. This is done with the following:
Chris@76 20
Chris@76 21 void preparsecode(string &message, boolean previewing = false)
Chris@76 22 - takes a message and parses it, returning nothing.
Chris@76 23 - cleans up links (javascript, etc.) and code/quote sections.
Chris@76 24 - won't convert \n's and a few other things if previewing is true.
Chris@76 25
Chris@76 26 string un_preparsecode(string message)
Chris@76 27 // !!!
Chris@76 28
Chris@76 29 void fixTags(string &message)
Chris@76 30 - used by preparsecode, fixes links in message and returns nothing.
Chris@76 31
Chris@76 32 void fixTag(string &message, string myTag, string protocol,
Chris@76 33 bool embeddedUrl = false, bool hasEqualSign = false,
Chris@76 34 bool hasExtra = false)
Chris@76 35 - used by fixTags, fixes a specific tag's links.
Chris@76 36 - myTag is the tag, protocol is http of ftp, embeddedUrl is whether
Chris@76 37 it *can* be set to something, hasEqualSign is whether it *is*
Chris@76 38 set to something, and hasExtra is whether it can have extra
Chris@76 39 cruft after the begin tag.
Chris@76 40
Chris@76 41 bool sendmail(array to, string subject, string message,
Chris@76 42 string message_id = auto, string from = webmaster,
Chris@76 43 bool send_html = false, int priority = 3, bool hotmail_fix = null)
Chris@76 44 - sends an email to the specified recipient.
Chris@76 45 - uses the mail_type setting and the webmaster_email global.
Chris@76 46 - to is he email(s), string or array, to send to.
Chris@76 47 - subject and message are those of the email - expected to have
Chris@76 48 slashes but not be parsed.
Chris@76 49 - subject is expected to have entities, message is not.
Chris@76 50 - from is a string which masks the address for use with replies.
Chris@76 51 - if message_id is specified, uses that as the local-part of the
Chris@76 52 Message-ID header.
Chris@76 53 - send_html indicates whether or not the message is HTML vs. plain
Chris@76 54 text, and does not add any HTML.
Chris@76 55 - returns whether or not the email was sent properly.
Chris@76 56
Chris@76 57 bool AddMailQueue(bool flush = true, array to_array = array(), string subject = '', string message = '',
Chris@76 58 string headers = '', bool send_html = false, int priority = 3)
Chris@76 59 //!!
Chris@76 60
Chris@76 61 array sendpm(array recipients, string subject, string message,
Chris@76 62 bool store_outbox = false, array from = current_member, int pm_head = 0)
Chris@76 63 - sends an personal message from the specified person to the
Chris@76 64 specified people. (from defaults to the user.)
Chris@76 65 - recipients should be an array containing the arrays 'to' and 'bcc',
Chris@76 66 both containing id_member's.
Chris@76 67 - subject and message should have no slashes and no html entities.
Chris@76 68 - pm_head is the ID of the chain being replied to - if any.
Chris@76 69 - from is an array, with the id, name, and username of the member.
Chris@76 70 - returns an array with log entries telling how many recipients were
Chris@76 71 successful and which recipients it failed to send to.
Chris@76 72
Chris@76 73 string mimespecialchars(string text, bool with_charset = true,
Chris@76 74 hotmail_fix = false, string custom_charset = null)
Chris@76 75 - prepare text strings for sending as email.
Chris@76 76 - in case there are higher ASCII characters in the given string, this
Chris@76 77 function will attempt the transport method 'quoted-printable'.
Chris@76 78 Otherwise the transport method '7bit' is used.
Chris@76 79 - with hotmail_fix set all higher ASCII characters are converted to
Chris@76 80 HTML entities to assure proper display of the mail.
Chris@76 81 - uses character set custom_charset if set.
Chris@76 82 - returns an array containing the character set, the converted string
Chris@76 83 and the transport method.
Chris@76 84
Chris@76 85 bool smtp_mail(array mail_to_array, string subject, string message,
Chris@76 86 string headers)
Chris@76 87 - sends mail, like mail() but over SMTP. Used internally.
Chris@76 88 - takes email addresses, a subject and message, and any headers.
Chris@76 89 - expects no slashes or entities.
Chris@76 90 - returns whether it sent or not.
Chris@76 91
Chris@76 92 bool server_parse(string message, resource socket, string response)
Chris@76 93 - sends the specified message to the server, and checks for the
Chris@76 94 expected response. (used internally.)
Chris@76 95 - takes the message to send, socket to send on, and the expected
Chris@76 96 response code.
Chris@76 97 - returns whether it responded as such.
Chris@76 98
Chris@76 99 void SpellCheck()
Chris@76 100 - spell checks the post for typos ;).
Chris@76 101 - uses the pspell library, which MUST be installed.
Chris@76 102 - has problems with internationalization.
Chris@76 103 - is accessed via ?action=spellcheck.
Chris@76 104
Chris@76 105 void sendNotifications(array topics, string type, array exclude = array(), array members_only = array())
Chris@76 106 - sends a notification to members who have elected to receive emails
Chris@76 107 when things happen to a topic, such as replies are posted.
Chris@76 108 - uses the Post langauge file.
Chris@76 109 - topics represents the topics the action is happening to.
Chris@76 110 - the type can be any of reply, sticky, lock, unlock, remove, move,
Chris@76 111 merge, and split. An appropriate message will be sent for each.
Chris@76 112 - automatically finds the subject and its board, and checks permissions
Chris@76 113 for each member who is "signed up" for notifications.
Chris@76 114 - will not send 'reply' notifications more than once in a row.
Chris@76 115 - members in the exclude array will not be processed for the topic with the same key.
Chris@76 116 - members_only are the only ones that will be sent the notification if they have it on.
Chris@76 117
Chris@76 118 bool createPost(&array msgOptions, &array topicOptions, &array posterOptions)
Chris@76 119 // !!!
Chris@76 120
Chris@76 121 bool createAttachment(&array attachmentOptions)
Chris@76 122 // !!!
Chris@76 123
Chris@76 124 bool modifyPost(&array msgOptions, &array topicOptions, &array posterOptions)
Chris@76 125 // !!!
Chris@76 126
Chris@76 127 bool approvePosts(array msgs, bool approve)
Chris@76 128 // !!!
Chris@76 129
Chris@76 130 array approveTopics(array topics, bool approve)
Chris@76 131 // !!!
Chris@76 132
Chris@76 133 void sendApprovalNotifications(array topicData)
Chris@76 134 // !!!
Chris@76 135
Chris@76 136 void updateLastMessages(array id_board's, int id_msg)
Chris@76 137 - takes an array of board IDs and updates their last messages.
Chris@76 138 - if the board has a parent, that parent board is also automatically
Chris@76 139 updated.
Chris@76 140 - columns updated are id_last_msg and lastUpdated.
Chris@76 141 - note that id_last_msg should always be updated using this function,
Chris@76 142 and is not automatically updated upon other changes.
Chris@76 143
Chris@76 144 void adminNotify(string type, int memberID, string member_name = null)
Chris@76 145 - sends all admins an email to let them know a new member has joined.
Chris@76 146 - types supported are 'approval', 'activation', and 'standard'.
Chris@76 147 - called by registerMember() function in Subs-Members.php.
Chris@76 148 - email is sent to all groups that have the moderate_forum permission.
Chris@76 149 - uses the Login language file.
Chris@76 150 - the language set by each member is being used (if available).
Chris@76 151
Chris@76 152 Sending emails from SMF:
Chris@76 153 ---------------------------------------------------------------------------
Chris@76 154 // !!!
Chris@76 155 */
Chris@76 156
Chris@76 157 // Parses some bbc before sending into the database...
Chris@76 158 function preparsecode(&$message, $previewing = false)
Chris@76 159 {
Chris@76 160 global $user_info, $modSettings, $smcFunc, $context;
Chris@76 161
Chris@76 162 // This line makes all languages *theoretically* work even with the wrong charset ;).
Chris@76 163 $message = preg_replace('~&amp;#(\d{4,5}|[2-9]\d{2,4}|1[2-9]\d);~', '&#$1;', $message);
Chris@76 164
Chris@76 165 // Clean up after nobbc ;).
Chris@76 166 $message = preg_replace('~\[nobbc\](.+?)\[/nobbc\]~ie', '\'[nobbc]\' . strtr(\'$1\', array(\'[\' => \'&#91;\', \']\' => \'&#93;\', \':\' => \'&#58;\', \'@\' => \'&#64;\')) . \'[/nobbc]\'', $message);
Chris@76 167
Chris@76 168 // Remove \r's... they're evil!
Chris@76 169 $message = strtr($message, array("\r" => ''));
Chris@76 170
Chris@76 171 // You won't believe this - but too many periods upsets apache it seems!
Chris@76 172 $message = preg_replace('~\.{100,}~', '...', $message);
Chris@76 173
Chris@76 174 // Trim off trailing quotes - these often happen by accident.
Chris@76 175 while (substr($message, -7) == '[quote]')
Chris@76 176 $message = substr($message, 0, -7);
Chris@76 177 while (substr($message, 0, 8) == '[/quote]')
Chris@76 178 $message = substr($message, 8);
Chris@76 179
Chris@76 180 // Find all code blocks, work out whether we'd be parsing them, then ensure they are all closed.
Chris@76 181 $in_tag = false;
Chris@76 182 $had_tag = false;
Chris@76 183 $codeopen = 0;
Chris@76 184 if (preg_match_all('~(\[(/)*code(?:=[^\]]+)?\])~is', $message, $matches))
Chris@76 185 foreach ($matches[0] as $index => $dummy)
Chris@76 186 {
Chris@76 187 // Closing?
Chris@76 188 if (!empty($matches[2][$index]))
Chris@76 189 {
Chris@76 190 // If it's closing and we're not in a tag we need to open it...
Chris@76 191 if (!$in_tag)
Chris@76 192 $codeopen = true;
Chris@76 193 // Either way we ain't in one any more.
Chris@76 194 $in_tag = false;
Chris@76 195 }
Chris@76 196 // Opening tag...
Chris@76 197 else
Chris@76 198 {
Chris@76 199 $had_tag = true;
Chris@76 200 // If we're in a tag don't do nought!
Chris@76 201 if (!$in_tag)
Chris@76 202 $in_tag = true;
Chris@76 203 }
Chris@76 204 }
Chris@76 205
Chris@76 206 // If we have an open tag, close it.
Chris@76 207 if ($in_tag)
Chris@76 208 $message .= '[/code]';
Chris@76 209 // Open any ones that need to be open, only if we've never had a tag.
Chris@76 210 if ($codeopen && !$had_tag)
Chris@76 211 $message = '[code]' . $message;
Chris@76 212
Chris@76 213 // Now that we've fixed all the code tags, let's fix the img and url tags...
Chris@76 214 $parts = preg_split('~(\[/code\]|\[code(?:=[^\]]+)?\])~i', $message, -1, PREG_SPLIT_DELIM_CAPTURE);
Chris@76 215
Chris@76 216 // The regular expression non breaking space has many versions.
Chris@76 217 $non_breaking_space = $context['utf8'] ? ($context['server']['complex_preg_chars'] ? '\x{A0}' : "\xC2\xA0") : '\xA0';
Chris@76 218
Chris@76 219 // Only mess with stuff outside [code] tags.
Chris@76 220 for ($i = 0, $n = count($parts); $i < $n; $i++)
Chris@76 221 {
Chris@76 222 // It goes 0 = outside, 1 = begin tag, 2 = inside, 3 = close tag, repeat.
Chris@76 223 if ($i % 4 == 0)
Chris@76 224 {
Chris@76 225 fixTags($parts[$i]);
Chris@76 226
Chris@76 227 // Replace /me.+?\n with [me=name]dsf[/me]\n.
Chris@76 228 if (strpos($user_info['name'], '[') !== false || strpos($user_info['name'], ']') !== false || strpos($user_info['name'], '\'') !== false || strpos($user_info['name'], '"') !== false)
Chris@76 229 $parts[$i] = preg_replace('~(\A|\n)/me(?: |&nbsp;)([^\n]*)(?:\z)?~i', '$1[me=&quot;' . $user_info['name'] . '&quot;]$2[/me]', $parts[$i]);
Chris@76 230 else
Chris@76 231 $parts[$i] = preg_replace('~(\A|\n)/me(?: |&nbsp;)([^\n]*)(?:\z)?~i', '$1[me=' . $user_info['name'] . ']$2[/me]', $parts[$i]);
Chris@76 232
Chris@76 233 if (!$previewing && strpos($parts[$i], '[html]') !== false)
Chris@76 234 {
Chris@76 235 if (allowedTo('admin_forum'))
Chris@76 236 $parts[$i] = preg_replace('~\[html\](.+?)\[/html\]~ise', '\'[html]\' . strtr(un_htmlspecialchars(\'$1\'), array("\n" => \'&#13;\', \' \' => \' &#32;\', \'[\' => \'&#91;\', \']\' => \'&#93;\')) . \'[/html]\'', $parts[$i]);
Chris@76 237
Chris@76 238 // We should edit them out, or else if an admin edits the message they will get shown...
Chris@76 239 else
Chris@76 240 {
Chris@76 241 while (strpos($parts[$i], '[html]') !== false)
Chris@76 242 $parts[$i] = preg_replace('~\[[/]?html\]~i', '', $parts[$i]);
Chris@76 243 }
Chris@76 244 }
Chris@76 245
Chris@76 246 // Let's look at the time tags...
Chris@76 247 $parts[$i] = preg_replace('~\[time(?:=(absolute))*\](.+?)\[/time\]~ie', '\'[time]\' . (is_numeric(\'$2\') || @strtotime(\'$2\') == 0 ? \'$2\' : strtotime(\'$2\') - (\'$1\' == \'absolute\' ? 0 : (($modSettings[\'time_offset\'] + $user_info[\'time_offset\']) * 3600))) . \'[/time]\'', $parts[$i]);
Chris@76 248
Chris@76 249 // Change the color specific tags to [color=the color].
Chris@76 250 $parts[$i] = preg_replace('~\[(black|blue|green|red|white)\]~', '[color=$1]', $parts[$i]); // First do the opening tags.
Chris@76 251 $parts[$i] = preg_replace('~\[/(black|blue|green|red|white)\]~', '[/color]', $parts[$i]); // And now do the closing tags
Chris@76 252
Chris@76 253 // Make sure all tags are lowercase.
Chris@76 254 $parts[$i] = preg_replace('~\[([/]?)(list|li|table|tr|td)((\s[^\]]+)*)\]~ie', '\'[$1\' . strtolower(\'$2\') . \'$3]\'', $parts[$i]);
Chris@76 255
Chris@76 256 $list_open = substr_count($parts[$i], '[list]') + substr_count($parts[$i], '[list ');
Chris@76 257 $list_close = substr_count($parts[$i], '[/list]');
Chris@76 258 if ($list_close - $list_open > 0)
Chris@76 259 $parts[$i] = str_repeat('[list]', $list_close - $list_open) . $parts[$i];
Chris@76 260 if ($list_open - $list_close > 0)
Chris@76 261 $parts[$i] = $parts[$i] . str_repeat('[/list]', $list_open - $list_close);
Chris@76 262
Chris@76 263 $mistake_fixes = array(
Chris@76 264 // Find [table]s not followed by [tr].
Chris@76 265 '~\[table\](?![\s' . $non_breaking_space . ']*\[tr\])~s' . ($context['utf8'] ? 'u' : '') => '[table][tr]',
Chris@76 266 // Find [tr]s not followed by [td].
Chris@76 267 '~\[tr\](?![\s' . $non_breaking_space . ']*\[td\])~s' . ($context['utf8'] ? 'u' : '') => '[tr][td]',
Chris@76 268 // Find [/td]s not followed by something valid.
Chris@76 269 '~\[/td\](?![\s' . $non_breaking_space . ']*(?:\[td\]|\[/tr\]|\[/table\]))~s' . ($context['utf8'] ? 'u' : '') => '[/td][/tr]',
Chris@76 270 // Find [/tr]s not followed by something valid.
Chris@76 271 '~\[/tr\](?![\s' . $non_breaking_space . ']*(?:\[tr\]|\[/table\]))~s' . ($context['utf8'] ? 'u' : '') => '[/tr][/table]',
Chris@76 272 // Find [/td]s incorrectly followed by [/table].
Chris@76 273 '~\[/td\][\s' . $non_breaking_space . ']*\[/table\]~s' . ($context['utf8'] ? 'u' : '') => '[/td][/tr][/table]',
Chris@76 274 // Find [table]s, [tr]s, and [/td]s (possibly correctly) followed by [td].
Chris@76 275 '~\[(table|tr|/td)\]([\s' . $non_breaking_space . ']*)\[td\]~s' . ($context['utf8'] ? 'u' : '') => '[$1]$2[_td_]',
Chris@76 276 // Now, any [td]s left should have a [tr] before them.
Chris@76 277 '~\[td\]~s' => '[tr][td]',
Chris@76 278 // Look for [tr]s which are correctly placed.
Chris@76 279 '~\[(table|/tr)\]([\s' . $non_breaking_space . ']*)\[tr\]~s' . ($context['utf8'] ? 'u' : '') => '[$1]$2[_tr_]',
Chris@76 280 // Any remaining [tr]s should have a [table] before them.
Chris@76 281 '~\[tr\]~s' => '[table][tr]',
Chris@76 282 // Look for [/td]s followed by [/tr].
Chris@76 283 '~\[/td\]([\s' . $non_breaking_space . ']*)\[/tr\]~s' . ($context['utf8'] ? 'u' : '') => '[/td]$1[_/tr_]',
Chris@76 284 // Any remaining [/tr]s should have a [/td].
Chris@76 285 '~\[/tr\]~s' => '[/td][/tr]',
Chris@76 286 // Look for properly opened [li]s which aren't closed.
Chris@76 287 '~\[li\]([^\[\]]+?)\[li\]~s' => '[li]$1[_/li_][_li_]',
Chris@76 288 '~\[li\]([^\[\]]+?)\[/list\]~s' => '[_li_]$1[_/li_][/list]',
Chris@76 289 '~\[li\]([^\[\]]+?)$~s' => '[li]$1[/li]',
Chris@76 290 // Lists - find correctly closed items/lists.
Chris@76 291 '~\[/li\]([\s' . $non_breaking_space . ']*)\[/list\]~s' . ($context['utf8'] ? 'u' : '') => '[_/li_]$1[/list]',
Chris@76 292 // Find list items closed and then opened.
Chris@76 293 '~\[/li\]([\s' . $non_breaking_space . ']*)\[li\]~s' . ($context['utf8'] ? 'u' : '') => '[_/li_]$1[_li_]',
Chris@76 294 // Now, find any [list]s or [/li]s followed by [li].
Chris@76 295 '~\[(list(?: [^\]]*?)?|/li)\]([\s' . $non_breaking_space . ']*)\[li\]~s' . ($context['utf8'] ? 'u' : '') => '[$1]$2[_li_]',
Chris@76 296 // Allow for sub lists.
Chris@76 297 '~\[/li\]([\s' . $non_breaking_space . ']*)\[list\]~' . ($context['utf8'] ? 'u' : '') => '[_/li_]$1[list]',
Chris@76 298 '~\[/list\]([\s' . $non_breaking_space . ']*)\[li\]~' . ($context['utf8'] ? 'u' : '') => '[/list]$1[_li_]',
Chris@76 299 // Any remaining [li]s weren't inside a [list].
Chris@76 300 '~\[li\]~' => '[list][li]',
Chris@76 301 // Any remaining [/li]s weren't before a [/list].
Chris@76 302 '~\[/li\]~' => '[/li][/list]',
Chris@76 303 // Put the correct ones back how we found them.
Chris@76 304 '~\[_(li|/li|td|tr|/tr)_\]~' => '[$1]',
Chris@76 305 // Images with no real url.
Chris@76 306 '~\[img\]https?://.{0,7}\[/img\]~' => '',
Chris@76 307 );
Chris@76 308
Chris@76 309 // Fix up some use of tables without [tr]s, etc. (it has to be done more than once to catch it all.)
Chris@76 310 for ($j = 0; $j < 3; $j++)
Chris@76 311 $parts[$i] = preg_replace(array_keys($mistake_fixes), $mistake_fixes, $parts[$i]);
Chris@76 312
Chris@76 313 // Now we're going to do full scale table checking...
Chris@76 314 $table_check = $parts[$i];
Chris@76 315 $table_offset = 0;
Chris@76 316 $table_array = array();
Chris@76 317 $table_order = array(
Chris@76 318 'table' => 'td',
Chris@76 319 'tr' => 'table',
Chris@76 320 'td' => 'tr',
Chris@76 321 );
Chris@76 322 while (preg_match('~\[(/)*(table|tr|td)\]~', $table_check, $matches) != false)
Chris@76 323 {
Chris@76 324 // Keep track of where this is.
Chris@76 325 $offset = strpos($table_check, $matches[0]);
Chris@76 326 $remove_tag = false;
Chris@76 327
Chris@76 328 // Is it opening?
Chris@76 329 if ($matches[1] != '/')
Chris@76 330 {
Chris@76 331 // If the previous table tag isn't correct simply remove it.
Chris@76 332 if ((!empty($table_array) && $table_array[0] != $table_order[$matches[2]]) || (empty($table_array) && $matches[2] != 'table'))
Chris@76 333 $remove_tag = true;
Chris@76 334 // Record this was the last tag.
Chris@76 335 else
Chris@76 336 array_unshift($table_array, $matches[2]);
Chris@76 337 }
Chris@76 338 // Otherwise is closed!
Chris@76 339 else
Chris@76 340 {
Chris@76 341 // Only keep the tag if it's closing the right thing.
Chris@76 342 if (empty($table_array) || ($table_array[0] != $matches[2]))
Chris@76 343 $remove_tag = true;
Chris@76 344 else
Chris@76 345 array_shift($table_array);
Chris@76 346 }
Chris@76 347
Chris@76 348 // Removing?
Chris@76 349 if ($remove_tag)
Chris@76 350 {
Chris@76 351 $parts[$i] = substr($parts[$i], 0, $table_offset + $offset) . substr($parts[$i], $table_offset + strlen($matches[0]) + $offset);
Chris@76 352 // We've lost some data.
Chris@76 353 $table_offset -= strlen($matches[0]);
Chris@76 354 }
Chris@76 355
Chris@76 356 // Remove everything up to here.
Chris@76 357 $table_offset += $offset + strlen($matches[0]);
Chris@76 358 $table_check = substr($table_check, $offset + strlen($matches[0]));
Chris@76 359 }
Chris@76 360
Chris@76 361 // Close any remaining table tags.
Chris@76 362 foreach ($table_array as $tag)
Chris@76 363 $parts[$i] .= '[/' . $tag . ']';
Chris@76 364 }
Chris@76 365 }
Chris@76 366
Chris@76 367 // Put it back together!
Chris@76 368 if (!$previewing)
Chris@76 369 $message = strtr(implode('', $parts), array(' ' => '&nbsp; ', "\n" => '<br />', $context['utf8'] ? "\xC2\xA0" : "\xA0" => '&nbsp;'));
Chris@76 370 else
Chris@76 371 $message = strtr(implode('', $parts), array(' ' => '&nbsp; ', $context['utf8'] ? "\xC2\xA0" : "\xA0" => '&nbsp;'));
Chris@76 372
Chris@76 373 // Now let's quickly clean up things that will slow our parser (which are common in posted code.)
Chris@76 374 $message = strtr($message, array('[]' => '&#91;]', '[&#039;' => '&#91;&#039;'));
Chris@76 375 }
Chris@76 376
Chris@76 377 // This is very simple, and just removes things done by preparsecode.
Chris@76 378 function un_preparsecode($message)
Chris@76 379 {
Chris@76 380 global $smcFunc;
Chris@76 381
Chris@76 382 $parts = preg_split('~(\[/code\]|\[code(?:=[^\]]+)?\])~i', $message, -1, PREG_SPLIT_DELIM_CAPTURE);
Chris@76 383
Chris@76 384 // We're going to unparse only the stuff outside [code]...
Chris@76 385 for ($i = 0, $n = count($parts); $i < $n; $i++)
Chris@76 386 {
Chris@76 387 // If $i is a multiple of four (0, 4, 8, ...) then it's not a code section...
Chris@76 388 if ($i % 4 == 0)
Chris@76 389 {
Chris@76 390 $parts[$i] = preg_replace('~\[html\](.+?)\[/html\]~ie', '\'[html]\' . strtr(htmlspecialchars(\'$1\', ENT_QUOTES), array(\'\\&quot;\' => \'&quot;\', \'&amp;#13;\' => \'<br />\', \'&amp;#32;\' => \' \', \'&amp;#91;\' => \'[\', \'&amp;#93;\' => \']\')) . \'[/html]\'', $parts[$i]);
Chris@76 391 // $parts[$i] = preg_replace('~\[html\](.+?)\[/html\]~ie', '\'[html]\' . strtr(htmlspecialchars(\'$1\', ENT_QUOTES), array(\'\\&quot;\' => \'&quot;\', \'&amp;#13;\' => \'<br />\', \'&amp;#32;\' => \' \', \'&amp;#38;\' => \'&#38;\', \'&amp;#91;\' => \'[\', \'&amp;#93;\' => \']\')) . \'[/html]\'', $parts[$i]);
Chris@76 392
Chris@76 393 // Attempt to un-parse the time to something less awful.
Chris@76 394 $parts[$i] = preg_replace('~\[time\](\d{0,10})\[/time\]~ie', '\'[time]\' . timeformat(\'$1\', false) . \'[/time]\'', $parts[$i]);
Chris@76 395 }
Chris@76 396 }
Chris@76 397
Chris@76 398 // Change breaks back to \n's and &nsbp; back to spaces.
Chris@76 399 return preg_replace('~<br( /)?' . '>~', "\n", str_replace('&nbsp;', ' ', implode('', $parts)));
Chris@76 400 }
Chris@76 401
Chris@76 402 // Fix any URLs posted - ie. remove 'javascript:'.
Chris@76 403 function fixTags(&$message)
Chris@76 404 {
Chris@76 405 global $modSettings;
Chris@76 406
Chris@76 407 // WARNING: Editing the below can cause large security holes in your forum.
Chris@76 408 // Edit only if you are sure you know what you are doing.
Chris@76 409
Chris@76 410 $fixArray = array(
Chris@76 411 // [img]http://...[/img] or [img width=1]http://...[/img]
Chris@76 412 array(
Chris@76 413 'tag' => 'img',
Chris@76 414 'protocols' => array('http', 'https'),
Chris@76 415 'embeddedUrl' => false,
Chris@76 416 'hasEqualSign' => false,
Chris@76 417 'hasExtra' => true,
Chris@76 418 ),
Chris@76 419 // [url]http://...[/url]
Chris@76 420 array(
Chris@76 421 'tag' => 'url',
Chris@76 422 'protocols' => array('http', 'https'),
Chris@76 423 'embeddedUrl' => true,
Chris@76 424 'hasEqualSign' => false,
Chris@76 425 ),
Chris@76 426 // [url=http://...]name[/url]
Chris@76 427 array(
Chris@76 428 'tag' => 'url',
Chris@76 429 'protocols' => array('http', 'https'),
Chris@76 430 'embeddedUrl' => true,
Chris@76 431 'hasEqualSign' => true,
Chris@76 432 ),
Chris@76 433 // [iurl]http://...[/iurl]
Chris@76 434 array(
Chris@76 435 'tag' => 'iurl',
Chris@76 436 'protocols' => array('http', 'https'),
Chris@76 437 'embeddedUrl' => true,
Chris@76 438 'hasEqualSign' => false,
Chris@76 439 ),
Chris@76 440 // [iurl=http://...]name[/iurl]
Chris@76 441 array(
Chris@76 442 'tag' => 'iurl',
Chris@76 443 'protocols' => array('http', 'https'),
Chris@76 444 'embeddedUrl' => true,
Chris@76 445 'hasEqualSign' => true,
Chris@76 446 ),
Chris@76 447 // [ftp]ftp://...[/ftp]
Chris@76 448 array(
Chris@76 449 'tag' => 'ftp',
Chris@76 450 'protocols' => array('ftp', 'ftps'),
Chris@76 451 'embeddedUrl' => true,
Chris@76 452 'hasEqualSign' => false,
Chris@76 453 ),
Chris@76 454 // [ftp=ftp://...]name[/ftp]
Chris@76 455 array(
Chris@76 456 'tag' => 'ftp',
Chris@76 457 'protocols' => array('ftp', 'ftps'),
Chris@76 458 'embeddedUrl' => true,
Chris@76 459 'hasEqualSign' => true,
Chris@76 460 ),
Chris@76 461 // [flash]http://...[/flash]
Chris@76 462 array(
Chris@76 463 'tag' => 'flash',
Chris@76 464 'protocols' => array('http', 'https'),
Chris@76 465 'embeddedUrl' => false,
Chris@76 466 'hasEqualSign' => false,
Chris@76 467 'hasExtra' => true,
Chris@76 468 ),
Chris@76 469 );
Chris@76 470
Chris@76 471 // Fix each type of tag.
Chris@76 472 foreach ($fixArray as $param)
Chris@76 473 fixTag($message, $param['tag'], $param['protocols'], $param['embeddedUrl'], $param['hasEqualSign'], !empty($param['hasExtra']));
Chris@76 474
Chris@76 475 // Now fix possible security problems with images loading links automatically...
Chris@76 476 $message = preg_replace('~(\[img.*?\])(.+?)\[/img\]~eis', '\'$1\' . preg_replace(\'~action(=|%3d)(?!dlattach)~i\', \'action-\', \'$2\') . \'[/img]\'', $message);
Chris@76 477
Chris@76 478 // Limit the size of images posted?
Chris@76 479 if (!empty($modSettings['max_image_width']) || !empty($modSettings['max_image_height']))
Chris@76 480 {
Chris@76 481 // Find all the img tags - with or without width and height.
Chris@76 482 preg_match_all('~\[img(\s+width=\d+)?(\s+height=\d+)?(\s+width=\d+)?\](.+?)\[/img\]~is', $message, $matches, PREG_PATTERN_ORDER);
Chris@76 483
Chris@76 484 $replaces = array();
Chris@76 485 foreach ($matches[0] as $match => $dummy)
Chris@76 486 {
Chris@76 487 // If the width was after the height, handle it.
Chris@76 488 $matches[1][$match] = !empty($matches[3][$match]) ? $matches[3][$match] : $matches[1][$match];
Chris@76 489
Chris@76 490 // Now figure out if they had a desired height or width...
Chris@76 491 $desired_width = !empty($matches[1][$match]) ? (int) substr(trim($matches[1][$match]), 6) : 0;
Chris@76 492 $desired_height = !empty($matches[2][$match]) ? (int) substr(trim($matches[2][$match]), 7) : 0;
Chris@76 493
Chris@76 494 // One was omitted, or both. We'll have to find its real size...
Chris@76 495 if (empty($desired_width) || empty($desired_height))
Chris@76 496 {
Chris@76 497 list ($width, $height) = url_image_size(un_htmlspecialchars($matches[4][$match]));
Chris@76 498
Chris@76 499 // They don't have any desired width or height!
Chris@76 500 if (empty($desired_width) && empty($desired_height))
Chris@76 501 {
Chris@76 502 $desired_width = $width;
Chris@76 503 $desired_height = $height;
Chris@76 504 }
Chris@76 505 // Scale it to the width...
Chris@76 506 elseif (empty($desired_width) && !empty($height))
Chris@76 507 $desired_width = (int) (($desired_height * $width) / $height);
Chris@76 508 // Scale if to the height.
Chris@76 509 elseif (!empty($width))
Chris@76 510 $desired_height = (int) (($desired_width * $height) / $width);
Chris@76 511 }
Chris@76 512
Chris@76 513 // If the width and height are fine, just continue along...
Chris@76 514 if ($desired_width <= $modSettings['max_image_width'] && $desired_height <= $modSettings['max_image_height'])
Chris@76 515 continue;
Chris@76 516
Chris@76 517 // Too bad, it's too wide. Make it as wide as the maximum.
Chris@76 518 if ($desired_width > $modSettings['max_image_width'] && !empty($modSettings['max_image_width']))
Chris@76 519 {
Chris@76 520 $desired_height = (int) (($modSettings['max_image_width'] * $desired_height) / $desired_width);
Chris@76 521 $desired_width = $modSettings['max_image_width'];
Chris@76 522 }
Chris@76 523
Chris@76 524 // Now check the height, as well. Might have to scale twice, even...
Chris@76 525 if ($desired_height > $modSettings['max_image_height'] && !empty($modSettings['max_image_height']))
Chris@76 526 {
Chris@76 527 $desired_width = (int) (($modSettings['max_image_height'] * $desired_width) / $desired_height);
Chris@76 528 $desired_height = $modSettings['max_image_height'];
Chris@76 529 }
Chris@76 530
Chris@76 531 $replaces[$matches[0][$match]] = '[img' . (!empty($desired_width) ? ' width=' . $desired_width : '') . (!empty($desired_height) ? ' height=' . $desired_height : '') . ']' . $matches[4][$match] . '[/img]';
Chris@76 532 }
Chris@76 533
Chris@76 534 // If any img tags were actually changed...
Chris@76 535 if (!empty($replaces))
Chris@76 536 $message = strtr($message, $replaces);
Chris@76 537 }
Chris@76 538 }
Chris@76 539
Chris@76 540 // Fix a specific class of tag - ie. url with =.
Chris@76 541 function fixTag(&$message, $myTag, $protocols, $embeddedUrl = false, $hasEqualSign = false, $hasExtra = false)
Chris@76 542 {
Chris@76 543 global $boardurl, $scripturl;
Chris@76 544
Chris@76 545 if (preg_match('~^([^:]+://[^/]+)~', $boardurl, $match) != 0)
Chris@76 546 $domain_url = $match[1];
Chris@76 547 else
Chris@76 548 $domain_url = $boardurl . '/';
Chris@76 549
Chris@76 550 $replaces = array();
Chris@76 551
Chris@76 552 if ($hasEqualSign)
Chris@76 553 preg_match_all('~\[(' . $myTag . ')=([^\]]*?)\](?:(.+?)\[/(' . $myTag . ')\])?~is', $message, $matches);
Chris@76 554 else
Chris@76 555 preg_match_all('~\[(' . $myTag . ($hasExtra ? '(?:[^\]]*?)' : '') . ')\](.+?)\[/(' . $myTag . ')\]~is', $message, $matches);
Chris@76 556
Chris@76 557 foreach ($matches[0] as $k => $dummy)
Chris@76 558 {
Chris@76 559 // Remove all leading and trailing whitespace.
Chris@76 560 $replace = trim($matches[2][$k]);
Chris@76 561 $this_tag = $matches[1][$k];
Chris@76 562 $this_close = $hasEqualSign ? (empty($matches[4][$k]) ? '' : $matches[4][$k]) : $matches[3][$k];
Chris@76 563
Chris@76 564 $found = false;
Chris@76 565 foreach ($protocols as $protocol)
Chris@76 566 {
Chris@76 567 $found = strncasecmp($replace, $protocol . '://', strlen($protocol) + 3) === 0;
Chris@76 568 if ($found)
Chris@76 569 break;
Chris@76 570 }
Chris@76 571
Chris@76 572 if (!$found && $protocols[0] == 'http')
Chris@76 573 {
Chris@76 574 if (substr($replace, 0, 1) == '/')
Chris@76 575 $replace = $domain_url . $replace;
Chris@76 576 elseif (substr($replace, 0, 1) == '?')
Chris@76 577 $replace = $scripturl . $replace;
Chris@76 578 elseif (substr($replace, 0, 1) == '#' && $embeddedUrl)
Chris@76 579 {
Chris@76 580 $replace = '#' . preg_replace('~[^A-Za-z0-9_\-#]~', '', substr($replace, 1));
Chris@76 581 $this_tag = 'iurl';
Chris@76 582 $this_close = 'iurl';
Chris@76 583 }
Chris@76 584 else
Chris@76 585 $replace = $protocols[0] . '://' . $replace;
Chris@76 586 }
Chris@76 587 elseif (!$found && $protocols[0] == 'ftp')
Chris@76 588 $replace = $protocols[0] . '://' . preg_replace('~^(?!ftps?)[^:]+://~', '', $replace);
Chris@76 589 elseif (!$found)
Chris@76 590 $replace = $protocols[0] . '://' . $replace;
Chris@76 591
Chris@76 592 if ($hasEqualSign && $embeddedUrl)
Chris@76 593 $replaces[$matches[0][$k]] = '[' . $this_tag . '=' . $replace . ']' . (empty($matches[4][$k]) ? '' : $matches[3][$k] . '[/' . $this_close . ']');
Chris@76 594 elseif ($hasEqualSign)
Chris@76 595 $replaces['[' . $matches[1][$k] . '=' . $matches[2][$k] . ']'] = '[' . $this_tag . '=' . $replace . ']';
Chris@76 596 elseif ($embeddedUrl)
Chris@76 597 $replaces['[' . $matches[1][$k] . ']' . $matches[2][$k] . '[/' . $matches[3][$k] . ']'] = '[' . $this_tag . '=' . $replace . ']' . $matches[2][$k] . '[/' . $this_close . ']';
Chris@76 598 else
Chris@76 599 $replaces['[' . $matches[1][$k] . ']' . $matches[2][$k] . '[/' . $matches[3][$k] . ']'] = '[' . $this_tag . ']' . $replace . '[/' . $this_close . ']';
Chris@76 600 }
Chris@76 601
Chris@76 602 foreach ($replaces as $k => $v)
Chris@76 603 {
Chris@76 604 if ($k == $v)
Chris@76 605 unset($replaces[$k]);
Chris@76 606 }
Chris@76 607
Chris@76 608 if (!empty($replaces))
Chris@76 609 $message = strtr($message, $replaces);
Chris@76 610 }
Chris@76 611
Chris@76 612 // Send off an email.
Chris@76 613 function sendmail($to, $subject, $message, $from = null, $message_id = null, $send_html = false, $priority = 3, $hotmail_fix = null, $is_private = false)
Chris@76 614 {
Chris@76 615 global $webmaster_email, $context, $modSettings, $txt, $scripturl;
Chris@76 616 global $smcFunc;
Chris@76 617
Chris@76 618 // Use sendmail if it's set or if no SMTP server is set.
Chris@76 619 $use_sendmail = empty($modSettings['mail_type']) || $modSettings['smtp_host'] == '';
Chris@76 620
Chris@76 621 // Line breaks need to be \r\n only in windows or for SMTP.
Chris@76 622 $line_break = $context['server']['is_windows'] || !$use_sendmail ? "\r\n" : "\n";
Chris@76 623
Chris@76 624 // So far so good.
Chris@76 625 $mail_result = true;
Chris@76 626
Chris@76 627 // If the recipient list isn't an array, make it one.
Chris@76 628 $to_array = is_array($to) ? $to : array($to);
Chris@76 629
Chris@76 630 // Once upon a time, Hotmail could not interpret non-ASCII mails.
Chris@76 631 // In honour of those days, it's still called the 'hotmail fix'.
Chris@76 632 if ($hotmail_fix === null)
Chris@76 633 {
Chris@76 634 $hotmail_to = array();
Chris@76 635 foreach ($to_array as $i => $to_address)
Chris@76 636 {
Chris@76 637 if (preg_match('~@(att|comcast|bellsouth)\.[a-zA-Z\.]{2,6}$~i', $to_address) === 1)
Chris@76 638 {
Chris@76 639 $hotmail_to[] = $to_address;
Chris@76 640 $to_array = array_diff($to_array, array($to_address));
Chris@76 641 }
Chris@76 642 }
Chris@76 643
Chris@76 644 // Call this function recursively for the hotmail addresses.
Chris@76 645 if (!empty($hotmail_to))
Chris@76 646 $mail_result = sendmail($hotmail_to, $subject, $message, $from, $message_id, $send_html, $priority, true);
Chris@76 647
Chris@76 648 // The remaining addresses no longer need the fix.
Chris@76 649 $hotmail_fix = false;
Chris@76 650
Chris@76 651 // No other addresses left? Return instantly.
Chris@76 652 if (empty($to_array))
Chris@76 653 return $mail_result;
Chris@76 654 }
Chris@76 655
Chris@76 656 // Get rid of entities.
Chris@76 657 $subject = un_htmlspecialchars($subject);
Chris@76 658 // Make the message use the proper line breaks.
Chris@76 659 $message = str_replace(array("\r", "\n"), array('', $line_break), $message);
Chris@76 660
Chris@76 661 // Make sure hotmail mails are sent as HTML so that HTML entities work.
Chris@76 662 if ($hotmail_fix && !$send_html)
Chris@76 663 {
Chris@76 664 $send_html = true;
Chris@76 665 $message = strtr($message, array($line_break => '<br />' . $line_break));
Chris@76 666 $message = preg_replace('~(' . preg_quote($scripturl, '~') . '(?:[?/][\w\-_%\.,\?&;=#]+)?)~', '<a href="$1">$1</a>', $message);
Chris@76 667 }
Chris@76 668
Chris@76 669 list (, $from_name) = mimespecialchars(addcslashes($from !== null ? $from : $context['forum_name'], '<>()\'\\"'), true, $hotmail_fix, $line_break);
Chris@76 670 list (, $subject) = mimespecialchars($subject, true, $hotmail_fix, $line_break);
Chris@76 671
Chris@76 672 // Construct the mail headers...
Chris@76 673 $headers = 'From: "' . $from_name . '" <' . (empty($modSettings['mail_from']) ? $webmaster_email : $modSettings['mail_from']) . '>' . $line_break;
Chris@76 674 $headers .= $from !== null ? 'Reply-To: <' . $from . '>' . $line_break : '';
Chris@76 675 $headers .= 'Return-Path: ' . (empty($modSettings['mail_from']) ? $webmaster_email : $modSettings['mail_from']) . $line_break;
Chris@76 676 $headers .= 'Date: ' . gmdate('D, d M Y H:i:s') . ' -0000' . $line_break;
Chris@76 677
Chris@76 678 if ($message_id !== null && empty($modSettings['mail_no_message_id']))
Chris@76 679 $headers .= 'Message-ID: <' . md5($scripturl . microtime()) . '-' . $message_id . strstr(empty($modSettings['mail_from']) ? $webmaster_email : $modSettings['mail_from'], '@') . '>' . $line_break;
Chris@76 680 $headers .= 'X-Mailer: SMF' . $line_break;
Chris@76 681
Chris@76 682 // Pass this to the integration before we start modifying the output -- it'll make it easier later.
Chris@76 683 if (in_array(false, call_integration_hook('integrate_outgoing_email', array(&$subject, &$message, &$headers)), true))
Chris@76 684 return false;
Chris@76 685
Chris@76 686 // Save the original message...
Chris@76 687 $orig_message = $message;
Chris@76 688
Chris@76 689 // The mime boundary separates the different alternative versions.
Chris@76 690 $mime_boundary = 'SMF-' . md5($message . time());
Chris@76 691
Chris@76 692 // Using mime, as it allows to send a plain unencoded alternative.
Chris@76 693 $headers .= 'Mime-Version: 1.0' . $line_break;
Chris@76 694 $headers .= 'Content-Type: multipart/alternative; boundary="' . $mime_boundary . '"' . $line_break;
Chris@76 695 $headers .= 'Content-Transfer-Encoding: 7bit' . $line_break;
Chris@76 696
Chris@76 697 // Sending HTML? Let's plop in some basic stuff, then.
Chris@76 698 if ($send_html)
Chris@76 699 {
Chris@76 700 $no_html_message = un_htmlspecialchars(strip_tags(strtr($orig_message, array('</title>' => $line_break))));
Chris@76 701
Chris@76 702 // But, then, dump it and use a plain one for dinosaur clients.
Chris@76 703 list(, $plain_message) = mimespecialchars($no_html_message, false, true, $line_break);
Chris@76 704 $message = $plain_message . $line_break . '--' . $mime_boundary . $line_break;
Chris@76 705
Chris@76 706 // This is the plain text version. Even if no one sees it, we need it for spam checkers.
Chris@76 707 list($charset, $plain_charset_message, $encoding) = mimespecialchars($no_html_message, false, false, $line_break);
Chris@76 708 $message .= 'Content-Type: text/plain; charset=' . $charset . $line_break;
Chris@76 709 $message .= 'Content-Transfer-Encoding: ' . $encoding . $line_break . $line_break;
Chris@76 710 $message .= $plain_charset_message . $line_break . '--' . $mime_boundary . $line_break;
Chris@76 711
Chris@76 712 // This is the actual HTML message, prim and proper. If we wanted images, they could be inlined here (with multipart/related, etc.)
Chris@76 713 list($charset, $html_message, $encoding) = mimespecialchars($orig_message, false, $hotmail_fix, $line_break);
Chris@76 714 $message .= 'Content-Type: text/html; charset=' . $charset . $line_break;
Chris@76 715 $message .= 'Content-Transfer-Encoding: ' . ($encoding == '' ? '7bit' : $encoding) . $line_break . $line_break;
Chris@76 716 $message .= $html_message . $line_break . '--' . $mime_boundary . '--';
Chris@76 717 }
Chris@76 718 // Text is good too.
Chris@76 719 else
Chris@76 720 {
Chris@76 721 // Send a plain message first, for the older web clients.
Chris@76 722 list(, $plain_message) = mimespecialchars($orig_message, false, true, $line_break);
Chris@76 723 $message = $plain_message . $line_break . '--' . $mime_boundary . $line_break;
Chris@76 724
Chris@76 725 // Now add an encoded message using the forum's character set.
Chris@76 726 list ($charset, $encoded_message, $encoding) = mimespecialchars($orig_message, false, false, $line_break);
Chris@76 727 $message .= 'Content-Type: text/plain; charset=' . $charset . $line_break;
Chris@76 728 $message .= 'Content-Transfer-Encoding: ' . $encoding . $line_break . $line_break;
Chris@76 729 $message .= $encoded_message . $line_break . '--' . $mime_boundary . '--';
Chris@76 730 }
Chris@76 731
Chris@76 732 // Are we using the mail queue, if so this is where we butt in...
Chris@76 733 if (!empty($modSettings['mail_queue']) && $priority != 0)
Chris@76 734 return AddMailQueue(false, $to_array, $subject, $message, $headers, $send_html, $priority, $is_private);
Chris@76 735
Chris@76 736 // If it's a priority mail, send it now - note though that this should NOT be used for sending many at once.
Chris@76 737 elseif (!empty($modSettings['mail_queue']) && !empty($modSettings['mail_limit']))
Chris@76 738 {
Chris@76 739 list ($last_mail_time, $mails_this_minute) = @explode('|', $modSettings['mail_recent']);
Chris@76 740 if (empty($mails_this_minute) || time() > $last_mail_time + 60)
Chris@76 741 $new_queue_stat = time() . '|' . 1;
Chris@76 742 else
Chris@76 743 $new_queue_stat = $last_mail_time . '|' . ((int) $mails_this_minute + 1);
Chris@76 744
Chris@76 745 updateSettings(array('mail_recent' => $new_queue_stat));
Chris@76 746 }
Chris@76 747
Chris@76 748 // SMTP or sendmail?
Chris@76 749 if ($use_sendmail)
Chris@76 750 {
Chris@76 751 $subject = strtr($subject, array("\r" => '', "\n" => ''));
Chris@76 752 if (!empty($modSettings['mail_strip_carriage']))
Chris@76 753 {
Chris@76 754 $message = strtr($message, array("\r" => ''));
Chris@76 755 $headers = strtr($headers, array("\r" => ''));
Chris@76 756 }
Chris@76 757
Chris@76 758 foreach ($to_array as $to)
Chris@76 759 {
Chris@76 760 if (!mail(strtr($to, array("\r" => '', "\n" => '')), $subject, $message, $headers))
Chris@76 761 {
Chris@76 762 log_error(sprintf($txt['mail_send_unable'], $to));
Chris@76 763 $mail_result = false;
Chris@76 764 }
Chris@76 765
Chris@76 766 // Wait, wait, I'm still sending here!
Chris@76 767 @set_time_limit(300);
Chris@76 768 if (function_exists('apache_reset_timeout'))
Chris@76 769 @apache_reset_timeout();
Chris@76 770 }
Chris@76 771 }
Chris@76 772 else
Chris@76 773 $mail_result = $mail_result && smtp_mail($to_array, $subject, $message, $headers);
Chris@76 774
Chris@76 775 // Everything go smoothly?
Chris@76 776 return $mail_result;
Chris@76 777 }
Chris@76 778
Chris@76 779 // Add an email to the mail queue.
Chris@76 780 function AddMailQueue($flush = false, $to_array = array(), $subject = '', $message = '', $headers = '', $send_html = false, $priority = 3, $is_private = false)
Chris@76 781 {
Chris@76 782 global $context, $modSettings, $smcFunc;
Chris@76 783
Chris@76 784 static $cur_insert = array();
Chris@76 785 static $cur_insert_len = 0;
Chris@76 786
Chris@76 787 if ($cur_insert_len == 0)
Chris@76 788 $cur_insert = array();
Chris@76 789
Chris@76 790 // If we're flushing, make the final inserts - also if we're near the MySQL length limit!
Chris@76 791 if (($flush || $cur_insert_len > 800000) && !empty($cur_insert))
Chris@76 792 {
Chris@76 793 // Only do these once.
Chris@76 794 $cur_insert_len = 0;
Chris@76 795
Chris@76 796 // Dump the data...
Chris@76 797 $smcFunc['db_insert']('',
Chris@76 798 '{db_prefix}mail_queue',
Chris@76 799 array(
Chris@76 800 'time_sent' => 'int', 'recipient' => 'string-255', 'body' => 'string-65534', 'subject' => 'string-255',
Chris@76 801 'headers' => 'string-65534', 'send_html' => 'int', 'priority' => 'int', 'private' => 'int',
Chris@76 802 ),
Chris@76 803 $cur_insert,
Chris@76 804 array('id_mail')
Chris@76 805 );
Chris@76 806
Chris@76 807 $cur_insert = array();
Chris@76 808 $context['flush_mail'] = false;
Chris@76 809 }
Chris@76 810
Chris@76 811 // If we're flushing we're done.
Chris@76 812 if ($flush)
Chris@76 813 {
Chris@76 814 $nextSendTime = time() + 10;
Chris@76 815
Chris@76 816 $smcFunc['db_query']('', '
Chris@76 817 UPDATE {db_prefix}settings
Chris@76 818 SET value = {string:nextSendTime}
Chris@76 819 WHERE variable = {string:mail_next_send}
Chris@76 820 AND value = {string:no_outstanding}',
Chris@76 821 array(
Chris@76 822 'nextSendTime' => $nextSendTime,
Chris@76 823 'mail_next_send' => 'mail_next_send',
Chris@76 824 'no_outstanding' => '0',
Chris@76 825 )
Chris@76 826 );
Chris@76 827
Chris@76 828 return true;
Chris@76 829 }
Chris@76 830
Chris@76 831 // Ensure we tell obExit to flush.
Chris@76 832 $context['flush_mail'] = true;
Chris@76 833
Chris@76 834 foreach ($to_array as $to)
Chris@76 835 {
Chris@76 836 // Will this insert go over MySQL's limit?
Chris@76 837 $this_insert_len = strlen($to) + strlen($message) + strlen($headers) + 700;
Chris@76 838
Chris@76 839 // Insert limit of 1M (just under the safety) is reached?
Chris@76 840 if ($this_insert_len + $cur_insert_len > 1000000)
Chris@76 841 {
Chris@76 842 // Flush out what we have so far.
Chris@76 843 $smcFunc['db_insert']('',
Chris@76 844 '{db_prefix}mail_queue',
Chris@76 845 array(
Chris@76 846 'time_sent' => 'int', 'recipient' => 'string-255', 'body' => 'string-65534', 'subject' => 'string-255',
Chris@76 847 'headers' => 'string-65534', 'send_html' => 'int', 'priority' => 'int', 'private' => 'int',
Chris@76 848 ),
Chris@76 849 $cur_insert,
Chris@76 850 array('id_mail')
Chris@76 851 );
Chris@76 852
Chris@76 853 // Clear this out.
Chris@76 854 $cur_insert = array();
Chris@76 855 $cur_insert_len = 0;
Chris@76 856 }
Chris@76 857
Chris@76 858 // Now add the current insert to the array...
Chris@76 859 $cur_insert[] = array(time(), (string) $to, (string) $message, (string) $subject, (string) $headers, ($send_html ? 1 : 0), $priority, (int) $is_private);
Chris@76 860 $cur_insert_len += $this_insert_len;
Chris@76 861 }
Chris@76 862
Chris@76 863 // If they are using SSI there is a good chance obExit will never be called. So lets be nice and flush it for them.
Chris@76 864 if (SMF === 'SSI')
Chris@76 865 return AddMailQueue(true);
Chris@76 866
Chris@76 867 return true;
Chris@76 868 }
Chris@76 869
Chris@76 870 // Send off a personal message.
Chris@76 871 function sendpm($recipients, $subject, $message, $store_outbox = false, $from = null, $pm_head = 0)
Chris@76 872 {
Chris@76 873 global $scripturl, $txt, $user_info, $language;
Chris@76 874 global $modSettings, $smcFunc;
Chris@76 875
Chris@76 876 // Make sure the PM language file is loaded, we might need something out of it.
Chris@76 877 loadLanguage('PersonalMessage');
Chris@76 878
Chris@76 879 $onBehalf = $from !== null;
Chris@76 880
Chris@76 881 // Initialize log array.
Chris@76 882 $log = array(
Chris@76 883 'failed' => array(),
Chris@76 884 'sent' => array()
Chris@76 885 );
Chris@76 886
Chris@76 887 if ($from === null)
Chris@76 888 $from = array(
Chris@76 889 'id' => $user_info['id'],
Chris@76 890 'name' => $user_info['name'],
Chris@76 891 'username' => $user_info['username']
Chris@76 892 );
Chris@76 893 // Probably not needed. /me something should be of the typer.
Chris@76 894 else
Chris@76 895 $user_info['name'] = $from['name'];
Chris@76 896
Chris@76 897 // This is the one that will go in their inbox.
Chris@76 898 $htmlmessage = $smcFunc['htmlspecialchars']($message, ENT_QUOTES);
Chris@76 899 $htmlsubject = $smcFunc['htmlspecialchars']($subject);
Chris@76 900 preparsecode($htmlmessage);
Chris@76 901
Chris@76 902 // Integrated PMs
Chris@76 903 call_integration_hook('integrate_personal_message', array($recipients, $from['username'], $subject, $message));
Chris@76 904
Chris@76 905 // Get a list of usernames and convert them to IDs.
Chris@76 906 $usernames = array();
Chris@76 907 foreach ($recipients as $rec_type => $rec)
Chris@76 908 {
Chris@76 909 foreach ($rec as $id => $member)
Chris@76 910 {
Chris@76 911 if (!is_numeric($recipients[$rec_type][$id]))
Chris@76 912 {
Chris@76 913 $recipients[$rec_type][$id] = $smcFunc['strtolower'](trim(preg_replace('/[<>&"\'=\\\]/', '', $recipients[$rec_type][$id])));
Chris@76 914 $usernames[$recipients[$rec_type][$id]] = 0;
Chris@76 915 }
Chris@76 916 }
Chris@76 917 }
Chris@76 918 if (!empty($usernames))
Chris@76 919 {
Chris@76 920 $request = $smcFunc['db_query']('pm_find_username', '
Chris@76 921 SELECT id_member, member_name
Chris@76 922 FROM {db_prefix}members
Chris@76 923 WHERE ' . ($smcFunc['db_case_sensitive'] ? 'LOWER(member_name)' : 'member_name') . ' IN ({array_string:usernames})',
Chris@76 924 array(
Chris@76 925 'usernames' => array_keys($usernames),
Chris@76 926 )
Chris@76 927 );
Chris@76 928 while ($row = $smcFunc['db_fetch_assoc']($request))
Chris@76 929 if (isset($usernames[$smcFunc['strtolower']($row['member_name'])]))
Chris@76 930 $usernames[$smcFunc['strtolower']($row['member_name'])] = $row['id_member'];
Chris@76 931 $smcFunc['db_free_result']($request);
Chris@76 932
Chris@76 933 // Replace the usernames with IDs. Drop usernames that couldn't be found.
Chris@76 934 foreach ($recipients as $rec_type => $rec)
Chris@76 935 foreach ($rec as $id => $member)
Chris@76 936 {
Chris@76 937 if (is_numeric($recipients[$rec_type][$id]))
Chris@76 938 continue;
Chris@76 939
Chris@76 940 if (!empty($usernames[$member]))
Chris@76 941 $recipients[$rec_type][$id] = $usernames[$member];
Chris@76 942 else
Chris@76 943 {
Chris@76 944 $log['failed'][$id] = sprintf($txt['pm_error_user_not_found'], $recipients[$rec_type][$id]);
Chris@76 945 unset($recipients[$rec_type][$id]);
Chris@76 946 }
Chris@76 947 }
Chris@76 948 }
Chris@76 949
Chris@76 950 // Make sure there are no duplicate 'to' members.
Chris@76 951 $recipients['to'] = array_unique($recipients['to']);
Chris@76 952
Chris@76 953 // Only 'bcc' members that aren't already in 'to'.
Chris@76 954 $recipients['bcc'] = array_diff(array_unique($recipients['bcc']), $recipients['to']);
Chris@76 955
Chris@76 956 // Combine 'to' and 'bcc' recipients.
Chris@76 957 $all_to = array_merge($recipients['to'], $recipients['bcc']);
Chris@76 958
Chris@76 959 // Check no-one will want it deleted right away!
Chris@76 960 $request = $smcFunc['db_query']('', '
Chris@76 961 SELECT
Chris@76 962 id_member, criteria, is_or
Chris@76 963 FROM {db_prefix}pm_rules
Chris@76 964 WHERE id_member IN ({array_int:to_members})
Chris@76 965 AND delete_pm = {int:delete_pm}',
Chris@76 966 array(
Chris@76 967 'to_members' => $all_to,
Chris@76 968 'delete_pm' => 1,
Chris@76 969 )
Chris@76 970 );
Chris@76 971 $deletes = array();
Chris@76 972 // Check whether we have to apply anything...
Chris@76 973 while ($row = $smcFunc['db_fetch_assoc']($request))
Chris@76 974 {
Chris@76 975 $criteria = unserialize($row['criteria']);
Chris@76 976 // Note we don't check the buddy status, cause deletion from buddy = madness!
Chris@76 977 $delete = false;
Chris@76 978 foreach ($criteria as $criterium)
Chris@76 979 {
Chris@76 980 $match = false;
Chris@76 981 if (($criterium['t'] == 'mid' && $criterium['v'] == $from['id']) || ($criterium['t'] == 'gid' && in_array($criterium['v'], $user_info['groups'])) || ($criterium['t'] == 'sub' && strpos($subject, $criterium['v']) !== false) || ($criterium['t'] == 'msg' && strpos($message, $criterium['v']) !== false))
Chris@76 982 $delete = true;
Chris@76 983 // If we're adding and one criteria don't match then we stop!
Chris@76 984 elseif (!$row['is_or'])
Chris@76 985 {
Chris@76 986 $delete = false;
Chris@76 987 break;
Chris@76 988 }
Chris@76 989 }
Chris@76 990 if ($delete)
Chris@76 991 $deletes[$row['id_member']] = 1;
Chris@76 992 }
Chris@76 993 $smcFunc['db_free_result']($request);
Chris@76 994
Chris@76 995 // Load the membergrounp message limits.
Chris@76 996 //!!! Consider caching this?
Chris@76 997 static $message_limit_cache = array();
Chris@76 998 if (!allowedTo('moderate_forum') && empty($message_limit_cache))
Chris@76 999 {
Chris@76 1000 $request = $smcFunc['db_query']('', '
Chris@76 1001 SELECT id_group, max_messages
Chris@76 1002 FROM {db_prefix}membergroups',
Chris@76 1003 array(
Chris@76 1004 )
Chris@76 1005 );
Chris@76 1006 while ($row = $smcFunc['db_fetch_assoc']($request))
Chris@76 1007 $message_limit_cache[$row['id_group']] = $row['max_messages'];
Chris@76 1008 $smcFunc['db_free_result']($request);
Chris@76 1009 }
Chris@76 1010
Chris@76 1011 // Load the groups that are allowed to read PMs.
Chris@76 1012 $allowed_groups = array();
Chris@76 1013 $disallowed_groups = array();
Chris@76 1014 $request = $smcFunc['db_query']('', '
Chris@76 1015 SELECT id_group, add_deny
Chris@76 1016 FROM {db_prefix}permissions
Chris@76 1017 WHERE permission = {string:read_permission}',
Chris@76 1018 array(
Chris@76 1019 'read_permission' => 'pm_read',
Chris@76 1020 )
Chris@76 1021 );
Chris@76 1022
Chris@76 1023 while ($row = $smcFunc['db_fetch_assoc']($request))
Chris@76 1024 {
Chris@76 1025 if (empty($row['add_deny']))
Chris@76 1026 $disallowed_groups[] = $row['id_group'];
Chris@76 1027 else
Chris@76 1028 $allowed_groups[] = $row['id_group'];
Chris@76 1029 }
Chris@76 1030
Chris@76 1031 $smcFunc['db_free_result']($request);
Chris@76 1032
Chris@76 1033 if (empty($modSettings['permission_enable_deny']))
Chris@76 1034 $disallowed_groups = array();
Chris@76 1035
Chris@76 1036 $request = $smcFunc['db_query']('', '
Chris@76 1037 SELECT
Chris@76 1038 member_name, real_name, id_member, email_address, lngfile,
Chris@76 1039 pm_email_notify, instant_messages,' . (allowedTo('moderate_forum') ? ' 0' : '
Chris@76 1040 (pm_receive_from = {int:admins_only}' . (empty($modSettings['enable_buddylist']) ? '' : ' OR
Chris@76 1041 (pm_receive_from = {int:buddies_only} AND FIND_IN_SET({string:from_id}, buddy_list) = 0) OR
Chris@76 1042 (pm_receive_from = {int:not_on_ignore_list} AND FIND_IN_SET({string:from_id}, pm_ignore_list) != 0)') . ')') . ' AS ignored,
Chris@76 1043 FIND_IN_SET({string:from_id}, buddy_list) != 0 AS is_buddy, is_activated,
Chris@76 1044 additional_groups, id_group, id_post_group
Chris@76 1045 FROM {db_prefix}members
Chris@76 1046 WHERE id_member IN ({array_int:recipients})
Chris@76 1047 ORDER BY lngfile
Chris@76 1048 LIMIT {int:count_recipients}',
Chris@76 1049 array(
Chris@76 1050 'not_on_ignore_list' => 1,
Chris@76 1051 'buddies_only' => 2,
Chris@76 1052 'admins_only' => 3,
Chris@76 1053 'recipients' => $all_to,
Chris@76 1054 'count_recipients' => count($all_to),
Chris@76 1055 'from_id' => $from['id'],
Chris@76 1056 )
Chris@76 1057 );
Chris@76 1058 $notifications = array();
Chris@76 1059 while ($row = $smcFunc['db_fetch_assoc']($request))
Chris@76 1060 {
Chris@76 1061 // Don't do anything for members to be deleted!
Chris@76 1062 if (isset($deletes[$row['id_member']]))
Chris@76 1063 continue;
Chris@76 1064
Chris@76 1065 // We need to know this members groups.
Chris@76 1066 $groups = explode(',', $row['additional_groups']);
Chris@76 1067 $groups[] = $row['id_group'];
Chris@76 1068 $groups[] = $row['id_post_group'];
Chris@76 1069
Chris@76 1070 $message_limit = -1;
Chris@76 1071 // For each group see whether they've gone over their limit - assuming they're not an admin.
Chris@76 1072 if (!in_array(1, $groups))
Chris@76 1073 {
Chris@76 1074 foreach ($groups as $id)
Chris@76 1075 {
Chris@76 1076 if (isset($message_limit_cache[$id]) && $message_limit != 0 && $message_limit < $message_limit_cache[$id])
Chris@76 1077 $message_limit = $message_limit_cache[$id];
Chris@76 1078 }
Chris@76 1079
Chris@76 1080 if ($message_limit > 0 && $message_limit <= $row['instant_messages'])
Chris@76 1081 {
Chris@76 1082 $log['failed'][$row['id_member']] = sprintf($txt['pm_error_data_limit_reached'], $row['real_name']);
Chris@76 1083 unset($all_to[array_search($row['id_member'], $all_to)]);
Chris@76 1084 continue;
Chris@76 1085 }
Chris@76 1086
Chris@76 1087 // Do they have any of the allowed groups?
Chris@76 1088 if (count(array_intersect($allowed_groups, $groups)) == 0 || count(array_intersect($disallowed_groups, $groups)) != 0)
Chris@76 1089 {
Chris@76 1090 $log['failed'][$row['id_member']] = sprintf($txt['pm_error_user_cannot_read'], $row['real_name']);
Chris@76 1091 unset($all_to[array_search($row['id_member'], $all_to)]);
Chris@76 1092 continue;
Chris@76 1093 }
Chris@76 1094 }
Chris@76 1095
Chris@76 1096 // Note that PostgreSQL can return a lowercase t/f for FIND_IN_SET
Chris@76 1097 if (!empty($row['ignored']) && $row['ignored'] != 'f' && $row['id_member'] != $from['id'])
Chris@76 1098 {
Chris@76 1099 $log['failed'][$row['id_member']] = sprintf($txt['pm_error_ignored_by_user'], $row['real_name']);
Chris@76 1100 unset($all_to[array_search($row['id_member'], $all_to)]);
Chris@76 1101 continue;
Chris@76 1102 }
Chris@76 1103
Chris@76 1104 // If the receiving account is banned (>=10) or pending deletion (4), refuse to send the PM.
Chris@76 1105 if ($row['is_activated'] >= 10 || ($row['is_activated'] == 4 && !$user_info['is_admin']))
Chris@76 1106 {
Chris@76 1107 $log['failed'][$row['id_member']] = sprintf($txt['pm_error_user_cannot_read'], $row['real_name']);
Chris@76 1108 unset($all_to[array_search($row['id_member'], $all_to)]);
Chris@76 1109 continue;
Chris@76 1110 }
Chris@76 1111
Chris@76 1112 // Send a notification, if enabled - taking the buddy list into account.
Chris@76 1113 if (!empty($row['email_address']) && ($row['pm_email_notify'] == 1 || ($row['pm_email_notify'] > 1 && (!empty($modSettings['enable_buddylist']) && $row['is_buddy']))) && $row['is_activated'] == 1)
Chris@76 1114 $notifications[empty($row['lngfile']) || empty($modSettings['userLanguage']) ? $language : $row['lngfile']][] = $row['email_address'];
Chris@76 1115
Chris@76 1116 $log['sent'][$row['id_member']] = sprintf(isset($txt['pm_successfully_sent']) ? $txt['pm_successfully_sent'] : '', $row['real_name']);
Chris@76 1117 }
Chris@76 1118 $smcFunc['db_free_result']($request);
Chris@76 1119
Chris@76 1120 // Only 'send' the message if there are any recipients left.
Chris@76 1121 if (empty($all_to))
Chris@76 1122 return $log;
Chris@76 1123
Chris@76 1124 // Insert the message itself and then grab the last insert id.
Chris@76 1125 $smcFunc['db_insert']('',
Chris@76 1126 '{db_prefix}personal_messages',
Chris@76 1127 array(
Chris@76 1128 'id_pm_head' => 'int', 'id_member_from' => 'int', 'deleted_by_sender' => 'int',
Chris@76 1129 'from_name' => 'string-255', 'msgtime' => 'int', 'subject' => 'string-255', 'body' => 'string-65534',
Chris@76 1130 ),
Chris@76 1131 array(
Chris@76 1132 $pm_head, $from['id'], ($store_outbox ? 0 : 1),
Chris@76 1133 $from['username'], time(), $htmlsubject, $htmlmessage,
Chris@76 1134 ),
Chris@76 1135 array('id_pm')
Chris@76 1136 );
Chris@76 1137 $id_pm = $smcFunc['db_insert_id']('{db_prefix}personal_messages', 'id_pm');
Chris@76 1138
Chris@76 1139 // Add the recipients.
Chris@76 1140 if (!empty($id_pm))
Chris@76 1141 {
Chris@76 1142 // If this is new we need to set it part of it's own conversation.
Chris@76 1143 if (empty($pm_head))
Chris@76 1144 $smcFunc['db_query']('', '
Chris@76 1145 UPDATE {db_prefix}personal_messages
Chris@76 1146 SET id_pm_head = {int:id_pm_head}
Chris@76 1147 WHERE id_pm = {int:id_pm_head}',
Chris@76 1148 array(
Chris@76 1149 'id_pm_head' => $id_pm,
Chris@76 1150 )
Chris@76 1151 );
Chris@76 1152
Chris@76 1153 // Some people think manually deleting personal_messages is fun... it's not. We protect against it though :)
Chris@76 1154 $smcFunc['db_query']('', '
Chris@76 1155 DELETE FROM {db_prefix}pm_recipients
Chris@76 1156 WHERE id_pm = {int:id_pm}',
Chris@76 1157 array(
Chris@76 1158 'id_pm' => $id_pm,
Chris@76 1159 )
Chris@76 1160 );
Chris@76 1161
Chris@76 1162 $insertRows = array();
Chris@76 1163 foreach ($all_to as $to)
Chris@76 1164 {
Chris@76 1165 $insertRows[] = array($id_pm, $to, in_array($to, $recipients['bcc']) ? 1 : 0, isset($deletes[$to]) ? 1 : 0, 1);
Chris@76 1166 }
Chris@76 1167
Chris@76 1168 $smcFunc['db_insert']('insert',
Chris@76 1169 '{db_prefix}pm_recipients',
Chris@76 1170 array(
Chris@76 1171 'id_pm' => 'int', 'id_member' => 'int', 'bcc' => 'int', 'deleted' => 'int', 'is_new' => 'int'
Chris@76 1172 ),
Chris@76 1173 $insertRows,
Chris@76 1174 array('id_pm', 'id_member')
Chris@76 1175 );
Chris@76 1176 }
Chris@76 1177
Chris@76 1178 censorText($message);
Chris@76 1179 censorText($subject);
Chris@76 1180 $message = trim(un_htmlspecialchars(strip_tags(strtr(parse_bbc(htmlspecialchars($message), false), array('<br />' => "\n", '</div>' => "\n", '</li>' => "\n", '&#91;' => '[', '&#93;' => ']')))));
Chris@76 1181
Chris@76 1182 foreach ($notifications as $lang => $notification_list)
Chris@76 1183 {
Chris@76 1184 // Make sure to use the right language.
Chris@76 1185 loadLanguage('index+PersonalMessage', $lang, false);
Chris@76 1186
Chris@76 1187 // Replace the right things in the message strings.
Chris@76 1188 $mailsubject = str_replace(array('SUBJECT', 'SENDER'), array($subject, un_htmlspecialchars($from['name'])), $txt['new_pm_subject']);
Chris@76 1189 $mailmessage = str_replace(array('SUBJECT', 'MESSAGE', 'SENDER'), array($subject, $message, un_htmlspecialchars($from['name'])), $txt['pm_email']);
Chris@76 1190 $mailmessage .= "\n\n" . $txt['instant_reply'] . ' ' . $scripturl . '?action=pm;sa=send;f=inbox;pmsg=' . $id_pm . ';quote;u=' . $from['id'];
Chris@76 1191
Chris@76 1192 // Off the notification email goes!
Chris@76 1193 sendmail($notification_list, $mailsubject, $mailmessage, null, 'p' . $id_pm, false, 2, null, true);
Chris@76 1194 }
Chris@76 1195
Chris@76 1196 // Back to what we were on before!
Chris@76 1197 loadLanguage('index+PersonalMessage');
Chris@76 1198
Chris@76 1199 // Add one to their unread and read message counts.
Chris@76 1200 foreach ($all_to as $k => $id)
Chris@76 1201 if (isset($deletes[$id]))
Chris@76 1202 unset($all_to[$k]);
Chris@76 1203 if (!empty($all_to))
Chris@76 1204 updateMemberData($all_to, array('instant_messages' => '+', 'unread_messages' => '+', 'new_pm' => 1));
Chris@76 1205
Chris@76 1206 return $log;
Chris@76 1207 }
Chris@76 1208
Chris@76 1209 // Prepare text strings for sending as email body or header.
Chris@76 1210 function mimespecialchars($string, $with_charset = true, $hotmail_fix = false, $line_break = "\r\n", $custom_charset = null)
Chris@76 1211 {
Chris@76 1212 global $context;
Chris@76 1213
Chris@76 1214 $charset = $custom_charset !== null ? $custom_charset : $context['character_set'];
Chris@76 1215
Chris@76 1216 // This is the fun part....
Chris@76 1217 if (preg_match_all('~&#(\d{3,8});~', $string, $matches) !== 0 && !$hotmail_fix)
Chris@76 1218 {
Chris@76 1219 // Let's, for now, assume there are only &#021;'ish characters.
Chris@76 1220 $simple = true;
Chris@76 1221
Chris@76 1222 foreach ($matches[1] as $entity)
Chris@76 1223 if ($entity > 128)
Chris@76 1224 $simple = false;
Chris@76 1225 unset($matches);
Chris@76 1226
Chris@76 1227 if ($simple)
Chris@76 1228 $string = preg_replace('~&#(\d{3,8});~e', 'chr(\'$1\')', $string);
Chris@76 1229 else
Chris@76 1230 {
Chris@76 1231 // Try to convert the string to UTF-8.
Chris@76 1232 if (!$context['utf8'] && function_exists('iconv'))
Chris@76 1233 {
Chris@76 1234 $newstring = @iconv($context['character_set'], 'UTF-8', $string);
Chris@76 1235 if ($newstring)
Chris@76 1236 $string = $newstring;
Chris@76 1237 }
Chris@76 1238
Chris@76 1239 $fixchar = create_function('$n', '
Chris@76 1240 if ($n < 128)
Chris@76 1241 return chr($n);
Chris@76 1242 elseif ($n < 2048)
Chris@76 1243 return chr(192 | $n >> 6) . chr(128 | $n & 63);
Chris@76 1244 elseif ($n < 65536)
Chris@76 1245 return chr(224 | $n >> 12) . chr(128 | $n >> 6 & 63) . chr(128 | $n & 63);
Chris@76 1246 else
Chris@76 1247 return chr(240 | $n >> 18) . chr(128 | $n >> 12 & 63) . chr(128 | $n >> 6 & 63) . chr(128 | $n & 63);');
Chris@76 1248
Chris@76 1249 $string = preg_replace('~&#(\d{3,8});~e', '$fixchar(\'$1\')', $string);
Chris@76 1250
Chris@76 1251 // Unicode, baby.
Chris@76 1252 $charset = 'UTF-8';
Chris@76 1253 }
Chris@76 1254 }
Chris@76 1255
Chris@76 1256 // Convert all special characters to HTML entities...just for Hotmail :-\
Chris@76 1257 if ($hotmail_fix && ($context['utf8'] || function_exists('iconv') || $context['character_set'] === 'ISO-8859-1'))
Chris@76 1258 {
Chris@76 1259 if (!$context['utf8'] && function_exists('iconv'))
Chris@76 1260 {
Chris@76 1261 $newstring = @iconv($context['character_set'], 'UTF-8', $string);
Chris@76 1262 if ($newstring)
Chris@76 1263 $string = $newstring;
Chris@76 1264 }
Chris@76 1265
Chris@76 1266 $entityConvert = create_function('$c', '
Chris@76 1267 if (strlen($c) === 1 && ord($c[0]) <= 0x7F)
Chris@76 1268 return $c;
Chris@76 1269 elseif (strlen($c) === 2 && ord($c[0]) >= 0xC0 && ord($c[0]) <= 0xDF)
Chris@76 1270 return "&#" . (((ord($c[0]) ^ 0xC0) << 6) + (ord($c[1]) ^ 0x80)) . ";";
Chris@76 1271 elseif (strlen($c) === 3 && ord($c[0]) >= 0xE0 && ord($c[0]) <= 0xEF)
Chris@76 1272 return "&#" . (((ord($c[0]) ^ 0xE0) << 12) + ((ord($c[1]) ^ 0x80) << 6) + (ord($c[2]) ^ 0x80)) . ";";
Chris@76 1273 elseif (strlen($c) === 4 && ord($c[0]) >= 0xF0 && ord($c[0]) <= 0xF7)
Chris@76 1274 return "&#" . (((ord($c[0]) ^ 0xF0) << 18) + ((ord($c[1]) ^ 0x80) << 12) + ((ord($c[2]) ^ 0x80) << 6) + (ord($c[3]) ^ 0x80)) . ";";
Chris@76 1275 else
Chris@76 1276 return "";');
Chris@76 1277
Chris@76 1278 // Convert all 'special' characters to HTML entities.
Chris@76 1279 return array($charset, preg_replace('~([\x80-' . ($context['server']['complex_preg_chars'] ? '\x{10FFFF}' : "\xF7\xBF\xBF\xBF") . '])~eu', '$entityConvert(\'\1\')', $string), '7bit');
Chris@76 1280 }
Chris@76 1281
Chris@76 1282 // We don't need to mess with the subject line if no special characters were in it..
Chris@76 1283 elseif (!$hotmail_fix && preg_match('~([^\x09\x0A\x0D\x20-\x7F])~', $string) === 1)
Chris@76 1284 {
Chris@76 1285 // Base64 encode.
Chris@76 1286 $string = base64_encode($string);
Chris@76 1287
Chris@76 1288 // Show the characterset and the transfer-encoding for header strings.
Chris@76 1289 if ($with_charset)
Chris@76 1290 $string = '=?' . $charset . '?B?' . $string . '?=';
Chris@76 1291
Chris@76 1292 // Break it up in lines (mail body).
Chris@76 1293 else
Chris@76 1294 $string = chunk_split($string, 76, $line_break);
Chris@76 1295
Chris@76 1296 return array($charset, $string, 'base64');
Chris@76 1297 }
Chris@76 1298
Chris@76 1299 else
Chris@76 1300 return array($charset, $string, '7bit');
Chris@76 1301 }
Chris@76 1302
Chris@76 1303 // Send an email via SMTP.
Chris@76 1304 function smtp_mail($mail_to_array, $subject, $message, $headers)
Chris@76 1305 {
Chris@76 1306 global $modSettings, $webmaster_email, $txt;
Chris@76 1307
Chris@76 1308 $modSettings['smtp_host'] = trim($modSettings['smtp_host']);
Chris@76 1309
Chris@76 1310 // Try POP3 before SMTP?
Chris@76 1311 // !!! There's no interface for this yet.
Chris@76 1312 if ($modSettings['mail_type'] == 2 && $modSettings['smtp_username'] != '' && $modSettings['smtp_password'] != '')
Chris@76 1313 {
Chris@76 1314 $socket = fsockopen($modSettings['smtp_host'], 110, $errno, $errstr, 2);
Chris@76 1315 if (!$socket && (substr($modSettings['smtp_host'], 0, 5) == 'smtp.' || substr($modSettings['smtp_host'], 0, 11) == 'ssl://smtp.'))
Chris@76 1316 $socket = fsockopen(strtr($modSettings['smtp_host'], array('smtp.' => 'pop.')), 110, $errno, $errstr, 2);
Chris@76 1317
Chris@76 1318 if ($socket)
Chris@76 1319 {
Chris@76 1320 fgets($socket, 256);
Chris@76 1321 fputs($socket, 'USER ' . $modSettings['smtp_username'] . "\r\n");
Chris@76 1322 fgets($socket, 256);
Chris@76 1323 fputs($socket, 'PASS ' . base64_decode($modSettings['smtp_password']) . "\r\n");
Chris@76 1324 fgets($socket, 256);
Chris@76 1325 fputs($socket, 'QUIT' . "\r\n");
Chris@76 1326
Chris@76 1327 fclose($socket);
Chris@76 1328 }
Chris@76 1329 }
Chris@76 1330
Chris@76 1331 // Try to connect to the SMTP server... if it doesn't exist, only wait three seconds.
Chris@76 1332 if (!$socket = fsockopen($modSettings['smtp_host'], empty($modSettings['smtp_port']) ? 25 : $modSettings['smtp_port'], $errno, $errstr, 3))
Chris@76 1333 {
Chris@76 1334 // Maybe we can still save this? The port might be wrong.
Chris@76 1335 if (substr($modSettings['smtp_host'], 0, 4) == 'ssl:' && (empty($modSettings['smtp_port']) || $modSettings['smtp_port'] == 25))
Chris@76 1336 {
Chris@76 1337 if ($socket = fsockopen($modSettings['smtp_host'], 465, $errno, $errstr, 3))
Chris@76 1338 log_error($txt['smtp_port_ssl']);
Chris@76 1339 }
Chris@76 1340
Chris@76 1341 // Unable to connect! Don't show any error message, but just log one and try to continue anyway.
Chris@76 1342 if (!$socket)
Chris@76 1343 {
Chris@76 1344 log_error($txt['smtp_no_connect'] . ': ' . $errno . ' : ' . $errstr);
Chris@76 1345 return false;
Chris@76 1346 }
Chris@76 1347 }
Chris@76 1348
Chris@76 1349 // Wait for a response of 220, without "-" continuer.
Chris@76 1350 if (!server_parse(null, $socket, '220'))
Chris@76 1351 return false;
Chris@76 1352
Chris@76 1353 if ($modSettings['mail_type'] == 1 && $modSettings['smtp_username'] != '' && $modSettings['smtp_password'] != '')
Chris@76 1354 {
Chris@76 1355 // !!! These should send the CURRENT server's name, not the mail server's!
Chris@76 1356
Chris@76 1357 // EHLO could be understood to mean encrypted hello...
Chris@76 1358 if (server_parse('EHLO ' . $modSettings['smtp_host'], $socket, null) == '250')
Chris@76 1359 {
Chris@76 1360 if (!server_parse('AUTH LOGIN', $socket, '334'))
Chris@76 1361 return false;
Chris@76 1362 // Send the username and password, encoded.
Chris@76 1363 if (!server_parse(base64_encode($modSettings['smtp_username']), $socket, '334'))
Chris@76 1364 return false;
Chris@76 1365 // The password is already encoded ;)
Chris@76 1366 if (!server_parse($modSettings['smtp_password'], $socket, '235'))
Chris@76 1367 return false;
Chris@76 1368 }
Chris@76 1369 elseif (!server_parse('HELO ' . $modSettings['smtp_host'], $socket, '250'))
Chris@76 1370 return false;
Chris@76 1371 }
Chris@76 1372 else
Chris@76 1373 {
Chris@76 1374 // Just say "helo".
Chris@76 1375 if (!server_parse('HELO ' . $modSettings['smtp_host'], $socket, '250'))
Chris@76 1376 return false;
Chris@76 1377 }
Chris@76 1378
Chris@76 1379 // Fix the message for any lines beginning with a period! (the first is ignored, you see.)
Chris@76 1380 $message = strtr($message, array("\r\n" . '.' => "\r\n" . '..'));
Chris@76 1381
Chris@76 1382 // !! Theoretically, we should be able to just loop the RCPT TO.
Chris@76 1383 $mail_to_array = array_values($mail_to_array);
Chris@76 1384 foreach ($mail_to_array as $i => $mail_to)
Chris@76 1385 {
Chris@76 1386 // Reset the connection to send another email.
Chris@76 1387 if ($i != 0)
Chris@76 1388 {
Chris@76 1389 if (!server_parse('RSET', $socket, '250'))
Chris@76 1390 return false;
Chris@76 1391 }
Chris@76 1392
Chris@76 1393 // From, to, and then start the data...
Chris@76 1394 if (!server_parse('MAIL FROM: <' . (empty($modSettings['mail_from']) ? $webmaster_email : $modSettings['mail_from']) . '>', $socket, '250'))
Chris@76 1395 return false;
Chris@76 1396 if (!server_parse('RCPT TO: <' . $mail_to . '>', $socket, '250'))
Chris@76 1397 return false;
Chris@76 1398 if (!server_parse('DATA', $socket, '354'))
Chris@76 1399 return false;
Chris@76 1400 fputs($socket, 'Subject: ' . $subject . "\r\n");
Chris@76 1401 if (strlen($mail_to) > 0)
Chris@76 1402 fputs($socket, 'To: <' . $mail_to . '>' . "\r\n");
Chris@76 1403 fputs($socket, $headers . "\r\n\r\n");
Chris@76 1404 fputs($socket, $message . "\r\n");
Chris@76 1405
Chris@76 1406 // Send a ., or in other words "end of data".
Chris@76 1407 if (!server_parse('.', $socket, '250'))
Chris@76 1408 return false;
Chris@76 1409
Chris@76 1410 // Almost done, almost done... don't stop me just yet!
Chris@76 1411 @set_time_limit(300);
Chris@76 1412 if (function_exists('apache_reset_timeout'))
Chris@76 1413 @apache_reset_timeout();
Chris@76 1414 }
Chris@76 1415 fputs($socket, 'QUIT' . "\r\n");
Chris@76 1416 fclose($socket);
Chris@76 1417
Chris@76 1418 return true;
Chris@76 1419 }
Chris@76 1420
Chris@76 1421 // Parse a message to the SMTP server.
Chris@76 1422 function server_parse($message, $socket, $response)
Chris@76 1423 {
Chris@76 1424 global $txt;
Chris@76 1425
Chris@76 1426 if ($message !== null)
Chris@76 1427 fputs($socket, $message . "\r\n");
Chris@76 1428
Chris@76 1429 // No response yet.
Chris@76 1430 $server_response = '';
Chris@76 1431
Chris@76 1432 while (substr($server_response, 3, 1) != ' ')
Chris@76 1433 if (!($server_response = fgets($socket, 256)))
Chris@76 1434 {
Chris@76 1435 // !!! Change this message to reflect that it may mean bad user/password/server issues/etc.
Chris@76 1436 log_error($txt['smtp_bad_response']);
Chris@76 1437 return false;
Chris@76 1438 }
Chris@76 1439
Chris@76 1440 if ($response === null)
Chris@76 1441 return substr($server_response, 0, 3);
Chris@76 1442
Chris@76 1443 if (substr($server_response, 0, 3) != $response)
Chris@76 1444 {
Chris@76 1445 log_error($txt['smtp_error'] . $server_response);
Chris@76 1446 return false;
Chris@76 1447 }
Chris@76 1448
Chris@76 1449 return true;
Chris@76 1450 }
Chris@76 1451
Chris@76 1452 function SpellCheck()
Chris@76 1453 {
Chris@76 1454 global $txt, $context, $smcFunc;
Chris@76 1455
Chris@76 1456 // A list of "words" we know about but pspell doesn't.
Chris@76 1457 $known_words = array('smf', 'php', 'mysql', 'www', 'gif', 'jpeg', 'png', 'http', 'smfisawesome', 'grandia', 'terranigma', 'rpgs');
Chris@76 1458
Chris@76 1459 loadLanguage('Post');
Chris@76 1460 loadTemplate('Post');
Chris@76 1461
Chris@76 1462 // Okay, this looks funny, but it actually fixes a weird bug.
Chris@76 1463 ob_start();
Chris@76 1464 $old = error_reporting(0);
Chris@76 1465
Chris@76 1466 // See, first, some windows machines don't load pspell properly on the first try. Dumb, but this is a workaround.
Chris@76 1467 pspell_new('en');
Chris@76 1468
Chris@76 1469 // Next, the dictionary in question may not exist. So, we try it... but...
Chris@76 1470 $pspell_link = pspell_new($txt['lang_dictionary'], $txt['lang_spelling'], '', strtr($context['character_set'], array('iso-' => 'iso', 'ISO-' => 'iso')), PSPELL_FAST | PSPELL_RUN_TOGETHER);
Chris@76 1471
Chris@76 1472 // Most people don't have anything but English installed... So we use English as a last resort.
Chris@76 1473 if (!$pspell_link)
Chris@76 1474 $pspell_link = pspell_new('en', '', '', '', PSPELL_FAST | PSPELL_RUN_TOGETHER);
Chris@76 1475
Chris@76 1476 error_reporting($old);
Chris@76 1477 ob_end_clean();
Chris@76 1478
Chris@76 1479 if (!isset($_POST['spellstring']) || !$pspell_link)
Chris@76 1480 die;
Chris@76 1481
Chris@76 1482 // Construct a bit of Javascript code.
Chris@76 1483 $context['spell_js'] = '
Chris@76 1484 var txt = {"done": "' . $txt['spellcheck_done'] . '"};
Chris@76 1485 var mispstr = window.opener.document.forms[spell_formname][spell_fieldname].value;
Chris@76 1486 var misps = Array(';
Chris@76 1487
Chris@76 1488 // Get all the words (Javascript already separated them).
Chris@76 1489 $alphas = explode("\n", strtr($_POST['spellstring'], array("\r" => '')));
Chris@76 1490
Chris@76 1491 $found_words = false;
Chris@76 1492 for ($i = 0, $n = count($alphas); $i < $n; $i++)
Chris@76 1493 {
Chris@76 1494 // Words are sent like 'word|offset_begin|offset_end'.
Chris@76 1495 $check_word = explode('|', $alphas[$i]);
Chris@76 1496
Chris@76 1497 // If the word is a known word, or spelled right...
Chris@76 1498 if (in_array($smcFunc['strtolower']($check_word[0]), $known_words) || pspell_check($pspell_link, $check_word[0]) || !isset($check_word[2]))
Chris@76 1499 continue;
Chris@76 1500
Chris@76 1501 // Find the word, and move up the "last occurance" to here.
Chris@76 1502 $found_words = true;
Chris@76 1503
Chris@76 1504 // Add on the javascript for this misspelling.
Chris@76 1505 $context['spell_js'] .= '
Chris@76 1506 new misp("' . strtr($check_word[0], array('\\' => '\\\\', '"' => '\\"', '<' => '', '&gt;' => '')) . '", ' . (int) $check_word[1] . ', ' . (int) $check_word[2] . ', [';
Chris@76 1507
Chris@76 1508 // If there are suggestions, add them in...
Chris@76 1509 $suggestions = pspell_suggest($pspell_link, $check_word[0]);
Chris@76 1510 if (!empty($suggestions))
Chris@76 1511 {
Chris@76 1512 // But first check they aren't going to be censored - no naughty words!
Chris@76 1513 foreach ($suggestions as $k => $word)
Chris@76 1514 if ($suggestions[$k] != censorText($word))
Chris@76 1515 unset($suggestions[$k]);
Chris@76 1516
Chris@76 1517 if (!empty($suggestions))
Chris@76 1518 $context['spell_js'] .= '"' . implode('", "', $suggestions) . '"';
Chris@76 1519 }
Chris@76 1520
Chris@76 1521 $context['spell_js'] .= ']),';
Chris@76 1522 }
Chris@76 1523
Chris@76 1524 // If words were found, take off the last comma.
Chris@76 1525 if ($found_words)
Chris@76 1526 $context['spell_js'] = substr($context['spell_js'], 0, -1);
Chris@76 1527
Chris@76 1528 $context['spell_js'] .= '
Chris@76 1529 );';
Chris@76 1530
Chris@76 1531 // And instruct the template system to just show the spellcheck sub template.
Chris@76 1532 $context['template_layers'] = array();
Chris@76 1533 $context['sub_template'] = 'spellcheck';
Chris@76 1534 }
Chris@76 1535
Chris@76 1536 // Notify members that something has happened to a topic they marked!
Chris@76 1537 function sendNotifications($topics, $type, $exclude = array(), $members_only = array())
Chris@76 1538 {
Chris@76 1539 global $txt, $scripturl, $language, $user_info;
Chris@76 1540 global $modSettings, $sourcedir, $context, $smcFunc;
Chris@76 1541
Chris@76 1542 // Can't do it if there's no topics.
Chris@76 1543 if (empty($topics))
Chris@76 1544 return;
Chris@76 1545 // It must be an array - it must!
Chris@76 1546 if (!is_array($topics))
Chris@76 1547 $topics = array($topics);
Chris@76 1548
Chris@76 1549 // Get the subject and body...
Chris@76 1550 $result = $smcFunc['db_query']('', '
Chris@76 1551 SELECT mf.subject, ml.body, ml.id_member, t.id_last_msg, t.id_topic,
Chris@76 1552 IFNULL(mem.real_name, ml.poster_name) AS poster_name
Chris@76 1553 FROM {db_prefix}topics AS t
Chris@76 1554 INNER JOIN {db_prefix}messages AS mf ON (mf.id_msg = t.id_first_msg)
Chris@76 1555 INNER JOIN {db_prefix}messages AS ml ON (ml.id_msg = t.id_last_msg)
Chris@76 1556 LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = ml.id_member)
Chris@76 1557 WHERE t.id_topic IN ({array_int:topic_list})
Chris@76 1558 LIMIT 1',
Chris@76 1559 array(
Chris@76 1560 'topic_list' => $topics,
Chris@76 1561 )
Chris@76 1562 );
Chris@76 1563 $topicData = array();
Chris@76 1564 while ($row = $smcFunc['db_fetch_assoc']($result))
Chris@76 1565 {
Chris@76 1566 // Clean it up.
Chris@76 1567 censorText($row['subject']);
Chris@76 1568 censorText($row['body']);
Chris@76 1569 $row['subject'] = un_htmlspecialchars($row['subject']);
Chris@76 1570 $row['body'] = trim(un_htmlspecialchars(strip_tags(strtr(parse_bbc($row['body'], false, $row['id_last_msg']), array('<br />' => "\n", '</div>' => "\n", '</li>' => "\n", '&#91;' => '[', '&#93;' => ']')))));
Chris@76 1571
Chris@76 1572 $topicData[$row['id_topic']] = array(
Chris@76 1573 'subject' => $row['subject'],
Chris@76 1574 'body' => $row['body'],
Chris@76 1575 'last_id' => $row['id_last_msg'],
Chris@76 1576 'topic' => $row['id_topic'],
Chris@76 1577 'name' => $user_info['name'],
Chris@76 1578 'exclude' => '',
Chris@76 1579 );
Chris@76 1580 }
Chris@76 1581 $smcFunc['db_free_result']($result);
Chris@76 1582
Chris@76 1583 // Work out any exclusions...
Chris@76 1584 foreach ($topics as $key => $id)
Chris@76 1585 if (isset($topicData[$id]) && !empty($exclude[$key]))
Chris@76 1586 $topicData[$id]['exclude'] = (int) $exclude[$key];
Chris@76 1587
Chris@76 1588 // Nada?
Chris@76 1589 if (empty($topicData))
Chris@76 1590 trigger_error('sendNotifications(): topics not found', E_USER_NOTICE);
Chris@76 1591
Chris@76 1592 $topics = array_keys($topicData);
Chris@76 1593 // Just in case they've gone walkies.
Chris@76 1594 if (empty($topics))
Chris@76 1595 return;
Chris@76 1596
Chris@76 1597 // Insert all of these items into the digest log for those who want notifications later.
Chris@76 1598 $digest_insert = array();
Chris@76 1599 foreach ($topicData as $id => $data)
Chris@76 1600 $digest_insert[] = array($data['topic'], $data['last_id'], $type, (int) $data['exclude']);
Chris@76 1601 $smcFunc['db_insert']('',
Chris@76 1602 '{db_prefix}log_digest',
Chris@76 1603 array(
Chris@76 1604 'id_topic' => 'int', 'id_msg' => 'int', 'note_type' => 'string', 'exclude' => 'int',
Chris@76 1605 ),
Chris@76 1606 $digest_insert,
Chris@76 1607 array()
Chris@76 1608 );
Chris@76 1609
Chris@76 1610 // Find the members with notification on for this topic.
Chris@76 1611 $members = $smcFunc['db_query']('', '
Chris@76 1612 SELECT
Chris@76 1613 mem.id_member, mem.email_address, mem.notify_regularity, mem.notify_types, mem.notify_send_body, mem.lngfile,
Chris@76 1614 ln.sent, mem.id_group, mem.additional_groups, b.member_groups, mem.id_post_group, t.id_member_started,
Chris@76 1615 ln.id_topic
Chris@76 1616 FROM {db_prefix}log_notify AS ln
Chris@76 1617 INNER JOIN {db_prefix}members AS mem ON (mem.id_member = ln.id_member)
Chris@76 1618 INNER JOIN {db_prefix}topics AS t ON (t.id_topic = ln.id_topic)
Chris@76 1619 INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
Chris@76 1620 WHERE ln.id_topic IN ({array_int:topic_list})
Chris@76 1621 AND mem.notify_types < {int:notify_types}
Chris@76 1622 AND mem.notify_regularity < {int:notify_regularity}
Chris@76 1623 AND mem.is_activated = {int:is_activated}
Chris@76 1624 AND ln.id_member != {int:current_member}' .
Chris@76 1625 (empty($members_only) ? '' : ' AND ln.id_member IN ({array_int:members_only})') . '
Chris@76 1626 ORDER BY mem.lngfile',
Chris@76 1627 array(
Chris@76 1628 'current_member' => $user_info['id'],
Chris@76 1629 'topic_list' => $topics,
Chris@76 1630 'notify_types' => $type == 'reply' ? '4' : '3',
Chris@76 1631 'notify_regularity' => 2,
Chris@76 1632 'is_activated' => 1,
Chris@76 1633 'members_only' => is_array($members_only) ? $members_only : array($members_only),
Chris@76 1634 )
Chris@76 1635 );
Chris@76 1636 $sent = 0;
Chris@76 1637 while ($row = $smcFunc['db_fetch_assoc']($members))
Chris@76 1638 {
Chris@76 1639 // Don't do the excluded...
Chris@76 1640 if ($topicData[$row['id_topic']]['exclude'] == $row['id_member'])
Chris@76 1641 continue;
Chris@76 1642
Chris@76 1643 // Easier to check this here... if they aren't the topic poster do they really want to know?
Chris@76 1644 if ($type != 'reply' && $row['notify_types'] == 2 && $row['id_member'] != $row['id_member_started'])
Chris@76 1645 continue;
Chris@76 1646
Chris@76 1647 if ($row['id_group'] != 1)
Chris@76 1648 {
Chris@76 1649 $allowed = explode(',', $row['member_groups']);
Chris@76 1650 $row['additional_groups'] = explode(',', $row['additional_groups']);
Chris@76 1651 $row['additional_groups'][] = $row['id_group'];
Chris@76 1652 $row['additional_groups'][] = $row['id_post_group'];
Chris@76 1653
Chris@76 1654 if (count(array_intersect($allowed, $row['additional_groups'])) == 0)
Chris@76 1655 continue;
Chris@76 1656 }
Chris@76 1657
Chris@76 1658 $needed_language = empty($row['lngfile']) || empty($modSettings['userLanguage']) ? $language : $row['lngfile'];
Chris@76 1659 if (empty($current_language) || $current_language != $needed_language)
Chris@76 1660 $current_language = loadLanguage('Post', $needed_language, false);
Chris@76 1661
Chris@76 1662 $message_type = 'notification_' . $type;
Chris@76 1663 $replacements = array(
Chris@76 1664 'TOPICSUBJECT' => $topicData[$row['id_topic']]['subject'],
Chris@76 1665 'POSTERNAME' => un_htmlspecialchars($topicData[$row['id_topic']]['name']),
Chris@76 1666 'TOPICLINK' => $scripturl . '?topic=' . $row['id_topic'] . '.new;topicseen#new',
Chris@76 1667 'UNSUBSCRIBELINK' => $scripturl . '?action=notify;topic=' . $row['id_topic'] . '.0',
Chris@76 1668 );
Chris@76 1669
Chris@76 1670 if ($type == 'remove')
Chris@76 1671 unset($replacements['TOPICLINK'], $replacements['UNSUBSCRIBELINK']);
Chris@76 1672 // Do they want the body of the message sent too?
Chris@76 1673 if (!empty($row['notify_send_body']) && $type == 'reply' && empty($modSettings['disallow_sendBody']))
Chris@76 1674 {
Chris@76 1675 $message_type .= '_body';
Chris@76 1676 $replacements['MESSAGE'] = $topicData[$row['id_topic']]['body'];
Chris@76 1677 }
Chris@76 1678 if (!empty($row['notify_regularity']) && $type == 'reply')
Chris@76 1679 $message_type .= '_once';
Chris@76 1680
Chris@76 1681 // Send only if once is off or it's on and it hasn't been sent.
Chris@76 1682 if ($type != 'reply' || empty($row['notify_regularity']) || empty($row['sent']))
Chris@76 1683 {
Chris@76 1684 $emaildata = loadEmailTemplate($message_type, $replacements, $needed_language);
Chris@76 1685 sendmail($row['email_address'], $emaildata['subject'], $emaildata['body'], null, 'm' . $topicData[$row['id_topic']]['last_id']);
Chris@76 1686 $sent++;
Chris@76 1687 }
Chris@76 1688 }
Chris@76 1689 $smcFunc['db_free_result']($members);
Chris@76 1690
Chris@76 1691 if (isset($current_language) && $current_language != $user_info['language'])
Chris@76 1692 loadLanguage('Post');
Chris@76 1693
Chris@76 1694 // Sent!
Chris@76 1695 if ($type == 'reply' && !empty($sent))
Chris@76 1696 $smcFunc['db_query']('', '
Chris@76 1697 UPDATE {db_prefix}log_notify
Chris@76 1698 SET sent = {int:is_sent}
Chris@76 1699 WHERE id_topic IN ({array_int:topic_list})
Chris@76 1700 AND id_member != {int:current_member}',
Chris@76 1701 array(
Chris@76 1702 'current_member' => $user_info['id'],
Chris@76 1703 'topic_list' => $topics,
Chris@76 1704 'is_sent' => 1,
Chris@76 1705 )
Chris@76 1706 );
Chris@76 1707
Chris@76 1708 // For approvals we need to unsend the exclusions (This *is* the quickest way!)
Chris@76 1709 if (!empty($sent) && !empty($exclude))
Chris@76 1710 {
Chris@76 1711 foreach ($topicData as $id => $data)
Chris@76 1712 if ($data['exclude'])
Chris@76 1713 $smcFunc['db_query']('', '
Chris@76 1714 UPDATE {db_prefix}log_notify
Chris@76 1715 SET sent = {int:not_sent}
Chris@76 1716 WHERE id_topic = {int:id_topic}
Chris@76 1717 AND id_member = {int:id_member}',
Chris@76 1718 array(
Chris@76 1719 'not_sent' => 0,
Chris@76 1720 'id_topic' => $id,
Chris@76 1721 'id_member' => $data['exclude'],
Chris@76 1722 )
Chris@76 1723 );
Chris@76 1724 }
Chris@76 1725 }
Chris@76 1726
Chris@76 1727 // Create a post, either as new topic (id_topic = 0) or in an existing one.
Chris@76 1728 // The input parameters of this function assume:
Chris@76 1729 // - Strings have been escaped.
Chris@76 1730 // - Integers have been cast to integer.
Chris@76 1731 // - Mandatory parameters are set.
Chris@76 1732 function createPost(&$msgOptions, &$topicOptions, &$posterOptions)
Chris@76 1733 {
Chris@76 1734 global $user_info, $txt, $modSettings, $smcFunc, $context;
Chris@76 1735
Chris@76 1736 // Set optional parameters to the default value.
Chris@76 1737 $msgOptions['icon'] = empty($msgOptions['icon']) ? 'xx' : $msgOptions['icon'];
Chris@76 1738 $msgOptions['smileys_enabled'] = !empty($msgOptions['smileys_enabled']);
Chris@76 1739 $msgOptions['attachments'] = empty($msgOptions['attachments']) ? array() : $msgOptions['attachments'];
Chris@76 1740 $msgOptions['approved'] = isset($msgOptions['approved']) ? (int) $msgOptions['approved'] : 1;
Chris@76 1741 $topicOptions['id'] = empty($topicOptions['id']) ? 0 : (int) $topicOptions['id'];
Chris@76 1742 $topicOptions['poll'] = isset($topicOptions['poll']) ? (int) $topicOptions['poll'] : null;
Chris@76 1743 $topicOptions['lock_mode'] = isset($topicOptions['lock_mode']) ? $topicOptions['lock_mode'] : null;
Chris@76 1744 $topicOptions['sticky_mode'] = isset($topicOptions['sticky_mode']) ? $topicOptions['sticky_mode'] : null;
Chris@76 1745 $posterOptions['id'] = empty($posterOptions['id']) ? 0 : (int) $posterOptions['id'];
Chris@76 1746 $posterOptions['ip'] = empty($posterOptions['ip']) ? $user_info['ip'] : $posterOptions['ip'];
Chris@76 1747
Chris@76 1748 // We need to know if the topic is approved. If we're told that's great - if not find out.
Chris@76 1749 if (!$modSettings['postmod_active'])
Chris@76 1750 $topicOptions['is_approved'] = true;
Chris@76 1751 elseif (!empty($topicOptions['id']) && !isset($topicOptions['is_approved']))
Chris@76 1752 {
Chris@76 1753 $request = $smcFunc['db_query']('', '
Chris@76 1754 SELECT approved
Chris@76 1755 FROM {db_prefix}topics
Chris@76 1756 WHERE id_topic = {int:id_topic}
Chris@76 1757 LIMIT 1',
Chris@76 1758 array(
Chris@76 1759 'id_topic' => $topicOptions['id'],
Chris@76 1760 )
Chris@76 1761 );
Chris@76 1762 list ($topicOptions['is_approved']) = $smcFunc['db_fetch_row']($request);
Chris@76 1763 $smcFunc['db_free_result']($request);
Chris@76 1764 }
Chris@76 1765
Chris@76 1766 // If nothing was filled in as name/e-mail address, try the member table.
Chris@76 1767 if (!isset($posterOptions['name']) || $posterOptions['name'] == '' || (empty($posterOptions['email']) && !empty($posterOptions['id'])))
Chris@76 1768 {
Chris@76 1769 if (empty($posterOptions['id']))
Chris@76 1770 {
Chris@76 1771 $posterOptions['id'] = 0;
Chris@76 1772 $posterOptions['name'] = $txt['guest_title'];
Chris@76 1773 $posterOptions['email'] = '';
Chris@76 1774 }
Chris@76 1775 elseif ($posterOptions['id'] != $user_info['id'])
Chris@76 1776 {
Chris@76 1777 $request = $smcFunc['db_query']('', '
Chris@76 1778 SELECT member_name, email_address
Chris@76 1779 FROM {db_prefix}members
Chris@76 1780 WHERE id_member = {int:id_member}
Chris@76 1781 LIMIT 1',
Chris@76 1782 array(
Chris@76 1783 'id_member' => $posterOptions['id'],
Chris@76 1784 )
Chris@76 1785 );
Chris@76 1786 // Couldn't find the current poster?
Chris@76 1787 if ($smcFunc['db_num_rows']($request) == 0)
Chris@76 1788 {
Chris@76 1789 trigger_error('createPost(): Invalid member id ' . $posterOptions['id'], E_USER_NOTICE);
Chris@76 1790 $posterOptions['id'] = 0;
Chris@76 1791 $posterOptions['name'] = $txt['guest_title'];
Chris@76 1792 $posterOptions['email'] = '';
Chris@76 1793 }
Chris@76 1794 else
Chris@76 1795 list ($posterOptions['name'], $posterOptions['email']) = $smcFunc['db_fetch_row']($request);
Chris@76 1796 $smcFunc['db_free_result']($request);
Chris@76 1797 }
Chris@76 1798 else
Chris@76 1799 {
Chris@76 1800 $posterOptions['name'] = $user_info['name'];
Chris@76 1801 $posterOptions['email'] = $user_info['email'];
Chris@76 1802 }
Chris@76 1803 }
Chris@76 1804
Chris@76 1805 // It's do or die time: forget any user aborts!
Chris@76 1806 $previous_ignore_user_abort = ignore_user_abort(true);
Chris@76 1807
Chris@76 1808 $new_topic = empty($topicOptions['id']);
Chris@76 1809
Chris@76 1810 // Insert the post.
Chris@76 1811 $smcFunc['db_insert']('',
Chris@76 1812 '{db_prefix}messages',
Chris@76 1813 array(
Chris@76 1814 'id_board' => 'int', 'id_topic' => 'int', 'id_member' => 'int', 'subject' => 'string-255', 'body' => (!empty($modSettings['max_messageLength']) && $modSettings['max_messageLength'] > 65534 ? 'string-' . $modSettings['max_messageLength'] : 'string-65534'),
Chris@76 1815 'poster_name' => 'string-255', 'poster_email' => 'string-255', 'poster_time' => 'int', 'poster_ip' => 'string-255',
Chris@76 1816 'smileys_enabled' => 'int', 'modified_name' => 'string', 'icon' => 'string-16', 'approved' => 'int',
Chris@76 1817 ),
Chris@76 1818 array(
Chris@76 1819 $topicOptions['board'], $topicOptions['id'], $posterOptions['id'], $msgOptions['subject'], $msgOptions['body'],
Chris@76 1820 $posterOptions['name'], $posterOptions['email'], time(), $posterOptions['ip'],
Chris@76 1821 $msgOptions['smileys_enabled'] ? 1 : 0, '', $msgOptions['icon'], $msgOptions['approved'],
Chris@76 1822 ),
Chris@76 1823 array('id_msg')
Chris@76 1824 );
Chris@76 1825 $msgOptions['id'] = $smcFunc['db_insert_id']('{db_prefix}messages', 'id_msg');
Chris@76 1826
Chris@76 1827 // Something went wrong creating the message...
Chris@76 1828 if (empty($msgOptions['id']))
Chris@76 1829 return false;
Chris@76 1830
Chris@76 1831 // Fix the attachments.
Chris@76 1832 if (!empty($msgOptions['attachments']))
Chris@76 1833 $smcFunc['db_query']('', '
Chris@76 1834 UPDATE {db_prefix}attachments
Chris@76 1835 SET id_msg = {int:id_msg}
Chris@76 1836 WHERE id_attach IN ({array_int:attachment_list})',
Chris@76 1837 array(
Chris@76 1838 'attachment_list' => $msgOptions['attachments'],
Chris@76 1839 'id_msg' => $msgOptions['id'],
Chris@76 1840 )
Chris@76 1841 );
Chris@76 1842
Chris@76 1843 // Insert a new topic (if the topicID was left empty.)
Chris@76 1844 if ($new_topic)
Chris@76 1845 {
Chris@76 1846 $smcFunc['db_insert']('',
Chris@76 1847 '{db_prefix}topics',
Chris@76 1848 array(
Chris@76 1849 'id_board' => 'int', 'id_member_started' => 'int', 'id_member_updated' => 'int', 'id_first_msg' => 'int',
Chris@76 1850 'id_last_msg' => 'int', 'locked' => 'int', 'is_sticky' => 'int', 'num_views' => 'int',
Chris@76 1851 'id_poll' => 'int', 'unapproved_posts' => 'int', 'approved' => 'int',
Chris@76 1852 ),
Chris@76 1853 array(
Chris@76 1854 $topicOptions['board'], $posterOptions['id'], $posterOptions['id'], $msgOptions['id'],
Chris@76 1855 $msgOptions['id'], $topicOptions['lock_mode'] === null ? 0 : $topicOptions['lock_mode'], $topicOptions['sticky_mode'] === null ? 0 : $topicOptions['sticky_mode'], 0,
Chris@76 1856 $topicOptions['poll'] === null ? 0 : $topicOptions['poll'], $msgOptions['approved'] ? 0 : 1, $msgOptions['approved'],
Chris@76 1857 ),
Chris@76 1858 array('id_topic')
Chris@76 1859 );
Chris@76 1860 $topicOptions['id'] = $smcFunc['db_insert_id']('{db_prefix}topics', 'id_topic');
Chris@76 1861
Chris@76 1862 // The topic couldn't be created for some reason.
Chris@76 1863 if (empty($topicOptions['id']))
Chris@76 1864 {
Chris@76 1865 // We should delete the post that did work, though...
Chris@76 1866 $smcFunc['db_query']('', '
Chris@76 1867 DELETE FROM {db_prefix}messages
Chris@76 1868 WHERE id_msg = {int:id_msg}',
Chris@76 1869 array(
Chris@76 1870 'id_msg' => $msgOptions['id'],
Chris@76 1871 )
Chris@76 1872 );
Chris@76 1873
Chris@76 1874 return false;
Chris@76 1875 }
Chris@76 1876
Chris@76 1877 // Fix the message with the topic.
Chris@76 1878 $smcFunc['db_query']('', '
Chris@76 1879 UPDATE {db_prefix}messages
Chris@76 1880 SET id_topic = {int:id_topic}
Chris@76 1881 WHERE id_msg = {int:id_msg}',
Chris@76 1882 array(
Chris@76 1883 'id_topic' => $topicOptions['id'],
Chris@76 1884 'id_msg' => $msgOptions['id'],
Chris@76 1885 )
Chris@76 1886 );
Chris@76 1887
Chris@76 1888 // There's been a new topic AND a new post today.
Chris@76 1889 trackStats(array('topics' => '+', 'posts' => '+'));
Chris@76 1890
Chris@76 1891 updateStats('topic', true);
Chris@76 1892 updateStats('subject', $topicOptions['id'], $msgOptions['subject']);
Chris@76 1893
Chris@76 1894 // What if we want to export new topics out to a CMS?
Chris@76 1895 call_integration_hook('integrate_create_topic', array($msgOptions, $topicOptions, $posterOptions));
Chris@76 1896 }
Chris@76 1897 // The topic already exists, it only needs a little updating.
Chris@76 1898 else
Chris@76 1899 {
Chris@76 1900 $countChange = $msgOptions['approved'] ? 'num_replies = num_replies + 1' : 'unapproved_posts = unapproved_posts + 1';
Chris@76 1901
Chris@76 1902 // Update the number of replies and the lock/sticky status.
Chris@76 1903 $smcFunc['db_query']('', '
Chris@76 1904 UPDATE {db_prefix}topics
Chris@76 1905 SET
Chris@76 1906 ' . ($msgOptions['approved'] ? 'id_member_updated = {int:poster_id}, id_last_msg = {int:id_msg},' : '') . '
Chris@76 1907 ' . $countChange . ($topicOptions['lock_mode'] === null ? '' : ',
Chris@76 1908 locked = {int:locked}') . ($topicOptions['sticky_mode'] === null ? '' : ',
Chris@76 1909 is_sticky = {int:is_sticky}') . '
Chris@76 1910 WHERE id_topic = {int:id_topic}',
Chris@76 1911 array(
Chris@76 1912 'poster_id' => $posterOptions['id'],
Chris@76 1913 'id_msg' => $msgOptions['id'],
Chris@76 1914 'locked' => $topicOptions['lock_mode'],
Chris@76 1915 'is_sticky' => $topicOptions['sticky_mode'],
Chris@76 1916 'id_topic' => $topicOptions['id'],
Chris@76 1917 )
Chris@76 1918 );
Chris@76 1919
Chris@76 1920 // One new post has been added today.
Chris@76 1921 trackStats(array('posts' => '+'));
Chris@76 1922 }
Chris@76 1923
Chris@76 1924 // Creating is modifying...in a way.
Chris@76 1925 //!!! Why not set id_msg_modified on the insert?
Chris@76 1926 $smcFunc['db_query']('', '
Chris@76 1927 UPDATE {db_prefix}messages
Chris@76 1928 SET id_msg_modified = {int:id_msg}
Chris@76 1929 WHERE id_msg = {int:id_msg}',
Chris@76 1930 array(
Chris@76 1931 'id_msg' => $msgOptions['id'],
Chris@76 1932 )
Chris@76 1933 );
Chris@76 1934
Chris@76 1935 // Increase the number of posts and topics on the board.
Chris@76 1936 if ($msgOptions['approved'])
Chris@76 1937 $smcFunc['db_query']('', '
Chris@76 1938 UPDATE {db_prefix}boards
Chris@76 1939 SET num_posts = num_posts + 1' . ($new_topic ? ', num_topics = num_topics + 1' : '') . '
Chris@76 1940 WHERE id_board = {int:id_board}',
Chris@76 1941 array(
Chris@76 1942 'id_board' => $topicOptions['board'],
Chris@76 1943 )
Chris@76 1944 );
Chris@76 1945 else
Chris@76 1946 {
Chris@76 1947 $smcFunc['db_query']('', '
Chris@76 1948 UPDATE {db_prefix}boards
Chris@76 1949 SET unapproved_posts = unapproved_posts + 1' . ($new_topic ? ', unapproved_topics = unapproved_topics + 1' : '') . '
Chris@76 1950 WHERE id_board = {int:id_board}',
Chris@76 1951 array(
Chris@76 1952 'id_board' => $topicOptions['board'],
Chris@76 1953 )
Chris@76 1954 );
Chris@76 1955
Chris@76 1956 // Add to the approval queue too.
Chris@76 1957 $smcFunc['db_insert']('',
Chris@76 1958 '{db_prefix}approval_queue',
Chris@76 1959 array(
Chris@76 1960 'id_msg' => 'int',
Chris@76 1961 ),
Chris@76 1962 array(
Chris@76 1963 $msgOptions['id'],
Chris@76 1964 ),
Chris@76 1965 array()
Chris@76 1966 );
Chris@76 1967 }
Chris@76 1968
Chris@76 1969 // Mark inserted topic as read (only for the user calling this function).
Chris@76 1970 if (!empty($topicOptions['mark_as_read']) && !$user_info['is_guest'])
Chris@76 1971 {
Chris@76 1972 // Since it's likely they *read* it before replying, let's try an UPDATE first.
Chris@76 1973 if (!$new_topic)
Chris@76 1974 {
Chris@76 1975 $smcFunc['db_query']('', '
Chris@76 1976 UPDATE {db_prefix}log_topics
Chris@76 1977 SET id_msg = {int:id_msg}
Chris@76 1978 WHERE id_member = {int:current_member}
Chris@76 1979 AND id_topic = {int:id_topic}',
Chris@76 1980 array(
Chris@76 1981 'current_member' => $posterOptions['id'],
Chris@76 1982 'id_msg' => $msgOptions['id'],
Chris@76 1983 'id_topic' => $topicOptions['id'],
Chris@76 1984 )
Chris@76 1985 );
Chris@76 1986
Chris@76 1987 $flag = $smcFunc['db_affected_rows']() != 0;
Chris@76 1988 }
Chris@76 1989
Chris@76 1990 if (empty($flag))
Chris@76 1991 {
Chris@76 1992 $smcFunc['db_insert']('ignore',
Chris@76 1993 '{db_prefix}log_topics',
Chris@76 1994 array('id_topic' => 'int', 'id_member' => 'int', 'id_msg' => 'int'),
Chris@76 1995 array($topicOptions['id'], $posterOptions['id'], $msgOptions['id']),
Chris@76 1996 array('id_topic', 'id_member')
Chris@76 1997 );
Chris@76 1998 }
Chris@76 1999 }
Chris@76 2000
Chris@76 2001 // If there's a custom search index, it needs updating...
Chris@76 2002 if (!empty($modSettings['search_custom_index_config']))
Chris@76 2003 {
Chris@76 2004 $customIndexSettings = unserialize($modSettings['search_custom_index_config']);
Chris@76 2005
Chris@76 2006 $inserts = array();
Chris@76 2007 foreach (text2words($msgOptions['body'], $customIndexSettings['bytes_per_word'], true) as $word)
Chris@76 2008 $inserts[] = array($word, $msgOptions['id']);
Chris@76 2009
Chris@76 2010 if (!empty($inserts))
Chris@76 2011 $smcFunc['db_insert']('ignore',
Chris@76 2012 '{db_prefix}log_search_words',
Chris@76 2013 array('id_word' => 'int', 'id_msg' => 'int'),
Chris@76 2014 $inserts,
Chris@76 2015 array('id_word', 'id_msg')
Chris@76 2016 );
Chris@76 2017 }
Chris@76 2018
Chris@76 2019 // Increase the post counter for the user that created the post.
Chris@76 2020 if (!empty($posterOptions['update_post_count']) && !empty($posterOptions['id']) && $msgOptions['approved'])
Chris@76 2021 {
Chris@76 2022 // Are you the one that happened to create this post?
Chris@76 2023 if ($user_info['id'] == $posterOptions['id'])
Chris@76 2024 $user_info['posts']++;
Chris@76 2025 updateMemberData($posterOptions['id'], array('posts' => '+'));
Chris@76 2026 }
Chris@76 2027
Chris@76 2028 // They've posted, so they can make the view count go up one if they really want. (this is to keep views >= replies...)
Chris@76 2029 $_SESSION['last_read_topic'] = 0;
Chris@76 2030
Chris@76 2031 // Better safe than sorry.
Chris@76 2032 if (isset($_SESSION['topicseen_cache'][$topicOptions['board']]))
Chris@76 2033 $_SESSION['topicseen_cache'][$topicOptions['board']]--;
Chris@76 2034
Chris@76 2035 // Update all the stats so everyone knows about this new topic and message.
Chris@76 2036 updateStats('message', true, $msgOptions['id']);
Chris@76 2037
Chris@76 2038 // Update the last message on the board assuming it's approved AND the topic is.
Chris@76 2039 if ($msgOptions['approved'])
Chris@76 2040 updateLastMessages($topicOptions['board'], $new_topic || !empty($topicOptions['is_approved']) ? $msgOptions['id'] : 0);
Chris@76 2041
Chris@76 2042 // Alright, done now... we can abort now, I guess... at least this much is done.
Chris@76 2043 ignore_user_abort($previous_ignore_user_abort);
Chris@76 2044
Chris@76 2045 // Success.
Chris@76 2046 return true;
Chris@76 2047 }
Chris@76 2048
Chris@76 2049 // !!!
Chris@76 2050 function createAttachment(&$attachmentOptions)
Chris@76 2051 {
Chris@76 2052 global $modSettings, $sourcedir, $smcFunc, $context;
Chris@76 2053
Chris@76 2054 require_once($sourcedir . '/Subs-Graphics.php');
Chris@76 2055
Chris@76 2056 // We need to know where this thing is going.
Chris@76 2057 if (!empty($modSettings['currentAttachmentUploadDir']))
Chris@76 2058 {
Chris@76 2059 if (!is_array($modSettings['attachmentUploadDir']))
Chris@76 2060 $modSettings['attachmentUploadDir'] = unserialize($modSettings['attachmentUploadDir']);
Chris@76 2061
Chris@76 2062 // Just use the current path for temp files.
Chris@76 2063 $attach_dir = $modSettings['attachmentUploadDir'][$modSettings['currentAttachmentUploadDir']];
Chris@76 2064 $id_folder = $modSettings['currentAttachmentUploadDir'];
Chris@76 2065 }
Chris@76 2066 else
Chris@76 2067 {
Chris@76 2068 $attach_dir = $modSettings['attachmentUploadDir'];
Chris@76 2069 $id_folder = 1;
Chris@76 2070 }
Chris@76 2071
Chris@76 2072 $attachmentOptions['errors'] = array();
Chris@76 2073 if (!isset($attachmentOptions['post']))
Chris@76 2074 $attachmentOptions['post'] = 0;
Chris@76 2075 if (!isset($attachmentOptions['approved']))
Chris@76 2076 $attachmentOptions['approved'] = 1;
Chris@76 2077
Chris@76 2078 $already_uploaded = preg_match('~^post_tmp_' . $attachmentOptions['poster'] . '_\d+$~', $attachmentOptions['tmp_name']) != 0;
Chris@76 2079 $file_restricted = @ini_get('open_basedir') != '' && !$already_uploaded;
Chris@76 2080
Chris@76 2081 if ($already_uploaded)
Chris@76 2082 $attachmentOptions['tmp_name'] = $attach_dir . '/' . $attachmentOptions['tmp_name'];
Chris@76 2083
Chris@76 2084 // Make sure the file actually exists... sometimes it doesn't.
Chris@76 2085 if ((!$file_restricted && !file_exists($attachmentOptions['tmp_name'])) || (!$already_uploaded && !is_uploaded_file($attachmentOptions['tmp_name'])))
Chris@76 2086 {
Chris@76 2087 $attachmentOptions['errors'] = array('could_not_upload');
Chris@76 2088 return false;
Chris@76 2089 }
Chris@76 2090
Chris@76 2091 // These are the only valid image types for SMF.
Chris@76 2092 $validImageTypes = array(
Chris@76 2093 1 => 'gif',
Chris@76 2094 2 => 'jpeg',
Chris@76 2095 3 => 'png',
Chris@76 2096 5 => 'psd',
Chris@76 2097 6 => 'bmp',
Chris@76 2098 7 => 'tiff',
Chris@76 2099 8 => 'tiff',
Chris@76 2100 9 => 'jpeg',
Chris@76 2101 14 => 'iff'
Chris@76 2102 );
Chris@76 2103
Chris@76 2104 if (!$file_restricted || $already_uploaded)
Chris@76 2105 {
Chris@76 2106 $size = @getimagesize($attachmentOptions['tmp_name']);
Chris@76 2107 list ($attachmentOptions['width'], $attachmentOptions['height']) = $size;
Chris@76 2108
Chris@76 2109 // If it's an image get the mime type right.
Chris@76 2110 if (empty($attachmentOptions['mime_type']) && $attachmentOptions['width'])
Chris@76 2111 {
Chris@76 2112 // Got a proper mime type?
Chris@76 2113 if (!empty($size['mime']))
Chris@76 2114 $attachmentOptions['mime_type'] = $size['mime'];
Chris@76 2115 // Otherwise a valid one?
Chris@76 2116 elseif (isset($validImageTypes[$size[2]]))
Chris@76 2117 $attachmentOptions['mime_type'] = 'image/' . $validImageTypes[$size[2]];
Chris@76 2118 }
Chris@76 2119 }
Chris@76 2120
Chris@76 2121 // Get the hash if no hash has been given yet.
Chris@76 2122 if (empty($attachmentOptions['file_hash']))
Chris@76 2123 $attachmentOptions['file_hash'] = getAttachmentFilename($attachmentOptions['name'], false, null, true);
Chris@76 2124
Chris@76 2125 // Is the file too big?
Chris@76 2126 if (!empty($modSettings['attachmentSizeLimit']) && $attachmentOptions['size'] > $modSettings['attachmentSizeLimit'] * 1024)
Chris@76 2127 $attachmentOptions['errors'][] = 'too_large';
Chris@76 2128
Chris@76 2129 if (!empty($modSettings['attachmentCheckExtensions']))
Chris@76 2130 {
Chris@76 2131 $allowed = explode(',', strtolower($modSettings['attachmentExtensions']));
Chris@76 2132 foreach ($allowed as $k => $dummy)
Chris@76 2133 $allowed[$k] = trim($dummy);
Chris@76 2134
Chris@76 2135 if (!in_array(strtolower(substr(strrchr($attachmentOptions['name'], '.'), 1)), $allowed))
Chris@76 2136 $attachmentOptions['errors'][] = 'bad_extension';
Chris@76 2137 }
Chris@76 2138
Chris@76 2139 if (!empty($modSettings['attachmentDirSizeLimit']))
Chris@76 2140 {
Chris@76 2141 // Make sure the directory isn't full.
Chris@76 2142 $dirSize = 0;
Chris@76 2143 $dir = @opendir($attach_dir) or fatal_lang_error('cant_access_upload_path', 'critical');
Chris@76 2144 while ($file = readdir($dir))
Chris@76 2145 {
Chris@76 2146 if ($file == '.' || $file == '..')
Chris@76 2147 continue;
Chris@76 2148
Chris@76 2149 if (preg_match('~^post_tmp_\d+_\d+$~', $file) != 0)
Chris@76 2150 {
Chris@76 2151 // Temp file is more than 5 hours old!
Chris@76 2152 if (filemtime($attach_dir . '/' . $file) < time() - 18000)
Chris@76 2153 @unlink($attach_dir . '/' . $file);
Chris@76 2154 continue;
Chris@76 2155 }
Chris@76 2156
Chris@76 2157 $dirSize += filesize($attach_dir . '/' . $file);
Chris@76 2158 }
Chris@76 2159 closedir($dir);
Chris@76 2160
Chris@76 2161 // Too big! Maybe you could zip it or something...
Chris@76 2162 if ($attachmentOptions['size'] + $dirSize > $modSettings['attachmentDirSizeLimit'] * 1024)
Chris@76 2163 $attachmentOptions['errors'][] = 'directory_full';
Chris@76 2164 // Soon to be too big - warn the admins...
Chris@76 2165 elseif (!isset($modSettings['attachment_full_notified']) && $modSettings['attachmentDirSizeLimit'] > 4000 && $attachmentOptions['size'] + $dirSize > ($modSettings['attachmentDirSizeLimit'] - 2000) * 1024)
Chris@76 2166 {
Chris@76 2167 require_once($sourcedir . '/Subs-Admin.php');
Chris@76 2168 emailAdmins('admin_attachments_full');
Chris@76 2169 updateSettings(array('attachment_full_notified' => 1));
Chris@76 2170 }
Chris@76 2171 }
Chris@76 2172
Chris@76 2173 // Check if the file already exists.... (for those who do not encrypt their filenames...)
Chris@76 2174 if (empty($modSettings['attachmentEncryptFilenames']))
Chris@76 2175 {
Chris@76 2176 // Make sure they aren't trying to upload a nasty file.
Chris@76 2177 $disabledFiles = array('con', 'com1', 'com2', 'com3', 'com4', 'prn', 'aux', 'lpt1', '.htaccess', 'index.php');
Chris@76 2178 if (in_array(strtolower(basename($attachmentOptions['name'])), $disabledFiles))
Chris@76 2179 $attachmentOptions['errors'][] = 'bad_filename';
Chris@76 2180
Chris@76 2181 // Check if there's another file with that name...
Chris@76 2182 $request = $smcFunc['db_query']('', '
Chris@76 2183 SELECT id_attach
Chris@76 2184 FROM {db_prefix}attachments
Chris@76 2185 WHERE filename = {string:filename}
Chris@76 2186 LIMIT 1',
Chris@76 2187 array(
Chris@76 2188 'filename' => strtolower($attachmentOptions['name']),
Chris@76 2189 )
Chris@76 2190 );
Chris@76 2191 if ($smcFunc['db_num_rows']($request) > 0)
Chris@76 2192 $attachmentOptions['errors'][] = 'taken_filename';
Chris@76 2193 $smcFunc['db_free_result']($request);
Chris@76 2194 }
Chris@76 2195
Chris@76 2196 if (!empty($attachmentOptions['errors']))
Chris@76 2197 return false;
Chris@76 2198
Chris@76 2199 if (!is_writable($attach_dir))
Chris@76 2200 fatal_lang_error('attachments_no_write', 'critical');
Chris@76 2201
Chris@76 2202 // Assuming no-one set the extension let's take a look at it.
Chris@76 2203 if (empty($attachmentOptions['fileext']))
Chris@76 2204 {
Chris@76 2205 $attachmentOptions['fileext'] = strtolower(strrpos($attachmentOptions['name'], '.') !== false ? substr($attachmentOptions['name'], strrpos($attachmentOptions['name'], '.') + 1) : '');
Chris@76 2206 if (strlen($attachmentOptions['fileext']) > 8 || '.' . $attachmentOptions['fileext'] == $attachmentOptions['name'])
Chris@76 2207 $attachmentOptions['fileext'] = '';
Chris@76 2208 }
Chris@76 2209
Chris@76 2210 $smcFunc['db_insert']('',
Chris@76 2211 '{db_prefix}attachments',
Chris@76 2212 array(
Chris@76 2213 'id_folder' => 'int', 'id_msg' => 'int', 'filename' => 'string-255', 'file_hash' => 'string-40', 'fileext' => 'string-8',
Chris@76 2214 'size' => 'int', 'width' => 'int', 'height' => 'int',
Chris@76 2215 'mime_type' => 'string-20', 'approved' => 'int',
Chris@76 2216 ),
Chris@76 2217 array(
Chris@76 2218 $id_folder, (int) $attachmentOptions['post'], $attachmentOptions['name'], $attachmentOptions['file_hash'], $attachmentOptions['fileext'],
Chris@76 2219 (int) $attachmentOptions['size'], (empty($attachmentOptions['width']) ? 0 : (int) $attachmentOptions['width']), (empty($attachmentOptions['height']) ? '0' : (int) $attachmentOptions['height']),
Chris@76 2220 (!empty($attachmentOptions['mime_type']) ? $attachmentOptions['mime_type'] : ''), (int) $attachmentOptions['approved'],
Chris@76 2221 ),
Chris@76 2222 array('id_attach')
Chris@76 2223 );
Chris@76 2224 $attachmentOptions['id'] = $smcFunc['db_insert_id']('{db_prefix}attachments', 'id_attach');
Chris@76 2225
Chris@76 2226 if (empty($attachmentOptions['id']))
Chris@76 2227 return false;
Chris@76 2228
Chris@76 2229 // If it's not approved add to the approval queue.
Chris@76 2230 if (!$attachmentOptions['approved'])
Chris@76 2231 $smcFunc['db_insert']('',
Chris@76 2232 '{db_prefix}approval_queue',
Chris@76 2233 array(
Chris@76 2234 'id_attach' => 'int', 'id_msg' => 'int',
Chris@76 2235 ),
Chris@76 2236 array(
Chris@76 2237 $attachmentOptions['id'], (int) $attachmentOptions['post'],
Chris@76 2238 ),
Chris@76 2239 array()
Chris@76 2240 );
Chris@76 2241
Chris@76 2242 $attachmentOptions['destination'] = getAttachmentFilename(basename($attachmentOptions['name']), $attachmentOptions['id'], $id_folder, false, $attachmentOptions['file_hash']);
Chris@76 2243
Chris@76 2244 if ($already_uploaded)
Chris@76 2245 rename($attachmentOptions['tmp_name'], $attachmentOptions['destination']);
Chris@76 2246 elseif (!move_uploaded_file($attachmentOptions['tmp_name'], $attachmentOptions['destination']))
Chris@76 2247 fatal_lang_error('attach_timeout', 'critical');
Chris@76 2248
Chris@76 2249 // Attempt to chmod it.
Chris@76 2250 @chmod($attachmentOptions['destination'], 0644);
Chris@76 2251
Chris@76 2252 $size = @getimagesize($attachmentOptions['destination']);
Chris@76 2253 list ($attachmentOptions['width'], $attachmentOptions['height']) = empty($size) ? array(null, null, null) : $size;
Chris@76 2254
Chris@76 2255 // We couldn't access the file before...
Chris@76 2256 if ($file_restricted)
Chris@76 2257 {
Chris@76 2258 // Have a go at getting the right mime type.
Chris@76 2259 if (empty($attachmentOptions['mime_type']) && $attachmentOptions['width'])
Chris@76 2260 {
Chris@76 2261 if (!empty($size['mime']))
Chris@76 2262 $attachmentOptions['mime_type'] = $size['mime'];
Chris@76 2263 elseif (isset($validImageTypes[$size[2]]))
Chris@76 2264 $attachmentOptions['mime_type'] = 'image/' . $validImageTypes[$size[2]];
Chris@76 2265 }
Chris@76 2266
Chris@76 2267 if (!empty($attachmentOptions['width']) && !empty($attachmentOptions['height']))
Chris@76 2268 $smcFunc['db_query']('', '
Chris@76 2269 UPDATE {db_prefix}attachments
Chris@76 2270 SET
Chris@76 2271 width = {int:width},
Chris@76 2272 height = {int:height},
Chris@76 2273 mime_type = {string:mime_type}
Chris@76 2274 WHERE id_attach = {int:id_attach}',
Chris@76 2275 array(
Chris@76 2276 'width' => (int) $attachmentOptions['width'],
Chris@76 2277 'height' => (int) $attachmentOptions['height'],
Chris@76 2278 'id_attach' => $attachmentOptions['id'],
Chris@76 2279 'mime_type' => empty($attachmentOptions['mime_type']) ? '' : $attachmentOptions['mime_type'],
Chris@76 2280 )
Chris@76 2281 );
Chris@76 2282 }
Chris@76 2283
Chris@76 2284 // Security checks for images
Chris@76 2285 // Do we have an image? If yes, we need to check it out!
Chris@76 2286 if (isset($validImageTypes[$size[2]]))
Chris@76 2287 {
Chris@76 2288 if (!checkImageContents($attachmentOptions['destination'], !empty($modSettings['attachment_image_paranoid'])))
Chris@76 2289 {
Chris@76 2290 // It's bad. Last chance, maybe we can re-encode it?
Chris@76 2291 if (empty($modSettings['attachment_image_reencode']) || (!reencodeImage($attachmentOptions['destination'], $size[2])))
Chris@76 2292 {
Chris@76 2293 // Nothing to do: not allowed or not successful re-encoding it.
Chris@76 2294 require_once($sourcedir . '/ManageAttachments.php');
Chris@76 2295 removeAttachments(array(
Chris@76 2296 'id_attach' => $attachmentOptions['id']
Chris@76 2297 ));
Chris@76 2298 $attachmentOptions['id'] = null;
Chris@76 2299 $attachmentOptions['errors'][] = 'bad_attachment';
Chris@76 2300
Chris@76 2301 return false;
Chris@76 2302 }
Chris@76 2303 // Success! However, successes usually come for a price:
Chris@76 2304 // we might get a new format for our image...
Chris@76 2305 $old_format = $size[2];
Chris@76 2306 $size = @getimagesize($attachmentOptions['destination']);
Chris@76 2307 if (!(empty($size)) && ($size[2] != $old_format))
Chris@76 2308 {
Chris@76 2309 // Let's update the image information
Chris@76 2310 // !!! This is becoming a mess: we keep coming back and update the database,
Chris@76 2311 // instead of getting it right the first time.
Chris@76 2312 if (isset($validImageTypes[$size[2]]))
Chris@76 2313 {
Chris@76 2314 $attachmentOptions['mime_type'] = 'image/' . $validImageTypes[$size[2]];
Chris@76 2315 $smcFunc['db_query']('', '
Chris@76 2316 UPDATE {db_prefix}attachments
Chris@76 2317 SET
Chris@76 2318 mime_type = {string:mime_type}
Chris@76 2319 WHERE id_attach = {int:id_attach}',
Chris@76 2320 array(
Chris@76 2321 'id_attach' => $attachmentOptions['id'],
Chris@76 2322 'mime_type' => $attachmentOptions['mime_type'],
Chris@76 2323 )
Chris@76 2324 );
Chris@76 2325 }
Chris@76 2326 }
Chris@76 2327 }
Chris@76 2328 }
Chris@76 2329
Chris@76 2330 if (!empty($attachmentOptions['skip_thumbnail']) || (empty($attachmentOptions['width']) && empty($attachmentOptions['height'])))
Chris@76 2331 return true;
Chris@76 2332
Chris@76 2333 // Like thumbnails, do we?
Chris@76 2334 if (!empty($modSettings['attachmentThumbnails']) && !empty($modSettings['attachmentThumbWidth']) && !empty($modSettings['attachmentThumbHeight']) && ($attachmentOptions['width'] > $modSettings['attachmentThumbWidth'] || $attachmentOptions['height'] > $modSettings['attachmentThumbHeight']))
Chris@76 2335 {
Chris@76 2336 if (createThumbnail($attachmentOptions['destination'], $modSettings['attachmentThumbWidth'], $modSettings['attachmentThumbHeight']))
Chris@76 2337 {
Chris@76 2338 // Figure out how big we actually made it.
Chris@76 2339 $size = @getimagesize($attachmentOptions['destination'] . '_thumb');
Chris@76 2340 list ($thumb_width, $thumb_height) = $size;
Chris@76 2341
Chris@76 2342 if (!empty($size['mime']))
Chris@76 2343 $thumb_mime = $size['mime'];
Chris@76 2344 elseif (isset($validImageTypes[$size[2]]))
Chris@76 2345 $thumb_mime = 'image/' . $validImageTypes[$size[2]];
Chris@76 2346 // Lord only knows how this happened...
Chris@76 2347 else
Chris@76 2348 $thumb_mime = '';
Chris@76 2349
Chris@76 2350 $thumb_filename = $attachmentOptions['name'] . '_thumb';
Chris@76 2351 $thumb_size = filesize($attachmentOptions['destination'] . '_thumb');
Chris@76 2352 $thumb_file_hash = getAttachmentFilename($thumb_filename, false, null, true);
Chris@76 2353
Chris@76 2354 // To the database we go!
Chris@76 2355 $smcFunc['db_insert']('',
Chris@76 2356 '{db_prefix}attachments',
Chris@76 2357 array(
Chris@76 2358 'id_folder' => 'int', 'id_msg' => 'int', 'attachment_type' => 'int', 'filename' => 'string-255', 'file_hash' => 'string-40', 'fileext' => 'string-8',
Chris@76 2359 'size' => 'int', 'width' => 'int', 'height' => 'int', 'mime_type' => 'string-20', 'approved' => 'int',
Chris@76 2360 ),
Chris@76 2361 array(
Chris@76 2362 $id_folder, (int) $attachmentOptions['post'], 3, $thumb_filename, $thumb_file_hash, $attachmentOptions['fileext'],
Chris@76 2363 $thumb_size, $thumb_width, $thumb_height, $thumb_mime, (int) $attachmentOptions['approved'],
Chris@76 2364 ),
Chris@76 2365 array('id_attach')
Chris@76 2366 );
Chris@76 2367 $attachmentOptions['thumb'] = $smcFunc['db_insert_id']('{db_prefix}attachments', 'id_attach');
Chris@76 2368
Chris@76 2369 if (!empty($attachmentOptions['thumb']))
Chris@76 2370 {
Chris@76 2371 $smcFunc['db_query']('', '
Chris@76 2372 UPDATE {db_prefix}attachments
Chris@76 2373 SET id_thumb = {int:id_thumb}
Chris@76 2374 WHERE id_attach = {int:id_attach}',
Chris@76 2375 array(
Chris@76 2376 'id_thumb' => $attachmentOptions['thumb'],
Chris@76 2377 'id_attach' => $attachmentOptions['id'],
Chris@76 2378 )
Chris@76 2379 );
Chris@76 2380
Chris@76 2381 rename($attachmentOptions['destination'] . '_thumb', getAttachmentFilename($thumb_filename, $attachmentOptions['thumb'], $id_folder, false, $thumb_file_hash));
Chris@76 2382 }
Chris@76 2383 }
Chris@76 2384 }
Chris@76 2385
Chris@76 2386 return true;
Chris@76 2387 }
Chris@76 2388
Chris@76 2389 // !!!
Chris@76 2390 function modifyPost(&$msgOptions, &$topicOptions, &$posterOptions)
Chris@76 2391 {
Chris@76 2392 global $user_info, $modSettings, $smcFunc, $context;
Chris@76 2393
Chris@76 2394 $topicOptions['poll'] = isset($topicOptions['poll']) ? (int) $topicOptions['poll'] : null;
Chris@76 2395 $topicOptions['lock_mode'] = isset($topicOptions['lock_mode']) ? $topicOptions['lock_mode'] : null;
Chris@76 2396 $topicOptions['sticky_mode'] = isset($topicOptions['sticky_mode']) ? $topicOptions['sticky_mode'] : null;
Chris@76 2397
Chris@76 2398 // This is longer than it has to be, but makes it so we only set/change what we have to.
Chris@76 2399 $messages_columns = array();
Chris@76 2400 if (isset($posterOptions['name']))
Chris@76 2401 $messages_columns['poster_name'] = $posterOptions['name'];
Chris@76 2402 if (isset($posterOptions['email']))
Chris@76 2403 $messages_columns['poster_email'] = $posterOptions['email'];
Chris@76 2404 if (isset($msgOptions['icon']))
Chris@76 2405 $messages_columns['icon'] = $msgOptions['icon'];
Chris@76 2406 if (isset($msgOptions['subject']))
Chris@76 2407 $messages_columns['subject'] = $msgOptions['subject'];
Chris@76 2408 if (isset($msgOptions['body']))
Chris@76 2409 {
Chris@76 2410 $messages_columns['body'] = $msgOptions['body'];
Chris@76 2411
Chris@76 2412 if (!empty($modSettings['search_custom_index_config']))
Chris@76 2413 {
Chris@76 2414 $request = $smcFunc['db_query']('', '
Chris@76 2415 SELECT body
Chris@76 2416 FROM {db_prefix}messages
Chris@76 2417 WHERE id_msg = {int:id_msg}',
Chris@76 2418 array(
Chris@76 2419 'id_msg' => $msgOptions['id'],
Chris@76 2420 )
Chris@76 2421 );
Chris@76 2422 list ($old_body) = $smcFunc['db_fetch_row']($request);
Chris@76 2423 $smcFunc['db_free_result']($request);
Chris@76 2424 }
Chris@76 2425 }
Chris@76 2426 if (!empty($msgOptions['modify_time']))
Chris@76 2427 {
Chris@76 2428 $messages_columns['modified_time'] = $msgOptions['modify_time'];
Chris@76 2429 $messages_columns['modified_name'] = $msgOptions['modify_name'];
Chris@76 2430 $messages_columns['id_msg_modified'] = $modSettings['maxMsgID'];
Chris@76 2431 }
Chris@76 2432 if (isset($msgOptions['smileys_enabled']))
Chris@76 2433 $messages_columns['smileys_enabled'] = empty($msgOptions['smileys_enabled']) ? 0 : 1;
Chris@76 2434
Chris@76 2435 // Which columns need to be ints?
Chris@76 2436 $messageInts = array('modified_time', 'id_msg_modified', 'smileys_enabled');
Chris@76 2437 $update_parameters = array(
Chris@76 2438 'id_msg' => $msgOptions['id'],
Chris@76 2439 );
Chris@76 2440
Chris@76 2441 foreach ($messages_columns as $var => $val)
Chris@76 2442 {
Chris@76 2443 $messages_columns[$var] = $var . ' = {' . (in_array($var, $messageInts) ? 'int' : 'string') . ':var_' . $var . '}';
Chris@76 2444 $update_parameters['var_' . $var] = $val;
Chris@76 2445 }
Chris@76 2446
Chris@76 2447 // Nothing to do?
Chris@76 2448 if (empty($messages_columns))
Chris@76 2449 return true;
Chris@76 2450
Chris@76 2451 // Change the post.
Chris@76 2452 $smcFunc['db_query']('', '
Chris@76 2453 UPDATE {db_prefix}messages
Chris@76 2454 SET ' . implode(', ', $messages_columns) . '
Chris@76 2455 WHERE id_msg = {int:id_msg}',
Chris@76 2456 $update_parameters
Chris@76 2457 );
Chris@76 2458
Chris@76 2459 // Lock and or sticky the post.
Chris@76 2460 if ($topicOptions['sticky_mode'] !== null || $topicOptions['lock_mode'] !== null || $topicOptions['poll'] !== null)
Chris@76 2461 {
Chris@76 2462 $smcFunc['db_query']('', '
Chris@76 2463 UPDATE {db_prefix}topics
Chris@76 2464 SET
Chris@76 2465 is_sticky = {raw:is_sticky},
Chris@76 2466 locked = {raw:locked},
Chris@76 2467 id_poll = {raw:id_poll}
Chris@76 2468 WHERE id_topic = {int:id_topic}',
Chris@76 2469 array(
Chris@76 2470 'is_sticky' => $topicOptions['sticky_mode'] === null ? 'is_sticky' : (int) $topicOptions['sticky_mode'],
Chris@76 2471 'locked' => $topicOptions['lock_mode'] === null ? 'locked' : (int) $topicOptions['lock_mode'],
Chris@76 2472 'id_poll' => $topicOptions['poll'] === null ? 'id_poll' : (int) $topicOptions['poll'],
Chris@76 2473 'id_topic' => $topicOptions['id'],
Chris@76 2474 )
Chris@76 2475 );
Chris@76 2476 }
Chris@76 2477
Chris@76 2478 // Mark the edited post as read.
Chris@76 2479 if (!empty($topicOptions['mark_as_read']) && !$user_info['is_guest'])
Chris@76 2480 {
Chris@76 2481 // Since it's likely they *read* it before editing, let's try an UPDATE first.
Chris@76 2482 $smcFunc['db_query']('', '
Chris@76 2483 UPDATE {db_prefix}log_topics
Chris@76 2484 SET id_msg = {int:id_msg}
Chris@76 2485 WHERE id_member = {int:current_member}
Chris@76 2486 AND id_topic = {int:id_topic}',
Chris@76 2487 array(
Chris@76 2488 'current_member' => $user_info['id'],
Chris@76 2489 'id_msg' => $modSettings['maxMsgID'],
Chris@76 2490 'id_topic' => $topicOptions['id'],
Chris@76 2491 )
Chris@76 2492 );
Chris@76 2493
Chris@76 2494 $flag = $smcFunc['db_affected_rows']() != 0;
Chris@76 2495
Chris@76 2496 if (empty($flag))
Chris@76 2497 {
Chris@76 2498 $smcFunc['db_insert']('ignore',
Chris@76 2499 '{db_prefix}log_topics',
Chris@76 2500 array('id_topic' => 'int', 'id_member' => 'int', 'id_msg' => 'int'),
Chris@76 2501 array($topicOptions['id'], $user_info['id'], $modSettings['maxMsgID']),
Chris@76 2502 array('id_topic', 'id_member')
Chris@76 2503 );
Chris@76 2504 }
Chris@76 2505 }
Chris@76 2506
Chris@76 2507 // If there's a custom search index, it needs to be modified...
Chris@76 2508 if (isset($msgOptions['body']) && !empty($modSettings['search_custom_index_config']))
Chris@76 2509 {
Chris@76 2510 $customIndexSettings = unserialize($modSettings['search_custom_index_config']);
Chris@76 2511
Chris@76 2512 $stopwords = empty($modSettings['search_stopwords']) ? array() : explode(',', $modSettings['search_stopwords']);
Chris@76 2513 $old_index = text2words($old_body, $customIndexSettings['bytes_per_word'], true);
Chris@76 2514 $new_index = text2words($msgOptions['body'], $customIndexSettings['bytes_per_word'], true);
Chris@76 2515
Chris@76 2516 // Calculate the words to be added and removed from the index.
Chris@76 2517 $removed_words = array_diff(array_diff($old_index, $new_index), $stopwords);
Chris@76 2518 $inserted_words = array_diff(array_diff($new_index, $old_index), $stopwords);
Chris@76 2519 // Delete the removed words AND the added ones to avoid key constraints.
Chris@76 2520 if (!empty($removed_words))
Chris@76 2521 {
Chris@76 2522 $removed_words = array_merge($removed_words, $inserted_words);
Chris@76 2523 $smcFunc['db_query']('', '
Chris@76 2524 DELETE FROM {db_prefix}log_search_words
Chris@76 2525 WHERE id_msg = {int:id_msg}
Chris@76 2526 AND id_word IN ({array_int:removed_words})',
Chris@76 2527 array(
Chris@76 2528 'removed_words' => $removed_words,
Chris@76 2529 'id_msg' => $msgOptions['id'],
Chris@76 2530 )
Chris@76 2531 );
Chris@76 2532 }
Chris@76 2533
Chris@76 2534 // Add the new words to be indexed.
Chris@76 2535 if (!empty($inserted_words))
Chris@76 2536 {
Chris@76 2537 $inserts = array();
Chris@76 2538 foreach ($inserted_words as $word)
Chris@76 2539 $inserts[] = array($word, $msgOptions['id']);
Chris@76 2540 $smcFunc['db_insert']('insert',
Chris@76 2541 '{db_prefix}log_search_words',
Chris@76 2542 array('id_word' => 'string', 'id_msg' => 'int'),
Chris@76 2543 $inserts,
Chris@76 2544 array('id_word', 'id_msg')
Chris@76 2545 );
Chris@76 2546 }
Chris@76 2547 }
Chris@76 2548
Chris@76 2549 if (isset($msgOptions['subject']))
Chris@76 2550 {
Chris@76 2551 // Only update the subject if this was the first message in the topic.
Chris@76 2552 $request = $smcFunc['db_query']('', '
Chris@76 2553 SELECT id_topic
Chris@76 2554 FROM {db_prefix}topics
Chris@76 2555 WHERE id_first_msg = {int:id_first_msg}
Chris@76 2556 LIMIT 1',
Chris@76 2557 array(
Chris@76 2558 'id_first_msg' => $msgOptions['id'],
Chris@76 2559 )
Chris@76 2560 );
Chris@76 2561 if ($smcFunc['db_num_rows']($request) == 1)
Chris@76 2562 updateStats('subject', $topicOptions['id'], $msgOptions['subject']);
Chris@76 2563 $smcFunc['db_free_result']($request);
Chris@76 2564 }
Chris@76 2565
Chris@76 2566 // Finally, if we are setting the approved state we need to do much more work :(
Chris@76 2567 if ($modSettings['postmod_active'] && isset($msgOptions['approved']))
Chris@76 2568 approvePosts($msgOptions['id'], $msgOptions['approved']);
Chris@76 2569
Chris@76 2570 return true;
Chris@76 2571 }
Chris@76 2572
Chris@76 2573 // Approve (or not) some posts... without permission checks...
Chris@76 2574 function approvePosts($msgs, $approve = true)
Chris@76 2575 {
Chris@76 2576 global $sourcedir, $smcFunc;
Chris@76 2577
Chris@76 2578 if (!is_array($msgs))
Chris@76 2579 $msgs = array($msgs);
Chris@76 2580
Chris@76 2581 if (empty($msgs))
Chris@76 2582 return false;
Chris@76 2583
Chris@76 2584 // May as well start at the beginning, working out *what* we need to change.
Chris@76 2585 $request = $smcFunc['db_query']('', '
Chris@76 2586 SELECT m.id_msg, m.approved, m.id_topic, m.id_board, t.id_first_msg, t.id_last_msg,
Chris@76 2587 m.body, m.subject, IFNULL(mem.real_name, m.poster_name) AS poster_name, m.id_member,
Chris@76 2588 t.approved AS topic_approved, b.count_posts
Chris@76 2589 FROM {db_prefix}messages AS m
Chris@76 2590 INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)
Chris@76 2591 INNER JOIN {db_prefix}boards AS b ON (b.id_board = m.id_board)
Chris@76 2592 LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
Chris@76 2593 WHERE m.id_msg IN ({array_int:message_list})
Chris@76 2594 AND m.approved = {int:approved_state}',
Chris@76 2595 array(
Chris@76 2596 'message_list' => $msgs,
Chris@76 2597 'approved_state' => $approve ? 0 : 1,
Chris@76 2598 )
Chris@76 2599 );
Chris@76 2600 $msgs = array();
Chris@76 2601 $topics = array();
Chris@76 2602 $topic_changes = array();
Chris@76 2603 $board_changes = array();
Chris@76 2604 $notification_topics = array();
Chris@76 2605 $notification_posts = array();
Chris@76 2606 $member_post_changes = array();
Chris@76 2607 while ($row = $smcFunc['db_fetch_assoc']($request))
Chris@76 2608 {
Chris@76 2609 // Easy...
Chris@76 2610 $msgs[] = $row['id_msg'];
Chris@76 2611 $topics[] = $row['id_topic'];
Chris@76 2612
Chris@76 2613 // Ensure our change array exists already.
Chris@76 2614 if (!isset($topic_changes[$row['id_topic']]))
Chris@76 2615 $topic_changes[$row['id_topic']] = array(
Chris@76 2616 'id_last_msg' => $row['id_last_msg'],
Chris@76 2617 'approved' => $row['topic_approved'],
Chris@76 2618 'replies' => 0,
Chris@76 2619 'unapproved_posts' => 0,
Chris@76 2620 );
Chris@76 2621 if (!isset($board_changes[$row['id_board']]))
Chris@76 2622 $board_changes[$row['id_board']] = array(
Chris@76 2623 'posts' => 0,
Chris@76 2624 'topics' => 0,
Chris@76 2625 'unapproved_posts' => 0,
Chris@76 2626 'unapproved_topics' => 0,
Chris@76 2627 );
Chris@76 2628
Chris@76 2629 // If it's the first message then the topic state changes!
Chris@76 2630 if ($row['id_msg'] == $row['id_first_msg'])
Chris@76 2631 {
Chris@76 2632 $topic_changes[$row['id_topic']]['approved'] = $approve ? 1 : 0;
Chris@76 2633
Chris@76 2634 $board_changes[$row['id_board']]['unapproved_topics'] += $approve ? -1 : 1;
Chris@76 2635 $board_changes[$row['id_board']]['topics'] += $approve ? 1 : -1;
Chris@76 2636
Chris@76 2637 // Note we need to ensure we announce this topic!
Chris@76 2638 $notification_topics[] = array(
Chris@76 2639 'body' => $row['body'],
Chris@76 2640 'subject' => $row['subject'],
Chris@76 2641 'name' => $row['poster_name'],
Chris@76 2642 'board' => $row['id_board'],
Chris@76 2643 'topic' => $row['id_topic'],
Chris@76 2644 'msg' => $row['id_first_msg'],
Chris@76 2645 'poster' => $row['id_member'],
Chris@76 2646 );
Chris@76 2647 }
Chris@76 2648 else
Chris@76 2649 {
Chris@76 2650 $topic_changes[$row['id_topic']]['replies'] += $approve ? 1 : -1;
Chris@76 2651
Chris@76 2652 // This will be a post... but don't notify unless it's not followed by approved ones.
Chris@76 2653 if ($row['id_msg'] > $row['id_last_msg'])
Chris@76 2654 $notification_posts[$row['id_topic']][] = array(
Chris@76 2655 'id' => $row['id_msg'],
Chris@76 2656 'body' => $row['body'],
Chris@76 2657 'subject' => $row['subject'],
Chris@76 2658 'name' => $row['poster_name'],
Chris@76 2659 'topic' => $row['id_topic'],
Chris@76 2660 );
Chris@76 2661 }
Chris@76 2662
Chris@76 2663 // If this is being approved and id_msg is higher than the current id_last_msg then it changes.
Chris@76 2664 if ($approve && $row['id_msg'] > $topic_changes[$row['id_topic']]['id_last_msg'])
Chris@76 2665 $topic_changes[$row['id_topic']]['id_last_msg'] = $row['id_msg'];
Chris@76 2666 // If this is being unapproved, and it's equal to the id_last_msg we need to find a new one!
Chris@76 2667 elseif (!$approve)
Chris@76 2668 // Default to the first message and then we'll override in a bit ;)
Chris@76 2669 $topic_changes[$row['id_topic']]['id_last_msg'] = $row['id_first_msg'];
Chris@76 2670
Chris@76 2671 $topic_changes[$row['id_topic']]['unapproved_posts'] += $approve ? -1 : 1;
Chris@76 2672 $board_changes[$row['id_board']]['unapproved_posts'] += $approve ? -1 : 1;
Chris@76 2673 $board_changes[$row['id_board']]['posts'] += $approve ? 1 : -1;
Chris@76 2674
Chris@76 2675 // Post count for the user?
Chris@76 2676 if ($row['id_member'] && empty($row['count_posts']))
Chris@76 2677 $member_post_changes[$row['id_member']] = isset($member_post_changes[$row['id_member']]) ? $member_post_changes[$row['id_member']] + 1 : 1;
Chris@76 2678 }
Chris@76 2679 $smcFunc['db_free_result']($request);
Chris@76 2680
Chris@76 2681 if (empty($msgs))
Chris@76 2682 return;
Chris@76 2683
Chris@76 2684 // Now we have the differences make the changes, first the easy one.
Chris@76 2685 $smcFunc['db_query']('', '
Chris@76 2686 UPDATE {db_prefix}messages
Chris@76 2687 SET approved = {int:approved_state}
Chris@76 2688 WHERE id_msg IN ({array_int:message_list})',
Chris@76 2689 array(
Chris@76 2690 'message_list' => $msgs,
Chris@76 2691 'approved_state' => $approve ? 1 : 0,
Chris@76 2692 )
Chris@76 2693 );
Chris@76 2694
Chris@76 2695 // If we were unapproving find the last msg in the topics...
Chris@76 2696 if (!$approve)
Chris@76 2697 {
Chris@76 2698 $request = $smcFunc['db_query']('', '
Chris@76 2699 SELECT id_topic, MAX(id_msg) AS id_last_msg
Chris@76 2700 FROM {db_prefix}messages
Chris@76 2701 WHERE id_topic IN ({array_int:topic_list})
Chris@76 2702 AND approved = {int:approved}
Chris@76 2703 GROUP BY id_topic',
Chris@76 2704 array(
Chris@76 2705 'topic_list' => $topics,
Chris@76 2706 'approved' => 1,
Chris@76 2707 )
Chris@76 2708 );
Chris@76 2709 while ($row = $smcFunc['db_fetch_assoc']($request))
Chris@76 2710 $topic_changes[$row['id_topic']]['id_last_msg'] = $row['id_last_msg'];
Chris@76 2711 $smcFunc['db_free_result']($request);
Chris@76 2712 }
Chris@76 2713
Chris@76 2714 // ... next the topics...
Chris@76 2715 foreach ($topic_changes as $id => $changes)
Chris@76 2716 $smcFunc['db_query']('', '
Chris@76 2717 UPDATE {db_prefix}topics
Chris@76 2718 SET approved = {int:approved}, unapproved_posts = unapproved_posts + {int:unapproved_posts},
Chris@76 2719 num_replies = num_replies + {int:num_replies}, id_last_msg = {int:id_last_msg}
Chris@76 2720 WHERE id_topic = {int:id_topic}',
Chris@76 2721 array(
Chris@76 2722 'approved' => $changes['approved'],
Chris@76 2723 'unapproved_posts' => $changes['unapproved_posts'],
Chris@76 2724 'num_replies' => $changes['replies'],
Chris@76 2725 'id_last_msg' => $changes['id_last_msg'],
Chris@76 2726 'id_topic' => $id,
Chris@76 2727 )
Chris@76 2728 );
Chris@76 2729
Chris@76 2730 // ... finally the boards...
Chris@76 2731 foreach ($board_changes as $id => $changes)
Chris@76 2732 $smcFunc['db_query']('', '
Chris@76 2733 UPDATE {db_prefix}boards
Chris@76 2734 SET num_posts = num_posts + {int:num_posts}, unapproved_posts = unapproved_posts + {int:unapproved_posts},
Chris@76 2735 num_topics = num_topics + {int:num_topics}, unapproved_topics = unapproved_topics + {int:unapproved_topics}
Chris@76 2736 WHERE id_board = {int:id_board}',
Chris@76 2737 array(
Chris@76 2738 'num_posts' => $changes['posts'],
Chris@76 2739 'unapproved_posts' => $changes['unapproved_posts'],
Chris@76 2740 'num_topics' => $changes['topics'],
Chris@76 2741 'unapproved_topics' => $changes['unapproved_topics'],
Chris@76 2742 'id_board' => $id,
Chris@76 2743 )
Chris@76 2744 );
Chris@76 2745
Chris@76 2746 // Finally, least importantly, notifications!
Chris@76 2747 if ($approve)
Chris@76 2748 {
Chris@76 2749 if (!empty($notification_topics))
Chris@76 2750 {
Chris@76 2751 require_once($sourcedir . '/Post.php');
Chris@76 2752 notifyMembersBoard($notification_topics);
Chris@76 2753 }
Chris@76 2754 if (!empty($notification_posts))
Chris@76 2755 sendApprovalNotifications($notification_posts);
Chris@76 2756
Chris@76 2757 $smcFunc['db_query']('', '
Chris@76 2758 DELETE FROM {db_prefix}approval_queue
Chris@76 2759 WHERE id_msg IN ({array_int:message_list})
Chris@76 2760 AND id_attach = {int:id_attach}',
Chris@76 2761 array(
Chris@76 2762 'message_list' => $msgs,
Chris@76 2763 'id_attach' => 0,
Chris@76 2764 )
Chris@76 2765 );
Chris@76 2766 }
Chris@76 2767 // If unapproving add to the approval queue!
Chris@76 2768 else
Chris@76 2769 {
Chris@76 2770 $msgInserts = array();
Chris@76 2771 foreach ($msgs as $msg)
Chris@76 2772 $msgInserts[] = array($msg);
Chris@76 2773
Chris@76 2774 $smcFunc['db_insert']('ignore',
Chris@76 2775 '{db_prefix}approval_queue',
Chris@76 2776 array('id_msg' => 'int'),
Chris@76 2777 $msgInserts,
Chris@76 2778 array('id_msg')
Chris@76 2779 );
Chris@76 2780 }
Chris@76 2781
Chris@76 2782 // Update the last messages on the boards...
Chris@76 2783 updateLastMessages(array_keys($board_changes));
Chris@76 2784
Chris@76 2785 // Post count for the members?
Chris@76 2786 if (!empty($member_post_changes))
Chris@76 2787 foreach ($member_post_changes as $id_member => $count_change)
Chris@76 2788 updateMemberData($id_member, array('posts' => 'posts ' . ($approve ? '+' : '-') . ' ' . $count_change));
Chris@76 2789
Chris@76 2790 return true;
Chris@76 2791 }
Chris@76 2792
Chris@76 2793 // Approve topics?
Chris@76 2794 function approveTopics($topics, $approve = true)
Chris@76 2795 {
Chris@76 2796 global $smcFunc;
Chris@76 2797
Chris@76 2798 if (!is_array($topics))
Chris@76 2799 $topics = array($topics);
Chris@76 2800
Chris@76 2801 if (empty($topics))
Chris@76 2802 return false;
Chris@76 2803
Chris@76 2804 $approve_type = $approve ? 0 : 1;
Chris@76 2805
Chris@76 2806 // Just get the messages to be approved and pass through...
Chris@76 2807 $request = $smcFunc['db_query']('', '
Chris@76 2808 SELECT id_msg
Chris@76 2809 FROM {db_prefix}messages
Chris@76 2810 WHERE id_topic IN ({array_int:topic_list})
Chris@76 2811 AND approved = {int:approve_type}',
Chris@76 2812 array(
Chris@76 2813 'topic_list' => $topics,
Chris@76 2814 'approve_type' => $approve_type,
Chris@76 2815 )
Chris@76 2816 );
Chris@76 2817 $msgs = array();
Chris@76 2818 while ($row = $smcFunc['db_fetch_assoc']($request))
Chris@76 2819 $msgs[] = $row['id_msg'];
Chris@76 2820 $smcFunc['db_free_result']($request);
Chris@76 2821
Chris@76 2822 return approvePosts($msgs, $approve);
Chris@76 2823 }
Chris@76 2824
Chris@76 2825 // A special function for handling the hell which is sending approval notifications.
Chris@76 2826 function sendApprovalNotifications(&$topicData)
Chris@76 2827 {
Chris@76 2828 global $txt, $scripturl, $language, $user_info;
Chris@76 2829 global $modSettings, $sourcedir, $context, $smcFunc;
Chris@76 2830
Chris@76 2831 // Clean up the data...
Chris@76 2832 if (!is_array($topicData) || empty($topicData))
Chris@76 2833 return;
Chris@76 2834
Chris@76 2835 $topics = array();
Chris@76 2836 $digest_insert = array();
Chris@76 2837 foreach ($topicData as $topic => $msgs)
Chris@76 2838 foreach ($msgs as $msgKey => $msg)
Chris@76 2839 {
Chris@76 2840 censorText($topicData[$topic][$msgKey]['subject']);
Chris@76 2841 censorText($topicData[$topic][$msgKey]['body']);
Chris@76 2842 $topicData[$topic][$msgKey]['subject'] = un_htmlspecialchars($topicData[$topic][$msgKey]['subject']);
Chris@76 2843 $topicData[$topic][$msgKey]['body'] = trim(un_htmlspecialchars(strip_tags(strtr(parse_bbc($topicData[$topic][$msgKey]['body'], false), array('<br />' => "\n", '</div>' => "\n", '</li>' => "\n", '&#91;' => '[', '&#93;' => ']')))));
Chris@76 2844
Chris@76 2845 $topics[] = $msg['id'];
Chris@76 2846 $digest_insert[] = array($msg['topic'], $msg['id'], 'reply', $user_info['id']);
Chris@76 2847 }
Chris@76 2848
Chris@76 2849 // These need to go into the digest too...
Chris@76 2850 $smcFunc['db_insert']('',
Chris@76 2851 '{db_prefix}log_digest',
Chris@76 2852 array(
Chris@76 2853 'id_topic' => 'int', 'id_msg' => 'int', 'note_type' => 'string', 'exclude' => 'int',
Chris@76 2854 ),
Chris@76 2855 $digest_insert,
Chris@76 2856 array()
Chris@76 2857 );
Chris@76 2858
Chris@76 2859 // Find everyone who needs to know about this.
Chris@76 2860 $members = $smcFunc['db_query']('', '
Chris@76 2861 SELECT
Chris@76 2862 mem.id_member, mem.email_address, mem.notify_regularity, mem.notify_types, mem.notify_send_body, mem.lngfile,
Chris@76 2863 ln.sent, mem.id_group, mem.additional_groups, b.member_groups, mem.id_post_group, t.id_member_started,
Chris@76 2864 ln.id_topic
Chris@76 2865 FROM {db_prefix}log_notify AS ln
Chris@76 2866 INNER JOIN {db_prefix}members AS mem ON (mem.id_member = ln.id_member)
Chris@76 2867 INNER JOIN {db_prefix}topics AS t ON (t.id_topic = ln.id_topic)
Chris@76 2868 INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
Chris@76 2869 WHERE ln.id_topic IN ({array_int:topic_list})
Chris@76 2870 AND mem.is_activated = {int:is_activated}
Chris@76 2871 AND mem.notify_types < {int:notify_types}
Chris@76 2872 AND mem.notify_regularity < {int:notify_regularity}
Chris@76 2873 GROUP BY mem.id_member, ln.id_topic, mem.email_address, mem.notify_regularity, mem.notify_types, mem.notify_send_body, mem.lngfile, ln.sent, mem.id_group, mem.additional_groups, b.member_groups, mem.id_post_group, t.id_member_started
Chris@76 2874 ORDER BY mem.lngfile',
Chris@76 2875 array(
Chris@76 2876 'topic_list' => $topics,
Chris@76 2877 'is_activated' => 1,
Chris@76 2878 'notify_types' => 4,
Chris@76 2879 'notify_regularity' => 2,
Chris@76 2880 )
Chris@76 2881 );
Chris@76 2882 $sent = 0;
Chris@76 2883 while ($row = $smcFunc['db_fetch_assoc']($members))
Chris@76 2884 {
Chris@76 2885 if ($row['id_group'] != 1)
Chris@76 2886 {
Chris@76 2887 $allowed = explode(',', $row['member_groups']);
Chris@76 2888 $row['additional_groups'] = explode(',', $row['additional_groups']);
Chris@76 2889 $row['additional_groups'][] = $row['id_group'];
Chris@76 2890 $row['additional_groups'][] = $row['id_post_group'];
Chris@76 2891
Chris@76 2892 if (count(array_intersect($allowed, $row['additional_groups'])) == 0)
Chris@76 2893 continue;
Chris@76 2894 }
Chris@76 2895
Chris@76 2896 $needed_language = empty($row['lngfile']) || empty($modSettings['userLanguage']) ? $language : $row['lngfile'];
Chris@76 2897 if (empty($current_language) || $current_language != $needed_language)
Chris@76 2898 $current_language = loadLanguage('Post', $needed_language, false);
Chris@76 2899
Chris@76 2900 $sent_this_time = false;
Chris@76 2901 // Now loop through all the messages to send.
Chris@76 2902 foreach ($topicData[$row['id_topic']] as $msg)
Chris@76 2903 {
Chris@76 2904 $replacements = array(
Chris@76 2905 'TOPICSUBJECT' => $topicData[$row['id_topic']]['subject'],
Chris@76 2906 'POSTERNAME' => un_htmlspecialchars($topicData[$row['id_topic']]['name']),
Chris@76 2907 'TOPICLINK' => $scripturl . '?topic=' . $row['id_topic'] . '.new;topicseen#new',
Chris@76 2908 'UNSUBSCRIBELINK' => $scripturl . '?action=notify;topic=' . $row['id_topic'] . '.0',
Chris@76 2909 );
Chris@76 2910
Chris@76 2911 $message_type = 'notification_reply';
Chris@76 2912 // Do they want the body of the message sent too?
Chris@76 2913 if (!empty($row['notify_send_body']) && empty($modSettings['disallow_sendBody']))
Chris@76 2914 {
Chris@76 2915 $message_type .= '_body';
Chris@76 2916 $replacements['BODY'] = $topicData[$row['id_topic']]['body'];
Chris@76 2917 }
Chris@76 2918 if (!empty($row['notify_regularity']))
Chris@76 2919 $message_type .= '_once';
Chris@76 2920
Chris@76 2921 // Send only if once is off or it's on and it hasn't been sent.
Chris@76 2922 if (empty($row['notify_regularity']) || (empty($row['sent']) && !$sent_this_time))
Chris@76 2923 {
Chris@76 2924 $emaildata = loadEmailTemplate($message_type, $replacements, $needed_language);
Chris@76 2925 sendmail($row['email_address'], $emaildata['subject'], $emaildata['body'], null, 'm' . $topicData[$row['id_topic']]['last_id']);
Chris@76 2926 $sent++;
Chris@76 2927 }
Chris@76 2928
Chris@76 2929 $sent_this_time = true;
Chris@76 2930 }
Chris@76 2931 }
Chris@76 2932 $smcFunc['db_free_result']($members);
Chris@76 2933
Chris@76 2934 if (isset($current_language) && $current_language != $user_info['language'])
Chris@76 2935 loadLanguage('Post');
Chris@76 2936
Chris@76 2937 // Sent!
Chris@76 2938 if (!empty($sent))
Chris@76 2939 $smcFunc['db_query']('', '
Chris@76 2940 UPDATE {db_prefix}log_notify
Chris@76 2941 SET sent = {int:is_sent}
Chris@76 2942 WHERE id_topic IN ({array_int:topic_list})
Chris@76 2943 AND id_member != {int:current_member}',
Chris@76 2944 array(
Chris@76 2945 'current_member' => $user_info['id'],
Chris@76 2946 'topic_list' => $topics,
Chris@76 2947 'is_sent' => 1,
Chris@76 2948 )
Chris@76 2949 );
Chris@76 2950 }
Chris@76 2951
Chris@76 2952 // Update the last message in a board, and its parents.
Chris@76 2953 function updateLastMessages($setboards, $id_msg = 0)
Chris@76 2954 {
Chris@76 2955 global $board_info, $board, $modSettings, $smcFunc;
Chris@76 2956
Chris@76 2957 // Please - let's be sane.
Chris@76 2958 if (empty($setboards))
Chris@76 2959 return false;
Chris@76 2960
Chris@76 2961 if (!is_array($setboards))
Chris@76 2962 $setboards = array($setboards);
Chris@76 2963
Chris@76 2964 // If we don't know the id_msg we need to find it.
Chris@76 2965 if (!$id_msg)
Chris@76 2966 {
Chris@76 2967 // Find the latest message on this board (highest id_msg.)
Chris@76 2968 $request = $smcFunc['db_query']('', '
Chris@76 2969 SELECT id_board, MAX(id_last_msg) AS id_msg
Chris@76 2970 FROM {db_prefix}topics
Chris@76 2971 WHERE id_board IN ({array_int:board_list})
Chris@76 2972 AND approved = {int:approved}
Chris@76 2973 GROUP BY id_board',
Chris@76 2974 array(
Chris@76 2975 'board_list' => $setboards,
Chris@76 2976 'approved' => 1,
Chris@76 2977 )
Chris@76 2978 );
Chris@76 2979 $lastMsg = array();
Chris@76 2980 while ($row = $smcFunc['db_fetch_assoc']($request))
Chris@76 2981 $lastMsg[$row['id_board']] = $row['id_msg'];
Chris@76 2982 $smcFunc['db_free_result']($request);
Chris@76 2983 }
Chris@76 2984 else
Chris@76 2985 {
Chris@76 2986 // Just to note - there should only be one board passed if we are doing this.
Chris@76 2987 foreach ($setboards as $id_board)
Chris@76 2988 $lastMsg[$id_board] = $id_msg;
Chris@76 2989 }
Chris@76 2990
Chris@76 2991 $parent_boards = array();
Chris@76 2992 // Keep track of last modified dates.
Chris@76 2993 $lastModified = $lastMsg;
Chris@76 2994 // Get all the child boards for the parents, if they have some...
Chris@76 2995 foreach ($setboards as $id_board)
Chris@76 2996 {
Chris@76 2997 if (!isset($lastMsg[$id_board]))
Chris@76 2998 {
Chris@76 2999 $lastMsg[$id_board] = 0;
Chris@76 3000 $lastModified[$id_board] = 0;
Chris@76 3001 }
Chris@76 3002
Chris@76 3003 if (!empty($board) && $id_board == $board)
Chris@76 3004 $parents = $board_info['parent_boards'];
Chris@76 3005 else
Chris@76 3006 $parents = getBoardParents($id_board);
Chris@76 3007
Chris@76 3008 // Ignore any parents on the top child level.
Chris@76 3009 //!!! Why?
Chris@76 3010 foreach ($parents as $id => $parent)
Chris@76 3011 {
Chris@76 3012 if ($parent['level'] != 0)
Chris@76 3013 {
Chris@76 3014 // If we're already doing this one as a board, is this a higher last modified?
Chris@76 3015 if (isset($lastModified[$id]) && $lastModified[$id_board] > $lastModified[$id])
Chris@76 3016 $lastModified[$id] = $lastModified[$id_board];
Chris@76 3017 elseif (!isset($lastModified[$id]) && (!isset($parent_boards[$id]) || $parent_boards[$id] < $lastModified[$id_board]))
Chris@76 3018 $parent_boards[$id] = $lastModified[$id_board];
Chris@76 3019 }
Chris@76 3020 }
Chris@76 3021 }
Chris@76 3022
Chris@76 3023 // Note to help understand what is happening here. For parents we update the timestamp of the last message for determining
Chris@76 3024 // whether there are child boards which have not been read. For the boards themselves we update both this and id_last_msg.
Chris@76 3025
Chris@76 3026 $board_updates = array();
Chris@76 3027 $parent_updates = array();
Chris@76 3028 // Finally, to save on queries make the changes...
Chris@76 3029 foreach ($parent_boards as $id => $msg)
Chris@76 3030 {
Chris@76 3031 if (!isset($parent_updates[$msg]))
Chris@76 3032 $parent_updates[$msg] = array($id);
Chris@76 3033 else
Chris@76 3034 $parent_updates[$msg][] = $id;
Chris@76 3035 }
Chris@76 3036
Chris@76 3037 foreach ($lastMsg as $id => $msg)
Chris@76 3038 {
Chris@76 3039 if (!isset($board_updates[$msg . '-' . $lastModified[$id]]))
Chris@76 3040 $board_updates[$msg . '-' . $lastModified[$id]] = array(
Chris@76 3041 'id' => $msg,
Chris@76 3042 'updated' => $lastModified[$id],
Chris@76 3043 'boards' => array($id)
Chris@76 3044 );
Chris@76 3045
Chris@76 3046 else
Chris@76 3047 $board_updates[$msg . '-' . $lastModified[$id]]['boards'][] = $id;
Chris@76 3048 }
Chris@76 3049
Chris@76 3050 // Now commit the changes!
Chris@76 3051 foreach ($parent_updates as $id_msg => $boards)
Chris@76 3052 {
Chris@76 3053 $smcFunc['db_query']('', '
Chris@76 3054 UPDATE {db_prefix}boards
Chris@76 3055 SET id_msg_updated = {int:id_msg_updated}
Chris@76 3056 WHERE id_board IN ({array_int:board_list})
Chris@76 3057 AND id_msg_updated < {int:id_msg_updated}',
Chris@76 3058 array(
Chris@76 3059 'board_list' => $boards,
Chris@76 3060 'id_msg_updated' => $id_msg,
Chris@76 3061 )
Chris@76 3062 );
Chris@76 3063 }
Chris@76 3064 foreach ($board_updates as $board_data)
Chris@76 3065 {
Chris@76 3066 $smcFunc['db_query']('', '
Chris@76 3067 UPDATE {db_prefix}boards
Chris@76 3068 SET id_last_msg = {int:id_last_msg}, id_msg_updated = {int:id_msg_updated}
Chris@76 3069 WHERE id_board IN ({array_int:board_list})',
Chris@76 3070 array(
Chris@76 3071 'board_list' => $board_data['boards'],
Chris@76 3072 'id_last_msg' => $board_data['id'],
Chris@76 3073 'id_msg_updated' => $board_data['updated'],
Chris@76 3074 )
Chris@76 3075 );
Chris@76 3076 }
Chris@76 3077 }
Chris@76 3078
Chris@76 3079 // This simple function gets a list of all administrators and sends them an email to let them know a new member has joined.
Chris@77 3080 function adminNotify($type, $memberID, $member_name = null, $justify = null)
Chris@76 3081 {
Chris@76 3082 global $txt, $modSettings, $language, $scripturl, $user_info, $context, $smcFunc;
Chris@76 3083
Chris@76 3084 // If the setting isn't enabled then just exit.
Chris@76 3085 if (empty($modSettings['notify_new_registration']))
Chris@76 3086 return;
Chris@76 3087
Chris@77 3088 $member_email = null;
Chris@77 3089
Chris@76 3090 if ($member_name == null)
Chris@76 3091 {
Chris@76 3092 // Get the new user's name....
Chris@76 3093 $request = $smcFunc['db_query']('', '
Chris@77 3094 SELECT real_name, email_address
Chris@76 3095 FROM {db_prefix}members
Chris@76 3096 WHERE id_member = {int:id_member}
Chris@76 3097 LIMIT 1',
Chris@76 3098 array(
Chris@76 3099 'id_member' => $memberID,
Chris@76 3100 )
Chris@76 3101 );
Chris@77 3102 list ($member_name, $member_email) = $smcFunc['db_fetch_row']($request);
Chris@76 3103 $smcFunc['db_free_result']($request);
Chris@76 3104 }
Chris@76 3105
Chris@76 3106 $toNotify = array();
Chris@76 3107 $groups = array();
Chris@76 3108
Chris@76 3109 // All membergroups who can approve members.
Chris@76 3110 $request = $smcFunc['db_query']('', '
Chris@76 3111 SELECT id_group
Chris@76 3112 FROM {db_prefix}permissions
Chris@76 3113 WHERE permission = {string:moderate_forum}
Chris@76 3114 AND add_deny = {int:add_deny}
Chris@76 3115 AND id_group != {int:id_group}',
Chris@76 3116 array(
Chris@76 3117 'add_deny' => 1,
Chris@76 3118 'id_group' => 0,
Chris@76 3119 'moderate_forum' => 'moderate_forum',
Chris@76 3120 )
Chris@76 3121 );
Chris@76 3122 while ($row = $smcFunc['db_fetch_assoc']($request))
Chris@76 3123 $groups[] = $row['id_group'];
Chris@76 3124 $smcFunc['db_free_result']($request);
Chris@76 3125
Chris@76 3126 // Add administrators too...
Chris@76 3127 $groups[] = 1;
Chris@76 3128 $groups = array_unique($groups);
Chris@76 3129
Chris@76 3130 // Get a list of all members who have ability to approve accounts - these are the people who we inform.
Chris@76 3131 $request = $smcFunc['db_query']('', '
Chris@76 3132 SELECT id_member, lngfile, email_address
Chris@76 3133 FROM {db_prefix}members
Chris@76 3134 WHERE (id_group IN ({array_int:group_list}) OR FIND_IN_SET({raw:group_array_implode}, additional_groups) != 0)
Chris@76 3135 AND notify_types != {int:notify_types}
Chris@76 3136 ORDER BY lngfile',
Chris@76 3137 array(
Chris@76 3138 'group_list' => $groups,
Chris@76 3139 'notify_types' => 4,
Chris@76 3140 'group_array_implode' => implode(', additional_groups) != 0 OR FIND_IN_SET(', $groups),
Chris@76 3141 )
Chris@76 3142 );
Chris@76 3143 while ($row = $smcFunc['db_fetch_assoc']($request))
Chris@76 3144 {
Chris@76 3145 $replacements = array(
Chris@76 3146 'USERNAME' => $member_name,
Chris@77 3147 'USEREMAIL' => $member_email,
Chris@76 3148 'PROFILELINK' => $scripturl . '?action=profile;u=' . $memberID
Chris@76 3149 );
Chris@76 3150 $emailtype = 'admin_notify';
Chris@76 3151
Chris@76 3152 // If they need to be approved add more info...
Chris@76 3153 if ($type == 'approval')
Chris@76 3154 {
Chris@76 3155 $replacements['APPROVALLINK'] = $scripturl . '?action=admin;area=viewmembers;sa=browse;type=approve';
Chris@76 3156 $emailtype .= '_approval';
Chris@76 3157 }
Chris@76 3158
Chris@76 3159 $emaildata = loadEmailTemplate($emailtype, $replacements, empty($row['lngfile']) || empty($modSettings['userLanguage']) ? $language : $row['lngfile']);
Chris@76 3160
Chris@76 3161 // And do the actual sending...
Chris@77 3162 sendmail($row['email_address'], $emaildata['subject'], $emaildata['body'] . "\n\nJustification: $justify\n\n", null, null, false, 0);
Chris@76 3163 }
Chris@76 3164 $smcFunc['db_free_result']($request);
Chris@76 3165
Chris@76 3166 if (isset($current_language) && $current_language != $user_info['language'])
Chris@76 3167 loadLanguage('Login');
Chris@76 3168 }
Chris@76 3169
Chris@76 3170 function loadEmailTemplate($template, $replacements = array(), $lang = '', $loadLang = true)
Chris@76 3171 {
Chris@76 3172 global $txt, $mbname, $scripturl, $settings, $user_info;
Chris@76 3173
Chris@76 3174 // First things first, load up the email templates language file, if we need to.
Chris@76 3175 if ($loadLang)
Chris@76 3176 loadLanguage('EmailTemplates', $lang);
Chris@76 3177
Chris@76 3178 if (!isset($txt['emails'][$template]))
Chris@76 3179 fatal_lang_error('email_no_template', 'template', array($template));
Chris@76 3180
Chris@76 3181 $ret = array(
Chris@76 3182 'subject' => $txt['emails'][$template]['subject'],
Chris@76 3183 'body' => $txt['emails'][$template]['body'],
Chris@76 3184 );
Chris@76 3185
Chris@76 3186 // Add in the default replacements.
Chris@76 3187 $replacements += array(
Chris@76 3188 'FORUMNAME' => $mbname,
Chris@76 3189 'SCRIPTURL' => $scripturl,
Chris@76 3190 'THEMEURL' => $settings['theme_url'],
Chris@76 3191 'IMAGESURL' => $settings['images_url'],
Chris@76 3192 'DEFAULT_THEMEURL' => $settings['default_theme_url'],
Chris@76 3193 'REGARDS' => $txt['regards_team'],
Chris@76 3194 );
Chris@76 3195
Chris@76 3196 // Split the replacements up into two arrays, for use with str_replace
Chris@76 3197 $find = array();
Chris@76 3198 $replace = array();
Chris@76 3199
Chris@76 3200 foreach ($replacements as $f => $r)
Chris@76 3201 {
Chris@76 3202 $find[] = '{' . $f . '}';
Chris@76 3203 $replace[] = $r;
Chris@76 3204 }
Chris@76 3205
Chris@76 3206 // Do the variable replacements.
Chris@76 3207 $ret['subject'] = str_replace($find, $replace, $ret['subject']);
Chris@76 3208 $ret['body'] = str_replace($find, $replace, $ret['body']);
Chris@76 3209
Chris@76 3210 // Now deal with the {USER.variable} items.
Chris@76 3211 $ret['subject'] = preg_replace_callback('~{USER.([^}]+)}~', 'user_info_callback', $ret['subject']);
Chris@76 3212 $ret['body'] = preg_replace_callback('~{USER.([^}]+)}~', 'user_info_callback', $ret['body']);
Chris@76 3213
Chris@76 3214 // Finally return the email to the caller so they can send it out.
Chris@76 3215 return $ret;
Chris@76 3216 }
Chris@76 3217
Chris@76 3218 function user_info_callback($matches)
Chris@76 3219 {
Chris@76 3220 global $user_info;
Chris@76 3221 if (empty($matches[1]))
Chris@76 3222 return '';
Chris@76 3223
Chris@76 3224 $use_ref = true;
Chris@76 3225 $ref = &$user_info;
Chris@76 3226
Chris@76 3227 foreach (explode('.', $matches[1]) as $index)
Chris@76 3228 {
Chris@76 3229 if ($use_ref && isset($ref[$index]))
Chris@76 3230 $ref = &$ref[$index];
Chris@76 3231 else
Chris@76 3232 {
Chris@76 3233 $use_ref = false;
Chris@76 3234 break;
Chris@76 3235 }
Chris@76 3236 }
Chris@76 3237
Chris@76 3238 return $use_ref ? $ref : $matches[0];
Chris@76 3239 }
Chris@76 3240
Chris@77 3241 ?>