Source Plugin

Description

This plugin allows you to include the contents of another file, with syntax highlighting, into the current page.

Syntax:

<source filename language|title>
  • filename — required, the name of the file to be included. This can either be a normal path & file name or a URI. If you wish to use file URI's then allow_url_fopen=On must be set in the webserver's php.ini file (also refer to the location setting and the security warning below).
  • language — optional, the language string to be passed to GeSHi for syntax highlighting. This plug-in accepts the same language strings as Dokuwiki's <code> markup. If the language string is not given, the plugin will attempt to deduce the language from the file extension.
  • title — optional, a title to be displayed above the file contents. Everything after the pipe (|) is treated as the title. If not present the file name will be used, e.g. "file: filename"

You can see the plugin in action here.

Warnings

Indiscriminate use of this plug in can be a serious security risk to your web server. It has the potential to expose any file on the web server computer that is accessible to the web server software. In particular:

  • allow_url_fopen=On is a potential security risk. If you use this setting, I strongly recommend ensuring 'php' is included in the denied extension list (refer $deny setting below).
  • ensure the php.ini setting open_basedir is correctly set. If not, this plugin has the potential to expose any file accessible to the webserver to the page creator/editor.
  • Attempting to use URIs to link in php source files resident on a php enabled webserver will result in the webserver attempting to process the php script. This can have unpredictable results.
  • Be aware that often a dynamic website will have files containing plain text passwords for access to other server systems (e.g. databases).


For further information, see PHP File System Security

Settings

Security

  • $location — This value will be preprended to all file names. It can be used to restrict the portion of the file space (or URI space) exposed to the <source> command.

    By setting $location='http://' you can force all file retrieval through webservers and thereby make use of the webservers' own restrictions (e.g. in Apache systems, DocumentRoot, .htaccess files) which are likely to be stronger than that of the file system itself.

    If there is a value for $location all file names which include the path traversal ".." will be rejected.

  • $allow — An array of file extension strings. If this array is empty it is ignored. If it has any members only files with the listed extensions may be "sourced".
  • $deny — An array of file extension strings. If $allow is empty, no file with an extension included in $deny may be "sourced". If $allow is non-empty $deny is ignored.

Other

  • $extensions — An associative array matching file extensions to recognised GeSHi languages. Value pairs are of the form "file-extension" => "GeSHI-language".

Installation

Plugin sources: zip format (3k), tar.gz format (2k)

Download the source to your plugin folder, lib/plugins and extract its contents. That will create a new plugin folder, lib/plugins/source and install the plugin there.

The folder will contain:

style.css                              styles for the new boxes and titles
syntax.php                             syntax plugin script

The plugin is now installed.

Details

syntax.php

source/syntax.php

<?php
/**
 * Source Plugin: includes a source file using the geshi highlighter
 *
 * Syntax:     <source filename lang|title>
 *   filename  (required) can be a local path/file name or a remote file uri
 *             to use remote file uri, allow_url_fopen=On must be set in the server's php.ini
 *   lang      (optional) programming language name, is passed to geshi for code highlighting
 *             if not provided, the plugin will attempt to derive a value from the file name
 *             (refer $extensions in render() method)
 *   title     (optional) all text after '|' will be rendered above the main code text with a
 *             different style. If no title is present, it will be set to "file: filename"
 *
 *  *** WARNING ***
 *
 *  Unless configured correctly this plugin can be a huge security risk.
 *  Please review/consider
 *    - users who have access to the wiki
 *    - php.ini setting, allow_url_fopen
 *    - php.ini setting, base_dir
 *    - $location, $allow & $deny settings below.
 * 
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author     Christopher Smith <chris@jalakai.co.uk>  
 */
 
if(!defined('DOKU_INC')) define('DOKU_INC',realpath(dirname(__FILE__).'/../../').'/');
if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
require_once(DOKU_PLUGIN.'syntax.php');
 
global $extensions, $location, $allow, $deny;
 
//------------------------[ Security settings ] ---------------------------------------------
// $location is prepended to all file names, restricting the filespace exposed to the plugin
$location = '';
 
// if $allow array contains any elements, ONLY files with the extensions listed will be allowed
$allow = array();
 
// if the $allow array is empty, any file with an extension listed in $deny array will be denied 
$deny = array('php');
 
//------------------------[ Other settings ] ---------------------------------------------
// list of common file extensions and their language equivalent
// (required only where the extensiosn and the language is not the same)
$extensions = array(
    'htm' => 'html4strict',
    'html' => 'html4strict',
    'js' => 'javascript'
  );
 
/**
 * All DokuWiki plugins to extend the parser/rendering mechanism
 * need to inherit from this class
 */
class syntax_plugin_source extends DokuWiki_Syntax_Plugin {
 
