Location: PHPKode > projects > Ratawiki > ratawiki-0.5/wikisources/wiki_format.php
<?php

$config['formatVersion'] = "$Rev: 88 $";

/// This variable keeps all formats. If required, you can always add
/// another by inserting it. At some point the array is sorted and split,
/// so you can insert them anywhere you see fit.
$format_array = array(
	// XML cleanup
	"00amp" =>	array("/&/", "&amp;"),
	"00lt"	=>	array("/</", "&lt;"),
	"00gt"	=>	array("/>/", "&gt;"),
	//"00quot"=>	array("/\"/", "&quot;"),
	
	// Basic formatting
	"01bi"	=>	array("/'{5}(.*?)'{5}/m",	"<em><strong>$1</strong></em>"),
	"02b"	=>	array("/'{3}(.*?)'{3}/m",	"<strong>$1</strong>"),
	"03i"	=>	array("/'{2}(.*?)'{2}/m",	"<em>$1</em>"),
	"04tt"	=>	array("/\"{2}(.*?)\"{2}/m",	"<tt>$1</tt>"),
	
	// Somewhat advanced formatting
	"02imgblock" => array("/^\[\@img(|left|right) ([^ ]*) (.*)\@\]/me", "'<div class=\"img'.(('x\$1'=='x')?'block':'\$1').'\"><a href=\"\$2\"><img src=\"\$2\" alt=\"\$2\" /></a><br/><p>\$3</p></div>'" ),
	"03lrblock" => array("/^\[\@(left|right)( title=([^\;\]]*);){0,1} (.*)\@\]/me", "'<div class=\"block\$1\">'.(('\$3'=='')?'':'<h2>\$3</h2>').'\$4</div>'") ,
	"04includeblock" => array("/^\[\@include ([^ ]*) (.*)\@\]/me", "wiki_parse_include('\$1', '\$2')" ),

	// Hyperlinks -- watch utf-8 conformance with the u modifier for preg
	"20doclink" => array("/\[\[([-\w\dáéíóúÁÉÍÓÚÑñ _?'&;:]*?)\]\]/emu", "preg_replace(\"/'/\", \"&#39;\", '<a href=\"'.wiki_format_urlfix('\$1').'\">\$1</a>')" ) ,
	"21url" => array("/\{\{http:([^\} ]*) (.+?)\}\}/em", "'<a href=\"http:'.wiki_format_urlfix('$1').'\">$2</a>'"),
	"22url" => array("/\{\{http:([^\} ]*)\}\}/em", "'<a href=\"http:'.wiki_format_urlfix('$1').'\">http:$1</a>'"),
	"23urlfree" => array("/\{\{([^\} ]*) (.+?)\}\}/em", "'<a href=\"'.wiki_format_urlfix('$1').'\">$2</a>'") ,
	"24urlfree2" => array("/\{\{([^\} ]*)\}\}/em", "'<a href=\"'.wiki_format_urlfix('$1').'\">$1</a>'"),
	"25urlimg" => array("/(?<![{\"'>=:])http:([^ ]*)\.(jpg|jpeg|gif|png)/ime", "'<img src=\"http:'.'$1.$2'.'\" alt=\"http:'.'$1.$2'.'\" />'"),
	"26mp3player" => array("/(?<![{\"'>=:])http:([^ ]*)\.(mp3)/ime", "'<embed type=\"application/x-shockwave-flash\" src=\"http://www.google.com/reader/ui/3247397568-audio-player.swf?audioUrl=http:\$1.\$2\" width=\"100%\" height=\"27\" allowscriptaccess=\"never\" quality=\"best\" bgcolor=\"#ffffff\" wmode=\"window\" flashvars=\"playerMode=embedded\" />'"),
	"27autolink" => array("/(?<![{\"'>=:])(http:|ftp:|mailto:)([^ ]*)/me", "'<a href=\"'.wiki_format_urlfix('\$1\$2').'\">\$1\$2</a>'"),
	"28youtube" => array("/(?<![{\"'>])(youtube:)([^ ]*)/me", "'<object type=\"application/x-shockwave-flash\" style=\"width:480px; height:385px;\" data=\"http://www.youtube.com/v/\$2&amp;hl=es&amp;fs=1\"><param name=\"movie\" value=\"http://www.youtube.com/v/\$2&amp;hl=es&amp;fs=1\" /></object>'"),
	"28youtubelist" => array("/(?<![{\"'>])(youtubelist:)([^ ]*)/me", "'<object type=\"application/x-shockwave-flash\" style=\"width:480px; height:385px;\" data=\"http://www.youtube.com/p/\$2&amp;hl=es&amp;fs=1\"><param name=\"movie\" value=\"http://www.youtube.com/p/\$2&amp;hl=es&amp;fs=1\" /></object>'"),
);

