PageRenderTime 60ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/sources/subs/Editor.subs.php

https://github.com/Arantor/Elkarte
PHP | 2235 lines | 1632 code | 275 blank | 328 comment | 287 complexity | 5b6e9b55f728e476a434456089b477fb MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-3.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * @name ElkArte Forum
  4. * @copyright ElkArte Forum contributors
  5. * @license BSD http://opensource.org/licenses/BSD-3-Clause
  6. *
  7. * This software is a derived product, based on:
  8. *
  9. * Simple Machines Forum (SMF)
  10. * copyright: 2011 Simple Machines (http://www.simplemachines.org)
  11. * license: BSD, See included LICENSE.TXT for terms and conditions.
  12. *
  13. * @version 1.0 Alpha
  14. *
  15. * This file contains those functions specific to the editing box and is
  16. * generally used for WYSIWYG type functionality.
  17. *
  18. */
  19. if (!defined('ELKARTE'))
  20. die('No access...');
  21. /**
  22. * Creates the javascript code for localization of the editor (SCEditor)
  23. */
  24. function action_loadlocale()
  25. {
  26. global $context, $txt, $editortxt, $modSettings;
  27. loadLanguage('Editor');
  28. $context['template_layers'] = array();
  29. // Lets make sure we aren't going to output anything nasty.
  30. @ob_end_clean();
  31. if (!empty($modSettings['enableCompressedOutput']))
  32. @ob_start('ob_gzhandler');
  33. else
  34. @ob_start();
  35. // If we don't have any locale better avoid broken js
  36. if (empty($txt['lang_locale']))
  37. die();
  38. $file_data = '(function ($) {
  39. \'use strict\';
  40. $.sceditor.locale[' . javaScriptEscape($txt['lang_locale']) . '] = {';
  41. foreach ($editortxt as $key => $val)
  42. $file_data .= '
  43. ' . javaScriptEscape($key) . ': ' . javaScriptEscape($val) . ',';
  44. $file_data .= '
  45. dateFormat: "day.month.year"
  46. }
  47. })(jQuery);';
  48. // Make sure they know what type of file we are.
  49. header('Content-Type: text/javascript');
  50. echo $file_data;
  51. obExit(false);
  52. }
  53. /**
  54. * Retrieves a list of message icons.
  55. * - Based on the settings, the array will either contain a list of default
  56. * message icons or a list of custom message icons retrieved from the database.
  57. * - The board_id is needed for the custom message icons (which can be set for
  58. * each board individually).
  59. *
  60. * @param int $board_id
  61. * @return array
  62. */
  63. function getMessageIcons($board_id)
  64. {
  65. global $modSettings, $context, $txt, $settings, $smcFunc;
  66. if (empty($modSettings['messageIcons_enable']))
  67. {
  68. loadLanguage('Post');
  69. $icons = array(
  70. array('value' => 'xx', 'name' => $txt['standard']),
  71. array('value' => 'thumbup', 'name' => $txt['thumbs_up']),
  72. array('value' => 'thumbdown', 'name' => $txt['thumbs_down']),
  73. array('value' => 'exclamation', 'name' => $txt['excamation_point']),
  74. array('value' => 'question', 'name' => $txt['question_mark']),
  75. array('value' => 'lamp', 'name' => $txt['lamp']),
  76. array('value' => 'smiley', 'name' => $txt['icon_smiley']),
  77. array('value' => 'angry', 'name' => $txt['icon_angry']),
  78. array('value' => 'cheesy', 'name' => $txt['icon_cheesy']),
  79. array('value' => 'grin', 'name' => $txt['icon_grin']),
  80. array('value' => 'sad', 'name' => $txt['icon_sad']),
  81. array('value' => 'wink', 'name' => $txt['icon_wink']),
  82. array('value' => 'poll', 'name' => $txt['icon_poll']),
  83. );
  84. foreach ($icons as $k => $dummy)
  85. {
  86. $icons[$k]['url'] = $settings['images_url'] . '/post/' . $dummy['value'] . '.png';
  87. $icons[$k]['is_last'] = false;
  88. }
  89. }
  90. // Otherwise load the icons, and check we give the right image too...
  91. else
  92. {
  93. if (($temp = cache_get_data('posting_icons-' . $board_id, 480)) == null)
  94. {
  95. $request = $smcFunc['db_query']('select_message_icons', '
  96. SELECT title, filename
  97. FROM {db_prefix}message_icons
  98. WHERE id_board IN (0, {int:board_id})',
  99. array(
  100. 'board_id' => $board_id,
  101. )
  102. );
  103. $icon_data = array();
  104. while ($row = $smcFunc['db_fetch_assoc']($request))
  105. $icon_data[] = $row;
  106. $smcFunc['db_free_result']($request);
  107. $icons = array();
  108. foreach ($icon_data as $icon)
  109. {
  110. $icons[$icon['filename']] = array(
  111. 'value' => $icon['filename'],
  112. 'name' => $icon['title'],
  113. 'url' => $settings[file_exists($settings['theme_dir'] . '/images/post/' . $icon['filename'] . '.png') ? 'images_url' : 'default_images_url'] . '/post/' . $icon['filename'] . '.png',
  114. 'is_last' => false,
  115. );
  116. }
  117. cache_put_data('posting_icons-' . $board_id, $icons, 480);
  118. }
  119. else
  120. $icons = $temp;
  121. }
  122. return array_values($icons);
  123. }
  124. /**
  125. * Creates a box that can be used for richedit stuff like BBC, Smileys etc.
  126. * @param array $editorOptions
  127. */
  128. function create_control_richedit($editorOptions)
  129. {
  130. global $txt, $modSettings, $options, $smcFunc;
  131. global $context, $settings, $user_info, $scripturl;
  132. // Load the Post language file... for the moment at least.
  133. loadLanguage('Post');
  134. if (!empty($context['drafts_save']) || !empty($context['drafts_pm_save']))
  135. loadLanguage('Drafts');
  136. // Every control must have a ID!
  137. assert(isset($editorOptions['id']));
  138. assert(isset($editorOptions['value']));
  139. // Is this the first richedit - if so we need to ensure things are initialised and that we load all of the needed files
  140. if (empty($context['controls']['richedit']))
  141. {
  142. // Some general stuff.
  143. $settings['smileys_url'] = $modSettings['smileys_url'] . '/' . $user_info['smiley_set'];
  144. if (!empty($context['drafts_autosave']) && !empty($options['drafts_autosave_enabled']))
  145. $context['drafts_autosave_frequency'] = empty($modSettings['drafts_autosave_frequency']) ? 30000 : $modSettings['drafts_autosave_frequency'] * 1000;
  146. // This really has some WYSIWYG stuff.
  147. loadTemplate('GenericControls', 'jquery.sceditor');
  148. // JS makes the editor go round
  149. loadJavascriptFile(array('jquery.sceditor.js', 'jquery.sceditor.bbcode.js', 'jquery.sceditor.elkarte.js', 'post.js'));
  150. addInlineJavascript('
  151. var smf_smileys_url = \'' . $settings['smileys_url'] . '\';
  152. var bbc_quote_from = \'' . addcslashes($txt['quote_from'], "'") . '\';
  153. var bbc_quote = \'' . addcslashes($txt['quote'], "'") . '\';
  154. var bbc_search_on = \'' . addcslashes($txt['search_on'], "'") . '\';');
  155. // editor language file
  156. if (!empty($txt['lang_locale']) && $txt['lang_locale'] != 'en_US')
  157. loadJavascriptFile($scripturl . '?action=loadeditorlocale', array(), 'sceditor_language');
  158. // Drafts?
  159. if ((!empty($context['drafts_save']) || !empty($context['drafts_pm_save'])) && !empty($context['drafts_autosave']) && !empty($options['drafts_autosave_enabled']))
  160. loadJavascriptFile('drafts.js');
  161. // Our not so concise shortcut line
  162. $context['shortcuts_text'] = $txt['shortcuts' . (!empty($context['drafts_save']) ? '_drafts' : '') . (isBrowser('is_firefox') ? '_firefox' : '')];
  163. // Spellcheck?
  164. $context['show_spellchecking'] = !empty($modSettings['enableSpellChecking']) && function_exists('pspell_new');
  165. if ($context['show_spellchecking'])
  166. {
  167. // Some hidden information is needed in order to make spell check work.
  168. if (!isset($_REQUEST['xml']))
  169. $context['insert_after_template'] .= '
  170. <form name="spell_form" id="spell_form" method="post" accept-charset="UTF-8" target="spellWindow" action="' . $scripturl . '?action=spellcheck">
  171. <input type="hidden" name="spellstring" value="" />
  172. <input type="hidden" name="fulleditor" value="" />
  173. </form>';
  174. loadJavascriptFile('spellcheck.js', array('defer' => true));
  175. }
  176. }
  177. // Start off the editor...
  178. $context['controls']['richedit'][$editorOptions['id']] = array(
  179. 'id' => $editorOptions['id'],
  180. 'value' => $editorOptions['value'],
  181. 'rich_value' => $editorOptions['value'], // 2.0 editor compatibility
  182. 'rich_active' => empty($modSettings['disable_wysiwyg']) && (!empty($options['wysiwyg_default']) || !empty($editorOptions['force_rich']) || !empty($_REQUEST[$editorOptions['id'] . '_mode'])),
  183. 'disable_smiley_box' => !empty($editorOptions['disable_smiley_box']),
  184. 'columns' => isset($editorOptions['columns']) ? $editorOptions['columns'] : 60,
  185. 'rows' => isset($editorOptions['rows']) ? $editorOptions['rows'] : 18,
  186. 'width' => isset($editorOptions['width']) ? $editorOptions['width'] : '70%',
  187. 'height' => isset($editorOptions['height']) ? $editorOptions['height'] : '250px',
  188. 'form' => isset($editorOptions['form']) ? $editorOptions['form'] : 'postmodify',
  189. 'bbc_level' => !empty($editorOptions['bbc_level']) ? $editorOptions['bbc_level'] : 'full',
  190. 'preview_type' => isset($editorOptions['preview_type']) ? (int) $editorOptions['preview_type'] : 1,
  191. 'labels' => !empty($editorOptions['labels']) ? $editorOptions['labels'] : array(),
  192. 'locale' => !empty($txt['lang_locale']) && substr($txt['lang_locale'], 0, 5) != 'en_US' ? $txt['lang_locale'] : '',
  193. );
  194. // Switch between default images and back... mostly in case you don't have an PersonalMessage template, but do have a Post template.
  195. if (isset($settings['use_default_images']) && $settings['use_default_images'] == 'defaults' && isset($settings['default_template']))
  196. {
  197. $temp1 = $settings['theme_url'];
  198. $settings['theme_url'] = $settings['default_theme_url'];
  199. $temp2 = $settings['images_url'];
  200. $settings['images_url'] = $settings['default_images_url'];
  201. $temp3 = $settings['theme_dir'];
  202. $settings['theme_dir'] = $settings['default_theme_dir'];
  203. }
  204. if (empty($context['bbc_tags']))
  205. {
  206. // The below array makes it dead easy to add images to this control. Add it to the array and everything else is done for you!
  207. /*
  208. array(
  209. 'image' => 'bold',
  210. 'code' => 'b',
  211. 'before' => '[b]',
  212. 'after' => '[/b]',
  213. 'description' => $txt['bold'],
  214. ),
  215. */
  216. $context['bbc_tags'] = array();
  217. $context['bbc_tags'][] = array(
  218. array(
  219. 'code' => 'bold',
  220. 'description' => $txt['bold'],
  221. ),
  222. array(
  223. 'code' => 'italic',
  224. 'description' => $txt['italic'],
  225. ),
  226. array(
  227. 'code' => 'underline',
  228. 'description' => $txt['underline']
  229. ),
  230. array(
  231. 'code' => 'strike',
  232. 'description' => $txt['strike']
  233. ),
  234. array(
  235. 'code' => 'superscript',
  236. 'description' => $txt['superscript']
  237. ),
  238. array(
  239. 'code' => 'subscript',
  240. 'description' => $txt['subscript']
  241. ),
  242. array(),
  243. array(
  244. 'code' => 'left',
  245. 'description' => $txt['left_align']
  246. ),
  247. array(
  248. 'code' => 'center',
  249. 'description' => $txt['center']
  250. ),
  251. array(
  252. 'code' => 'right',
  253. 'description' => $txt['right_align']
  254. ),
  255. array(
  256. 'code' => 'pre',
  257. 'description' => $txt['preformatted']
  258. ),
  259. array(
  260. 'code' => 'tt',
  261. 'description' => $txt['teletype']
  262. ),
  263. );
  264. $context['bbc_tags'][] = array(
  265. array(
  266. 'code' => 'bulletlist',
  267. 'description' => $txt['list_unordered']
  268. ),
  269. array(
  270. 'code' => 'orderedlist',
  271. 'description' => $txt['list_ordered']
  272. ),
  273. array(
  274. 'code' => 'horizontalrule',
  275. 'description' => $txt['horizontal_rule']
  276. ),
  277. array(),
  278. array(
  279. 'code' => 'table',
  280. 'description' => $txt['table']
  281. ),
  282. array(),
  283. array(
  284. 'code' => 'code',
  285. 'description' => $txt['bbc_code']
  286. ),
  287. array(
  288. 'code' => 'quote',
  289. 'description' => $txt['bbc_quote']
  290. ),
  291. array(),
  292. array(
  293. 'code' => 'image',
  294. 'description' => $txt['image']
  295. ),
  296. array(
  297. 'code' => 'link',
  298. 'description' => $txt['hyperlink']
  299. ),
  300. array(
  301. 'code' => 'email',
  302. 'description' => $txt['insert_email']
  303. ),
  304. array(
  305. 'code' => 'ftp',
  306. 'description' => $txt['ftp']
  307. ),
  308. array(
  309. 'code' => 'flash',
  310. 'description' => $txt['flash']
  311. ),
  312. array(),
  313. array(
  314. 'code' => 'glow',
  315. 'description' => $txt['glow']
  316. ),
  317. array(
  318. 'code' => 'shadow',
  319. 'description' => $txt['shadow']
  320. ),
  321. array(
  322. 'code' => 'move',
  323. 'description' => $txt['marquee']
  324. ),
  325. );
  326. // Allow mods to modify BBC buttons.
  327. // Note: passing the array here is not necessary and is deprecated, but it is kept for backward compatibility with 2.0
  328. call_integration_hook('integrate_bbc_buttons', array(&$context['bbc_tags']));
  329. // Show the toggle?
  330. if (empty($modSettings['disable_wysiwyg']))
  331. {
  332. $context['bbc_tags'][count($context['bbc_tags']) - 1][] = array();
  333. $context['bbc_tags'][count($context['bbc_tags']) - 1][] = array(
  334. 'code' => 'unformat',
  335. 'description' => $txt['unformat_text'],
  336. );
  337. $context['bbc_tags'][count($context['bbc_tags']) - 1][] = array(
  338. 'code' => 'toggle',
  339. 'description' => $txt['toggle_view'],
  340. );
  341. }
  342. // Generate a list of buttons that shouldn't be shown - this should be the fastest way to do this.
  343. $disabled_tags = array();
  344. if (!empty($modSettings['disabledBBC']))
  345. $disabled_tags = explode(',', $modSettings['disabledBBC']);
  346. if (empty($modSettings['enableEmbeddedFlash']))
  347. $disabled_tags[] = 'flash';
  348. foreach ($disabled_tags as $tag)
  349. {
  350. if ($tag === 'list')
  351. {
  352. $context['disabled_tags']['bulletlist'] = true;
  353. $context['disabled_tags']['orderedlist'] = true;
  354. }
  355. elseif ($tag === 'b')
  356. $context['disabled_tags']['bold'] = true;
  357. elseif ($tag === 'i')
  358. $context['disabled_tags']['italic'] = true;
  359. elseif ($tag === 'u')
  360. $context['disabled_tags']['underline'] = true;
  361. elseif ($tag === 's')
  362. $context['disabled_tags']['strike'] = true;
  363. elseif ($tag === 'img')
  364. $context['disabled_tags']['image'] = true;
  365. elseif ($tag === 'url')
  366. $context['disabled_tags']['link'] = true;
  367. elseif ($tag === 'sup')
  368. $context['disabled_tags']['superscript'] = true;
  369. elseif ($tag === 'sub')
  370. $context['disabled_tags']['subscript'] = true;
  371. elseif ($tag === 'hr')
  372. $context['disabled_tags']['horizontalrule'] = true;
  373. $context['disabled_tags'][trim($tag)] = true;
  374. }
  375. $bbcodes_styles = '';
  376. $context['bbcodes_handlers'] = '';
  377. $context['bbc_toolbar'] = array();
  378. // Build our toolbar, taking in to account any custom bbc codes from integration
  379. foreach ($context['bbc_tags'] as $row => $tagRow)
  380. {
  381. if (!isset($context['bbc_toolbar'][$row]))
  382. $context['bbc_toolbar'][$row] = array();
  383. $tagsRow = array();
  384. foreach ($tagRow as $tag)
  385. {
  386. if (!empty($tag))
  387. {
  388. if (empty($context['disabled_tags'][$tag['code']]))
  389. {
  390. $tagsRow[] = $tag['code'];
  391. // Special Image
  392. if (isset($tag['image']))
  393. $bbcodes_styles .= '
  394. .sceditor-button-' . $tag['code'] . ' div {
  395. background: url(\'' . $settings['default_theme_url'] . '/images/bbc/' . $tag['image'] . '.png\');
  396. }';
  397. // Special commands
  398. if (isset($tag['before']))
  399. {
  400. $context['bbcodes_handlers'] = '
  401. $.sceditor.command.set(
  402. ' . javaScriptEscape($tag['code']) . ', {
  403. exec: function () {
  404. this.wysiwygEditorInsertHtml(' . javaScriptEscape($tag['before']) . (isset($tag['after']) ? ', ' . javaScriptEscape($tag['after']) : '') . ');
  405. },
  406. tooltip:' . javaScriptEscape($tag['description']) . ',
  407. txtExec: [' . javaScriptEscape($tag['before']) . (isset($tag['after']) ? ', ' . javaScriptEscape($tag['after']) : '') . '],
  408. }
  409. );';
  410. }
  411. }
  412. }
  413. else
  414. {
  415. $context['bbc_toolbar'][$row][] = implode(',', $tagsRow);
  416. $tagsRow = array();
  417. }
  418. }
  419. if ($row === 0)
  420. {
  421. $context['bbc_toolbar'][$row][] = implode(',', $tagsRow);
  422. $tagsRow = array();
  423. if (!isset($context['disabled_tags']['font']))
  424. $tagsRow[] = 'font';
  425. if (!isset($context['disabled_tags']['size']))
  426. $tagsRow[] = 'size';
  427. if (!isset($context['disabled_tags']['color']))
  428. $tagsRow[] = 'color';
  429. }
  430. elseif ($row === 1 && empty($modSettings['disable_wysiwyg']))
  431. {
  432. $tmp = array();
  433. $tagsRow[] = 'removeformat';
  434. $tagsRow[] = 'source';
  435. if (!empty($tmp))
  436. $tagsRow[] = '|' . implode(',', $tmp);
  437. }
  438. if (!empty($tagsRow))
  439. $context['bbc_toolbar'][$row][] = implode(',', $tagsRow);
  440. }
  441. if (!empty($bbcodes_styles))
  442. $context['html_headers'] .= '
  443. <style type="text/css">' . $bbcodes_styles . '
  444. </style>';
  445. }
  446. // Initialize smiley array... if not loaded before.
  447. if (empty($context['smileys']) && empty($editorOptions['disable_smiley_box']))
  448. {
  449. $context['smileys'] = array(
  450. 'postform' => array(),
  451. 'popup' => array(),
  452. );
  453. // Load smileys - don't bother to run a query if we're not using the database's ones anyhow.
  454. if (empty($modSettings['smiley_enable']) && $user_info['smiley_set'] != 'none')
  455. $context['smileys']['postform'][] = array(
  456. 'smileys' => array(
  457. array(
  458. 'code' => ':)',
  459. 'filename' => 'smiley.gif',
  460. 'description' => $txt['icon_smiley'],
  461. ),
  462. array(
  463. 'code' => ';)',
  464. 'filename' => 'wink.gif',
  465. 'description' => $txt['icon_wink'],
  466. ),
  467. array(
  468. 'code' => ':D',
  469. 'filename' => 'cheesy.gif',
  470. 'description' => $txt['icon_cheesy'],
  471. ),
  472. array(
  473. 'code' => ';D',
  474. 'filename' => 'grin.gif',
  475. 'description' => $txt['icon_grin']
  476. ),
  477. array(
  478. 'code' => '>:(',
  479. 'filename' => 'angry.gif',
  480. 'description' => $txt['icon_angry'],
  481. ),
  482. array(
  483. 'code' => ':(',
  484. 'filename' => 'sad.gif',
  485. 'description' => $txt['icon_sad'],
  486. ),
  487. array(
  488. 'code' => ':o',
  489. 'filename' => 'shocked.gif',
  490. 'description' => $txt['icon_shocked'],
  491. ),
  492. array(
  493. 'code' => '8)',
  494. 'filename' => 'cool.gif',
  495. 'description' => $txt['icon_cool'],
  496. ),
  497. array(
  498. 'code' => '???',
  499. 'filename' => 'huh.gif',
  500. 'description' => $txt['icon_huh'],
  501. ),
  502. array(
  503. 'code' => '::)',
  504. 'filename' => 'rolleyes.gif',
  505. 'description' => $txt['icon_rolleyes'],
  506. ),
  507. array(
  508. 'code' => ':P',
  509. 'filename' => 'tongue.gif',
  510. 'description' => $txt['icon_tongue'],
  511. ),
  512. array(
  513. 'code' => ':-[',
  514. 'filename' => 'embarrassed.gif',
  515. 'description' => $txt['icon_embarrassed'],
  516. ),
  517. array(
  518. 'code' => ':-X',
  519. 'filename' => 'lipsrsealed.gif',
  520. 'description' => $txt['icon_lips'],
  521. ),
  522. array(
  523. 'code' => ':-\\',
  524. 'filename' => 'undecided.gif',
  525. 'description' => $txt['icon_undecided'],
  526. ),
  527. array(
  528. 'code' => ':-*',
  529. 'filename' => 'kiss.gif',
  530. 'description' => $txt['icon_kiss'],
  531. ),
  532. array(
  533. 'code' => ':\'(',
  534. 'filename' => 'cry.gif',
  535. 'description' => $txt['icon_cry'],
  536. 'isLast' => true,
  537. ),
  538. ),
  539. 'isLast' => true,
  540. );
  541. elseif ($user_info['smiley_set'] != 'none')
  542. {
  543. if (($temp = cache_get_data('posting_smileys', 480)) == null)
  544. {
  545. $request = $smcFunc['db_query']('', '
  546. SELECT code, filename, description, smiley_row, hidden
  547. FROM {db_prefix}smileys
  548. WHERE hidden IN (0, 2)
  549. ORDER BY smiley_row, smiley_order',
  550. array(
  551. )
  552. );
  553. while ($row = $smcFunc['db_fetch_assoc']($request))
  554. {
  555. $row['filename'] = htmlspecialchars($row['filename']);
  556. $row['description'] = htmlspecialchars($row['description']);
  557. $context['smileys'][empty($row['hidden']) ? 'postform' : 'popup'][$row['smiley_row']]['smileys'][] = $row;
  558. }
  559. $smcFunc['db_free_result']($request);
  560. foreach ($context['smileys'] as $section => $smileyRows)
  561. {
  562. foreach ($smileyRows as $rowIndex => $smileys)
  563. $context['smileys'][$section][$rowIndex]['smileys'][count($smileys['smileys']) - 1]['isLast'] = true;
  564. if (!empty($smileyRows))
  565. $context['smileys'][$section][count($smileyRows) - 1]['isLast'] = true;
  566. }
  567. cache_put_data('posting_smileys', $context['smileys'], 480);
  568. }
  569. else
  570. $context['smileys'] = $temp;
  571. }
  572. }
  573. // Set a flag so the sub template knows what to do...
  574. $context['show_bbc'] = !empty($modSettings['enableBBC']) && !empty($settings['show_bbc']);
  575. // Switch the URLs back... now we're back to whatever the main sub template is. (like folder in PersonalMessage.)
  576. if (isset($settings['use_default_images']) && $settings['use_default_images'] == 'defaults' && isset($settings['default_template']))
  577. {
  578. $settings['theme_url'] = $temp1;
  579. $settings['images_url'] = $temp2;
  580. $settings['theme_dir'] = $temp3;
  581. }
  582. if (!empty($editorOptions['live_errors']))
  583. {
  584. loadLanguage('Errors');
  585. addInlineJavascript('
  586. error_txts[\'no_subject\'] = ' . JavaScriptEscape($txt['error_no_subject']) . ';
  587. error_txts[\'no_message\'] = ' . JavaScriptEscape($txt['error_no_message']) . ';
  588. var subject_err = new errorbox_handler({
  589. self: \'subject_err\',
  590. error_box_id: \'post_error\',
  591. error_checks: [{
  592. code: \'no_subject\',
  593. function: function(box_value) {
  594. if (box_value.length == 0)
  595. return true;
  596. else
  597. return false;
  598. }
  599. }],
  600. check_id: "post_subject"
  601. });
  602. var body_err = new errorbox_handler({
  603. self: \'body_err\',
  604. error_box_id: \'post_error\',
  605. error_checks: [{
  606. code: \'no_message\',
  607. function: function(box_value) {
  608. if (box_value.length == 0)
  609. return true;
  610. else
  611. return false;
  612. }
  613. }],
  614. editor_id: \'' . $editorOptions['id'] . '\',
  615. editor: ' . JavaScriptEscape('
  616. function () {
  617. var editor = $("#' . $editorOptions['id'] . '").data("sceditor");
  618. var editor_val = \'\';
  619. if(editor.inSourceMode())
  620. editor_val = editor.getText();
  621. else
  622. editor_val = editor.getText();
  623. return editor_val;
  624. };') . '
  625. });', true);
  626. }
  627. }
  628. /**
  629. * Create a anti-bot verification control?
  630. * @param array &$verificationOptions
  631. * @param bool $do_test = false
  632. */
  633. function create_control_verification(&$verificationOptions, $do_test = false)
  634. {
  635. global $txt, $modSettings, $options, $smcFunc;
  636. global $context, $settings, $user_info, $scripturl;
  637. // First verification means we need to set up some bits...
  638. if (empty($context['controls']['verification']))
  639. {
  640. // The template
  641. loadTemplate('GenericControls');
  642. // Some javascript ma'am?
  643. if (!empty($verificationOptions['override_visual']) || (!empty($modSettings['visual_verification_type']) && !isset($verificationOptions['override_visual'])))
  644. loadJavascriptFile('captcha.js');
  645. $context['use_graphic_library'] = in_array('gd', get_loaded_extensions());
  646. // Skip I, J, L, O, Q, S and Z.
  647. $context['standard_captcha_range'] = array_merge(range('A', 'H'), array('K', 'M', 'N', 'P', 'R'), range('T', 'Y'));
  648. }
  649. // Always have an ID.
  650. assert(isset($verificationOptions['id']));
  651. $isNew = !isset($context['controls']['verification'][$verificationOptions['id']]);
  652. // Log this into our collection.
  653. if ($isNew)
  654. $context['controls']['verification'][$verificationOptions['id']] = array(
  655. 'id' => $verificationOptions['id'],
  656. 'show_visual' => !empty($verificationOptions['override_visual']) || (!empty($modSettings['visual_verification_type']) && !isset($verificationOptions['override_visual'])),
  657. 'number_questions' => isset($verificationOptions['override_qs']) ? $verificationOptions['override_qs'] : (!empty($modSettings['qa_verification_number']) ? $modSettings['qa_verification_number'] : 0),
  658. 'max_errors' => isset($verificationOptions['max_errors']) ? $verificationOptions['max_errors'] : 3,
  659. 'image_href' => $scripturl . '?action=verificationcode;vid=' . $verificationOptions['id'] . ';rand=' . md5(mt_rand()),
  660. 'text_value' => '',
  661. 'questions' => array(),
  662. );
  663. $thisVerification = &$context['controls']['verification'][$verificationOptions['id']];
  664. // Add javascript for the object.
  665. if ($context['controls']['verification'][$verificationOptions['id']]['show_visual'])
  666. addInlineJavascript('
  667. var verification' . $verificationOptions['id'] . 'Handle = new smfCaptcha("' . $thisVerification['image_href'] . '", "' . $verificationOptions['id'] . '", ' . ($context['use_graphic_library'] ? 1 : 0) . ');', true);
  668. // Is there actually going to be anything?
  669. if (empty($thisVerification['show_visual']) && empty($thisVerification['number_questions']))
  670. return false;
  671. elseif (!$isNew && !$do_test)
  672. return true;
  673. // If we want questions do we have a cache of all the IDs?
  674. if (!empty($thisVerification['number_questions']) && empty($modSettings['question_id_cache']))
  675. {
  676. if (($modSettings['question_id_cache'] = cache_get_data('verificationQuestionIds', 300)) == null)
  677. {
  678. $request = $smcFunc['db_query']('', '
  679. SELECT id_comment
  680. FROM {db_prefix}log_comments
  681. WHERE comment_type = {string:ver_test}',
  682. array(
  683. 'ver_test' => 'ver_test',
  684. )
  685. );
  686. $modSettings['question_id_cache'] = array();
  687. while ($row = $smcFunc['db_fetch_assoc']($request))
  688. $modSettings['question_id_cache'][] = $row['id_comment'];
  689. $smcFunc['db_free_result']($request);
  690. if (!empty($modSettings['cache_enable']))
  691. cache_put_data('verificationQuestionIds', $modSettings['question_id_cache'], 300);
  692. }
  693. }
  694. if (!isset($_SESSION[$verificationOptions['id'] . '_vv']))
  695. $_SESSION[$verificationOptions['id'] . '_vv'] = array();
  696. // Do we need to refresh the verification?
  697. if (!$do_test && (!empty($_SESSION[$verificationOptions['id'] . '_vv']['did_pass']) || empty($_SESSION[$verificationOptions['id'] . '_vv']['count']) || $_SESSION[$verificationOptions['id'] . '_vv']['count'] > 3) && empty($verificationOptions['dont_refresh']))
  698. $force_refresh = true;
  699. else
  700. $force_refresh = false;
  701. // This can also force a fresh, although unlikely.
  702. if (($thisVerification['show_visual'] && empty($_SESSION[$verificationOptions['id'] . '_vv']['code'])) || ($thisVerification['number_questions'] && empty($_SESSION[$verificationOptions['id'] . '_vv']['q'])))
  703. $force_refresh = true;
  704. $verification_errors = error_context::context($verificationOptions['id']);
  705. // Start with any testing.
  706. if ($do_test)
  707. {
  708. // This cannot happen!
  709. if (!isset($_SESSION[$verificationOptions['id'] . '_vv']['count']))
  710. fatal_lang_error('no_access', false);
  711. // ... nor this!
  712. if ($thisVerification['number_questions'] && (!isset($_SESSION[$verificationOptions['id'] . '_vv']['q']) || !isset($_REQUEST[$verificationOptions['id'] . '_vv']['q'])))
  713. fatal_lang_error('no_access', false);
  714. if ($thisVerification['show_visual'] && (empty($_REQUEST[$verificationOptions['id'] . '_vv']['code']) || empty($_SESSION[$verificationOptions['id'] . '_vv']['code']) || strtoupper($_REQUEST[$verificationOptions['id'] . '_vv']['code']) !== $_SESSION[$verificationOptions['id'] . '_vv']['code']))
  715. $verification_errors->addError('wrong_verification_code');
  716. if ($thisVerification['number_questions'])
  717. {
  718. // Get the answers and see if they are all right!
  719. $request = $smcFunc['db_query']('', '
  720. SELECT id_comment, recipient_name AS answer
  721. FROM {db_prefix}log_comments
  722. WHERE comment_type = {string:ver_test}
  723. AND id_comment IN ({array_int:comment_ids})',
  724. array(
  725. 'ver_test' => 'ver_test',
  726. 'comment_ids' => $_SESSION[$verificationOptions['id'] . '_vv']['q'],
  727. )
  728. );
  729. $incorrectQuestions = array();
  730. while ($row = $smcFunc['db_fetch_assoc']($request))
  731. {
  732. if (!isset($_REQUEST[$verificationOptions['id'] . '_vv']['q'][$row['id_comment']]) || trim($_REQUEST[$verificationOptions['id'] . '_vv']['q'][$row['id_comment']]) == '' || trim($smcFunc['htmlspecialchars'](strtolower($_REQUEST[$verificationOptions['id'] . '_vv']['q'][$row['id_comment']]))) != strtolower($row['answer']))
  733. $incorrectQuestions[] = $row['id_comment'];
  734. }
  735. $smcFunc['db_free_result']($request);
  736. if (!empty($incorrectQuestions))
  737. $verification_errors->addError('wrong_verification_answer');
  738. }
  739. }
  740. // Any errors means we refresh potentially.
  741. if ($verification_errors->hasError(array('wrong_verification_code', 'wrong_verification_answer')))
  742. {
  743. if (empty($_SESSION[$verificationOptions['id'] . '_vv']['errors']))
  744. $_SESSION[$verificationOptions['id'] . '_vv']['errors'] = 0;
  745. // Too many errors?
  746. elseif ($_SESSION[$verificationOptions['id'] . '_vv']['errors'] > $thisVerification['max_errors'])
  747. $force_refresh = true;
  748. // Keep a track of these.
  749. $_SESSION[$verificationOptions['id'] . '_vv']['errors']++;
  750. }
  751. // Are we refreshing then?
  752. if ($force_refresh)
  753. {
  754. // Assume nothing went before.
  755. $_SESSION[$verificationOptions['id'] . '_vv']['count'] = 0;
  756. $_SESSION[$verificationOptions['id'] . '_vv']['errors'] = 0;
  757. $_SESSION[$verificationOptions['id'] . '_vv']['did_pass'] = false;
  758. $_SESSION[$verificationOptions['id'] . '_vv']['q'] = array();
  759. $_SESSION[$verificationOptions['id'] . '_vv']['code'] = '';
  760. // Generating a new image.
  761. if ($thisVerification['show_visual'])
  762. {
  763. // Are we overriding the range?
  764. $character_range = !empty($verificationOptions['override_range']) ? $verificationOptions['override_range'] : $context['standard_captcha_range'];
  765. for ($i = 0; $i < 6; $i++)
  766. $_SESSION[$verificationOptions['id'] . '_vv']['code'] .= $character_range[array_rand($character_range)];
  767. }
  768. // Getting some new questions?
  769. if ($thisVerification['number_questions'])
  770. {
  771. // Pick some random IDs
  772. $questionIDs = array();
  773. if ($thisVerification['number_questions'] == 1)
  774. $questionIDs[] = $modSettings['question_id_cache'][array_rand($modSettings['question_id_cache'], $thisVerification['number_questions'])];
  775. else
  776. foreach (array_rand($modSettings['question_id_cache'], $thisVerification['number_questions']) as $index)
  777. $questionIDs[] = $modSettings['question_id_cache'][$index];
  778. }
  779. }
  780. else
  781. {
  782. // Same questions as before.
  783. $questionIDs = !empty($_SESSION[$verificationOptions['id'] . '_vv']['q']) ? $_SESSION[$verificationOptions['id'] . '_vv']['q'] : array();
  784. $thisVerification['text_value'] = !empty($_REQUEST[$verificationOptions['id'] . '_vv']['code']) ? $smcFunc['htmlspecialchars']($_REQUEST[$verificationOptions['id'] . '_vv']['code']) : '';
  785. }
  786. // Have we got some questions to load?
  787. if (!empty($questionIDs))
  788. {
  789. $request = $smcFunc['db_query']('', '
  790. SELECT id_comment, body AS question
  791. FROM {db_prefix}log_comments
  792. WHERE comment_type = {string:ver_test}
  793. AND id_comment IN ({array_int:comment_ids})',
  794. array(
  795. 'ver_test' => 'ver_test',
  796. 'comment_ids' => $questionIDs,
  797. )
  798. );
  799. $_SESSION[$verificationOptions['id'] . '_vv']['q'] = array();
  800. while ($row = $smcFunc['db_fetch_assoc']($request))
  801. {
  802. $thisVerification['questions'][] = array(
  803. 'id' => $row['id_comment'],
  804. 'q' => parse_bbc($row['question']),
  805. 'is_error' => !empty($incorrectQuestions) && in_array($row['id_comment'], $incorrectQuestions),
  806. // Remember a previous submission?
  807. 'a' => isset($_REQUEST[$verificationOptions['id'] . '_vv'], $_REQUEST[$verificationOptions['id'] . '_vv']['q'], $_REQUEST[$verificationOptions['id'] . '_vv']['q'][$row['id_comment']]) ? $smcFunc['htmlspecialchars']($_REQUEST[$verificationOptions['id'] . '_vv']['q'][$row['id_comment']]) : '',
  808. );
  809. $_SESSION[$verificationOptions['id'] . '_vv']['q'][] = $row['id_comment'];
  810. }
  811. $smcFunc['db_free_result']($request);
  812. }
  813. $_SESSION[$verificationOptions['id'] . '_vv']['count'] = empty($_SESSION[$verificationOptions['id'] . '_vv']['count']) ? 1 : $_SESSION[$verificationOptions['id'] . '_vv']['count'] + 1;
  814. // Return errors if we have them.
  815. if ($verification_errors->hasErrors())
  816. return true;
  817. // If we had a test that one, make a note.
  818. elseif ($do_test)
  819. $_SESSION[$verificationOptions['id'] . '_vv']['did_pass'] = true;
  820. // Say that everything went well chaps.
  821. return true;
  822. }
  823. /**
  824. * Compatibility function - used in 1.1 for showing a post box.
  825. *
  826. * @param string $msg
  827. * @return string
  828. */
  829. function theme_postbox($msg)
  830. {
  831. global $context;
  832. return template_control_richedit($context['post_box_name']);
  833. }
  834. /**
  835. * !!!Compatibility!!!
  836. * Since we changed the editor we don't need it any more, but let's keep it if any mod wants to use it
  837. * Convert only the BBC that can be edited in HTML mode for the editor.
  838. *
  839. * @param string $text
  840. * @param boolean $compat_mode if true will convert the text, otherwise not (default false)
  841. * @return string
  842. */
  843. function bbc_to_html($text, $compat_mode = false)
  844. {
  845. global $modSettings, $smcFunc;
  846. if (!$compat_mode)
  847. return $text;
  848. // Turn line breaks back into br's.
  849. $text = strtr($text, array("\r" => '', "\n" => '<br />'));
  850. // Prevent conversion of all bbcode inside these bbcodes.
  851. // @todo Tie in with bbc permissions ?
  852. foreach (array('code', 'php', 'nobbc') as $code)
  853. {
  854. if (strpos($text, '['. $code) !== false)
  855. {
  856. $parts = preg_split('~(\[/' . $code . '\]|\[' . $code . '(?:=[^\]]+)?\])~i', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
  857. // Only mess with stuff inside tags.
  858. for ($i = 0, $n = count($parts); $i < $n; $i++)
  859. {
  860. // Value of 2 means we're inside the tag.
  861. if ($i % 4 == 2)
  862. $parts[$i] = strtr($parts[$i], array('[' => '&#91;', ']' => '&#93;', "'" => "'"));
  863. }
  864. // Put our humpty dumpty message back together again.
  865. $text = implode('', $parts);
  866. }
  867. }
  868. // What tags do we allow?
  869. $allowed_tags = array('b', 'u', 'i', 's', 'hr', 'list', 'li', 'font', 'size', 'color', 'img', 'left', 'center', 'right', 'url', 'email', 'ftp', 'sub', 'sup');
  870. $text = parse_bbc($text, true, '', $allowed_tags);
  871. // Fix for having a line break then a thingy.
  872. $text = strtr($text, array('<br /><div' => '<div', "\n" => '', "\r" => ''));
  873. // Note that IE doesn't understand spans really - make them something "legacy"
  874. $working_html = array(
  875. '~<del>(.+?)</del>~i' => '<strike>$1</strike>',
  876. '~<span\sclass="bbc_u">(.+?)</span>~i' => '<u>$1</u>',
  877. '~<span\sstyle="color:\s*([#\d\w]+);" class="bbc_color">(.+?)</span>~i' => '<font color="$1">$2</font>',
  878. '~<span\sstyle="font-family:\s*([#\d\w\s]+);" class="bbc_font">(.+?)</span>~i' => '<font face="$1">$2</font>',
  879. '~<div\sstyle="text-align:\s*(left|right);">(.+?)</div>~i' => '<p align="$1">$2</p>',
  880. );
  881. $text = preg_replace(array_keys($working_html), array_values($working_html), $text);
  882. // Parse unique ID's and disable javascript into the smileys - using the double space.
  883. $i = 1;
  884. $text = preg_replace('~(?:\s|&nbsp;)?<(img\ssrc="' . preg_quote($modSettings['smileys_url'], '~') . '/[^<>]+?/([^<>]+?)"\s*)[^<>]*?class="smiley" />~e', '\'<\' . ' . 'stripslashes(\'$1\') . \'alt="" title="" onresizestart="return false;" id="smiley_\' . ' . "\$" . 'i++ . \'_$2" style="padding: 0 3px 0 3px;" />\'', $text);
  885. return $text;
  886. }
  887. /**
  888. * !!!Compatibility!!!
  889. *
  890. * This is not directly required any longer, but left for mod usage
  891. *
  892. * The harder one - wysiwyg to BBC!
  893. *
  894. * @param string $text
  895. * @return string
  896. */
  897. function html_to_bbc($text)
  898. {
  899. global $modSettings, $smcFunc, $scripturl, $context;
  900. // Replace newlines with spaces, as that's how browsers usually interpret them.
  901. $text = preg_replace("~\s*[\r\n]+\s*~", ' ', $text);
  902. // Though some of us love paragraphs, the parser will do better with breaks.
  903. $text = preg_replace('~</p>\s*?<p~i', '</p><br /><p', $text);
  904. $text = preg_replace('~</p>\s*(?!<)~i', '</p><br />', $text);
  905. // Safari/webkit wraps lines in Wysiwyg in <div>'s.
  906. if (isBrowser('webkit'))
  907. $text = preg_replace(array('~<div(?:\s(?:[^<>]*?))?' . '>~i', '</div>'), array('<br />', ''), $text);
  908. // If there's a trailing break get rid of it - Firefox tends to add one.
  909. $text = preg_replace('~<br\s?/?' . '>$~i', '', $text);
  910. // Remove any formatting within code tags.
  911. if (strpos($text, '[code') !== false)
  912. {
  913. $text = preg_replace('~<br\s?/?' . '>~i', '#smf_br_spec_grudge_cool!#', $text);
  914. $parts = preg_split('~(\[/code\]|\[code(?:=[^\]]+)?\])~i', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
  915. // Only mess with stuff outside [code] tags.
  916. for ($i = 0, $n = count($parts); $i < $n; $i++)
  917. {
  918. // Value of 2 means we're inside the tag.
  919. if ($i % 4 == 2)
  920. $parts[$i] = strip_tags($parts[$i]);
  921. }
  922. $text = strtr(implode('', $parts), array('#smf_br_spec_grudge_cool!#' => '<br />'));
  923. }
  924. // Remove scripts, style and comment blocks.
  925. $text = preg_replace('~<script[^>]*[^/]?' . '>.*?</script>~i', '', $text);
  926. $text = preg_replace('~<style[^>]*[^/]?' . '>.*?</style>~i', '', $text);
  927. $text = preg_replace('~\\<\\!--.*?-->~i', '', $text);
  928. $text = preg_replace('~\\<\\!\\[CDATA\\[.*?\\]\\]\\>~i', '', $text);
  929. // Do the smileys ultra first!
  930. preg_match_all('~<img\s+[^<>]*?id="*smiley_\d+_([^<>]+?)[\s"/>]\s*[^<>]*?/*>(?:\s)?~i', $text, $matches);
  931. if (!empty($matches[0]))
  932. {
  933. // Easy if it's not custom.
  934. if (empty($modSettings['smiley_enable']))
  935. {
  936. $smileysfrom = array('>:D', ':D', '::)', '>:(', ':)', ';)', ';D', ':(', ':o', '8)', ':P', '???', ':-[', ':-X', ':-*', ':\'(', ':-\\', '^-^', 'O0', 'C:-)', '0:)');
  937. $smileysto = array('evil.gif', 'cheesy.gif', 'rolleyes.gif', 'angry.gif', 'smiley.gif', 'wink.gif', 'grin.gif', 'sad.gif', 'shocked.gif', 'cool.gif', 'tongue.gif', 'huh.gif', 'embarrassed.gif', 'lipsrsealed.gif', 'kiss.gif', 'cry.gif', 'undecided.gif', 'azn.gif', 'afro.gif', 'police.gif', 'angel.gif');
  938. foreach ($matches[1] as $k => $file)
  939. {
  940. $found = array_search($file, $smileysto);
  941. // Note the weirdness here is to stop double spaces between smileys.
  942. if ($found)
  943. $matches[1][$k] = '-[]-smf_smily_start#|#' . htmlspecialchars($smileysfrom[$found]) . '-[]-smf_smily_end#|#';
  944. else
  945. $matches[1][$k] = '';
  946. }
  947. }
  948. else
  949. {
  950. // Load all the smileys.
  951. $names = array();
  952. foreach ($matches[1] as $file)
  953. $names[] = $file;
  954. $names = array_unique($names);
  955. if (!empty($names))
  956. {
  957. $request = $smcFunc['db_query']('', '
  958. SELECT code, filename
  959. FROM {db_prefix}smileys
  960. WHERE filename IN ({array_string:smiley_filenames})',
  961. array(
  962. 'smiley_filenames' => $names,
  963. )
  964. );
  965. $mappings = array();
  966. while ($row = $smcFunc['db_fetch_assoc']($request))
  967. $mappings[$row['filename']] = htmlspecialchars($row['code']);
  968. $smcFunc['db_free_result']($request);
  969. foreach ($matches[1] as $k => $file)
  970. if (isset($mappings[$file]))
  971. $matches[1][$k] = '-[]-smf_smily_start#|#' . $mappings[$file] . '-[]-smf_smily_end#|#';
  972. }
  973. }
  974. // Replace the tags!
  975. $text = str_replace($matches[0], $matches[1], $text);
  976. // Now sort out spaces
  977. $text = str_replace(array('-[]-smf_smily_end#|#-[]-smf_smily_start#|#', '-[]-smf_smily_end#|#', '-[]-smf_smily_start#|#'), ' ', $text);
  978. }
  979. // Only try to buy more time if the client didn't quit.
  980. if (connection_aborted() && $context['server']['is_apache'])
  981. @apache_reset_timeout();
  982. $parts = preg_split('~(<[A-Za-z]+\s*[^<>]*?style="?[^<>"]+"?[^<>]*?(?:/?)>|</[A-Za-z]+>)~', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
  983. $replacement = '';
  984. $stack = array();
  985. foreach ($parts as $part)
  986. {
  987. if (preg_match('~(<([A-Za-z]+)\s*[^<>]*?)style="?([^<>"]+)"?([^<>]*?(/?)>)~', $part, $matches) === 1)
  988. {
  989. // If it's being closed instantly, we can't deal with it...yet.
  990. if ($matches[5] === '/')
  991. continue;
  992. else
  993. {
  994. // Get an array of styles that apply to this element. (The strtr is there to combat HTML generated by Word.)
  995. $styles = explode(';', strtr($matches[3], array('&quot;' => '')));
  996. $curElement = $matches[2];
  997. $precedingStyle = $matches[1];
  998. $afterStyle = $matches[4];
  999. $curCloseTags = '';
  1000. $extra_attr = '';
  1001. foreach ($styles as $type_value_pair)
  1002. {
  1003. // Remove spaces and convert uppercase letters.
  1004. $clean_type_value_pair = strtolower(strtr(trim($type_value_pair), '=', ':'));
  1005. // Something like 'font-weight: bold' is expected here.
  1006. if (strpos($clean_type_value_pair, ':') === false)
  1007. continue;
  1008. // Capture the elements of a single style item (e.g. 'font-weight' and 'bold').
  1009. list ($style_type, $style_value) = explode(':', $type_value_pair);
  1010. $style_value = trim($style_value);
  1011. switch (trim($style_type))
  1012. {
  1013. case 'font-weight':
  1014. if ($style_value === 'bold')
  1015. {
  1016. $curCloseTags .= '[/b]';
  1017. $replacement .= '[b]';
  1018. }
  1019. break;
  1020. case 'text-decoration':
  1021. if ($style_value == 'underline')
  1022. {
  1023. $curCloseTags .= '[/u]';
  1024. $replacement .= '[u]';
  1025. }
  1026. elseif ($style_value == 'line-through')
  1027. {
  1028. $curCloseTags .= '[/s]';
  1029. $replacement .= '[s]';
  1030. }
  1031. break;
  1032. case 'text-align':
  1033. if ($style_value == 'left')
  1034. {
  1035. $curCloseTags .= '[/left]';
  1036. $replacement .= '[left]';
  1037. }
  1038. elseif ($style_value == 'center')
  1039. {
  1040. $curCloseTags .= '[/center]';
  1041. $replacement .= '[center]';
  1042. }
  1043. elseif ($style_value == 'right')
  1044. {
  1045. $curCloseTags .= '[/right]';
  1046. $replacement .= '[right]';
  1047. }
  1048. break;
  1049. case 'font-style':
  1050. if ($style_value == 'italic')
  1051. {
  1052. $curCloseTags .= '[/i]';
  1053. $replacement .= '[i]';
  1054. }
  1055. break;
  1056. case 'color':
  1057. $curCloseTags .= '[/color]';
  1058. $replacement .= '[color=' . $style_value . ']';
  1059. break;
  1060. case 'font-size':
  1061. // Sometimes people put decimals where decimals should not be.
  1062. if (preg_match('~(\d)+\.\d+(p[xt])~i', $style_value, $dec_matches) === 1)
  1063. $style_value = $dec_matches[1] . $dec_matches[2];
  1064. $curCloseTags .= '[/size]';
  1065. $replacement .= '[size=' . $style_value . ']';
  1066. break;
  1067. case 'font-family':
  1068. // Only get the first freaking font if there's a list!
  1069. if (strpos($style_value, ',') !== false)
  1070. $style_value = substr($style_value, 0, strpos($style_value, ','));
  1071. $curCloseTags .= '[/font]';
  1072. $replacement .= '[font=' . strtr($style_value, array("'" => '')) . ']';
  1073. break;
  1074. // This is a hack for images with dimensions embedded.
  1075. case 'width':
  1076. case 'height':
  1077. if (preg_match('~[1-9]\d*~i', $style_value, $dimension) === 1)
  1078. $extra_attr .= ' ' . $style_type . '="' . $dimension[0] . '"';
  1079. break;
  1080. case 'list-style-type':
  1081. if (preg_match('~none|disc|circle|square|decimal|decimal-leading-zero|lower-roman|upper-roman|lower-alpha|upper-alpha|lower-greek|lower-latin|upper-latin|hebrew|armenian|georgian|cjk-ideographic|hiragana|katakana|hiragana-iroha|katakana-iroha~i', $style_value, $listType) === 1)
  1082. $extra_attr .= ' listtype="' . $listType[0] . '"';
  1083. break;
  1084. }
  1085. }
  1086. // Preserve some tags stripping the styling.
  1087. if (in_array($matches[2], array('a', 'font', 'td')))
  1088. {
  1089. $replacement .= $precedingStyle . $afterStyle;
  1090. $curCloseTags = '</' . $matches[2] . '>' . $curCloseTags;
  1091. }
  1092. // If there's something that still needs closing, push it to the stack.
  1093. if (!empty($curCloseTags))
  1094. array_push($stack, array(
  1095. 'element' => strtolower($curElement),
  1096. 'closeTags' => $curCloseTags
  1097. )
  1098. );
  1099. elseif (!empty($extra_attr))
  1100. $replacement .= $precedingStyle . $extra_attr . $afterStyle;
  1101. }
  1102. }
  1103. elseif (preg_match('~</([A-Za-z]+)>~', $part, $matches) === 1)
  1104. {
  1105. // Is this the element that we've been waiting for to be closed?
  1106. if (!empty($stack) && strtolower($matches[1]) === $stack[count($stack) - 1]['element'])
  1107. {
  1108. $byebyeTag = array_pop($stack);
  1109. $replacement .= $byebyeTag['closeTags'];
  1110. }
  1111. // Must've been something else.
  1112. else
  1113. $replacement .= $part;
  1114. }
  1115. // In all other cases, just add the part to the replacement.
  1116. else
  1117. $replacement .= $part;
  1118. }
  1119. // Now put back the replacement in the text.
  1120. $text = $replacement;
  1121. // We are not finished yet, request more time.
  1122. if (connection_aborted() && $context['server']['is_apache'])
  1123. @apache_reset_timeout();
  1124. // Let's pull out any legacy alignments.
  1125. while (preg_match('~<([A-Za-z]+)\s+[^<>]*?(align="*(left|center|right)"*)[^<>]*?(/?)>~i', $text, $matches) === 1)
  1126. {
  1127. // Find the position in the text of this tag over again.
  1128. $start_pos = strpos($text, $matches[0]);
  1129. if ($start_pos === false)
  1130. break;
  1131. // End tag?
  1132. if ($matches[4] != '/' && strpos($text, '</' . $matches[1] . '>', $start_pos) !== false)
  1133. {
  1134. $end_length = strlen('</' . $matches[1] . '>');
  1135. $end_pos = strpos($text, '</' . $matches[1] . '>', $start_pos);
  1136. // Remove the align from that tag so it's never checked again.
  1137. $tag = substr($text, $start_pos, strlen($matches[0]));
  1138. $content = substr($text, $start_pos + strlen($matches[0]), $end_pos - $start_pos - strlen($matches[0]));
  1139. $tag = str_replace($matches[2], '', $tag);
  1140. // Put the tags back into the body.
  1141. $text = substr($text, 0, $start_pos) . $tag . '[' . $matches[3] . ']' . $content . '[/' . $matches[3] . ']' . substr($text, $end_pos);
  1142. }
  1143. else
  1144. {
  1145. // Just get rid of this evil tag.
  1146. $text = substr($text, 0, $start_pos) . substr($text, $start_pos + strlen($matches[0]));
  1147. }
  1148. }
  1149. // Let's do some special stuff for fonts - cause we all love fonts.
  1150. while (preg_match('~<font\s+([^<>]*)>~i', $text, $matches) === 1)
  1151. {
  1152. // Find the position of this again.
  1153. $start_pos = strpos($text, $matches[0]);
  1154. $end_pos = false;
  1155. if ($start_pos === false)
  1156. break;
  1157. // This must have an end tag - and we must find the right one.
  1158. $lower_text = strtolower($text);
  1159. $start_pos_test = $start_pos + 4;
  1160. // How many starting tags must we find closing ones for first?
  1161. $start_font_tag_stack = 0;
  1162. while ($start_pos_test < strlen($text))
  1163. {
  1164. // Where is the next starting font?
  1165. $next_start_pos = strpos($lower_text, '<font', $start_pos_test);
  1166. $next_end_pos = strpos($lower_text, '</font>', $start_pos_test);
  1167. // Did we past another starting tag before an end one?
  1168. if ($next_start_pos !== false && $next_start_pos < $next_end_pos)
  1169. {
  1170. $start_font_tag_stack++;
  1171. $start_pos_test = $next_start_pos + 4;
  1172. }
  1173. // Otherwise we have an end tag but not the right one?
  1174. elseif ($start_font_tag_stack)
  1175. {
  1176. $start_font_tag_stack--;
  1177. $start_pos_test = $next_end_pos + 4;
  1178. }
  1179. // Otherwise we're there!
  1180. else
  1181. {
  1182. $end_pos = $next_end_pos;
  1183. break;
  1184. }
  1185. }
  1186. if ($end_pos === false)
  1187. break;
  1188. // Now work out what the attributes are.
  1189. $attribs = fetchTagAttributes($matches[1]);
  1190. $tags = array();
  1191. $sizes_equivalence = array(1 => '8pt', '10pt', '12pt', '14pt', '18pt', '24pt', '36pt');
  1192. foreach ($attribs as $s => $v)
  1193. {
  1194. if ($s == 'size')
  1195. {
  1196. // Cast before empty chech because casting a string results in a 0 and we don't have zeros in the array! ;)
  1197. $v = (int) trim($v);
  1198. $v = empty($v) ? 1 : $v;
  1199. $tags[] = array('[size=' . $sizes_equivalence[$v] . ']', '[/size]');
  1200. }
  1201. elseif ($s == 'face')
  1202. $tags[] = array('[font=' . trim(strtolower($v)) . ']', '[/font]');
  1203. elseif ($s == 'color')
  1204. $tags[] = array('[color=' . trim(strtolower($v)) . ']', '[/color]');
  1205. }
  1206. // As before add in our tags.
  1207. $before = $after = '';
  1208. foreach ($tags as $tag)
  1209. {
  1210. $before .= $tag[0];
  1211. if (isset($tag[1]))
  1212. $after = $tag[1] . $after;
  1213. }
  1214. // Remove the tag so it's never checked again.
  1215. $content = substr($text, $start_pos + strlen($matches[0]), $end_pos - $start_pos - strlen($matches[0]));
  1216. // Put the tags back into the body.
  1217. $text = substr($text, 0, $start_pos) . $before . $content . $after . substr($text, $end_pos + 7);
  1218. }
  1219. // Almost there, just a little more time.
  1220. if (connection_aborted() && $context['server']['is_apache'])
  1221. @apache_reset_timeout();
  1222. if (count($parts = preg_split('~<(/?)(li|ol|ul)([^>]*)>~i', $text, null, PREG_SPLIT_DELIM_CAPTURE)) > 1)
  1223. {
  1224. // A toggle that dermines whether we're directly under a <ol> or <ul>.
  1225. $inList = false;
  1226. // Keep track of the number of nested list levels.
  1227. $listDepth = 0;
  1228. // Map what we can expect from the HTML to what is supported.
  1229. $listTypeMapping = array(
  1230. '1' => 'decimal',
  1231. 'A' => 'upper-alpha',
  1232. 'a' => 'lower-alpha',
  1233. 'I' => 'upper-roman',
  1234. 'i' => 'lower-roman',
  1235. 'disc' => 'disc',
  1236. 'square' => 'square',
  1237. 'circle' => 'circle',
  1238. );
  1239. // $i: text, $i + 1: '/', $i + 2: tag, $i + 3: tail.
  1240. for ($i = 0, $numParts = count($parts) - 1; $i < $numParts; $i += 4)
  1241. {
  1242. $tag = strtolower($parts[$i + 2]);
  1243. $isOpeningTag = $parts[$i + 1] === '';
  1244. if ($isOpeningTag)
  1245. {
  1246. switch ($tag)
  1247. {
  1248. case 'ol':
  1249. case 'ul':
  1250. // We have a problem, we're already in a list.
  1251. if ($inList)
  1252. {
  1253. // Inject a list opener, we'll deal with the ol/ul next loop.
  1254. array_splice($parts, $i, 0, array(
  1255. '',
  1256. '',
  1257. str_repeat("\t", $listDepth) . '[li]',
  1258. '',
  1259. ));
  1260. $numParts = count($parts) - 1;
  1261. // The inlist status changes a bit.
  1262. $inList = false;
  1263. }
  1264. // Just starting a new list.
  1265. else
  1266. {
  1267. $inList = true;
  1268. if ($tag === 'ol')
  1269. $listType = 'decimal';
  1270. elseif (preg_match('~type="?(' . implode('|', array_keys($listTypeMapping)) . ')"?~', $parts[$i + 3], $match) === 1)
  1271. $listType = $listTypeMapping[$match[1]];
  1272. else
  1273. $listType = null;
  1274. $listDepth++;
  1275. $parts[$i + 2] = '[list' . ($listType === null ? '' : ' type=' . $listType) . ']' . "\n";
  1276. $parts[$i + 3] = '';
  1277. }
  1278. break;
  1279. case 'li':
  1280. // This is how it should be: a list item inside the list.
  1281. if ($inList)
  1282. {
  1283. $parts[$i + 2] = str_repeat("\t", $listDepth) . '[li]';
  1284. $parts[$i + 3] = '';
  1285. // Within a list item, it's almost as if you're outside.
  1286. $inList = false;
  1287. }
  1288. // The li is no direct child of a list.
  1289. else
  1290. {
  1291. // We are apparently in a list item.
  1292. if ($listDepth > 0)
  1293. {
  1294. $parts[$i + 2] = '[/li]' . "\n" . str_repeat("\t", $listDepth) . '[li]';
  1295. $parts[$i + 3] = '';
  1296. }
  1297. // We're not even near a list.
  1298. else
  1299. {
  1300. // Quickly create a list with an item.
  1301. $listDepth++;
  1302. $parts[$i + 2] = '[list]' . "\n\t" . '[li]';
  1303. $parts[$i + 3] = '';
  1304. }
  1305. }
  1306. break;
  1307. }
  1308. }
  1309. // Handle all the closing tags.
  1310. else
  1311. {
  1312. switch ($tag)
  1313. {
  1314. case 'ol':
  1315. case 'ul':
  1316. // As we expected it, closing the list while we're in it.
  1317. if ($inList)
  1318. {
  1319. $inList = false;
  1320. $listDepth--;
  1321. $parts[$i + 1] = '';
  1322. $parts[$i + 2] = str_repeat("\t", $listDepth) . '[/list]';
  1323. $parts[$i + 3] = '';
  1324. }
  1325. else
  1326. {
  1327. // We're in a list item.
  1328. if ($listDepth > 0)
  1329. {
  1330. // Inject closure for this list item first.
  1331. // The content of $parts[$i] is left as is!
  1332. array_splice($parts, $i + 1, 0, array(
  1333. '', // $i + 1
  1334. '[/li]' . "\n", // $i + 2
  1335. '', // $i + 3
  1336. '', // $i + 4
  1337. ));
  1338. $numParts = count($parts) - 1;
  1339. // Now that we've closed the li, we're in list space.
  1340. $inList = true;
  1341. }
  1342. // We're not even in a list, ignore
  1343. else
  1344. {
  1345. $parts[$i + 1] = '';
  1346. $parts[$i + 2] = '';
  1347. $parts[$i + 3] = '';
  1348. }
  1349. }
  1350. break;
  1351. case 'li':

Large files files are truncated, but you can click here to view the full file