login  Naam:   Wachtwoord: 
Registreer je!
 Scripts:

Scripts > PHP > UBB & Smilies > CodeBlock en Ubb classes

CodeBlock en Ubb classes

Auteur: Thomas - 27 december 2013 - 22:24 - Gekeurd door: UpLink - Hits: 4457 - Aantal punten: (0 stemmen)



Update 2014-10-07:
- breedtes compleet verwijderd uit classes, de code-wrapper div vult nu automatisch de maximale beschikbare breedte uit

Update 2014-09-16:
- horizontale scrollbalk nu alleen zichtbaar indien nodig
- hoogtes verwijderd uit template
- CSS aanpassingen

Noot 2014-03-05:
Let op bij het gebruik van de htmlspecialchars() aanroepen in de onderstaande code. Hier is geen encoding (3e parameter) opgegeven. Wellicht doe je er verstandig aan deze expliciet op te geven. Afhankelijk van je PHP versie kan de default waarde van deze parameter verschillen.

Korte uitleg
Dit script bevat twee classes en wat CSS code.

De CodeBlock class gebruik je om code af te drukken in een nette (div-)tabel compleet met regelnummers. Meestal is de breedte voor content op een webpagina beperkt. Deze class speelt hier op in: je kunt een vaste breedte instellen voor deze codeblokken.

De CSS code is bedoeld voor het opmaken van de codeblokken.

De Ubb class geeft een (voorbeeld)implementatie van UBB-functionaliteit met hierin ondersteuning voor CodeBlocks, maar je hoeft deze niet per sé te gebruiken - je kunt de CodeBlock class ook in afzondering gebruiken of combineren met je eigen UBB-functionaliteit. Ook kun je deze Ubb class uitbreiden door hier je eigen UBB-functionaliteit in op te nemen (op de daarvoor aangegeven plaats).

Installatie
Include de CodeBlock of beide classes in je code en zorg dat je de CSS laadt als je CodeBlock gebruikt.

Gebruik
Zie hieronder voor voorbeelden van gebruik. De code zelf is voorzien van redelijk wat commentaar (in het Engels).

Code:
Class CodeBlock (heeft CSS nodig):
  1. <?php
  2. /*
  3.  * Class for printing code in a HTML formatted block, complete with line numbers.
  4.  * It is also suited to be included in other UBB-like functionality.
  5.  */
  6. class CodeBlock
  7. {
  8. protected $options;
  9. protected $output;
  10.  
  11. public function __construct($text, $options=array()) {
  12. // Set options; first overwrites second (the defaults).
  13. $this->options = $options + self::getDefaultOptions();
  14.  
  15. // Do we still need to strip tags?
  16. if (!$this->options['tags_stripped'] && ini_get('magic_quotes_gpc')) {
  17. $returnText = stripslashes($text);
  18. } else {
  19. $returnText = $text;
  20. }
  21.  
  22. // Convert any tabs to spaces.
  23. $returnText = str_replace("\t", str_repeat(' ', $this->options['tabspaces']), $returnText);
  24.  
  25. // Convert all linebreaks to "\n".
  26. $returnText = str_replace("\r\n", "\n", $returnText);
  27.  
  28. // Remove all whitespace characters from the end of each line, this will also trim empty lines.
  29. $lines = explode("\n", $returnText);
  30. $returnText = implode("\n", array_map('rtrim', $lines));
  31.  
  32. // Do we want to apply PHP code highlighting?
  33. if ($this->options['highlight']) {
  34. $returnText = @highlight_string($returnText, true); // suppress possible errors
  35.  
  36. // Clean up some of the HTML generated by highlight_string():
  37. // Replace all <br /> tags with "\n" and fix the start and end of the returned HTML.
  38. $returnText = str_replace(
  39. array('<br />', '<code><span style="color: #000000">'."\n", '</span>'."\n".'</code>'),
  40. array("\n", '<span style="color: #000000">', '</span>'),
  41. $returnText
  42. );
  43. } else {
  44. // Just neutralize everything.
  45. $returnText = htmlspecialchars($returnText, ENT_QUOTES, 'UTF-8');
  46. }
  47.  
  48. // Create the code block, starting with linenumbers.
  49. $nrs = implode("\n", range(1, count($lines))); // seems faster than a for-loop, alternatively: use <br /> instead of \n for implosion
  50. ?><div class="code-wrapper">
  51. <div class="index"><pre><?php echo $nrs ?></pre></div>
  52. <div class="code"><pre><?php echo $returnText ?></pre></div>
  53. </div><?php
  54. $this->output = ob_get_clean();
  55. } // __construct
  56.  
  57. public static function getDefaultOptions() {
  58. return array(
  59. 'tabspaces' => 4, // number of spaces that tab-characters are replaced with
  60. 'highlight' => true, // whether to use the PHP function highlight_string() for highlighting code
  61. // The next default should not be changed here unless you use the CodeBlock class directly,
  62. // or when magic_quotes_gpc is on but you already stripped these extra slashes before you
  63. // passed the input to this class.
  64. 'tags_stripped' => false, // keeps track of whether we already stripped tags for when magic_quotes_gpc is on
  65. );
  66. } // getDefaultOptions
  67.  
  68. public function getOutput() {
  69. return $this->output;
  70. } // getOutput
  71. } // class
  72. ?>


