add some properties
[phpbb.git] / phpBB / includes / functions_content.php
blob56f91eff3b42a0a5f35d615cacfe8db92e095301
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 $sort_dir_text = array('a' => phpbb::$user->lang['ASCENDING'], 'd' => phpbb::$user->lang['DESCENDING']);
48 $sorts = array(
49 'st' => array(
50 'key' => 'sort_days',
51 'default' => $def_st,
52 'options' => $limit_days,
53 'output' => &$s_limit_days,
56 'sk' => array(
57 'key' => 'sort_key',
58 'default' => $def_sk,
59 'options' => $sort_by_text,
60 'output' => &$s_sort_key,
63 'sd' => array(
64 'key' => 'sort_dir',
65 'default' => $def_sd,
66 'options' => $sort_dir_text,
67 'output' => &$s_sort_dir,
70 $u_sort_param = '';
72 foreach ($sorts as $name => $sort_ary)
74 $key = $sort_ary['key'];
75 $selected = $$sort_ary['key'];
77 // Check if the key is selectable. If not, we reset to the default or first key found.
78 // This ensures the values are always valid. We also set $sort_dir/sort_key/etc. to the
79 // correct value, else the protection is void. ;)
80 if (!isset($sort_ary['options'][$selected]))
82 if ($sort_ary['default'] !== false)
84 $selected = $$key = $sort_ary['default'];
86 else
88 @reset($sort_ary['options']);
89 $selected = $$key = key($sort_ary['options']);
93 $sort_ary['output'] = '<select name="' . $name . '" id="' . $name . '">';
94 foreach ($sort_ary['options'] as $option => $text)
96 $sort_ary['output'] .= '<option value="' . $option . '"' . (($selected == $option) ? ' selected="selected"' : '') . '>' . $text . '</option>';
98 $sort_ary['output'] .= '</select>';
100 $u_sort_param .= ($selected !== $sort_ary['default']) ? ((strlen($u_sort_param)) ? '&amp;' : '') . "{$name}={$selected}" : '';
103 return;
107 * Generate Jumpbox
109 function make_jumpbox($action, $forum_id = false, $select_all = false, $acl_list = false, $force_display = false)
111 // We only return if the jumpbox is not forced to be displayed (in case it is needed for functionality)
112 if (!phpbb::$config['load_jumpbox'] && $force_display === false)
114 return;
117 $sql = 'SELECT forum_id, forum_name, parent_id, forum_type, left_id, right_id
118 FROM ' . FORUMS_TABLE . '
119 ORDER BY left_id ASC';
120 $result = phpbb::$db->sql_query($sql, 600);
122 $right = $padding = 0;
123 $padding_store = array('0' => 0);
124 $display_jumpbox = false;
125 $iteration = 0;
127 // Sometimes it could happen that forums will be displayed here not be displayed within the index page
128 // This is the result of forums not displayed at index, having list permissions and a parent of a forum with no permissions.
129 // If this happens, the padding could be "broken"
131 while ($row = phpbb::$db->sql_fetchrow($result))
133 if ($row['left_id'] < $right)
135 $padding++;
136 $padding_store[$row['parent_id']] = $padding;
138 else if ($row['left_id'] > $right + 1)
140 // Ok, if the $padding_store for this parent is empty there is something wrong. For now we will skip over it.
141 // @todo digging deep to find out "how" this can happen.
142 $padding = (isset($padding_store[$row['parent_id']])) ? $padding_store[$row['parent_id']] : $padding;
145 $right = $row['right_id'];
147 if ($row['forum_type'] == FORUM_CAT && ($row['left_id'] + 1 == $row['right_id']))
149 // Non-postable forum with no subforums, don't display
150 continue;
153 if (!phpbb::$acl->acl_get('f_list', $row['forum_id']))
155 // if the user does not have permissions to list this forum skip
156 continue;
159 if ($acl_list && !phpbb::$acl->acl_gets($acl_list, $row['forum_id']))
161 continue;
164 if (!$display_jumpbox)
166 phpbb::$template->assign_block_vars('jumpbox_forums', array(
167 'FORUM_ID' => ($select_all) ? 0 : -1,
168 'FORUM_NAME' => ($select_all) ? phpbb::$user->lang['ALL_FORUMS'] : phpbb::$user->lang['SELECT_FORUM'],
169 'S_FORUM_COUNT' => $iteration)
172 $iteration++;
173 $display_jumpbox = true;
176 phpbb::$template->assign_block_vars('jumpbox_forums', array(
177 'FORUM_ID' => $row['forum_id'],
178 'FORUM_NAME' => $row['forum_name'],
179 'SELECTED' => ($row['forum_id'] == $forum_id) ? ' selected="selected"' : '',
180 'S_FORUM_COUNT' => $iteration,
181 'S_IS_CAT' => ($row['forum_type'] == FORUM_CAT) ? true : false,
182 'S_IS_LINK' => ($row['forum_type'] == FORUM_LINK) ? true : false,
183 'S_IS_POST' => ($row['forum_type'] == FORUM_POST) ? true : false)
186 for ($i = 0; $i < $padding; $i++)
188 phpbb::$template->assign_block_vars('jumpbox_forums.level', array());
190 $iteration++;
192 phpbb::$db->sql_freeresult($result);
193 unset($padding_store);
195 phpbb::$template->assign_vars(array(
196 'S_DISPLAY_JUMPBOX' => $display_jumpbox,
197 'S_JUMPBOX_ACTION' => phpbb::$url->append_sid($action),
200 return;
204 * Bump Topic Check - used by posting and viewtopic
206 function bump_topic_allowed($forum_id, $topic_bumped, $last_post_time, $topic_poster, $last_topic_poster)
208 // Check permission and make sure the last post was not already bumped
209 if (!phpbb::$acl->acl_get('f_bump', $forum_id) || $topic_bumped)
211 return false;
214 // Check bump time range, is the user really allowed to bump the topic at this time?
215 $bump_time = (phpbb::$config['bump_type'] == 'm') ? phpbb::$config['bump_interval'] * 60 : ((phpbb::$config['bump_type'] == 'h') ? phpbb::$config['bump_interval'] * 3600 : phpbb::$config['bump_interval'] * 86400);
217 // Check bump time
218 if ($last_post_time + $bump_time > time())
220 return false;
223 // Check bumper, only topic poster and last poster are allowed to bump
224 if ($topic_poster != phpbb::$user->data['user_id'] && $last_topic_poster != phpbb::$user->data['user_id'])
226 return false;
229 // A bump time of 0 will completely disable the bump feature... not intended but might be useful.
230 return $bump_time;
234 * Generates a text with approx. the specified length which contains the specified words and their context
236 * @param string $text The full text from which context shall be extracted
237 * @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!)
238 * @param int $length The desired length of the resulting text, however the result might be shorter or longer than this value
240 * @return string Context of the specified words separated by "..."
242 function get_context($text, $words, $length = 400)
244 // first replace all whitespaces with single spaces
245 $text = preg_replace('/ +/', ' ', strtr($text, "\t\n\r\x0C ", ' '));
247 $word_indizes = array();
248 if (sizeof($words))
250 $match = '';
251 // find the starting indizes of all words
252 foreach ($words as $word)
254 if ($word)
256 if (preg_match('#(?:[^\w]|^)(' . $word . ')(?:[^\w]|$)#i', $text, $match))
258 $pos = utf8_strpos($text, $match[1]);
259 if ($pos !== false)
261 $word_indizes[] = $pos;
266 unset($match);
268 if (sizeof($word_indizes))
270 $word_indizes = array_unique($word_indizes);
271 sort($word_indizes);
273 $wordnum = sizeof($word_indizes);
274 // number of characters on the right and left side of each word
275 $sequence_length = (int) ($length / (2 * $wordnum)) - 2;
276 $final_text = '';
277 $word = $j = 0;
278 $final_text_index = -1;
280 // cycle through every character in the original text
281 for ($i = $word_indizes[$word], $n = utf8_strlen($text); $i < $n; $i++)
283 // if the current position is the start of one of the words then append $sequence_length characters to the final text
284 if (isset($word_indizes[$word]) && ($i == $word_indizes[$word]))
286 if ($final_text_index < $i - $sequence_length - 1)
288 $final_text .= '... ' . preg_replace('#^([^ ]*)#', '', utf8_substr($text, $i - $sequence_length, $sequence_length));
290 else
292 // if the final text is already nearer to the current word than $sequence_length we only append the text
293 // from its current index on and distribute the unused length to all other sequenes
294 $sequence_length += (int) (($final_text_index - $i + $sequence_length + 1) / (2 * $wordnum));
295 $final_text .= utf8_substr($text, $final_text_index + 1, $i - $final_text_index - 1);
297 $final_text_index = $i - 1;
299 // add the following characters to the final text (see below)
300 $word++;
301 $j = 1;
304 if ($j > 0)
306 // add the character to the final text and increment the sequence counter
307 $final_text .= utf8_substr($text, $i, 1);
308 $final_text_index++;
309 $j++;
311 // if this is a whitespace then check whether we are done with this sequence
312 if (utf8_substr($text, $i, 1) == ' ')
314 // only check whether we have to exit the context generation completely if we haven't already reached the end anyway
315 if ($i + 4 < $n)
317 if (($j > $sequence_length && $word >= $wordnum) || utf8_strlen($final_text) > $length)
319 $final_text .= ' ...';
320 break;
323 else
325 // make sure the text really reaches the end
326 $j -= 4;
329 // stop context generation and wait for the next word
330 if ($j > $sequence_length)
332 $j = 0;
337 return $final_text;
341 if (!sizeof($words) || !sizeof($word_indizes))
343 return (utf8_strlen($text) >= $length + 3) ? utf8_substr($text, 0, $length) . '...' : $text;
348 * Decode text whereby text is coming from the db and expected to be pre-parsed content
349 * We are placing this outside of the message parser because we are often in need of it...
351 function decode_message(&$message, $bbcode_uid = '')
353 if ($bbcode_uid)
355 $match = array('<br />', "[/*:m:$bbcode_uid]", ":u:$bbcode_uid", ":o:$bbcode_uid", ":$bbcode_uid");
356 $replace = array("\n", '', '', '', '');
358 else
360 $match = array('<br />');
361 $replace = array("\n");
364 $message = str_replace($match, $replace, $message);
366 $match = get_preg_expression('bbcode_htm');
367 $replace = array('\1', '\1', '\2', '\1', '', '');
369 $message = preg_replace($match, $replace, $message);
373 * Strips all bbcode from a text and returns the plain content
375 function strip_bbcode(&$text, $uid = '')
377 if (!$uid)
379 $uid = '[0-9a-z]{5,}';
382 $text = preg_replace("#\[\/?[a-z0-9\*\+\-]+(?:=(?:&quot;.*&quot;|[^\]]*))?(?::[a-z])?(\:$uid)\]#", ' ', $text);
384 $match = get_preg_expression('bbcode_htm');
385 $replace = array('\1', '\1', '\2', '\1', '', '');
387 $text = preg_replace($match, $replace, $text);
391 * For display of custom parsed text on user-facing pages
392 * Expects $text to be the value directly from the database (stored value)
394 function generate_text_for_display($text, $uid, $bitfield, $flags)
396 static $bbcode;
398 if (!$text)
400 return '';
403 $text = censor_text($text);
405 // Parse bbcode if bbcode uid stored and bbcode enabled
406 if ($uid && ($flags & OPTION_FLAG_BBCODE))
408 if (!class_exists('bbcode'))
410 include(PHPBB_ROOT_PATH . 'includes/bbcode.' . PHP_EXT);
413 if (empty($bbcode))
415 $bbcode = new bbcode($bitfield);
417 else
419 $bbcode->bbcode($bitfield);
422 $bbcode->bbcode_second_pass($text, $uid);
425 $text = bbcode_nl2br($text);
426 $text = smiley_text($text, !($flags & OPTION_FLAG_SMILIES));
428 return $text;
432 * For parsing custom parsed text to be stored within the database.
433 * This function additionally returns the uid and bitfield that needs to be stored.
434 * Expects $text to be the value directly from request_var() and in it's non-parsed form
436 function generate_text_for_storage(&$text, &$uid, &$bitfield, &$flags, $allow_bbcode = false, $allow_urls = false, $allow_smilies = false)
438 $uid = $bitfield = '';
439 $flags = (($allow_bbcode) ? OPTION_FLAG_BBCODE : 0) + (($allow_smilies) ? OPTION_FLAG_SMILIES : 0) + (($allow_urls) ? OPTION_FLAG_LINKS : 0);
441 if (!$text)
443 return;
446 if (!class_exists('parse_message'))
448 include(PHPBB_ROOT_PATH . 'includes/message_parser.' . PHP_EXT);
451 $message_parser = new parse_message($text);
452 $message_parser->parse($allow_bbcode, $allow_urls, $allow_smilies);
454 $text = $message_parser->message;
455 $uid = $message_parser->bbcode_uid;
457 // If the bbcode_bitfield is empty, there is no need for the uid to be stored.
458 if (!$message_parser->bbcode_bitfield)
460 $uid = '';
463 $bitfield = $message_parser->bbcode_bitfield;
465 return;
469 * For decoding custom parsed text for edits as well as extracting the flags
470 * Expects $text to be the value directly from the database (pre-parsed content)
472 function generate_text_for_edit($text, $uid, $flags)
474 decode_message($text, $uid);
476 return array(
477 'allow_bbcode' => ($flags & OPTION_FLAG_BBCODE) ? 1 : 0,
478 'allow_smilies' => ($flags & OPTION_FLAG_SMILIES) ? 1 : 0,
479 'allow_urls' => ($flags & OPTION_FLAG_LINKS) ? 1 : 0,
480 'text' => $text
485 * A subroutine of make_clickable used with preg_replace
486 * It places correct HTML around an url, shortens the displayed text
487 * and makes sure no entities are inside URLs
489 function make_clickable_callback($type, $whitespace, $url, $relative_url, $class)
491 $orig_url = $url;
492 $orig_relative = $relative_url;
493 $append = '';
494 $url = htmlspecialchars_decode($url);
495 $relative_url = htmlspecialchars_decode($relative_url);
497 // make sure no HTML entities were matched
498 $chars = array('<', '>', '"');
499 $split = false;
501 foreach ($chars as $char)
503 $next_split = strpos($url, $char);
504 if ($next_split !== false)
506 $split = ($split !== false) ? min($split, $next_split) : $next_split;
510 if ($split !== false)
512 // an HTML entity was found, so the URL has to end before it
513 $append = substr($url, $split) . $relative_url;
514 $url = substr($url, 0, $split);
515 $relative_url = '';
517 else if ($relative_url)
519 // same for $relative_url
520 $split = false;
521 foreach ($chars as $char)
523 $next_split = strpos($relative_url, $char);
524 if ($next_split !== false)
526 $split = ($split !== false) ? min($split, $next_split) : $next_split;
530 if ($split !== false)
532 $append = substr($relative_url, $split);
533 $relative_url = substr($relative_url, 0, $split);
537 // if the last character of the url is a punctuation mark, exclude it from the url
538 $last_char = ($relative_url) ? $relative_url[strlen($relative_url) - 1] : $url[strlen($url) - 1];
540 switch ($last_char)
542 case '.':
543 case '?':
544 case '!':
545 case ':':
546 case ',':
547 $append = $last_char;
548 if ($relative_url)
550 $relative_url = substr($relative_url, 0, -1);
552 else
554 $url = substr($url, 0, -1);
556 break;
558 // set last_char to empty here, so the variable can be used later to
559 // check whether a character was removed
560 default:
561 $last_char = '';
562 break;
565 $short_url = (strlen($url) > 55) ? substr($url, 0, 39) . ' ... ' . substr($url, -10) : $url;
567 switch ($type)
569 case MAGIC_URL_LOCAL:
570 $tag = 'l';
571 $relative_url = preg_replace('/[&?]sid=[0-9a-f]{32}$/', '', preg_replace('/([&?])sid=[0-9a-f]{32}&/', '$1', $relative_url));
572 $url = $url . '/' . $relative_url;
573 $text = $relative_url;
575 // this url goes to http://domain.tld/path/to/board/ which
576 // would result in an empty link if treated as local so
577 // don't touch it and let MAGIC_URL_FULL take care of it.
578 if (!$relative_url)
580 return $whitespace . $orig_url . '/' . $orig_relative; // slash is taken away by relative url pattern
582 break;
584 case MAGIC_URL_FULL:
585 $tag = 'm';
586 $text = $short_url;
587 break;
589 case MAGIC_URL_WWW:
590 $tag = 'w';
591 $url = 'http://' . $url;
592 $text = $short_url;
593 break;
595 case MAGIC_URL_EMAIL:
596 $tag = 'e';
597 $text = $short_url;
598 $url = 'mailto:' . $url;
599 break;
602 $url = htmlspecialchars($url);
603 $text = htmlspecialchars($text);
604 $append = htmlspecialchars($append);
606 $html = "$whitespace<!-- $tag --><a$class href=\"$url\">$text</a><!-- $tag -->$append";
608 return $html;
612 * make_clickable function
614 * Replace magic urls of form http://xxx.xxx., www.xxx. and xxx@xxx.xxx.
615 * Cuts down displayed size of link if over 50 chars, turns absolute links
616 * into relative versions when the server/script path matches the link
618 function make_clickable($text, $server_url = false, $class = 'postlink')
620 if ($server_url === false)
622 $server_url = generate_board_url();
625 static $magic_url_match;
626 static $magic_url_replace;
627 static $static_class;
629 if (!is_array($magic_url_match) || $static_class != $class)
631 $static_class = $class;
632 $class = ($static_class) ? ' class="' . $static_class . '"' : '';
633 $local_class = ($static_class) ? ' class="' . $static_class . '-local"' : '';
635 $magic_url_match = $magic_url_replace = array();
636 // Be sure to not let the matches cross over. ;)
638 // relative urls for this board
639 $magic_url_match[] = '#(^|[\n\t (>.])(' . preg_quote($server_url, '#') . ')/(' . get_preg_expression('relative_url_inline') . ')#ie';
640 $magic_url_replace[] = "make_clickable_callback(MAGIC_URL_LOCAL, '\$1', '\$2', '\$3', '$local_class')";
642 // matches a xxxx://aaaaa.bbb.cccc. ...
643 $magic_url_match[] = '#(^|[\n\t (>.])(' . get_preg_expression('url_inline') . ')#ie';
644 $magic_url_replace[] = "make_clickable_callback(MAGIC_URL_FULL, '\$1', '\$2', '', '$class')";
646 // matches a "www.xxxx.yyyy[/zzzz]" kinda lazy URL thing
647 $magic_url_match[] = '#(^|[\n\t (>])(' . get_preg_expression('www_url_inline') . ')#ie';
648 $magic_url_replace[] = "make_clickable_callback(MAGIC_URL_WWW, '\$1', '\$2', '', '$class')";
650 // matches an email@domain type address at the start of a line, or after a space or after what might be a BBCode.
651 $magic_url_match[] = '/(^|[\n\t (>])(' . get_preg_expression('email') . ')/ie';
652 $magic_url_replace[] = "make_clickable_callback(MAGIC_URL_EMAIL, '\$1', '\$2', '', '')";
655 return preg_replace($magic_url_match, $magic_url_replace, $text);
659 * Censoring
661 function censor_text($text)
663 static $censors;
665 // We moved the word censor checks in here because we call this function quite often - and then only need to do the check once
666 if (!isset($censors) || !is_array($censors))
668 // We check here if the user is having viewing censors disabled (and also allowed to do so).
669 if (!phpbb::$user->optionget('viewcensors') && phpbb::$config['allow_nocensors'] && phpbb::$acl->acl_get('u_chgcensors'))
671 $censors = array();
673 else
675 $censors = phpbb_cache::obtain_word_list();
679 if (sizeof($censors))
681 return preg_replace($censors['match'], $censors['replace'], $text);
684 return $text;
688 * custom version of nl2br which takes custom BBCodes into account
690 function bbcode_nl2br($text)
692 // custom BBCodes might contain carriage returns so they
693 // are not converted into <br /> so now revert that
694 $text = str_replace(array("\n", "\r"), array('<br />', "\n"), $text);
695 return $text;
699 * Smiley processing
701 function smiley_text($text, $force_option = false)
703 if ($force_option || !phpbb::$config['allow_smilies'] || !phpbb::$user->optionget('viewsmilies'))
705 return preg_replace('#<!\-\- s(.*?) \-\-><img src="\{SMILIES_PATH\}\/.*? \/><!\-\- s\1 \-\->#', '\1', $text);
707 else
709 return preg_replace('#<!\-\- s(.*?) \-\-><img src="\{SMILIES_PATH\}\/(.*?) \/><!\-\- s\1 \-\->#', '<img src="' . PHPBB_ROOT_PATH . phpbb::$config['smilies_path'] . '/\2 />', $text);
714 * General attachment parsing
716 * @param mixed $forum_id The forum id the attachments are displayed in (false if in private message)
717 * @param string &$message The post/private message
718 * @param array &$attachments The attachments to parse for (inline) display. The attachments array will hold templated data after parsing.
719 * @param array &$update_count The attachment counts to be updated - will be filled
720 * @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.
722 function parse_attachments($forum_id, &$message, &$attachments, &$update_count, $preview = false)
724 if (!sizeof($attachments))
726 return;
729 global $extensions;
732 $compiled_attachments = array();
734 // @todo: do we really need this check?
735 if (!isset(phpbb::$template->filename['attachment_tpl']))
737 phpbb::$template->set_filenames(array(
738 'attachment_tpl' => 'attachment.html')
742 if (empty($extensions) || !is_array($extensions))
744 $extensions = phpbb_cache::obtain_extensions_forum($forum_id);
747 // Look for missing attachment information...
748 $attach_ids = array();
749 foreach ($attachments as $pos => $attachment)
751 // If is_orphan is set, we need to retrieve the attachments again...
752 if (!isset($attachment['extension']) && !isset($attachment['physical_filename']))
754 $attach_ids[(int) $attachment['attach_id']] = $pos;
758 // Grab attachments (security precaution)
759 if (sizeof($attach_ids))
761 $new_attachment_data = array();
763 $sql = 'SELECT *
764 FROM ' . ATTACHMENTS_TABLE . '
765 WHERE ' . phpbb::$db->sql_in_set('attach_id', array_keys($attach_ids));
766 $result = phpbb::$db->sql_query($sql);
768 while ($row = phpbb::$db->sql_fetchrow($result))
770 if (!isset($attach_ids[$row['attach_id']]))
772 continue;
775 // If we preview attachments we will set some retrieved values here
776 if ($preview)
778 $row['attach_comment'] = $attachments[$attach_ids[$row['attach_id']]]['attach_comment'];
781 $new_attachment_data[$attach_ids[$row['attach_id']]] = $row;
783 phpbb::$db->sql_freeresult($result);
785 $attachments = $new_attachment_data;
786 unset($new_attachment_data);
789 // Sort correctly
790 if (phpbb::$config['display_order'])
792 // Ascending sort
793 krsort($attachments);
795 else
797 // Descending sort
798 ksort($attachments);
801 foreach ($attachments as $attachment)
803 if (!sizeof($attachment))
805 continue;
808 // We need to reset/empty the _file block var, because this function might be called more than once
809 phpbb::$template->destroy_block_vars('_file');
811 $block_array = array();
813 // Some basics...
814 $attachment['extension'] = strtolower(trim($attachment['extension']));
815 $filename = PHPBB_ROOT_PATH . phpbb::$config['upload_path'] . '/' . basename($attachment['physical_filename']);
816 $thumbnail_filename = PHPBB_ROOT_PATH . phpbb::$config['upload_path'] . '/thumb_' . basename($attachment['physical_filename']);
818 $upload_icon = '';
820 if (isset($extensions[$attachment['extension']]))
822 if (phpbb::$user->img('icon_topic_attach', '') && !$extensions[$attachment['extension']]['upload_icon'])
824 $upload_icon = phpbb::$user->img('icon_topic_attach', '');
826 else if ($extensions[$attachment['extension']]['upload_icon'])
828 $upload_icon = '<img src="' . PHPBB_ROOT_PATH . phpbb::$config['upload_icons_path'] . '/' . trim($extensions[$attachment['extension']]['upload_icon']) . '" alt="" />';
832 $filesize = $attachment['filesize'];
833 $size_lang = ($filesize >= 1048576) ? phpbb::$user->lang['MIB'] : (($filesize >= 1024) ? phpbb::$user->lang['KIB'] : phpbb::$user->lang['BYTES']);
834 $filesize = get_formatted_filesize($filesize, false);
836 $comment = bbcode_nl2br(censor_text($attachment['attach_comment']));
838 $block_array += array(
839 'UPLOAD_ICON' => $upload_icon,
840 'FILESIZE' => $filesize,
841 'SIZE_LANG' => $size_lang,
842 'DOWNLOAD_NAME' => basename($attachment['real_filename']),
843 'COMMENT' => $comment,
846 $denied = false;
848 if (!extension_allowed($forum_id, $attachment['extension'], $extensions))
850 $denied = true;
852 $block_array += array(
853 'S_DENIED' => true,
854 'DENIED_MESSAGE' => phpbb::$user->lang('EXTENSION_DISABLED_AFTER_POSTING', $attachment['extension']),
858 if (!$denied)
860 $l_downloaded_viewed = $download_link = '';
861 $display_cat = $extensions[$attachment['extension']]['display_cat'];
863 if ($display_cat == ATTACHMENT_CATEGORY_IMAGE)
865 if ($attachment['thumbnail'])
867 $display_cat = ATTACHMENT_CATEGORY_THUMB;
869 else
871 if (phpbb::$config['img_display_inlined'])
873 if (phpbb::$config['img_link_width'] || phpbb::$config['img_link_height'])
875 $dimension = @getimagesize($filename);
877 // If the dimensions could not be determined or the image being 0x0 we display it as a link for safety purposes
878 if ($dimension === false || empty($dimension[0]) || empty($dimension[1]))
880 $display_cat = ATTACHMENT_CATEGORY_NONE;
882 else
884 $display_cat = ($dimension[0] <= phpbb::$config['img_link_width'] && $dimension[1] <= phpbb::$config['img_link_height']) ? ATTACHMENT_CATEGORY_IMAGE : ATTACHMENT_CATEGORY_NONE;
888 else
890 $display_cat = ATTACHMENT_CATEGORY_NONE;
895 // Make some descisions based on user options being set.
896 if (($display_cat == ATTACHMENT_CATEGORY_IMAGE || $display_cat == ATTACHMENT_CATEGORY_THUMB) && !phpbb::$user->optionget('viewimg'))
898 $display_cat = ATTACHMENT_CATEGORY_NONE;
901 if ($display_cat == ATTACHMENT_CATEGORY_FLASH && !phpbb::$user->optionget('viewflash'))
903 $display_cat = ATTACHMENT_CATEGORY_NONE;
906 $download_link = append_sid('download/file', 'id=' . $attachment['attach_id']);
908 switch ($display_cat)
910 // Images
911 case ATTACHMENT_CATEGORY_IMAGE:
912 $l_downloaded_viewed = 'VIEWED_COUNT';
913 $inline_link = append_sid('download/file', 'id=' . $attachment['attach_id']);
914 $download_link .= '&amp;mode=view';
916 $block_array += array(
917 'S_IMAGE' => true,
918 'U_INLINE_LINK' => $inline_link,
921 $update_count[] = $attachment['attach_id'];
922 break;
924 // Images, but display Thumbnail
925 case ATTACHMENT_CATEGORY_THUMB:
926 $l_downloaded_viewed = 'VIEWED_COUNT';
927 $thumbnail_link = append_sid('download/file', 'id=' . $attachment['attach_id'] . '&amp;t=1');
928 $download_link .= '&amp;mode=view';
930 $block_array += array(
931 'S_THUMBNAIL' => true,
932 'THUMB_IMAGE' => $thumbnail_link,
934 break;
936 // Windows Media Streams
937 case ATTACHMENT_CATEGORY_WM:
938 $l_downloaded_viewed = 'VIEWED_COUNT';
940 // Giving the filename directly because within the wm object all variables are in local context making it impossible
941 // to validate against a valid session (all params can differ)
942 // $download_link = $filename;
944 $block_array += array(
945 'U_FORUM' => generate_board_url(),
946 'ATTACH_ID' => $attachment['attach_id'],
947 'S_WM_FILE' => true,
950 // Viewed/Heared File ... update the download count
951 $update_count[] = $attachment['attach_id'];
952 break;
954 // Real Media Streams
955 case ATTACHMENT_CATEGORY_RM:
956 case ATTACHMENT_CATEGORY_QUICKTIME:
957 $l_downloaded_viewed = 'VIEWED_COUNT';
959 $block_array += array(
960 'S_RM_FILE' => ($display_cat == ATTACHMENT_CATEGORY_RM) ? true : false,
961 'S_QUICKTIME_FILE' => ($display_cat == ATTACHMENT_CATEGORY_QUICKTIME) ? true : false,
962 'U_FORUM' => generate_board_url(),
963 'ATTACH_ID' => $attachment['attach_id'],
966 // Viewed/Heared File ... update the download count
967 $update_count[] = $attachment['attach_id'];
968 break;
970 // Macromedia Flash Files
971 case ATTACHMENT_CATEGORY_FLASH:
972 list($width, $height) = @getimagesize($filename);
974 $l_downloaded_viewed = 'VIEWED_COUNT';
976 $block_array += array(
977 'S_FLASH_FILE' => true,
978 'WIDTH' => $width,
979 'HEIGHT' => $height,
982 // Viewed/Heared File ... update the download count
983 $update_count[] = $attachment['attach_id'];
984 break;
986 default:
987 $l_downloaded_viewed = 'DOWNLOAD_COUNT';
989 $block_array += array(
990 'S_FILE' => true,
992 break;
995 $block_array += array(
996 'U_DOWNLOAD_LINK' => $download_link,
997 'L_DOWNLOAD_COUNT' => phpbb::$user->lang($l_downloaded_viewed, $attachment['download_count']),
1001 phpbb::$template->assign_block_vars('_file', $block_array);
1003 $compiled_attachments[] = phpbb::$template->assign_display('attachment_tpl');
1006 $attachments = $compiled_attachments;
1007 unset($compiled_attachments);
1009 $tpl_size = sizeof($attachments);
1011 $unset_tpl = array();
1013 preg_match_all('#<!\-\- ia([0-9]+) \-\->(.*?)<!\-\- ia\1 \-\->#', $message, $matches, PREG_PATTERN_ORDER);
1015 $replace = array();
1016 foreach ($matches[0] as $num => $capture)
1018 // Flip index if we are displaying the reverse way
1019 $index = (phpbb::$config['display_order']) ? ($tpl_size-($matches[1][$num] + 1)) : $matches[1][$num];
1021 $replace['from'][] = $matches[0][$num];
1022 $replace['to'][] = (isset($attachments[$index])) ? $attachments[$index] : sprintf(phpbb::$user->lang['MISSING_INLINE_ATTACHMENT'], $matches[2][array_search($index, $matches[1])]);
1024 $unset_tpl[] = $index;
1027 if (isset($replace['from']))
1029 $message = str_replace($replace['from'], $replace['to'], $message);
1032 $unset_tpl = array_unique($unset_tpl);
1034 // Needed to let not display the inlined attachments at the end of the post again
1035 foreach ($unset_tpl as $index)
1037 unset($attachments[$index]);
1042 * Check if extension is allowed to be posted.
1044 * @param mixed $forum_id The forum id to check or false if private message
1045 * @param string $extension The extension to check, for example zip.
1046 * @param array &$extensions The extension array holding the information from the cache (will be obtained if empty)
1048 * @return bool False if the extension is not allowed to be posted, else true.
1050 function extension_allowed($forum_id, $extension, &$extensions)
1052 if (empty($extensions))
1054 $extensions = phpbb_cache::obtain_extensions_forum($forum_id);
1057 return (!isset($extensions['_allowed_'][$extension])) ? false : true;
1061 * Truncates string while retaining special characters if going over the max length
1062 * The default max length is 60 at the moment
1063 * The maximum storage length is there to fit the string within the given length. The string may be further truncated due to html entities.
1064 * For example: string given is 'a "quote"' (length: 9), would be a stored as 'a &quot;quote&quot;' (length: 19)
1066 * @param string $string The text to truncate to the given length. String is specialchared.
1067 * @param int $max_length Maximum length of string (multibyte character count as 1 char / Html entity count as 1 char)
1068 * @param int $max_store_length Maximum character length of string (multibyte character count as 1 char / Html entity count as entity chars).
1069 * @param bool $allow_reply Allow Re: in front of string
1070 * @param string $append String to be appended
1072 function truncate_string($string, $max_length = 60, $max_store_length = 255, $allow_reply = true, $append = '')
1074 $chars = array();
1076 $strip_reply = false;
1077 $stripped = false;
1078 if ($allow_reply && strpos($string, 'Re: ') === 0)
1080 $strip_reply = true;
1081 $string = substr($string, 4);
1084 $_chars = utf8_str_split(htmlspecialchars_decode($string));
1085 $chars = array_map('utf8_htmlspecialchars', $_chars);
1087 // Now check the length ;)
1088 if (sizeof($chars) > $max_length)
1090 // Cut off the last elements from the array
1091 $string = implode('', array_slice($chars, 0, $max_length - utf8_strlen($append)));
1092 $stripped = true;
1095 // Due to specialchars, we may not be able to store the string...
1096 if (utf8_strlen($string) > $max_store_length)
1098 // let's split again, we do not want half-baked strings where entities are split
1099 $_chars = utf8_str_split(htmlspecialchars_decode($string));
1100 $chars = array_map('utf8_htmlspecialchars', $_chars);
1104 array_pop($chars);
1105 $string = implode('', $chars);
1107 while (utf8_strlen($string) > $max_store_length || !sizeof($chars));
1110 if ($strip_reply)
1112 $string = 'Re: ' . $string;
1115 if ($append != '' && $stripped)
1117 $string = $string . $append;
1120 return $string;
1124 * Get username details for placing into templates.
1125 * This function caches all modes on first call, except for no_profile - determined by $user_id/$guest_username combination.
1127 * @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)
1128 * @param int $user_id The users id
1129 * @param string $username The users name
1130 * @param string $username_colour The users colour
1131 * @param string $guest_username optional parameter to specify the guest username. It will be used in favor of the GUEST language variable then.
1132 * @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}
1134 * @return string A string consisting of what is wanted based on $mode.
1135 * @author BartVB, Acyd Burn
1137 function get_username_string($mode, $user_id, $username, $username_colour = '', $guest_username = false, $custom_profile_url = false)
1139 static $_profile_cache;
1141 // We cache some common variables we need within this function
1142 if (empty($_profile_cache))
1144 $_profile_cache['base_url'] = phpbb::$url->append_sid('memberlist', 'mode=viewprofile&amp;u={USER_ID}');
1145 $_profile_cache['tpl_noprofile'] = '{USERNAME}';
1146 $_profile_cache['tpl_noprofile_colour'] = '<span style="color: {USERNAME_COLOUR};" class="username-coloured">{USERNAME}</span>';
1147 $_profile_cache['tpl_profile'] = '<a href="{PROFILE_URL}">{USERNAME}</a>';
1148 $_profile_cache['tpl_profile_colour'] = '<a href="{PROFILE_URL}" style="color: {USERNAME_COLOUR};" class="username-coloured">{USERNAME}</a>';
1151 // This switch makes sure we only run code required for the mode
1152 switch ($mode)
1154 case 'full':
1155 case 'noprofile':
1156 case 'colour':
1158 // Build correct username colour
1159 $username_colour = ($username_colour) ? '#' . $username_colour : '';
1161 // Return colour
1162 if ($mode == 'colour')
1164 return $username_colour;
1167 // no break;
1169 case 'username':
1171 // Build correct username
1172 if ($guest_username === false)
1174 $username = ($username) ? $username : phpbb::$user->lang['GUEST'];
1176 else
1178 $username = ($user_id && $user_id != ANONYMOUS) ? $username : ((!empty($guest_username)) ? $guest_username : phpbb::$user->lang['GUEST']);
1181 // Return username
1182 if ($mode == 'username')
1184 return $username;
1187 // no break;
1189 case 'profile':
1191 // Build correct profile url - only show if not anonymous and permission to view profile if registered user
1192 // For anonymous the link leads to a login page.
1193 if ($user_id && $user_id != ANONYMOUS && (phpbb::$user->data['user_id'] == ANONYMOUS || phpbb::$acl->acl_get('u_viewprofile')))
1195 $profile_url = ($custom_profile_url !== false) ? $custom_profile_url . '&amp;u=' . (int) $user_id : str_replace(array('={USER_ID}', '=%7BUSER_ID%7D'), '=' . (int) $user_id, $_profile_cache['base_url']);
1197 else
1199 $profile_url = '';
1202 // Return profile
1203 if ($mode == 'profile')
1205 return $profile_url;
1208 // no break;
1211 if (($mode == 'full' && !$profile_url) || $mode == 'no_profile')
1213 return str_replace(array('{USERNAME_COLOUR}', '{USERNAME}'), array($username_colour, $username), (!$username_colour) ? $_profile_cache['tpl_noprofile'] : $_profile_cache['tpl_noprofile_colour']);
1216 return str_replace(array('{PROFILE_URL}', '{USERNAME_COLOUR}', '{USERNAME}'), array($profile_url, $username_colour, $username), (!$username_colour) ? $_profile_cache['tpl_profile'] : $_profile_cache['tpl_profile_colour']);
1220 * @package phpBB3
1222 class bitfield
1224 var $data;
1226 function __construct($bitfield = '')
1228 $this->data = base64_decode($bitfield);
1233 function get($n)
1235 // Get the ($n / 8)th char
1236 $byte = $n >> 3;
1238 if (strlen($this->data) >= $byte + 1)
1240 $c = $this->data[$byte];
1242 // Lookup the ($n % 8)th bit of the byte
1243 $bit = 7 - ($n & 7);
1244 return (bool) (ord($c) & (1 << $bit));
1246 else
1248 return false;
1252 function set($n)
1254 $byte = $n >> 3;
1255 $bit = 7 - ($n & 7);
1257 if (strlen($this->data) >= $byte + 1)
1259 $this->data[$byte] = $this->data[$byte] | chr(1 << $bit);
1261 else
1263 $this->data .= str_repeat("\0", $byte - strlen($this->data));
1264 $this->data .= chr(1 << $bit);
1268 function clear($n)
1270 $byte = $n >> 3;
1272 if (strlen($this->data) >= $byte + 1)
1274 $bit = 7 - ($n & 7);
1275 $this->data[$byte] = $this->data[$byte] &~ chr(1 << $bit);
1279 function get_blob()
1281 return $this->data;
1284 function get_base64()
1286 return base64_encode($this->data);
1289 function get_bin()
1291 $bin = '';
1292 $len = strlen($this->data);
1294 for ($i = 0; $i < $len; ++$i)
1296 $bin .= str_pad(decbin(ord($this->data[$i])), 8, '0', STR_PAD_LEFT);
1299 return $bin;
1302 function get_all_set()
1304 return array_keys(array_filter(str_split($this->get_bin())));
1307 function merge($bitfield)
1309 $this->data = $this->data | $bitfield->get_blob();