PageRenderTime 51ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

/forum/includes/functions_content.php

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