$format_sections = array(
	"default" => "wiki_format_paragraph",
	"code" => "wiki_format_section_code",
);

/// This turns the multidimensional $format_array into arrays $in and $out
function wiki_format_get_array() {
	global $format_array;
	
	$in = array();
	$out = array();

	ksort( $format_array, SORT_STRING);
	foreach ( $format_array as $key => $value ) {
		array_push($in,  $value[0]);
		array_push($out, $value[1]);
	}
	return array($in,$out);
}

/// Character-level formating
function wiki_char_format($line)
{
	list($in, $out) = wiki_format_get_array();
	
	return preg_replace($in,$out,$line);
}

/// Verifica y genera los includes que son tags mágicos 
function wiki_parse_include($name, $arg) {
	global $include;
	global $includeout;
	$includeout = "";
	if ( isset($include[$name]) ) {
		eval("$include[$name]('$arg');");
	}
	return $includeout;
}

/// Arregla una URL para evitar redirecciones
function wiki_format_urlfix($string)
{
	$string = strtr($string,
		"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
		"abcdefghijklmnopqrstuvwxyz");
	$string = preg_replace("/[_ ]/m", "_", $string);
	$string = preg_replace("/'/m", "", $string);
	if ( !preg_match('!^http:!', $string) )
		$string = preg_replace("/:/m", "%3A", $string);
	return $string;
}

/// Quita los acentos de una cadena. Lo hace mediante strtr 
function killaccents($string)
{
	return strtr($string,
utf8_decode("ÁÉÍÓÚáéíóúÀÈÌÒÙàèìòùÑñ"),
			"AEIOUaeiouAEIOUaeiouNn"
		);
}

/** Formato, v2 
	Con 100 lineas menos de código.
*/

function wiki_format_paragraph($text) {
	return wiki_format_v2($text);
}

function wiki_format_section_code($text) {
	$lines = explode("\n",$text);
	$lang = preg_replace('/^ ([a-z]+).*$/s', '$1', $text);
	$text = preg_replace('/^ [^\n]+\n(.*)$/s', '$1', $text);
	$text = htmlspecialchars($text);
	switch ( $lang ) {
	case "html":
		$text = preg_replace(
			array(
				'/(?<=&lt;)([a-z0-9]+)/i',
				'!(?<=&lt;/)([a-z0-9]+)!i',
				'/(&[lg]t;)/'
				),
			array(
				'<span class="keyword">$1</span>',
				'<span class="keyword">$1</span>',
				'<span class="operator">$1</span>',
				),
			$text);
		break;
	case "vb":
		$text = preg_replace(
			array(
				'/(if|then|else|break|continue|select|case|is|rem)/i',
				'!(\'.*)!',
				),
			array(
				'<span class="keyword">$1</span>',
				'<span class="comment">$1</span>',
				),
			$text);
		break;
	case "c":
	default:
		$text = preg_replace(
			array(
				'/(if|else|break|continue)/i',
				'!(//.*|/\*.*?\*/)!',
				),
			array(
				'<span class="keyword">$1</span>',
				'<span class="comment">$1</span>',
				),
			$text);
		break;
	}
	return '<em>'.$lang.'</em><pre class="code">'.$text."</pre>";
}