Bijbehorende CSS:
  1. @CHARSET "UTF-8";
  2.  
  3. div.code-wrapper { display: block; margin: 0; padding: 0; border: 1px solid #cccccc; background-color: #eeeeee; position: relative; overflow-x: auto; overflow-y: hidden; }
  4. div.code-wrapper pre { font-family: monospace; font-size: 13px; margin: 0; padding: 2px 5px; border: 0; line-height: 15px; }
  5. div.code-wrapper div { margin: 0; padding: 0; border: 0; }
  6. div.code-wrapper div.index { display: block; width: 40px; text-align: right; background-color: #cccccc; color: #333333; }
  7. div.code-wrapper div.code { display: block; position: absolute; top: 0px; left: 40px; color: #000000; }


Class Ubb:
  1. <?php
  2. /*
  3.  * Class for formatting output, codeblocks can be picked up as well.
  4.  */
  5. class Ubb
  6. {
  7. protected $options;
  8. protected $output;
  9. protected $codeBlocks; // stack (array) of CodeBlock objects
  10. protected $tag; // shorthand for $this->options['code_block_tag'], used for delimiting blocks of code
  11.  
  12. public function __construct($text, $options=array()) {
  13. $this->codeBlocks = array();
  14.  
  15. $this->options = $options + array(
  16. 'allow_html' => false, // allow HTML outside code blocks? be VERY careful with this
  17. 'use_code_block' => true, // use CodeBlock class for formatting blocks of code?
  18. 'code_block_tag' => 'code', // name of the UBB-tag for delimiting blocks of code, it will also enable us to print this code using this class :)
  19. 'code_block_options' => array(), // styling options for code blocks, see CodeBlock::getDefaultOptions()
  20. );
  21. $this->options['code_block_options'] = $this->options['code_block_options'] + CodeBlock::getDefaultOptions();
  22.  
  23. $this->tag = $this->options['code_block_tag'];
  24.  
  25. // Strip slashes if magic_quotes_gpc is on.
  26. if (ini_get('magic_quotes_gpc')) {
  27. $returnText = stripslashes($text);
  28. } else {
  29. $returnText = $text;
  30. }
  31. // We stripped tags; do not strip them again in CodeBlock calls.
  32. $this->options['code_block_options']['tags_stripped'] = true;
  33.  
  34. if ($this->options['use_code_block']) {
  35. // Backup code blocks, it needs separate treatment from the rest of the UBB-code).
  36. // preg_replace() will become deprecated in PHP 5.5.0, we use preg_replace_callback instead.
  37. $returnText = preg_replace_callback(
  38. '#\['.$this->tag.'](.*)\[/'.$this->tag.']#sU',
  39. array($this, 'backupCodeBlock'),
  40. $returnText
  41. );
  42. }
  43.  
  44. // Perform the rest of the UBB formatting, starting with (dis)allowing HTML.
  45. if ($this->options['allow_html'] == false) {
  46. // No HTML allowed, neutralize all HTML and convert newline characters to linebreak-tags.
  47. $returnText = nl2br(htmlspecialchars($returnText, ENT_QUOTES, 'UTF-8'));
  48.  
  49. if ($this->options['use_code_block']) {
  50. // Some extra styling: remove the <br /> after the closing tag of a code block.
  51. $returnText = str_replace('[/'.$this->tag.']<br />', '[/'.$this->tag.']', $returnText);
  52. }
  53. } // allow_html false
  54.  
  55. // Put the rest, if any, of your own UBB-styling here.
  56.  
  57. if ($this->options['use_code_block']) {
  58. // Restore code blocks.
  59. $returnText = preg_replace_callback(
  60. '#\['.$this->tag.'](\d+)\[/'.$this->tag.']#sU',
  61. array($this, 'restoreCodeBlock'),
  62. $returnText
  63. );
  64. }
  65.  
  66. // Store the processed input in $this->output.
  67. $this->output = $returnText;
  68. } // __construct
  69.  
  70. // Callback function for storing blocks of code.
  71. protected function backupCodeBlock($matches) {
  72. $currentBlock = count($this->codeBlocks);
  73.  
  74. $this->codeBlocks[$currentBlock] = new CodeBlock(
  75. // Note: strip backslash from escaped double quotes due to /e-switch is no longer necessary
  76. // because we do not use preg_match anymore.
  77. $matches[1],
  78. $this->options['code_block_options']
  79. );
  80.  
  81. // Return a HTML-safe placeholder to indicate where the codeblock should be placed back after
  82. // processing the rest of the UBB-code.
  83. return '['.$this->tag.']'.$currentBlock.'[/'.$this->tag.']';
  84. } // backupCodeBlock
  85.  
  86. // Callback function for restoring code blocks after the rest of the UBB-code is applied.
  87. protected function restoreCodeBlock($matches) {
  88. return $this->codeBlocks[$matches[1]]->getOutput();
  89. } // restoreCodeBlock
  90.  
  91. public function getOutput() {
  92. return $this->output;
  93. }
  94. } // class
  95. ?>


Gebruik:
Voor het afdrukken van één groot codeblock:
  1. <?php
  2. // creeer een CodeBlock object
  3. $code = new CodeBlock('je_code_hier');
  4.  
  5. // afdrukken!
  6. echo $code->getOutput();
  7. ?>


Voor het adrukken van een UBB-tekst met hierin codeblokken:
  1. <?php
  2. // creeer een Ubb object
  3. $ubb = new Ubb('je_tekst_met_codeblokken_hier');
  4.  
  5. // afdrukken!
  6. echo $ubb->getOutput();
  7. ?>


Je kunt ook een aantal opties meegeven (in zowel CodeBlock als Ubb), bijvoorbeeld je staat HTML toe (buiten codeblokken), je wilt geen highlight_string gebruiken voor PHP-code:
  1. <?php
  2. // aanmaken en instellen
  3. $ubb = new Ubb('je_tekst_met_codeblokken_hier', array(
  4. 'allow_html' => true,
  5. 'code_block_options' => array(
  6. 'highlight' => false,
  7. ),
  8. ));
  9.  
  10. // afdrukken
  11. echo $ubb->getOutput();
  12. ?>
Download code! Download code (.txt)

 Stemmen
Niet ingelogd.

 Reacties
Post een reactie
Lees de reacties (2)
© 2002-2024 Sitemasters.be - Regels - Laadtijd: 0.074s