Performance increase for get_username_string() (Bug #37545 - Patch by BartVB)
[phpbb.git] / phpBB / includes / functions_content.php
blob1a3d548e9325ed4b4d6f5202c00731e7aae4d873
1 <?php
2 /**
4 * @package phpBB3
5 * @version $Id$
6 * @copyright (c) 2005 phpBB Group
7 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
9 */
11 /**
12 * @ignore
14 if (!defined('IN_PHPBB'))
16 exit;
19 /**
20 * gen_sort_selects()
21 * make_jumpbox()
22 * bump_topic_allowed()
23 * get_context()
24 * decode_message()
25 * strip_bbcode()
26 * generate_text_for_display()
27 * generate_text_for_storage()
28 * generate_text_for_edit()
29 * make_clickable_callback()
30 * make_clickable()
31 * censor_text()
32 * bbcode_nl2br()
33 * smiley_text()
34 * parse_attachments()
35 * extension_allowed()
36 * truncate_string()
37 * get_username_string()
38 * class bitfield
41 /**
42 * Generate sort selection fields
44 function gen_sort_selects(&$limit_days, &$sort_by_text, &$sort_days, &$sort_key, &$sort_dir, &$s_limit_days, &$s_sort_key, &$s_sort_dir, &$u_sort_param, $def_st = false, $def_sk = false, $def_sd = false)
46 global $user;
48 $sort_dir_text = array('a' => $user->lang['ASCENDING'], 'd' => $user->lang['DESCENDING']);
50 $sorts = array(
51 'st' => array(
52 'key' => 'sort_days',
53 'default' => $def_st,
54 'options' => $limit_days,
55 'output' => &$s_limit_days,
58 'sk' => array(
59 'key' => 'sort_key',
60 'default' => $def_sk,
61 'options' => $sort_by_text,
62 'output' => &$s_sort_key,
65 'sd' => array(
66 'key' => 'sort_dir',
67 'default' => $def_sd,
68 'options' => $sort_dir_text,
69 'output' => &$s_sort_dir,
72 $u_sort_param = '';
74 foreach ($sorts as $name => $sort_ary)
76 $key = $sort_ary['key'];
77 $selected = $$sort_ary['key'];
79 // Check if the key is selectable. If not, we reset to the default or first key found.
80 // This ensures the values are always valid. We also set $sort_dir/sort_key/etc. to the
81 // correct value, else the protection is void. ;)
82 if (!isset($sort_ary['options'][$selected]))
84 if ($sort_ary['default'] !== false)
86 $selected = $$key = $sort_ary['default'];
88 else
90 @reset($sort_ary['options']);
91 $selected = $$key = key($sort_ary['options']);
95 $sort_ary['output'] = '<select name="' . $name . '" id="' . $name . '">';
96 foreach ($sort_ary['options'] as $option => $text)
98 $sort_ary['output'] .= '<option value="' . $option . '"' . (($selected == $option) ? ' selected="selected"' : '') . '>' . $text . '</option>';
100 $sort_ary['output'] .= '</select>';
102 $u_sort_param .= ($selected !== $sort_ary['default']) ? ((strlen($u_sort_param)) ? '&amp;' : '') . "{$name}={$selected}" : '';
105 return;
109 * Generate Jumpbox
111 function make_jumpbox($action, $forum_id = false, $select_all = false, $acl_list = false, $force_display = false)
113 global $config, $auth, $template, $user, $db;
115 // We only return if the jumpbox is not forced to be displayed (in case it is needed for functionality)
116 if (!$config['load_jumpbox'] && $force_display === false)
118 return;
121 $sql = 'SELECT forum_id, forum_name, parent_id, forum_type, left_id, right_id
122 FROM ' . FORUMS_TABLE . '
123 ORDER BY left_id ASC';
124 $result = $db->sql_query($sql, 600);
126 $right = $padding = 0;
127 $padding_store = array('0' => 0);
128 $display_jumpbox = false;
129 $iteration = 0;
131 // Sometimes it could happen that forums will be displayed here not be displayed within the index page
132 // This is the result of forums not displayed at index, having list permissions and a parent of a forum with no permissions.
133 // If this happens, the padding could be "broken"
135 while ($row = $db->sql_fetchrow($result))
137 if ($row['left_id'] < $right)
139 $padding++;
140 $padding_store[$row['parent_id']] = $padding;
142 else if ($row['left_id'] > $right + 1)
144 // Ok, if the $padding_store for this parent is empty there is something wrong. For now we will skip over it.
145 // @todo digging deep to find out "how" this can happen.
146 $padding = (isset($padding_store[$row['parent_id']])) ? $padding_store[$row['parent_id']] : $padding;
149 $right = $row['right_id'];
151 if ($row['forum_type'] == FORUM_CAT && ($row['left_id'] + 1 == $row['right_id']))
153 // Non-postable forum with no subforums, don't display
154 continue;
157 if (!$auth->acl_get('f_list', $row['forum_id']))
159 // if the user does not have permissions to list this forum skip
160 continue;
163 if ($acl_list && !$auth->acl_gets($acl_list, $row['forum_id']))
165 continue;
168 if (!$display_jumpbox)
170 $template->assign_block_vars('jumpbox_forums', array(
171 'FORUM_ID' => ($select_all) ? 0 : -1,
172 'FORUM_NAME' => ($select_all) ? $user->lang['ALL_FORUMS'] : $user->lang['SELECT_FORUM'],
173 'S_FORUM_COUNT' => $iteration)
176 $iteration++;
177 $display_jumpbox = true;
180 $template->assign_block_vars('jumpbox_forums', array(
181 'FORUM_ID' => $row['forum_id'],
182 'FORUM_NAME' => $row['forum_name'],
183 'SELECTED' => ($row['forum_id'] == $forum_id) ? ' selected="selected"' : '',
184 'S_FORUM_COUNT' => $iteration,
185 'S_IS_CAT' => ($row['forum_type'] == FORUM_CAT) ? true : false,
186 'S_IS_LINK' => ($row['forum_type'] == FORUM_LINK) ? true : false,
187 'S_IS_POST' => ($row['forum_type'] == FORUM_POST) ? true : false)
190 for ($i = 0; $i < $padding; $i++)
192 $template->assign_block_vars('jumpbox_forums.level', array());
194 $iteration++;
196 $db->sql_freeresult($result);
197 unset($padding_store);
199 $template->assign_vars(array(
200 'S_DISPLAY_JUMPBOX' => $display_jumpbox,
201 'S_JUMPBOX_ACTION' => $action)
204 return;
208 * Bump Topic Check - used by posting and viewtopic
210 function bump_topic_allowed($forum_id, $topic_bumped, $last_post_time, $topic_poster, $last_topic_poster)
212 global $config, $auth, $user;
214 // Check permission and make sure the last post was not already bumped
215 if (!$auth->acl_get('f_bump', $forum_id) || $topic_bumped)
217 return false;
220 // Check bump time range, is the user really allowed to bump the topic at this time?
221 $bump_time = ($config['bump_type'] == 'm') ? $config['bump_interval'] * 60 : (($config['bump_type'] == 'h') ? $config['bump_interval'] * 3600 : $config['bump_interval'] * 86400);
223 // Check bump time
224 if ($last_post_time + $bump_time > time())
226 return false;
229 // Check bumper, only topic poster and last poster are allowed to bump
230 if ($topic_poster != $user->data['user_id'] && $last_topic_poster != $user->data['user_id'])
232 return false;
235 // A bump time of 0 will completely disable the bump feature... not intended but might be useful.
236 return $bump_time;
240 * Generates a text with approx. the specified length which contains the specified words and their context
242 * @param string $text The full text from which context shall be extracted
243 * @param string $words An array of words which should be contained in the result, has to be a valid part of a PCRE pattern (escape with preg_quote!)
244 * @param int $length The desired length of the resulting text, however the result might be shorter or longer than this value
246 * @return string Context of the specified words separated by "..."
248 function get_context($text, $words, $length = 400)
250 // first replace all whitespaces with single spaces
251 $text = preg_replace('/ +/', ' ', strtr($text, "\t\n\r\x0C ", ' '));
253 $word_indizes = array();
254 if (sizeof($words))
256 $match = '';
257 // find the starting indizes of all words
258 foreach ($words as $word)
260 if ($word)
262 if (preg_match('#(?:[^\w]|^)(' . $word . ')(?:[^\w]|$)#i', $text, $match))
264 $pos = utf8_strpos($text, $match[1]);
265 if ($pos !== false)
267 $word_indizes[] = $pos;
272 unset($match);
274 if (sizeof($word_indizes))
276 $word_indizes = array_unique($word_indizes);
277 sort($word_indizes);
279 $wordnum = sizeof($word_indizes);
280 // number of characters on the right and left side of each word
281 $sequence_length = (int) ($length / (2 * $wordnum)) - 2;
282 $final_text = '';
283 $word = $j = 0;
284 $final_text_index = -1;
286 // cycle through every character in the original text
287 for ($i = $word_indizes[$word], $n = utf8_strlen($text); $i < $n; $i++)
289 // if the current position is the start of one of the words then append $sequence_length characters to the final text
290 if (isset($word_indizes[$word]) && ($i == $word_indizes[$word]))
292 if ($final_text_index < $i - $sequence_length - 1)
294 $final_text .= '... ' . preg_replace('#^([^ ]*)#', '', utf8_substr($text, $i - $sequence_length, $sequence_length));
296 else
298 // if the final text is already nearer to the current word than $sequence_length we only append the text
299 // from its current index on and distribute the unused length to all other sequenes
300 $sequence_length += (int) (($final_text_index - $i + $sequence_length + 1) / (2 * $wordnum));
301 $final_text .= utf8_substr($text, $final_text_index + 1, $i - $final_text_index - 1);
303 $final_text_index = $i - 1;
305 // add the following characters to the final text (see below)
306 $word++;
307 $j = 1;
310 if ($j > 0)
312 // add the character to the final text and increment the sequence counter
313 $final_text .= utf8_substr($text, $i, 1);
314 $final_text_index++;
315 $j++;
317 // if this is a whitespace then check whether we are done with this sequence
318 if (utf8_substr($text, $i, 1) == ' ')
320 // only check whether we have to exit the context generation completely if we haven't already reached the end anyway
321 if ($i + 4 < $n)
323 if (($j > $sequence_length && $word >= $wordnum) || utf8_strlen($final_text) > $length)
325 $final_text .= ' ...';
326 break;
329 else
331 // make sure the text really reaches the end
332 $j -= 4;
335 // stop context generation and wait for the next word
336 if ($j > $sequence_length)
338 $j = 0;
343 return $final_text;
347 if (!sizeof($words) || !sizeof($word_indizes))
349 return (utf8_strlen($text) >= $length + 3) ? utf8_substr($text, 0, $length) . '...' : $text;
354 * Decode text whereby text is coming from the db and expected to be pre-parsed content
355 * We are placing this outside of the message parser because we are often in need of it...
357 function decode_message(&$message, $bbcode_uid = '')
359 global $config;
361 if ($bbcode_uid)
363 $match = array('<br />', "[/*:m:$bbcode_uid]", ":u:$bbcode_uid", ":o:$bbcode_uid", ":$bbcode_uid");
364 $replace = array("\n", '', '', '', '');
366 else
368 $match = array('<br />');
369 $replace = array("\n");
372 $message = str_replace($match, $replace, $message);
374 $match = get_preg_expression('bbcode_htm');
375 $replace = array('\1', '\1', '\2', '\1', '', '');
377 $message = preg_replace($match, $replace, $message);
381 * Strips all bbcode from a text and returns the plain content
383 function strip_bbcode(&$text, $uid = '')
385 if (!$uid)
387 $uid = '[0-9a-z]{5,}';
390 $text = preg_replace("#\[\/?[a-z0-9\*\+\-]+(?:=(?:&quot;.*&quot;|[^\]]*))?(?::[a-z])?(\:$uid)\]#", ' ', $text);
392 $match = get_preg_expression('bbcode_htm');
393 $replace = array('\1', '\1', '\2', '\1', '', '');
395 $text = preg_replace($match, $replace, $text);
399 * For display of custom parsed text on user-facing pages
400 * Expects $text to be the value directly from the database (stored value)
402 function generate_text_for_display($text, $uid, $bitfield, $flags)
404 static $bbcode;
406 if (!$text)
408 return '';
411 $text = censor_text($text);
413 // Parse bbcode if bbcode uid stored and bbcode enabled
414 if ($uid && ($flags & OPTION_FLAG_BBCODE))
416 if (!class_exists('bbcode'))
418 include(PHPBB_ROOT_PATH . 'includes/bbcode.' . PHP_EXT);
421 if (empty($bbcode))
423 $bbcode = new bbcode($bitfield);
425 else
427 $bbcode->bbcode($bitfield);
430 $bbcode->bbcode_second_pass($text, $uid);
433 $text = bbcode_nl2br($text);
434 $text = smiley_text($text, !($flags & OPTION_FLAG_SMILIES));
436 return $text;
440 * For parsing custom parsed text to be stored within the database.
441 * This function additionally returns the uid and bitfield that needs to be stored.
442 * Expects $text to be the value directly from request_var() and in it's non-parsed form
444 function generate_text_for_storage(&$text, &$uid, &$bitfield, &$flags, $allow_bbcode = false, $allow_urls = false, $allow_smilies = false)
446 $uid = $bitfield = '';
447 $flags = (($allow_bbcode) ? OPTION_FLAG_BBCODE : 0) + (($allow_smilies) ? OPTION_FLAG_SMILIES : 0) + (($allow_urls) ? OPTION_FLAG_LINKS : 0);
449 if (!$text)
451 return;
454 if (!class_exists('parse_message'))
456 include(PHPBB_ROOT_PATH . 'includes/message_parser.' . PHP_EXT);
459 $message_parser = new parse_message($text);
460 $message_parser->parse($allow_bbcode, $allow_urls, $allow_smilies);
462 $text = $message_parser->message;
463 $uid = $message_parser->bbcode_uid;
465 // If the bbcode_bitfield is empty, there is no need for the uid to be stored.
466 if (!$message_parser->bbcode_bitfield)
468 $uid = '';
471 $bitfield = $message_parser->bbcode_bitfield;
473 return;
477 * For decoding custom parsed text for edits as well as extracting the flags
478 * Expects $text to be the value directly from the database (pre-parsed content)
480 function generate_text_for_edit($text, $uid, $flags)
482 decode_message($text, $uid);
484 return array(
485 'allow_bbcode' => ($flags & OPTION_FLAG_BBCODE) ? 1 : 0,
486 'allow_smilies' => ($flags & OPTION_FLAG_SMILIES) ? 1 : 0,
487 'allow_urls' => ($flags & OPTION_FLAG_LINKS) ? 1 : 0,
488 'text' => $text
493 * A subroutine of make_clickable used with preg_replace
494 * It places correct HTML around an url, shortens the displayed text
495 * and makes sure no entities are inside URLs
497 function make_clickable_callback($type, $whitespace, $url, $relative_url, $class)
499 $orig_url = $url;
500 $orig_relative = $relative_url;
501 $append = '';
502 $url = htmlspecialchars_decode($url);
503 $relative_url = htmlspecialchars_decode($relative_url);
505 // make sure no HTML entities were matched
506 $chars = array('<', '>', '"');
507 $split = false;
509 foreach ($chars as $char)
511 $next_split = strpos($url, $char);
512 if ($next_split !== false)
514 $split = ($split !== false) ? min($split, $next_split) : $next_split;
518 if ($split !== false)
520 // an HTML entity was found, so the URL has to end before it
521 $append = substr($url, $split) . $relative_url;
522 $url = substr($url, 0, $split);
523 $relative_url = '';
525 else if ($relative_url)
527 // same for $relative_url
528 $split = false;
529 foreach ($chars as $char)
531 $next_split = strpos($relative_url, $char);
532 if ($next_split !== false)
534 $split = ($split !== false) ? min($split, $next_split) : $next_split;
538 if ($split !== false)
540 $append = substr($relative_url, $split);
541 $relative_url = substr($relative_url, 0, $split);
545 // if the last character of the url is a punctuation mark, exclude it from the url
546 $last_char = ($relative_url) ? $relative_url[strlen($relative_url) - 1] : $url[strlen($url) - 1];
548 switch ($last_char)
550 case '.':
551 case '?':
552 case '!':
553 case ':':
554 case ',':
555 $append = $last_char;
556 if ($relative_url)
558 $relative_url = substr($relative_url, 0, -1);
560 else
562 $url = substr($url, 0, -1);
564 break;
566 // set last_char to empty here, so the variable can be used later to
567 // check whether a character was removed
568 default:
569 $last_char = '';
570 break;
573 $short_url = (strlen($url) > 55) ? substr($url, 0, 39) . ' ... ' . substr($url, -10) : $url;
575 switch ($type)
577 case MAGIC_URL_LOCAL:
578 $tag = 'l';
579 $relative_url = preg_replace('/[&?]sid=[0-9a-f]{32}$/', '', preg_replace('/([&?])sid=[0-9a-f]{32}&/', '$1', $relative_url));
580 $url = $url . '/' . $relative_url;
581 $text = $relative_url;
583 // this url goes to http://domain.tld/path/to/board/ which
584 // would result in an empty link if treated as local so
585 // don't touch it and let MAGIC_URL_FULL take care of it.
586 if (!$relative_url)
588 return $whitespace . $orig_url . '/' . $orig_relative; // slash is taken away by relative url pattern
590 break;
592 case MAGIC_URL_FULL:
593 $tag = 'm';
594 $text = $short_url;
595 break;
597 case MAGIC_URL_WWW:
598 $tag = 'w';
599 $url = 'http://' . $url;
600 $text = $short_url;
601 break;
603 case MAGIC_URL_EMAIL:
604 $tag = 'e';
605 $text = $short_url;
606 $url = 'mailto:' . $url;
607 break;
610 $url = htmlspecialchars($url);
611 $text = htmlspecialchars($text);
612 $append = htmlspecialchars($append);
614 $html = "$whitespace<!-- $tag --><a$class href=\"$url\">$text</a><!-- $tag -->$append";
616 return $html;
620 * make_clickable function
622 * Replace magic urls of form http://xxx.xxx., www.xxx. and xxx@xxx.xxx.
623 * Cuts down displayed size of link if over 50 chars, turns absolute links
624 * into relative versions when the server/script path matches the link
626 function make_clickable($text, $server_url = false, $class = 'postlink')
628 if ($server_url === false)
630 $server_url = generate_board_url();
633 static $magic_url_match;
634 static $magic_url_replace;
635 static $static_class;
637 if (!is_array($magic_url_match) || $static_class != $class)
639 $static_class = $class;
640 $class = ($static_class) ? ' class="' . $static_class . '"' : '';
641 $local_class = ($static_class) ? ' class="' . $static_class . '-local"' : '';
643 $magic_url_match = $magic_url_replace = array();
644 // Be sure to not let the matches cross over. ;)
646 // relative urls for this board
647 $magic_url_match[] = '#(^|[\n\t (>.])(' . preg_quote($server_url, '#') . ')/(' . get_preg_expression('relative_url_inline') . ')#ie';
648 $magic_url_replace[] = "make_clickable_callback(MAGIC_URL_LOCAL, '\$1', '\$2', '\$3', '$local_class')";
650 // matches a xxxx://aaaaa.bbb.cccc. ...
651 $magic_url_match[] = '#(^|[\n\t (>.])(' . get_preg_expression('url_inline') . ')#ie';
652 $magic_url_replace[] = "make_clickable_callback(MAGIC_URL_FULL, '\$1', '\$2', '', '$class')";
654 // matches a "www.xxxx.yyyy[/zzzz]" kinda lazy URL thing
655 $magic_url_match[] = '#(^|[\n\t (>])(' . get_preg_expression('www_url_inline') . ')#ie';
656 $magic_url_replace[] = "make_clickable_callback(MAGIC_URL_WWW, '\$1', '\$2', '', '$class')";
658 // matches an email@domain type address at the start of a line, or after a space or after what might be a BBCode.
659 $magic_url_match[] = '/(^|[\n\t (>])(' . get_preg_expression('email') . ')/ie';
660 $magic_url_replace[] = "make_clickable_callback(MAGIC_URL_EMAIL, '\$1', '\$2', '', '')";
663 return preg_replace($magic_url_match, $magic_url_replace, $text);
667 * Censoring
669 function censor_text($text)
671 static $censors;
673 // We moved the word censor checks in here because we call this function quite often - and then only need to do the check once
674 if (!isset($censors) || !is_array($censors))
676 global $config, $user, $auth, $cache;
678 // We check here if the user is having viewing censors disabled (and also allowed to do so).
679 if (!$user->optionget('viewcensors') && $config['allow_nocensors'] && $auth->acl_get('u_chgcensors'))
681 $censors = array();
683 else
685 $censors = cache::obtain_word_list();
689 if (sizeof($censors))
691 return preg_replace($censors['match'], $censors['replace'], $text);
694 return $text;
698 * custom version of nl2br which takes custom BBCodes into account
700 function bbcode_nl2br($text)
702 // custom BBCodes might contain carriage returns so they
703 // are not converted into <br /> so now revert that
704 $text = str_replace(array("\n", "\r"), array('<br />', "\n"), $text);
705 return $text;
709 * Smiley processing
711 function smiley_text($text, $force_option = false)
713 global $config, $user;
715 if ($force_option || !$config['allow_smilies'] || !$user->optionget('viewsmilies'))
717 return preg_replace('#<!\-\- s(.*?) \-\-><img src="\{SMILIES_PATH\}\/.*? \/><!\-\- s\1 \-\->#', '\1', $text);
719 else
721 return preg_replace('#<!\-\- s(.*?) \-\-><img src="\{SMILIES_PATH\}\/(.*?) \/><!\-\- s\1 \-\->#', '<img src="' . PHPBB_ROOT_PATH . $config['smilies_path'] . '/\2 />', $text);
726 * General attachment parsing
728 * @param mixed $forum_id The forum id the attachments are displayed in (false if in private message)
729 * @param string &$message The post/private message
730 * @param array &$attachments The attachments to parse for (inline) display. The attachments array will hold templated data after parsing.
731 * @param array &$update_count The attachment counts to be updated - will be filled
732 * @param bool $preview If set to true the attachments are parsed for preview. Within preview mode the comments are fetched from the given $attachments array and not fetched from the database.
734 function parse_attachments($forum_id, &$message, &$attachments, &$update_count, $preview = false)
736 if (!sizeof($attachments))
738 return;
741 global $template, $cache, $user;
742 global $extensions, $config;
745 $compiled_attachments = array();
747 // @todo: do we really need this check?
748 if (!isset($template->filename['attachment_tpl']))
750 $template->set_filenames(array(
751 'attachment_tpl' => 'attachment.html')
755 if (empty($extensions) || !is_array($extensions))
757 $extensions = cache::obtain_attach_extensions($forum_id);
760 // Look for missing attachment information...
761 $attach_ids = array();
762 foreach ($attachments as $pos => $attachment)
764 // If is_orphan is set, we need to retrieve the attachments again...
765 if (!isset($attachment['extension']) && !isset($attachment['physical_filename']))
767 $attach_ids[(int) $attachment['attach_id']] = $pos;
771 // Grab attachments (security precaution)
772 if (sizeof($attach_ids))
774 global $db;
776 $new_attachment_data = array();
778 $sql = 'SELECT *
779 FROM ' . ATTACHMENTS_TABLE . '
780 WHERE ' . $db->sql_in_set('attach_id', array_keys($attach_ids));
781 $result = $db->sql_query($sql);
783 while ($row = $db->sql_fetchrow($result))
785 if (!isset($attach_ids[$row['attach_id']]))
787 continue;
790 // If we preview attachments we will set some retrieved values here
791 if ($preview)
793 $row['attach_comment'] = $attachments[$attach_ids[$row['attach_id']]]['attach_comment'];
796 $new_attachment_data[$attach_ids[$row['attach_id']]] = $row;
798 $db->sql_freeresult($result);
800 $attachments = $new_attachment_data;
801 unset($new_attachment_data);
804 // Sort correctly
805 if ($config['display_order'])
807 // Ascending sort
808 krsort($attachments);
810 else
812 // Descending sort
813 ksort($attachments);
816 foreach ($attachments as $attachment)
818 if (!sizeof($attachment))
820 continue;
823 // We need to reset/empty the _file block var, because this function might be called more than once
824 $template->destroy_block_vars('_file');
826 $block_array = array();
828 // Some basics...
829 $attachment['extension'] = strtolower(trim($attachment['extension']));
830 $filename = PHPBB_ROOT_PATH . $config['upload_path'] . '/' . basename($attachment['physical_filename']);
831 $thumbnail_filename = PHPBB_ROOT_PATH . $config['upload_path'] . '/thumb_' . basename($attachment['physical_filename']);
833 $upload_icon = '';
835 if (isset($extensions[$attachment['extension']]))
837 if ($user->img('icon_topic_attach', '') && !$extensions[$attachment['extension']]['upload_icon'])
839 $upload_icon = $user->img('icon_topic_attach', '');
841 else if ($extensions[$attachment['extension']]['upload_icon'])
843 $upload_icon = '<img src="' . PHPBB_ROOT_PATH . $config['upload_icons_path'] . '/' . trim($extensions[$attachment['extension']]['upload_icon']) . '" alt="" />';
847 $filesize = $attachment['filesize'];
848 $size_lang = ($filesize >= 1048576) ? $user->lang['MIB'] : (($filesize >= 1024) ? $user->lang['KIB'] : $user->lang['BYTES']);
849 $filesize = get_formatted_filesize($filesize, false);
851 $comment = bbcode_nl2br(censor_text($attachment['attach_comment']));
853 $block_array += array(
854 'UPLOAD_ICON' => $upload_icon,
855 'FILESIZE' => $filesize,
856 'SIZE_LANG' => $size_lang,
857 'DOWNLOAD_NAME' => basename($attachment['real_filename']),
858 'COMMENT' => $comment,
861 $denied = false;
863 if (!extension_allowed($forum_id, $attachment['extension'], $extensions))
865 $denied = true;
867 $block_array += array(
868 'S_DENIED' => true,
869 'DENIED_MESSAGE' => sprintf($user->lang['EXTENSION_DISABLED_AFTER_POSTING'], $attachment['extension'])
873 if (!$denied)
875 $l_downloaded_viewed = $download_link = '';
876 $display_cat = $extensions[$attachment['extension']]['display_cat'];
878 if ($display_cat == ATTACHMENT_CATEGORY_IMAGE)
880 if ($attachment['thumbnail'])
882 $display_cat = ATTACHMENT_CATEGORY_THUMB;
884 else
886 if ($config['img_display_inlined'])
888 if ($config['img_link_width'] || $config['img_link_height'])
890 $dimension = @getimagesize($filename);
892 // If the dimensions could not be determined or the image being 0x0 we display it as a link for safety purposes
893 if ($dimension === false || empty($dimension[0]) || empty($dimension[1]))
895 $display_cat = ATTACHMENT_CATEGORY_NONE;
897 else
899 $display_cat = ($dimension[0] <= $config['img_link_width'] && $dimension[1] <= $config['img_link_height']) ? ATTACHMENT_CATEGORY_IMAGE : ATTACHMENT_CATEGORY_NONE;
903 else
905 $display_cat = ATTACHMENT_CATEGORY_NONE;
910 // Make some descisions based on user options being set.
911 if (($display_cat == ATTACHMENT_CATEGORY_IMAGE || $display_cat == ATTACHMENT_CATEGORY_THUMB) && !$user->optionget('viewimg'))
913 $display_cat = ATTACHMENT_CATEGORY_NONE;
916 if ($display_cat == ATTACHMENT_CATEGORY_FLASH && !$user->optionget('viewflash'))
918 $display_cat = ATTACHMENT_CATEGORY_NONE;
921 $download_link = append_sid('download/file', 'id=' . $attachment['attach_id']);
923 switch ($display_cat)
925 // Images
926 case ATTACHMENT_CATEGORY_IMAGE:
927 $l_downloaded_viewed = 'VIEWED_COUNT';
928 $inline_link = append_sid('download/file', 'id=' . $attachment['attach_id']);
929 $download_link .= '&amp;mode=view';
931 $block_array += array(
932 'S_IMAGE' => true,
933 'U_INLINE_LINK' => $inline_link,
936 $update_count[] = $attachment['attach_id'];
937 break;
939 // Images, but display Thumbnail
940 case ATTACHMENT_CATEGORY_THUMB:
941 $l_downloaded_viewed = 'VIEWED_COUNT';
942 $thumbnail_link = append_sid('download/file', 'id=' . $attachment['attach_id'] . '&amp;t=1');
943 $download_link .= '&amp;mode=view';
945 $block_array += array(
946 'S_THUMBNAIL' => true,
947 'THUMB_IMAGE' => $thumbnail_link,
949 break;
951 // Windows Media Streams
952 case ATTACHMENT_CATEGORY_WM:
953 $l_downloaded_viewed = 'VIEWED_COUNT';
955 // Giving the filename directly because within the wm object all variables are in local context making it impossible
956 // to validate against a valid session (all params can differ)
957 // $download_link = $filename;
959 $block_array += array(
960 'U_FORUM' => generate_board_url(),
961 'ATTACH_ID' => $attachment['attach_id'],
962 'S_WM_FILE' => true,
965 // Viewed/Heared File ... update the download count
966 $update_count[] = $attachment['attach_id'];
967 break;
969 // Real Media Streams
970 case ATTACHMENT_CATEGORY_RM:
971 case ATTACHMENT_CATEGORY_QUICKTIME:
972 $l_downloaded_viewed = 'VIEWED_COUNT';
974 $block_array += array(
975 'S_RM_FILE' => ($display_cat == ATTACHMENT_CATEGORY_RM) ? true : false,
976 'S_QUICKTIME_FILE' => ($display_cat == ATTACHMENT_CATEGORY_QUICKTIME) ? true : false,
977 'U_FORUM' => generate_board_url(),
978 'ATTACH_ID' => $attachment['attach_id'],
981 // Viewed/Heared File ... update the download count
982 $update_count[] = $attachment['attach_id'];
983 break;
985 // Macromedia Flash Files
986 case ATTACHMENT_CATEGORY_FLASH:
987 list($width, $height) = @getimagesize($filename);
989 $l_downloaded_viewed = 'VIEWED_COUNT';
991 $block_array += array(
992 'S_FLASH_FILE' => true,
993 'WIDTH' => $width,
994 'HEIGHT' => $height,
997 // Viewed/Heared File ... update the download count
998 $update_count[] = $attachment['attach_id'];
999 break;
1001 default:
1002 $l_downloaded_viewed = 'DOWNLOAD_COUNT';
1004 $block_array += array(
1005 'S_FILE' => true,
1007 break;
1010 $l_download_count = (!isset($attachment['download_count']) || $attachment['download_count'] == 0) ? $user->lang[$l_downloaded_viewed . '_NONE'] : (($attachment['download_count'] == 1) ? sprintf($user->lang[$l_downloaded_viewed], $attachment['download_count']) : sprintf($user->lang[$l_downloaded_viewed . 'S'], $attachment['download_count']));
1012 $block_array += array(
1013 'U_DOWNLOAD_LINK' => $download_link,
1014 'L_DOWNLOAD_COUNT' => $l_download_count
1018 $template->assign_block_vars('_file', $block_array);
1020 $compiled_attachments[] = $template->assign_display('attachment_tpl');
1023 $attachments = $compiled_attachments;
1024 unset($compiled_attachments);
1026 $tpl_size = sizeof($attachments);
1028 $unset_tpl = array();
1030 preg_match_all('#<!\-\- ia([0-9]+) \-\->(.*?)<!\-\- ia\1 \-\->#', $message, $matches, PREG_PATTERN_ORDER);
1032 $replace = array();
1033 foreach ($matches[0] as $num => $capture)
1035 // Flip index if we are displaying the reverse way
1036 $index = ($config['display_order']) ? ($tpl_size-($matches[1][$num] + 1)) : $matches[1][$num];
1038 $replace['from'][] = $matches[0][$num];
1039 $replace['to'][] = (isset($attachments[$index])) ? $attachments[$index] : sprintf($user->lang['MISSING_INLINE_ATTACHMENT'], $matches[2][array_search($index, $matches[1])]);
1041 $unset_tpl[] = $index;
1044 if (isset($replace['from']))
1046 $message = str_replace($replace['from'], $replace['to'], $message);
1049 $unset_tpl = array_unique($unset_tpl);
1051 // Needed to let not display the inlined attachments at the end of the post again
1052 foreach ($unset_tpl as $index)
1054 unset($attachments[$index]);
1059 * Check if extension is allowed to be posted.
1061 * @param mixed $forum_id The forum id to check or false if private message
1062 * @param string $extension The extension to check, for example zip.
1063 * @param array &$extensions The extension array holding the information from the cache (will be obtained if empty)
1065 * @return bool False if the extension is not allowed to be posted, else true.
1067 function extension_allowed($forum_id, $extension, &$extensions)
1069 if (empty($extensions))
1071 global $cache;
1072 $extensions = cache::obtain_attach_extensions($forum_id);
1075 return (!isset($extensions['_allowed_'][$extension])) ? false : true;
1079 * Truncates string while retaining special characters if going over the max length
1080 * The default max length is 60 at the moment
1081 * The maximum storage length is there to fit the string within the given length. The string may be further truncated due to html entities.
1082 * For example: string given is 'a "quote"' (length: 9), would be a stored as 'a &quot;quote&quot;' (length: 19)
1084 * @param string $string The text to truncate to the given length. String is specialchared.
1085 * @param int $max_length Maximum length of string (multibyte character count as 1 char / Html entity count as 1 char)
1086 * @param int $max_store_length Maximum character length of string (multibyte character count as 1 char / Html entity count as entity chars).
1087 * @param bool $allow_reply Allow Re: in front of string
1088 * @param string $append String to be appended
1090 function truncate_string($string, $max_length = 60, $max_store_length = 255, $allow_reply = true, $append = '')
1092 $chars = array();
1094 $strip_reply = false;
1095 $stripped = false;
1096 if ($allow_reply && strpos($string, 'Re: ') === 0)
1098 $strip_reply = true;
1099 $string = substr($string, 4);
1102 $_chars = utf8_str_split(htmlspecialchars_decode($string));
1103 $chars = array_map('utf8_htmlspecialchars', $_chars);
1105 // Now check the length ;)
1106 if (sizeof($chars) > $max_length)
1108 // Cut off the last elements from the array
1109 $string = implode('', array_slice($chars, 0, $max_length - utf8_strlen($append)));
1110 $stripped = true;
1113 // Due to specialchars, we may not be able to store the string...
1114 if (utf8_strlen($string) > $max_store_length)
1116 // let's split again, we do not want half-baked strings where entities are split
1117 $_chars = utf8_str_split(htmlspecialchars_decode($string));
1118 $chars = array_map('utf8_htmlspecialchars', $_chars);
1122 array_pop($chars);
1123 $string = implode('', $chars);
1125 while (utf8_strlen($string) > $max_store_length || !sizeof($chars));
1128 if ($strip_reply)
1130 $string = 'Re: ' . $string;
1133 if ($append != '' && $stripped)
1135 $string = $string . $append;
1138 return $string;
1142 * Get username details for placing into templates.
1143 * This function caches all modes on first call, except for no_profile - determined by $user_id/$guest_username combination.
1145 * @param string $mode Can be profile (for getting an url to the profile), username (for obtaining the username), colour (for obtaining the user colour), full (for obtaining a html string representing a coloured link to the users profile) or no_profile (the same as full but forcing no profile link)
1146 * @param int $user_id The users id
1147 * @param string $username The users name
1148 * @param string $username_colour The users colour
1149 * @param string $guest_username optional parameter to specify the guest username. It will be used in favor of the GUEST language variable then.
1150 * @param string $custom_profile_url optional parameter to specify a profile url. The user id get appended to this url as &amp;u={user_id}
1152 * @return string A string consisting of what is wanted based on $mode.
1153 * @author BartVB, Acyd Burn
1155 function get_username_string($mode, $user_id, $username, $username_colour = '', $guest_username = false, $custom_profile_url = false)
1157 static $_profile_cache;
1158 static $_base_profile_url;
1160 $cache_key = $user_id . (string) $guest_username;
1162 // If the get_username_string() function had been executed once with an (to us) unkown mode, all modes are pre-filled and we can just grab it.
1163 if (isset($_profile_cache[$cache_key][$mode]))
1165 // If the mode is 'no_profile', we simply construct the TPL code due to calls to this mode being very very rare
1166 if ($mode == 'no_profile')
1168 $tpl = (!$_profile_cache[$cache_key][$mode]['colour']) ? '{USERNAME}' : '<span style="color: {USERNAME_COLOUR};" class="username-coloured">{USERNAME}</span>';
1169 return str_replace(array('{USERNAME_COLOUR}', '{USERNAME}'), array($_profile_cache[$cache_key][$mode]['colour'], $_profile_cache[$cache_key][$mode]['username']), $tpl);
1172 return $_profile_cache[$cache_key][$mode];
1175 global $user, $auth;
1177 $username_colour = ($username_colour) ? '#' . $username_colour : '';
1179 if ($guest_username === false)
1181 $username = ($username) ? $username : $user->lang['GUEST'];
1183 else
1185 $username = ($user_id && $user_id != ANONYMOUS) ? $username : ((!empty($guest_username)) ? $guest_username : $user->lang['GUEST']);
1188 // Build cache for all modes
1189 $_profile_cache[$cache_key]['colour'] = $username_colour;
1190 $_profile_cache[$cache_key]['username'] = $username;
1191 $_profile_cache[$cache_key]['no_profile'] = true;
1193 // Profile url - only show if not anonymous and permission to view profile if registered user
1194 // For anonymous the link leads to a login page.
1195 if ($user_id && $user_id != ANONYMOUS && ($user->data['user_id'] == ANONYMOUS || $auth->acl_get('u_viewprofile')))
1197 if (empty($_base_profile_url))
1199 $_base_profile_url = append_sid('memberlist', 'mode=viewprofile&amp;u={USER_ID}');
1202 $profile_url = ($custom_profile_url !== false) ? $custom_profile_url . '&amp;u=' . (int) $user_id : str_replace('={USER_ID}', '=' . (int) $user_id, $_base_profile_url);
1203 $tpl = (!$username_colour) ? '<a href="{PROFILE_URL}">{USERNAME}</a>' : '<a href="{PROFILE_URL}" style="color: {USERNAME_COLOUR};" class="username-coloured">{USERNAME}</a>';
1204 $_profile_cache[$cache_key]['full'] = str_replace(array('{PROFILE_URL}', '{USERNAME_COLOUR}', '{USERNAME}'), array($profile_url, $username_colour, $username), $tpl);
1206 else
1208 $tpl = (!$username_colour) ? '{USERNAME}' : '<span style="color: {USERNAME_COLOUR};" class="username-coloured">{USERNAME}</span>';
1209 $_profile_cache[$cache_key]['full'] = str_replace(array('{USERNAME_COLOUR}', '{USERNAME}'), array($username_colour, $username), $tpl);
1210 $profile_url = '';
1213 // Use the profile url from above
1214 $_profile_cache[$cache_key]['profile'] = $profile_url;
1216 // If - by any chance - no_profile is called before any other mode, we need to do the calculation here
1217 if ($mode == 'no_profile')
1219 $tpl = (!$_profile_cache[$cache_key]['colour']) ? '{USERNAME}' : '<span style="color: {USERNAME_COLOUR};" class="username-coloured">{USERNAME}</span>';
1220 return str_replace(array('{USERNAME_COLOUR}', '{USERNAME}'), array($_profile_cache[$cache_key]['colour'], $_profile_cache[$cache_key]['username']), $tpl);
1223 return $_profile_cache[$cache_key][$mode];
1227 * @package phpBB3
1229 class bitfield
1231 var $data;
1233 function __construct($bitfield = '')
1235 $this->data = base64_decode($bitfield);
1240 function get($n)
1242 // Get the ($n / 8)th char
1243 $byte = $n >> 3;
1245 if (strlen($this->data) >= $byte + 1)
1247 $c = $this->data[$byte];
1249 // Lookup the ($n % 8)th bit of the byte
1250 $bit = 7 - ($n & 7);
1251 return (bool) (ord($c) & (1 << $bit));
1253 else
1255 return false;
1259 function set($n)
1261 $byte = $n >> 3;
1262 $bit = 7 - ($n & 7);
1264 if (strlen($this->data) >= $byte + 1)
1266 $this->data[$byte] = $this->data[$byte] | chr(1 << $bit);
1268 else
1270 $this->data .= str_repeat("\0", $byte - strlen($this->data));
1271 $this->data .= chr(1 << $bit);
1275 function clear($n)
1277 $byte = $n >> 3;
1279 if (strlen($this->data) >= $byte + 1)
1281 $bit = 7 - ($n & 7);
1282 $this->data[$byte] = $this->data[$byte] &~ chr(1 << $bit);
1286 function get_blob()
1288 return $this->data;
1291 function get_base64()
1293 return base64_encode($this->data);
1296 function get_bin()
1298 $bin = '';
1299 $len = strlen($this->data);
1301 for ($i = 0; $i < $len; ++$i)
1303 $bin .= str_pad(decbin(ord($this->data[$i])), 8, '0', STR_PAD_LEFT);
1306 return $bin;
1309 function get_all_set()
1311 return array_keys(array_filter(str_split($this->get_bin())));
1314 function merge($bitfield)
1316 $this->data = $this->data | $bitfield->get_blob();