function wiki_format($text) {
	global $format_sections;
	
	$ret = "";
	$sections = preg_split('/(§[A-Za-z0-9]*)/u', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
	
	for ( $i=0; $i<count($sections); $i++ ) {
		if ( preg_match('/^§/u', $sections[$i]) ) {
			$type = preg_replace('/^./u','',$sections[$i]);
			
			if ( $type == '' ||
				$type == 'normal'
			) { $type = 'default'; }
			
			if ( isset($format_sections[$type]) and
				function_exists($format_sections[$type]) ) {
				$ret .= call_user_func($format_sections[$type],
				$sections[$i+1]);
				$i++;
				continue;
			}
		}
		$ret .= call_user_func(
			$format_sections['default'],
			$sections[$i] );
	}
	
	return $ret;
}

function wiki_format_v2($text)
{
	$stack = array();
	$out = "";
	$last = "";
	$clear = "";
	$div = false;
	$skip = "";
	
	foreach ( explode("\n", $text) as $line ) {
		if ( $line == "" ) {
			if ( $last == ">" ) { $last = ""; }
			continue;
		}
		$sub = substr($line,1);
		$fsub = wiki_char_format($sub);
		
		if ( $line[0] != $last ) { $out.=$clear; $clear=""; }
		
		switch ( $line[0] ) {
		case "|":
			if ( $last != "|" ) { $out.="<table>\n"; $clear = "</table>\n"; }
			$out.="<tr>";
			foreach ( explode("|",$sub) as $cell) {
				if ( $cell[0] == "=" )
					$out.="<th>".wiki_char_format(substr($cell,1))."</th>";
				else
					$out.="<td>".wiki_char_format($cell)."</td>";
			}
			$out.="</tr>\n";
			break;
		case "#":
			if ( preg_match("/#/", $skip) ) { 
				$out.="<p>".wiki_char_format($line)."</p>\n";
				break;
			}
			if ( $last != "#" ) { $out.="<ol>\n"; $clear = "</ol>\n"; }
			$out.="<li>$fsub</li>\n";
			break;
		case "*":
			if ( $last != "*" ) { $out.="<ul>\n"; $clear = "</ul>\n"; }
			$out.="<li>$fsub</li>\n";
			break;
		case ">":
			if ( $last != ">" ) { 
				$out.="<blockquote>\n"; $clear = "</blockquote>\n"; }
			$out.="<p>$fsub</p>\n";
			break;
/*      case " ":
			if ( $last != " " ) { $out.="<pre>\n"; $clear = "</pre>\n"; }
			$out .= $fsub;*/
		case "=":
			$count = strlen(preg_replace("/^(=+).*/","\$1",$line));
			$out.="<h$count>".
				wiki_char_format(preg_replace("/^=+(.*)/","\$1",$line)).
				"</h$count>\n";
			$line = "=";
			break;
		case "%":
			if ( substr($line,1,1) == "%") {
				$out.="<div class=\"blank\">\n".
					wiki_char_format(substr($line,2)).
					"</div>\n";
			} else 	if ( !$div ) {
				if ( substr($line,1,5) == "right" ) {
					$out.="<div class=\"blockright\">\n";
					$div = true;
				} else if ( substr($line,1,4) == "left" ) {
					$out.="<div class=\"blockleft\">\n";
					$div = true;
				} else if ( substr($line,1,4) == "code" ) {
					$out.="<div class=\"code\">\n";
					$div = true;
					$skip = "#";
				} else if ( substr($line,1,5) == "lyric" ) {
					$out.="<div class=\"lyric\">";
					$div = true;
					$skip = "#";
				} else //if ( $sub != "" ) { $out .= "<p>$fsub</p>";    }
				{
					$class = preg_replace("/^.([A-Za-z0-9]+)$/",
						"\$1", $line);
					if ( $class != "" ) {
						$out .= "<div class=\"$class\">\n";
						$div = true;
					}
				}
			} else {
				$out .= "</div>\n";
				$div = false;
				$skip = "";
				if ( $sub != "" ) { $out .= "<p>$fsub</p>\n";   }
			}
			break;
		default:
			//if ( $line != "" )
				$out.="<p>".wiki_char_format($line)."</p>\n";
		}
		if ( isset($line[0]) ) $last = $line[0];
	}
	if ( $clear != "" ) { $out .= $clear; }
	if ( $div ) { $out .= "</div>\n"; }
	
	wiki_linktracker($out);
	return $out;
}


/// Alter a link
function tracklink($text,$url,$all,$complete) {
	global $tools, $config, $links;
	
	if ( ! is_array($links) ) $links = array( );
	if ( ! isset($links['missing'])  || ! is_array($links['missing'])  ) $links['missing']  = array();
	if ( ! isset($links['external']) || ! is_array($links['external']) ) $links['external'] = array();
	if ( ! isset($links['internal']) || ! is_array($links['internal']) ) $links['internal'] = array();
	$urlbase = preg_replace("!\?.*!","",$url);
	$urlbase = preg_replace("!%3A!",":",$url);
	
	if ( preg_match("! title=!",$all) ) {
		return "$all$text</a>";
	}

	// External link
	if ( preg_match("!^http://!", $url) ) {
		$all = preg_replace("/>/", " title=\"$url\">",$all);
		array_push($links['external'], $url);
		return "$all$text ".'</a><img src="/img/external.png" alt="(externo)" />';
	}
	
	// System (internal) link
	if ( isset( $tools[$urlbase] ) ) {
		$linktracker .= "<li>$url (system)</li>";
		return $complete;
	}
	
	// Not a wikidoc
	if ( !preg_match("!^[a-z0-9_\- /:%áéíóúñÁÉÍÓÚÑ]+$!i", $urlbase ) ) {
		$linktracker .= "<li>$url (unknown)</li>";
		return $complete;
	}
	
	// Existing wikidoc
	if ( file_exists("$config[datadir]/data-$urlbase.xml") ) {
		$linktracker .= "<li>$url (wikidoc, exists)</li>";
		$doc = wiki_load_file("$config[datadir]/data-$urlbase.xml", false);
		if ( !preg_match("!title=[\"'].*?[\"']!", $urlbase) ) {
			$tmp = "$doc[title]: $doc[description]";
			xml_clean($tmp);
			$all = preg_replace("!>!"," title=\"".$tmp."\">",$all);
		}
		array_push($links['internal'], $url);
		return "$all$text</a>";
	}
	
	//error_log("$config[datadir]/data-$urlbase.xml non-existing");
	// Defaults to nonexisting wikidoc
	$linktracker .= "<li>$url (wikidoc, non-exist)</li>";
	if ( ! preg_match("!title=[\"'].*[\"']!", $all)  ) {
		$tmp = $text;
		xml_clean($tmp);
		$all = preg_replace("/>/", " title=\"Crear el documento &quot;".
			$tmp."&quot;\">",$all);
	}

	$all = preg_replace("!(href=[\"'][^\"']+)([\"'])!i", "\$1?edit\$2", $all);
	if ( ! preg_match("/ref=[\"'][^\"']*nofollow[^\"']*[\"']/i", $all)  ) {
		$all = preg_replace("/>/", " rel=\"nofollow\">", $all);
	}

	array_push($links['missing'], $urlbase);
	return "<span class=\"newdoc\">{$all}$text</a></span>";
}

/// Find all links and report status
function wiki_linktracker(&$text) {
	global $linktracker;
	if ( !isset($linktracker) ) $linktracker = "";

	$text = preg_replace(
		"!(<a([^>]*?)(href=\"([^\"]+)\")([^>]*?)>)([^<]+)(</a>)!mie",
		// $1: <a...>
		// $2: pre-href
		// $3: href="..."
		// $4:       ...
		// $5: post-href
		// $6 <a>(...)</a>
		// $7 </a>
		'tracklink("$6","$4","$1","$1$6$7")',
		$text);
	
	return 0;
}

Return current item: Ratawiki