    /**
     * return some info
     */
    function getInfo(){
      return array(
        'author' => 'Christopher Smith',
        'email'  => 'chris@jalakai.co.uk',
        'date'   => '2005-08-18',
        'name'   => 'Source Plugin',
        'desc'   => 'Include a remote source file',
        'url'    => 'http://wiki.splitbrain.org/plugin:source',
      );
    }
 
    function getType(){ return 'substition'; }
    function getPType(){ return 'block'; }
    function getSort(){ return 330; }
 
    /**
     * Connect pattern to lexer
     */
    function connectTo($mode) {       
      $this->Lexer->addSpecialPattern('<source.*?>',$mode,substr(get_class($this), 7));
    }
 
    /**
     * Handle the match
     */
    function handle($match, $state, $pos, &$handler){
      $match = trim(substr($match,7,-1));                    //strip <source from start and > from end
      list($attr, $title) = preg_split('/\|/u', $match, 2);   //split out title
      list($file, $lang) = preg_split('/\s+/',$attr, 3);     //split out file name and language
 
      return array($file, (isset($lang)?$lang:''), (isset($title)?$title:''));
    }
 
    /**
     * Create output
     */
    function render($mode, &$renderer, $data) {
      global $extensions, $location, $allow, $deny;
 
      if($mode == 'xhtml'){
 
        list($file, $lang, $title) = $data;
        $ext = substr(strrchr($file, '.'),1);
 
        $ok = false;
        if (count($allow)) {
          if (in_array($ext, $allow)) $ok = true;
        } else {
          if (!in_array($ext, $deny)) $ok = true;
        }      
 
        // prevent filenames which attempt to move up directory tree by using ".."        
        if ($ok && $location && preg_match('/(?:^|\/)\.\.(?:\/|$)/', $file)) $ok = false;
 
        if ($ok && ($source = @file_get_contents($location.$file))) {
 
          if (!$lang) { $lang = isset($extensions[$ext]) ? $extensions[$ext] : $ext; }
          if (!$title) { $title = "file: $file"; }
 
          $renderer->doc .= "<div class='source'><p>".$renderer->_xmlEntities($title)."</p>";
          $renderer->code($source, $lang);
          $renderer->doc .= "</div>";
          return true;
        }
      }
      return false;
    }
}
 
//Setup VIM: ex: et ts=4 enc=utf-8 :

CSS

The plugin comes with some style additions in the style.css file.

  • The style colouring, green, has been chosen to complement but differentiate <source> blocks from the <code> (blue) and <file> (red) blocks rendered by the code plugin.
  • The styling itself is similar to and inspired by that used by gentoo-wiki, a media wiki installation.

These can of course can be modified to suit your own requirements. More details on modifying the styles are given after the file contents listing.

style.css

/*
 * source plugin extension - style additions
 *
 * @author  Christopher Smith  chris@jalakai.co.uk
 * @link    http://wiki.jalakai.co.uk/dokuwiki/doku.php/tutorials/codeplugin
 */
/* source plugin extensions */
 
/* layout */
.source {
  width: 92%;
  margin: 1em auto;
  border: 1px solid;
  padding: 4px;
}
 
.source p {
  font-size: 90%;
  margin: 0;
  padding: 2px;
}
 
.source pre.code {
  margin: 4px 0 0 0;
}
 
/* colours */
div.source {
  border-color:  #bdb;
  background: #e4f8f2;
}
 
div.source p {
  background: #c4e4d4;
}
 
div.source pre.code {
  border: 1px dashed #9c9;
  background: #ecfaf6;
}

The source file contents are wrapped within a <div> tag of class source and the file name is given above the contents. The html fragment will look like

<div class='source'>
  <p>{title}</p>
  <pre class='code {language}'>{file contents}</pre>
</div>
 
Therefore, standard Dokuwiki styling can be overridden with the following style selectors:
/* style the source file name */
/* set to display:none to prevent it being displayed at all */
.source p {}  
 
/* style the file contents, e.g. font, border & background */
  .source .code {} 
 
/* override the geshi hilight styles in /lib/styles/style.css */
  .source .code .<geshi-hilite-code> {}

Revision History

  • 2005-07-12 — released.
  • 2005-08-19 — updated; ".." directory traversal vulnerability removed, user specifiable title added, downloadable plugin package released.

To Do

  • Improve checks on file name to prevent use of ".." — DONE

Discussion

Hi Chris - I was using this plugin when I discovered that it does not handle filenames with spaces in them gracefully. Would you like me to replace the source above with a patched source that handles filenames with spaces (and handles ../ file security), or perhaps I could send it to you by e-mail first? oracle [dot] shinoda [at] gmail [dot] com (Nigel McNie)
I am interested in how to handle spaces in file names, email me or post a snippet here. The code above has been updated. The ".." problem should be fixed and a title parameter has been added. The best way to handle spaces maybe to require the file name to be surround in matched quotes. What do you think? — Christopher Smith 2005/08/19 23:49
 
tutorials/pluginsource.txt · Last modified: 2005/08/20 00:53 by chris
 
Recent changes RSS feed Creative Commons License Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki