source: trunk/forum/includes/functions_content.php@ 482

Last change on this file since 482 was 400, checked in by george, 16 years ago
  • Přidáno: Nové forum phpBB 3.
File size: 37.7 KB
Line 
1<?php
2/**
3*
4* @package phpBB3
5* @version $Id: functions_content.php 9184 2008-12-11 14:46:38Z acydburn $
6* @copyright (c) 2005 phpBB Group
7* @license http://opensource.org/licenses/gpl-license.php GNU Public License
8*
9*/
10
11/**
12* @ignore
13*/
14if (!defined('IN_PHPBB'))
15{
16 exit;
17}
18
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
39*/
40
41/**
42* Generate sort selection fields
43*/
44function 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)
45{
46 global $user;
47
48 $sort_dir_text = array('a' => $user->lang['ASCENDING'], 'd' => $user->lang['DESCENDING']);
49
50 $sorts = array(
51 'st' => array(
52 'key' => 'sort_days',
53 'default' => $def_st,
54 'options' => $limit_days,
55 'output' => &$s_limit_days,
56 ),
57
58 'sk' => array(
59 'key' => 'sort_key',
60 'default' => $def_sk,
61 'options' => $sort_by_text,
62 'output' => &$s_sort_key,
63 ),
64
65 'sd' => array(
66 'key' => 'sort_dir',
67 'default' => $def_sd,
68 'options' => $sort_dir_text,
69 'output' => &$s_sort_dir,
70 ),
71 );
72 $u_sort_param = '';
73
74 foreach ($sorts as $name => $sort_ary)
75 {
76 $key = $sort_ary['key'];
77 $selected = $$sort_ary['key'];
78
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]))
83 {
84 if ($sort_ary['default'] !== false)
85 {
86 $selected = $$key = $sort_ary['default'];
87 }
88 else
89 {
90 @reset($sort_ary['options']);
91 $selected = $$key = key($sort_ary['options']);
92 }
93 }
94
95 $sort_ary['output'] = '<select name="' . $name . '" id="' . $name . '">';
96 foreach ($sort_ary['options'] as $option => $text)
97 {
98 $sort_ary['output'] .= '<option value="' . $option . '"' . (($selected == $option) ? ' selected="selected"' : '') . '>' . $text . '</option>';
99 }
100 $sort_ary['output'] .= '</select>';
101
102 $u_sort_param .= ($selected !== $sort_ary['default']) ? ((strlen($u_sort_param)) ? '&amp;' : '') . "{$name}={$selected}" : '';
103 }
104
105 return;
106}
107
108/**
109* Generate Jumpbox
110*/
111function make_jumpbox($action, $forum_id = false, $select_all = false, $acl_list = false, $force_display = false)
112{
113 global $config, $auth, $template, $user, $db;
114
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)
117 {
118 return;
119 }
120
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);
125
126 $right = $padding = 0;
127 $padding_store = array('0' => 0);
128 $display_jumpbox = false;
129 $iteration = 0;
130
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"
134
135 while ($row = $db->sql_fetchrow($result))
136 {
137 if ($row['left_id'] < $right)
138 {
139 $padding++;
140 $padding_store[$row['parent_id']] = $padding;
141 }
142 else if ($row['left_id'] > $right + 1)
143 {
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;
147 }
148
149 $right = $row['right_id'];
150
151 if ($row['forum_type'] == FORUM_CAT && ($row['left_id'] + 1 == $row['right_id']))
152 {
153 // Non-postable forum with no subforums, don't display
154 continue;
155 }
156
157 if (!$auth->acl_get('f_list', $row['forum_id']))
158 {
159 // if the user does not have permissions to list this forum skip
160 continue;
161 }
162
163 if ($acl_list && !$auth->acl_gets($acl_list, $row['forum_id']))
164 {
165 continue;
166 }
167
168 if (!$display_jumpbox)
169 {
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)
174 );
175
176 $iteration++;
177 $display_jumpbox = true;
178 }
179
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)
188 );
189
190 for ($i = 0; $i < $padding; $i++)
191 {
192 $template->assign_block_vars('jumpbox_forums.level', array());
193 }
194 $iteration++;
195 }
196 $db->sql_freeresult($result);
197 unset($padding_store);
198
199 $template->assign_vars(array(
200 'S_DISPLAY_JUMPBOX' => $display_jumpbox,
201 'S_JUMPBOX_ACTION' => $action)
202 );
203
204 return;
205}
206
207/**
208* Bump Topic Check - used by posting and viewtopic
209*/
210function bump_topic_allowed($forum_id, $topic_bumped, $last_post_time, $topic_poster, $last_topic_poster)
211{
212 global $config, $auth, $user;
213
214 // Check permission and make sure the last post was not already bumped
215 if (!$auth->acl_get('f_bump', $forum_id) || $topic_bumped)
216 {
217 return false;
218 }
219
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);
222
223 // Check bump time
224 if ($last_post_time + $bump_time > time())
225 {
226 return false;
227 }
228
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'])
231 {
232 return false;
233 }
234
235 // A bump time of 0 will completely disable the bump feature... not intended but might be useful.
236 return $bump_time;
237}
238
239/**
240* Generates a text with approx. the specified length which contains the specified words and their context
241*
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
245*
246* @return string Context of the specified words separated by "..."
247*/
248function get_context($text, $words, $length = 400)
249{
250 // first replace all whitespaces with single spaces
251 $text = preg_replace('/ +/', ' ', strtr($text, "\t\n\r\x0C ", ' '));
252
253 $word_indizes = array();
254 if (sizeof($words))
255 {
256 $match = '';
257 // find the starting indizes of all words
258 foreach ($words as $word)
259 {
260 if ($word)
261 {
262 if (preg_match('#(?:[^\w]|^)(' . $word . ')(?:[^\w]|$)#i', $text, $match))
263 {
264 $pos = utf8_strpos($text, $match[1]);
265 if ($pos !== false)
266 {
267 $word_indizes[] = $pos;
268 }
269 }
270 }
271 }
272 unset($match);
273
274 if (sizeof($word_indizes))
275 {
276 $word_indizes = array_unique($word_indizes);
277 sort($word_indizes);
278
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;
285
286 // cycle through every character in the original text
287 for ($i = $word_indizes[$word], $n = utf8_strlen($text); $i < $n; $i++)
288 {
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]))
291 {
292 if ($final_text_index < $i - $sequence_length - 1)
293 {
294 $final_text .= '... ' . preg_replace('#^([^ ]*)#', '', utf8_substr($text, $i - $sequence_length, $sequence_length));
295 }
296 else
297 {
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);
302 }
303 $final_text_index = $i - 1;
304
305 // add the following characters to the final text (see below)
306 $word++;
307 $j = 1;
308 }
309
310 if ($j > 0)
311 {
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++;
316
317 // if this is a whitespace then check whether we are done with this sequence
318 if (utf8_substr($text, $i, 1) == ' ')
319 {
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)
322 {
323 if (($j > $sequence_length && $word >= $wordnum) || utf8_strlen($final_text) > $length)
324 {
325 $final_text .= ' ...';
326 break;
327 }
328 }
329 else
330 {
331 // make sure the text really reaches the end
332 $j -= 4;
333 }
334
335 // stop context generation and wait for the next word
336 if ($j > $sequence_length)
337 {
338 $j = 0;
339 }
340 }
341 }
342 }
343 return $final_text;
344 }
345 }
346
347 if (!sizeof($words) || !sizeof($word_indizes))
348 {
349 return (utf8_strlen($text) >= $length + 3) ? utf8_substr($text, 0, $length) . '...' : $text;
350 }
351}
352
353/**
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...
356*/
357function decode_message(&$message, $bbcode_uid = '')
358{
359 global $config;
360
361 if ($bbcode_uid)
362 {
363 $match = array('<br />', "[/*:m:$bbcode_uid]", ":u:$bbcode_uid", ":o:$bbcode_uid", ":$bbcode_uid");
364 $replace = array("\n", '', '', '', '');
365 }
366 else
367 {
368 $match = array('<br />');
369 $replace = array("\n");
370 }
371
372 $message = str_replace($match, $replace, $message);
373
374 $match = get_preg_expression('bbcode_htm');
375 $replace = array('\1', '\1', '\2', '\1', '', '');
376
377 $message = preg_replace($match, $replace, $message);
378}
379
380/**
381* Strips all bbcode from a text and returns the plain content
382*/
383function strip_bbcode(&$text, $uid = '')
384{
385 if (!$uid)
386 {
387 $uid = '[0-9a-z]{5,}';
388 }
389
390 $text = preg_replace("#\[\/?[a-z0-9\*\+\-]+(?:=(?:&quot;.*&quot;|[^\]]*))?(?::[a-z])?(\:$uid)\]#", ' ', $text);
391
392 $match = get_preg_expression('bbcode_htm');
393 $replace = array('\1', '\1', '\2', '\1', '', '');
394
395 $text = preg_replace($match, $replace, $text);
396}
397
398/**
399* For display of custom parsed text on user-facing pages
400* Expects $text to be the value directly from the database (stored value)
401*/
402function generate_text_for_display($text, $uid, $bitfield, $flags)
403{
404 static $bbcode;
405
406 if (!$text)
407 {
408 return '';
409 }
410
411 $text = censor_text($text);
412
413 // Parse bbcode if bbcode uid stored and bbcode enabled
414 if ($uid && ($flags & OPTION_FLAG_BBCODE))
415 {
416 if (!class_exists('bbcode'))
417 {
418 global $phpbb_root_path, $phpEx;
419 include($phpbb_root_path . 'includes/bbcode.' . $phpEx);
420 }
421
422 if (empty($bbcode))
423 {
424 $bbcode = new bbcode($bitfield);
425 }
426 else
427 {
428 $bbcode->bbcode($bitfield);
429 }
430
431 $bbcode->bbcode_second_pass($text, $uid);
432 }
433
434 $text = bbcode_nl2br($text);
435 $text = smiley_text($text, !($flags & OPTION_FLAG_SMILIES));
436
437 return $text;
438}
439
440/**
441* For parsing custom parsed text to be stored within the database.
442* This function additionally returns the uid and bitfield that needs to be stored.
443* Expects $text to be the value directly from request_var() and in it's non-parsed form
444*/
445function generate_text_for_storage(&$text, &$uid, &$bitfield, &$flags, $allow_bbcode = false, $allow_urls = false, $allow_smilies = false)
446{
447 global $phpbb_root_path, $phpEx;
448
449 $uid = $bitfield = '';
450 $flags = (($allow_bbcode) ? OPTION_FLAG_BBCODE : 0) + (($allow_smilies) ? OPTION_FLAG_SMILIES : 0) + (($allow_urls) ? OPTION_FLAG_LINKS : 0);
451
452 if (!$text)
453 {
454 return;
455 }
456
457 if (!class_exists('parse_message'))
458 {
459 include($phpbb_root_path . 'includes/message_parser.' . $phpEx);
460 }
461
462 $message_parser = new parse_message($text);
463 $message_parser->parse($allow_bbcode, $allow_urls, $allow_smilies);
464
465 $text = $message_parser->message;
466 $uid = $message_parser->bbcode_uid;
467
468 // If the bbcode_bitfield is empty, there is no need for the uid to be stored.
469 if (!$message_parser->bbcode_bitfield)
470 {
471 $uid = '';
472 }
473
474 $bitfield = $message_parser->bbcode_bitfield;
475
476 return;
477}
478
479/**
480* For decoding custom parsed text for edits as well as extracting the flags
481* Expects $text to be the value directly from the database (pre-parsed content)
482*/
483function generate_text_for_edit($text, $uid, $flags)
484{
485 global $phpbb_root_path, $phpEx;
486
487 decode_message($text, $uid);
488
489 return array(
490 'allow_bbcode' => ($flags & OPTION_FLAG_BBCODE) ? 1 : 0,
491 'allow_smilies' => ($flags & OPTION_FLAG_SMILIES) ? 1 : 0,
492 'allow_urls' => ($flags & OPTION_FLAG_LINKS) ? 1 : 0,
493 'text' => $text
494 );
495}
496
497/**
498* A subroutine of make_clickable used with preg_replace
499* It places correct HTML around an url, shortens the displayed text
500* and makes sure no entities are inside URLs
501*/
502function make_clickable_callback($type, $whitespace, $url, $relative_url, $class)
503{
504 $orig_url = $url;
505 $orig_relative = $relative_url;
506 $append = '';
507 $url = htmlspecialchars_decode($url);
508 $relative_url = htmlspecialchars_decode($relative_url);
509
510 // make sure no HTML entities were matched
511 $chars = array('<', '>', '"');
512 $split = false;
513
514 foreach ($chars as $char)
515 {
516 $next_split = strpos($url, $char);
517 if ($next_split !== false)
518 {
519 $split = ($split !== false) ? min($split, $next_split) : $next_split;
520 }
521 }
522
523 if ($split !== false)
524 {
525 // an HTML entity was found, so the URL has to end before it
526 $append = substr($url, $split) . $relative_url;
527 $url = substr($url, 0, $split);
528 $relative_url = '';
529 }
530 else if ($relative_url)
531 {
532 // same for $relative_url
533 $split = false;
534 foreach ($chars as $char)
535 {
536 $next_split = strpos($relative_url, $char);
537 if ($next_split !== false)
538 {
539 $split = ($split !== false) ? min($split, $next_split) : $next_split;
540 }
541 }
542
543 if ($split !== false)
544 {
545 $append = substr($relative_url, $split);
546 $relative_url = substr($relative_url, 0, $split);
547 }
548 }
549
550 // if the last character of the url is a punctuation mark, exclude it from the url
551 $last_char = ($relative_url) ? $relative_url[strlen($relative_url) - 1] : $url[strlen($url) - 1];
552
553 switch ($last_char)
554 {
555 case '.':
556 case '?':
557 case '!':
558 case ':':
559 case ',':
560 $append = $last_char;
561 if ($relative_url)
562 {
563 $relative_url = substr($relative_url, 0, -1);
564 }
565 else
566 {
567 $url = substr($url, 0, -1);
568 }
569 break;
570
571 // set last_char to empty here, so the variable can be used later to
572 // check whether a character was removed
573 default:
574 $last_char = '';
575 break;
576 }
577
578 $short_url = (strlen($url) > 55) ? substr($url, 0, 39) . ' ... ' . substr($url, -10) : $url;
579
580 switch ($type)
581 {
582 case MAGIC_URL_LOCAL:
583 $tag = 'l';
584 $relative_url = preg_replace('/[&?]sid=[0-9a-f]{32}$/', '', preg_replace('/([&?])sid=[0-9a-f]{32}&/', '$1', $relative_url));
585 $url = $url . '/' . $relative_url;
586 $text = $relative_url;
587
588 // this url goes to http://domain.tld/path/to/board/ which
589 // would result in an empty link if treated as local so
590 // don't touch it and let MAGIC_URL_FULL take care of it.
591 if (!$relative_url)
592 {
593 return $whitespace . $orig_url . '/' . $orig_relative; // slash is taken away by relative url pattern
594 }
595 break;
596
597 case MAGIC_URL_FULL:
598 $tag = 'm';
599 $text = $short_url;
600 break;
601
602 case MAGIC_URL_WWW:
603 $tag = 'w';
604 $url = 'http://' . $url;
605 $text = $short_url;
606 break;
607
608 case MAGIC_URL_EMAIL:
609 $tag = 'e';
610 $text = $short_url;
611 $url = 'mailto:' . $url;
612 break;
613 }
614
615 $url = htmlspecialchars($url);
616 $text = htmlspecialchars($text);
617 $append = htmlspecialchars($append);
618
619 $html = "$whitespace<!-- $tag --><a$class href=\"$url\">$text</a><!-- $tag -->$append";
620
621 return $html;
622}
623
624/**
625* make_clickable function
626*
627* Replace magic urls of form http://xxx.xxx., www.xxx. and xxx@xxx.xxx.
628* Cuts down displayed size of link if over 50 chars, turns absolute links
629* into relative versions when the server/script path matches the link
630*/
631function make_clickable($text, $server_url = false, $class = 'postlink')
632{
633 if ($server_url === false)
634 {
635 $server_url = generate_board_url();
636 }
637
638 static $magic_url_match;
639 static $magic_url_replace;
640 static $static_class;
641
642 if (!is_array($magic_url_match) || $static_class != $class)
643 {
644 $static_class = $class;
645 $class = ($static_class) ? ' class="' . $static_class . '"' : '';
646 $local_class = ($static_class) ? ' class="' . $static_class . '-local"' : '';
647
648 $magic_url_match = $magic_url_replace = array();
649 // Be sure to not let the matches cross over. ;)
650
651 // relative urls for this board
652 $magic_url_match[] = '#(^|[\n\t (>.])(' . preg_quote($server_url, '#') . ')/(' . get_preg_expression('relative_url_inline') . ')#ie';
653 $magic_url_replace[] = "make_clickable_callback(MAGIC_URL_LOCAL, '\$1', '\$2', '\$3', '$local_class')";
654
655 // matches a xxxx://aaaaa.bbb.cccc. ...
656 $magic_url_match[] = '#(^|[\n\t (>.])(' . get_preg_expression('url_inline') . ')#ie';
657 $magic_url_replace[] = "make_clickable_callback(MAGIC_URL_FULL, '\$1', '\$2', '', '$class')";
658
659 // matches a "www.xxxx.yyyy[/zzzz]" kinda lazy URL thing
660 $magic_url_match[] = '#(^|[\n\t (>])(' . get_preg_expression('www_url_inline') . ')#ie';
661 $magic_url_replace[] = "make_clickable_callback(MAGIC_URL_WWW, '\$1', '\$2', '', '$class')";
662
663 // matches an email@domain type address at the start of a line, or after a space or after what might be a BBCode.
664 $magic_url_match[] = '/(^|[\n\t (>])(' . get_preg_expression('email') . ')/ie';
665 $magic_url_replace[] = "make_clickable_callback(MAGIC_URL_EMAIL, '\$1', '\$2', '', '')";
666 }
667
668 return preg_replace($magic_url_match, $magic_url_replace, $text);
669}
670
671/**
672* Censoring
673*/
674function censor_text($text)
675{
676 static $censors;
677
678 // We moved the word censor checks in here because we call this function quite often - and then only need to do the check once
679 if (!isset($censors) || !is_array($censors))
680 {
681 global $config, $user, $auth, $cache;
682
683 // We check here if the user is having viewing censors disabled (and also allowed to do so).
684 if (!$user->optionget('viewcensors') && $config['allow_nocensors'] && $auth->acl_get('u_chgcensors'))
685 {
686 $censors = array();
687 }
688 else
689 {
690 $censors = $cache->obtain_word_list();
691 }
692 }
693
694 if (sizeof($censors))
695 {
696 return preg_replace($censors['match'], $censors['replace'], $text);
697 }
698
699 return $text;
700}
701
702/**
703* custom version of nl2br which takes custom BBCodes into account
704*/
705function bbcode_nl2br($text)
706{
707 // custom BBCodes might contain carriage returns so they
708 // are not converted into <br /> so now revert that
709 $text = str_replace(array("\n", "\r"), array('<br />', "\n"), $text);
710 return $text;
711}
712
713/**
714* Smiley processing
715*/
716function smiley_text($text, $force_option = false)
717{
718 global $config, $user, $phpbb_root_path;
719
720 if ($force_option || !$config['allow_smilies'] || !$user->optionget('viewsmilies'))
721 {
722 return preg_replace('#<!\-\- s(.*?) \-\-><img src="\{SMILIES_PATH\}\/.*? \/><!\-\- s\1 \-\->#', '\1', $text);
723 }
724 else
725 {
726 return preg_replace('#<!\-\- s(.*?) \-\-><img src="\{SMILIES_PATH\}\/(.*?) \/><!\-\- s\1 \-\->#', '<img src="' . $phpbb_root_path . $config['smilies_path'] . '/\2 />', $text);
727 }
728}
729
730/**
731* General attachment parsing
732*
733* @param mixed $forum_id The forum id the attachments are displayed in (false if in private message)
734* @param string &$message The post/private message
735* @param array &$attachments The attachments to parse for (inline) display. The attachments array will hold templated data after parsing.
736* @param array &$update_count The attachment counts to be updated - will be filled
737* @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.
738*/
739function parse_attachments($forum_id, &$message, &$attachments, &$update_count, $preview = false)
740{
741 if (!sizeof($attachments))
742 {
743 return;
744 }
745
746 global $template, $cache, $user;
747 global $extensions, $config, $phpbb_root_path, $phpEx;
748
749 //
750 $compiled_attachments = array();
751
752 if (!isset($template->filename['attachment_tpl']))
753 {
754 $template->set_filenames(array(
755 'attachment_tpl' => 'attachment.html')
756 );
757 }
758
759 if (empty($extensions) || !is_array($extensions))
760 {
761 $extensions = $cache->obtain_attach_extensions($forum_id);
762 }
763
764 // Look for missing attachment information...
765 $attach_ids = array();
766 foreach ($attachments as $pos => $attachment)
767 {
768 // If is_orphan is set, we need to retrieve the attachments again...
769 if (!isset($attachment['extension']) && !isset($attachment['physical_filename']))
770 {
771 $attach_ids[(int) $attachment['attach_id']] = $pos;
772 }
773 }
774
775 // Grab attachments (security precaution)
776 if (sizeof($attach_ids))
777 {
778 global $db;
779
780 $new_attachment_data = array();
781
782 $sql = 'SELECT *
783 FROM ' . ATTACHMENTS_TABLE . '
784 WHERE ' . $db->sql_in_set('attach_id', array_keys($attach_ids));
785 $result = $db->sql_query($sql);
786
787 while ($row = $db->sql_fetchrow($result))
788 {
789 if (!isset($attach_ids[$row['attach_id']]))
790 {
791 continue;
792 }
793
794 // If we preview attachments we will set some retrieved values here
795 if ($preview)
796 {
797 $row['attach_comment'] = $attachments[$attach_ids[$row['attach_id']]]['attach_comment'];
798 }
799
800 $new_attachment_data[$attach_ids[$row['attach_id']]] = $row;
801 }
802 $db->sql_freeresult($result);
803
804 $attachments = $new_attachment_data;
805 unset($new_attachment_data);
806 }
807
808 // Sort correctly
809 if ($config['display_order'])
810 {
811 // Ascending sort
812 krsort($attachments);
813 }
814 else
815 {
816 // Descending sort
817 ksort($attachments);
818 }
819
820 foreach ($attachments as $attachment)
821 {
822 if (!sizeof($attachment))
823 {
824 continue;
825 }
826
827 // We need to reset/empty the _file block var, because this function might be called more than once
828 $template->destroy_block_vars('_file');
829
830 $block_array = array();
831
832 // Some basics...
833 $attachment['extension'] = strtolower(trim($attachment['extension']));
834 $filename = $phpbb_root_path . $config['upload_path'] . '/' . basename($attachment['physical_filename']);
835 $thumbnail_filename = $phpbb_root_path . $config['upload_path'] . '/thumb_' . basename($attachment['physical_filename']);
836
837 $upload_icon = '';
838
839 if (isset($extensions[$attachment['extension']]))
840 {
841 if ($user->img('icon_topic_attach', '') && !$extensions[$attachment['extension']]['upload_icon'])
842 {
843 $upload_icon = $user->img('icon_topic_attach', '');
844 }
845 else if ($extensions[$attachment['extension']]['upload_icon'])
846 {
847 $upload_icon = '<img src="' . $phpbb_root_path . $config['upload_icons_path'] . '/' . trim($extensions[$attachment['extension']]['upload_icon']) . '" alt="" />';
848 }
849 }
850
851 $filesize = $attachment['filesize'];
852 $size_lang = ($filesize >= 1048576) ? $user->lang['MIB'] : (($filesize >= 1024) ? $user->lang['KIB'] : $user->lang['BYTES']);
853 $filesize = get_formatted_filesize($filesize, false);
854
855 $comment = bbcode_nl2br(censor_text($attachment['attach_comment']));
856
857 $block_array += array(
858 'UPLOAD_ICON' => $upload_icon,
859 'FILESIZE' => $filesize,
860 'SIZE_LANG' => $size_lang,
861 'DOWNLOAD_NAME' => basename($attachment['real_filename']),
862 'COMMENT' => $comment,
863 );
864
865 $denied = false;
866
867 if (!extension_allowed($forum_id, $attachment['extension'], $extensions))
868 {
869 $denied = true;
870
871 $block_array += array(
872 'S_DENIED' => true,
873 'DENIED_MESSAGE' => sprintf($user->lang['EXTENSION_DISABLED_AFTER_POSTING'], $attachment['extension'])
874 );
875 }
876
877 if (!$denied)
878 {
879 $l_downloaded_viewed = $download_link = '';
880 $display_cat = $extensions[$attachment['extension']]['display_cat'];
881
882 if ($display_cat == ATTACHMENT_CATEGORY_IMAGE)
883 {
884 if ($attachment['thumbnail'])
885 {
886 $display_cat = ATTACHMENT_CATEGORY_THUMB;
887 }
888 else
889 {
890 if ($config['img_display_inlined'])
891 {
892 if ($config['img_link_width'] || $config['img_link_height'])
893 {
894 $dimension = @getimagesize($filename);
895
896 // If the dimensions could not be determined or the image being 0x0 we display it as a link for safety purposes
897 if ($dimension === false || empty($dimension[0]) || empty($dimension[1]))
898 {
899 $display_cat = ATTACHMENT_CATEGORY_NONE;
900 }
901 else
902 {
903 $display_cat = ($dimension[0] <= $config['img_link_width'] && $dimension[1] <= $config['img_link_height']) ? ATTACHMENT_CATEGORY_IMAGE : ATTACHMENT_CATEGORY_NONE;
904 }
905 }
906 }
907 else
908 {
909 $display_cat = ATTACHMENT_CATEGORY_NONE;
910 }
911 }
912 }
913
914 // Make some descisions based on user options being set.
915 if (($display_cat == ATTACHMENT_CATEGORY_IMAGE || $display_cat == ATTACHMENT_CATEGORY_THUMB) && !$user->optionget('viewimg'))
916 {
917 $display_cat = ATTACHMENT_CATEGORY_NONE;
918 }
919
920 if ($display_cat == ATTACHMENT_CATEGORY_FLASH && !$user->optionget('viewflash'))
921 {
922 $display_cat = ATTACHMENT_CATEGORY_NONE;
923 }
924
925 $download_link = append_sid("{$phpbb_root_path}download/file.$phpEx", 'id=' . $attachment['attach_id']);
926
927 switch ($display_cat)
928 {
929 // Images
930 case ATTACHMENT_CATEGORY_IMAGE:
931 $l_downloaded_viewed = 'VIEWED_COUNT';
932 $inline_link = append_sid("{$phpbb_root_path}download/file.$phpEx", 'id=' . $attachment['attach_id']);
933 $download_link .= '&amp;mode=view';
934
935 $block_array += array(
936 'S_IMAGE' => true,
937 'U_INLINE_LINK' => $inline_link,
938 );
939
940 $update_count[] = $attachment['attach_id'];
941 break;
942
943 // Images, but display Thumbnail
944 case ATTACHMENT_CATEGORY_THUMB:
945 $l_downloaded_viewed = 'VIEWED_COUNT';
946 $thumbnail_link = append_sid("{$phpbb_root_path}download/file.$phpEx", 'id=' . $attachment['attach_id'] . '&amp;t=1');
947 $download_link .= '&amp;mode=view';
948
949 $block_array += array(
950 'S_THUMBNAIL' => true,
951 'THUMB_IMAGE' => $thumbnail_link,
952 );
953 break;
954
955 // Windows Media Streams
956 case ATTACHMENT_CATEGORY_WM:
957 $l_downloaded_viewed = 'VIEWED_COUNT';
958
959 // Giving the filename directly because within the wm object all variables are in local context making it impossible
960 // to validate against a valid session (all params can differ)
961 // $download_link = $filename;
962
963 $block_array += array(
964 'U_FORUM' => generate_board_url(),
965 'ATTACH_ID' => $attachment['attach_id'],
966 'S_WM_FILE' => true,
967 );
968
969 // Viewed/Heared File ... update the download count
970 $update_count[] = $attachment['attach_id'];
971 break;
972
973 // Real Media Streams
974 case ATTACHMENT_CATEGORY_RM:
975 case ATTACHMENT_CATEGORY_QUICKTIME:
976 $l_downloaded_viewed = 'VIEWED_COUNT';
977
978 $block_array += array(
979 'S_RM_FILE' => ($display_cat == ATTACHMENT_CATEGORY_RM) ? true : false,
980 'S_QUICKTIME_FILE' => ($display_cat == ATTACHMENT_CATEGORY_QUICKTIME) ? true : false,
981 'U_FORUM' => generate_board_url(),
982 'ATTACH_ID' => $attachment['attach_id'],
983 );
984
985 // Viewed/Heared File ... update the download count
986 $update_count[] = $attachment['attach_id'];
987 break;
988
989 // Macromedia Flash Files
990 case ATTACHMENT_CATEGORY_FLASH:
991 list($width, $height) = @getimagesize($filename);
992
993 $l_downloaded_viewed = 'VIEWED_COUNT';
994
995 $block_array += array(
996 'S_FLASH_FILE' => true,
997 'WIDTH' => $width,
998 'HEIGHT' => $height,
999 );
1000
1001 // Viewed/Heared File ... update the download count
1002 $update_count[] = $attachment['attach_id'];
1003 break;
1004
1005 default:
1006 $l_downloaded_viewed = 'DOWNLOAD_COUNT';
1007
1008 $block_array += array(
1009 'S_FILE' => true,
1010 );
1011 break;
1012 }
1013
1014 $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']));
1015
1016 $block_array += array(
1017 'U_DOWNLOAD_LINK' => $download_link,
1018 'L_DOWNLOAD_COUNT' => $l_download_count
1019 );
1020 }
1021
1022 $template->assign_block_vars('_file', $block_array);
1023
1024 $compiled_attachments[] = $template->assign_display('attachment_tpl');
1025 }
1026
1027 $attachments = $compiled_attachments;
1028 unset($compiled_attachments);
1029
1030 $tpl_size = sizeof($attachments);
1031
1032 $unset_tpl = array();
1033
1034 preg_match_all('#<!\-\- ia([0-9]+) \-\->(.*?)<!\-\- ia\1 \-\->#', $message, $matches, PREG_PATTERN_ORDER);
1035
1036 $replace = array();
1037 foreach ($matches[0] as $num => $capture)
1038 {
1039 // Flip index if we are displaying the reverse way
1040 $index = ($config['display_order']) ? ($tpl_size-($matches[1][$num] + 1)) : $matches[1][$num];
1041
1042 $replace['from'][] = $matches[0][$num];
1043 $replace['to'][] = (isset($attachments[$index])) ? $attachments[$index] : sprintf($user->lang['MISSING_INLINE_ATTACHMENT'], $matches[2][array_search($index, $matches[1])]);
1044
1045 $unset_tpl[] = $index;
1046 }
1047
1048 if (isset($replace['from']))
1049 {
1050 $message = str_replace($replace['from'], $replace['to'], $message);
1051 }
1052
1053 $unset_tpl = array_unique($unset_tpl);
1054
1055 // Needed to let not display the inlined attachments at the end of the post again
1056 foreach ($unset_tpl as $index)
1057 {
1058 unset($attachments[$index]);
1059 }
1060}
1061
1062/**
1063* Check if extension is allowed to be posted.
1064*
1065* @param mixed $forum_id The forum id to check or false if private message
1066* @param string $extension The extension to check, for example zip.
1067* @param array &$extensions The extension array holding the information from the cache (will be obtained if empty)
1068*
1069* @return bool False if the extension is not allowed to be posted, else true.
1070*/
1071function extension_allowed($forum_id, $extension, &$extensions)
1072{
1073 if (empty($extensions))
1074 {
1075 global $cache;
1076 $extensions = $cache->obtain_attach_extensions($forum_id);
1077 }
1078
1079 return (!isset($extensions['_allowed_'][$extension])) ? false : true;
1080}
1081
1082/**
1083* Truncates string while retaining special characters if going over the max length
1084* The default max length is 60 at the moment
1085* The maximum storage length is there to fit the string within the given length. The string may be further truncated due to html entities.
1086* For example: string given is 'a "quote"' (length: 9), would be a stored as 'a &quot;quote&quot;' (length: 19)
1087*
1088* @param string $string The text to truncate to the given length. String is specialchared.
1089* @param int $max_length Maximum length of string (multibyte character count as 1 char / Html entity count as 1 char)
1090* @param int $max_store_length Maximum character length of string (multibyte character count as 1 char / Html entity count as entity chars).
1091* @param bool $allow_reply Allow Re: in front of string
1092* @param string $append String to be appended
1093*/
1094function truncate_string($string, $max_length = 60, $max_store_length = 255, $allow_reply = true, $append = '')
1095{
1096 $chars = array();
1097
1098 $strip_reply = false;
1099 $stripped = false;
1100 if ($allow_reply && strpos($string, 'Re: ') === 0)
1101 {
1102 $strip_reply = true;
1103 $string = substr($string, 4);
1104 }
1105
1106 $_chars = utf8_str_split(htmlspecialchars_decode($string));
1107 $chars = array_map('utf8_htmlspecialchars', $_chars);
1108
1109 // Now check the length ;)
1110 if (sizeof($chars) > $max_length)
1111 {
1112 // Cut off the last elements from the array
1113 $string = implode('', array_slice($chars, 0, $max_length - utf8_strlen($append)));
1114 $stripped = true;
1115 }
1116
1117 // Due to specialchars, we may not be able to store the string...
1118 if (utf8_strlen($string) > $max_store_length)
1119 {
1120 // let's split again, we do not want half-baked strings where entities are split
1121 $_chars = utf8_str_split(htmlspecialchars_decode($string));
1122 $chars = array_map('utf8_htmlspecialchars', $_chars);
1123
1124 do
1125 {
1126 array_pop($chars);
1127 $string = implode('', $chars);
1128 }
1129 while (utf8_strlen($string) > $max_store_length || !sizeof($chars));
1130 }
1131
1132 if ($strip_reply)
1133 {
1134 $string = 'Re: ' . $string;
1135 }
1136
1137 if ($append != '' && $stripped)
1138 {
1139 $string = $string . $append;
1140 }
1141
1142 return $string;
1143}
1144
1145/**
1146* Get username details for placing into templates.
1147* This function caches all modes on first call, except for no_profile and anonymous user - determined by $user_id.
1148*
1149* @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)
1150* @param int $user_id The users id
1151* @param string $username The users name
1152* @param string $username_colour The users colour
1153* @param string $guest_username optional parameter to specify the guest username. It will be used in favor of the GUEST language variable then.
1154* @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}
1155*
1156* @return string A string consisting of what is wanted based on $mode.
1157* @author BartVB, Acyd Burn
1158*/
1159function get_username_string($mode, $user_id, $username, $username_colour = '', $guest_username = false, $custom_profile_url = false)
1160{
1161 static $_profile_cache;
1162 static $_base_profile_url;
1163
1164 $cache_key = $user_id;
1165
1166 // 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.
1167 if ($user_id && $user_id != ANONYMOUS && isset($_profile_cache[$cache_key][$mode]))
1168 {
1169 // If the mode is 'no_profile', we simply construct the TPL code due to calls to this mode being very very rare
1170 if ($mode == 'no_profile')
1171 {
1172 $tpl = (!$_profile_cache[$cache_key]['colour']) ? '{USERNAME}' : '<span style="color: {USERNAME_COLOUR};" class="username-coloured">{USERNAME}</span>';
1173 return str_replace(array('{USERNAME_COLOUR}', '{USERNAME}'), array($_profile_cache[$cache_key]['colour'], $_profile_cache[$cache_key]['username']), $tpl);
1174 }
1175
1176 return $_profile_cache[$cache_key][$mode];
1177 }
1178
1179 global $phpbb_root_path, $phpEx, $user, $auth;
1180
1181 $username_colour = ($username_colour) ? '#' . $username_colour : '';
1182
1183 if ($guest_username === false)
1184 {
1185 $username = ($username) ? $username : $user->lang['GUEST'];
1186 }
1187 else
1188 {
1189 $username = ($user_id && $user_id != ANONYMOUS) ? $username : ((!empty($guest_username)) ? $guest_username : $user->lang['GUEST']);
1190 }
1191
1192 // Build cache for all modes
1193 $_profile_cache[$cache_key]['colour'] = $username_colour;
1194 $_profile_cache[$cache_key]['username'] = $username;
1195 $_profile_cache[$cache_key]['no_profile'] = true;
1196
1197 // Profile url - only show if not anonymous and permission to view profile if registered user
1198 // For anonymous the link leads to a login page.
1199 if ($user_id && $user_id != ANONYMOUS && ($user->data['user_id'] == ANONYMOUS || $auth->acl_get('u_viewprofile')))
1200 {
1201 if (empty($_base_profile_url))
1202 {
1203 $_base_profile_url = append_sid("{$phpbb_root_path}memberlist.$phpEx", 'mode=viewprofile&amp;u={USER_ID}');
1204 }
1205
1206 $profile_url = ($custom_profile_url !== false) ? $custom_profile_url . '&amp;u=' . (int) $user_id : str_replace('={USER_ID}', '=' . (int) $user_id, $_base_profile_url);
1207 $tpl = (!$username_colour) ? '<a href="{PROFILE_URL}">{USERNAME}</a>' : '<a href="{PROFILE_URL}" style="color: {USERNAME_COLOUR};" class="username-coloured">{USERNAME}</a>';
1208 $_profile_cache[$cache_key]['full'] = str_replace(array('{PROFILE_URL}', '{USERNAME_COLOUR}', '{USERNAME}'), array($profile_url, $username_colour, $username), $tpl);
1209 }
1210 else
1211 {
1212 $tpl = (!$username_colour) ? '{USERNAME}' : '<span style="color: {USERNAME_COLOUR};" class="username-coloured">{USERNAME}</span>';
1213 $_profile_cache[$cache_key]['full'] = str_replace(array('{USERNAME_COLOUR}', '{USERNAME}'), array($username_colour, $username), $tpl);
1214 $profile_url = '';
1215 }
1216
1217 // Use the profile url from above
1218 $_profile_cache[$cache_key]['profile'] = $profile_url;
1219
1220 // If - by any chance - no_profile is called before any other mode, we need to do the calculation here
1221 if ($mode == 'no_profile')
1222 {
1223 $tpl = (!$_profile_cache[$cache_key]['colour']) ? '{USERNAME}' : '<span style="color: {USERNAME_COLOUR};" class="username-coloured">{USERNAME}</span>';
1224 return str_replace(array('{USERNAME_COLOUR}', '{USERNAME}'), array($_profile_cache[$cache_key]['colour'], $_profile_cache[$cache_key]['username']), $tpl);
1225 }
1226
1227 return $_profile_cache[$cache_key][$mode];
1228}
1229
1230/**
1231* @package phpBB3
1232*/
1233class bitfield
1234{
1235 var $data;
1236
1237 function bitfield($bitfield = '')
1238 {
1239 $this->data = base64_decode($bitfield);
1240 }
1241
1242 /**
1243 */
1244 function get($n)
1245 {
1246 // Get the ($n / 8)th char
1247 $byte = $n >> 3;
1248
1249 if (strlen($this->data) >= $byte + 1)
1250 {
1251 $c = $this->data[$byte];
1252
1253 // Lookup the ($n % 8)th bit of the byte
1254 $bit = 7 - ($n & 7);
1255 return (bool) (ord($c) & (1 << $bit));
1256 }
1257 else
1258 {
1259 return false;
1260 }
1261 }
1262
1263 function set($n)
1264 {
1265 $byte = $n >> 3;
1266 $bit = 7 - ($n & 7);
1267
1268 if (strlen($this->data) >= $byte + 1)
1269 {
1270 $this->data[$byte] = $this->data[$byte] | chr(1 << $bit);
1271 }
1272 else
1273 {
1274 $this->data .= str_repeat("\0", $byte - strlen($this->data));
1275 $this->data .= chr(1 << $bit);
1276 }
1277 }
1278
1279 function clear($n)
1280 {
1281 $byte = $n >> 3;
1282
1283 if (strlen($this->data) >= $byte + 1)
1284 {
1285 $bit = 7 - ($n & 7);
1286 $this->data[$byte] = $this->data[$byte] &~ chr(1 << $bit);
1287 }
1288 }
1289
1290 function get_blob()
1291 {
1292 return $this->data;
1293 }
1294
1295 function get_base64()
1296 {
1297 return base64_encode($this->data);
1298 }
1299
1300 function get_bin()
1301 {
1302 $bin = '';
1303 $len = strlen($this->data);
1304
1305 for ($i = 0; $i < $len; ++$i)
1306 {
1307 $bin .= str_pad(decbin(ord($this->data[$i])), 8, '0', STR_PAD_LEFT);
1308 }
1309
1310 return $bin;
1311 }
1312
1313 function get_all_set()
1314 {
1315 return array_keys(array_filter(str_split($this->get_bin())));
1316 }
1317
1318 function merge($bitfield)
1319 {
1320 $this->data = $this->data | $bitfield->get_blob();
1321 }
1322}
1323
1324?>
Note: See TracBrowser for help on using the repository browser.