Exemple #1
0
function bb2diaspora($Text, $preserve_nl = false, $fordiaspora = true)
{
    // Since Diaspora is creating a summary for links, this function removes them before posting
    if ($fordiaspora) {
        $Text = bb_remove_share_information($Text);
    }
    /**
     * Transform #tags, strip off the [url] and replace spaces with underscore
     */
    $URLSearchString = "^\\[\\]";
    $Text = preg_replace_callback("/#\\[url\\=([{$URLSearchString}]*)\\](.*?)\\[\\/url\\]/i", create_function('$match', 'return \'#\'. str_replace(\' \', \'_\', $match[2]);'), $Text);
    // Converting images with size parameters to simple images. Markdown doesn't know it.
    $Text = preg_replace("/\\[img\\=([0-9]*)x([0-9]*)\\](.*?)\\[\\/img\\]/ism", '[img]$3[/img]', $Text);
    // Convert it to HTML - don't try oembed
    if ($fordiaspora) {
        $Text = bbcode($Text, $preserve_nl, false, 3);
    } else {
        $Text = bbcode($Text, $preserve_nl, false, 4);
        // Libertree doesn't convert a harizontal rule if there isn't a linefeed
        $Text = str_replace("<hr />", "<br /><hr />", $Text);
    }
    // Now convert HTML to Markdown
    $md = new Markdownify(false, false, false);
    $Text = $md->parseString($Text);
    // The Markdownify converter converts underscores '_' in URLs to '\_', which
    // messes up the URL. Manually fix these
    $count = 1;
    $pos = bb_find_open_close($Text, '[', ']', $count);
    while ($pos !== false) {
        $start = substr($Text, 0, $pos['start']);
        $subject = substr($Text, $pos['start'], $pos['end'] - $pos['start'] + 1);
        $end = substr($Text, $pos['end'] + 1);
        $subject = str_replace('\\_', '_', $subject);
        $Text = $start . $subject . $end;
        $count++;
        $pos = bb_find_open_close($Text, '[', ']', $count);
    }
    // If the text going into bbcode() has a plain URL in it, i.e.
    // with no [url] tags around it, it will come out of parseString()
    // looking like: <http://url.com>, which gets removed by strip_tags().
    // So take off the angle brackets of any such URL
    $Text = preg_replace("/<http(.*?)>/is", "http\$1", $Text);
    // Remove all unconverted tags
    $Text = strip_tags($Text);
    // Remove any leading or trailing whitespace, as this will mess up
    // the Diaspora signature verification and cause the item to disappear
    $Text = trim($Text);
    call_hooks('bb2diaspora', $Text);
    return $Text;
}
 /**
  * Get edit content
  * 
  * @access public
  * @param array $params
  * @return string $content
  */
 public function get_edit_content($params = array())
 {
     global $config;
     $content = $this->data['content'];
     // Convert to markdown
     require_once $config['base'] . '/lib/includes/markdownify.php';
     $Markdownify = new Markdownify();
     $content = $Markdownify->parseString($content);
     return $content;
 }
 public function createBodies()
 {
     $this->createHtmlBody();
     if ($this->htmlBody > '') {
         $md = new Markdownify(true, false, false);
         //$this->txtBody = str_replace('</body></html>','',$md->parseString($this->htmlBody));
         $this->wrap($md->parseString($this->htmlBody));
     } else {
         $this->createTextBody();
     }
 }
Exemple #4
-1
 function markdownify(Silex\Application $app, Request $request)
 {
     $html = $_POST['html'];
     if (isHtml($html)) {
         require_once __DIR__ . '/classes/markdownify/markdownify_extra.php';
         $md = new Markdownify(false, 80, false);
         $output = $md->parseString($html);
     } else {
         $output = $html;
     }
     echo $output;
 }
Exemple #5
-1
function bb2diaspora($Text, $preserve_nl = false, $fordiaspora = true)
{
    // Re-enabling the converter again.
    // The bbcode parser now handles youtube-links (and the other stuff) correctly.
    // Additionally the html code is now fixed so that lists are now working.
    /**
     * Transform #tags, strip off the [url] and replace spaces with underscore
     */
    $Text = preg_replace_callback('/#\\[url\\=(\\w+.*?)\\](\\w+.*?)\\[\\/url\\]/i', create_function('$match', 'return \'#\'. str_replace(\' \', \'_\', $match[2]);'), $Text);
    // Converting images with size parameters to simple images. Markdown doesn't know it.
    $Text = preg_replace("/\\[img\\=([0-9]*)x([0-9]*)\\](.*?)\\[\\/img\\]/ism", '[img]$3[/img]', $Text);
    // the following was added on 10-January-2012 due to an inability of Diaspora's
    // new javascript markdown processor to handle links with images as the link "text"
    // It is not optimal and may be removed if this ability is restored in the future
    //if ($fordiaspora)
    //	$Text = preg_replace("/\[url\=([^\[\]]*)\]\s*\[img\](.*?)\[\/img\]\s*\[\/url\]/ism",
    //				"[url]$1[/url]\n[img]$2[/img]", $Text);
    // Remove the avatar picture since that isn't looking good on the other side
    //$Text = preg_replace("/\[share(.*?)avatar\s?=\s?'.*?'\s?(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","\n[share$1$2]$3[/share]",$Text);
    // Convert it to HTML - don't try oembed
    $Text = bbcode($Text, $preserve_nl, false);
    // Now convert HTML to Markdown
    $md = new Markdownify(false, false, false);
    $Text = $md->parseString($Text);
    // The Markdownify converter converts underscores '_' in URLs to '\_', which
    // messes up the URL. Manually fix these
    $count = 1;
    $pos = bb_find_open_close($Text, '[', ']', $count);
    while ($pos !== false) {
        $start = substr($Text, 0, $pos['start']);
        $subject = substr($Text, $pos['start'], $pos['end'] - $pos['start'] + 1);
        $end = substr($Text, $pos['end'] + 1);
        $subject = str_replace('\\_', '_', $subject);
        $Text = $start . $subject . $end;
        $count++;
        $pos = bb_find_open_close($Text, '[', ']', $count);
    }
    // If the text going into bbcode() has a plain URL in it, i.e.
    // with no [url] tags around it, it will come out of parseString()
    // looking like: <http://url.com>, which gets removed by strip_tags().
    // So take off the angle brackets of any such URL
    $Text = preg_replace("/<http(.*?)>/is", "http\$1", $Text);
    // Remove all unconverted tags
    $Text = strip_tags($Text);
    /* Old routine
    
    	$ev = bbtoevent($Text);
    
    	// Replace any html brackets with HTML Entities to prevent executing HTML or script
    	// Don't use strip_tags here because it breaks [url] search by replacing & with amp
    
    	$Text = str_replace("<", "&lt;", $Text);
    	$Text = str_replace(">", "&gt;", $Text);
    
    	// If we find any event code, turn it into an event.
    	// After we're finished processing the bbcode we'll
    	// replace all of the event code with a reformatted version.
    
    	if($preserve_nl)
    		$Text = str_replace(array("\n","\r"), array('',''),$Text);
    	else
    		// Remove the "return" character, as Diaspora uses only the "newline"
    		// character, so having the "return" character can cause signature
    		// failures
    		$Text = str_replace("\r", "", $Text);
    
    
    	// Set up the parameters for a URL search string
    	$URLSearchString = "^\[\]";
    	// Set up the parameters for a MAIL search string
    	$MAILSearchString = $URLSearchString;
    
    	// Perform URL Search
    
    	// [img]pathtoimage[/img]
    
    	// the following was added on 10-January-2012 due to an inability of Diaspora's
    	// new javascript markdown processor to handle links with images as the link "text"
    	// It is not optimal and may be removed if this ability is restored in the future
    
    	$Text = preg_replace("/\[url\=([$URLSearchString]*)\]\[img\](.*?)\[\/img\]\[\/url\]/ism",
    		'![' . t('image/photo') . '](' . '$2' . ')' . "\n" . '[' . t('link') . '](' . '$1' . ')', $Text);
    
    	$Text = preg_replace("/\[bookmark\]([$URLSearchString]*)\[\/bookmark\]/ism", '[$1]($1)', $Text);
    	$Text = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[$2]($1)', $Text);
    
    	$Text = preg_replace("/\[url\]([$URLSearchString]*)\[\/url\]/ism", '[$1]($1)', $Text);
    	$Text = preg_replace("/\#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[#$2]($1)', $Text);
    	$Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[$2]($1)', $Text);
    
    
    	$Text = preg_replace("/\[img\](.*?)\[\/img\]/", '![' . t('image/photo') . '](' . '$1' . ')', $Text);
    	$Text = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/", '![' . t('image/photo') . '](' . '$2' . ')', $Text);
    
    	// Perform MAIL Search
    	$Text = preg_replace("(\[mail\]([$MAILSearchString]*)\[/mail\])", '[$1](mailto:$1)', $Text);
    	$Text = preg_replace("/\[mail\=([$MAILSearchString]*)\](.*?)\[\/mail\]/", '[$2](mailto:$1)', $Text);
    
    	$Text = str_replace('*', '\\*', $Text);
    	$Text = str_replace('_', '\\_', $Text);
    
    	$Text = str_replace('`','\\`', $Text);
    
    	// Check for bold text
    	$Text = preg_replace("(\[b\](.*?)\[\/b\])is",'**$1**',$Text);
    
    	// Check for italics text
    	$Text = preg_replace("(\[i\](.*?)\[\/i\])is",'_$1_',$Text);
    
    	// Check for underline text
    	// Replace with italics since Diaspora doesn't have underline
    	$Text = preg_replace("(\[u\](.*?)\[\/u\])is",'_$1_',$Text);
    
    	// Check for strike-through text
    	$Text = preg_replace("(\[s\](.*?)\[\/s\])is",'**[strike]**$1**[/strike]**',$Text);
    
    	// Check for over-line text
    //	$Text = preg_replace("(\[o\](.*?)\[\/o\])is",'<span class="overline">$1</span>',$Text);
    
    	// Check for colored text
    	// Remove color since Diaspora doesn't support it
    	$Text = preg_replace("(\[color=(.*?)\](.*?)\[\/color\])is","$2",$Text);
    
    	// Check for sized text
    	// Remove it since Diaspora doesn't support sizes very well
    	$Text = preg_replace("(\[size=(.*?)\](.*?)\[\/size\])is","$2",$Text);
    
    	// Check for list text
    	$endlessloop = 0;
    	while ((((strpos($Text, "[/list]") !== false) && (strpos($Text, "[list") !== false)) ||
    	       ((strpos($Text, "[/ol]") !== false) && (strpos($Text, "[ol]") !== false)) || 
    	       ((strpos($Text, "[/ul]") !== false) && (strpos($Text, "[ul]") !== false)) || 
    	       ((strpos($Text, "[/li]") !== false) && (strpos($Text, "[li]") !== false))) && (++$endlessloop < 20)) {
    		$Text = preg_replace_callback("/\[list\](.*?)\[\/list\]/is", 'diaspora_ul', $Text);
    		$Text = preg_replace_callback("/\[list=1\](.*?)\[\/list\]/is", 'diaspora_ol', $Text);
    		$Text = preg_replace_callback("/\[list=i\](.*?)\[\/list\]/s",'diaspora_ol', $Text);
    		$Text = preg_replace_callback("/\[list=I\](.*?)\[\/list\]/s", 'diaspora_ol', $Text);
    		$Text = preg_replace_callback("/\[list=a\](.*?)\[\/list\]/s", 'diaspora_ol', $Text);
    		$Text = preg_replace_callback("/\[list=A\](.*?)\[\/list\]/s", 'diaspora_ol', $Text);
    		$Text = preg_replace_callback("/\[ul\](.*?)\[\/ul\]/is", 'diaspora_ul', $Text);
    		$Text = preg_replace_callback("/\[ol\](.*?)\[\/ol\]/is", 'diaspora_ol', $Text);
    		$Text = preg_replace("/\[li\]( *)(.*?)\[\/li\]/s", '* $2' ,$Text);
    	}
    
    	// Just get rid of table tags since Diaspora doesn't support tables
    	$Text = preg_replace("/\[th\](.*?)\[\/th\]/s", '$1' ,$Text);
    	$Text = preg_replace("/\[td\](.*?)\[\/td\]/s", '$1' ,$Text);
    	$Text = preg_replace("/\[tr\](.*?)\[\/tr\]/s", '$1' ,$Text);
    	$Text = preg_replace("/\[table\](.*?)\[\/table\]/s", '$1' ,$Text);
    
    	$Text = preg_replace("/\[table border=(.*?)\](.*?)\[\/table\]/s", '$2' ,$Text);
    //	$Text = preg_replace("/\[table border=0\](.*?)\[\/table\]/s", '<table border="0" >$1</table>' ,$Text);
    
    
    //	$Text = str_replace("[*]", "<li>", $Text);
    
    	// Check for font change text
    //	$Text = preg_replace("(\[font=(.*?)\](.*?)\[\/font\])","<span style=\"font-family: $1;\">$2</span>",$Text);
    
    
    	$Text = preg_replace_callback("/\[code\](.*?)\[\/code\]/is",'stripdcode_br_cb',$Text);
    
    	// Check for [code] text
    	$Text = preg_replace("/(\[code\])+(.*?)(\[\/code\])+/is","\t$2\n", $Text);
    
    
    
    
    	// Declare the format for [quote] layout
    	//	$QuoteLayout = '<blockquote>$1</blockquote>';
    	// Check for [quote] text
    	$Text = preg_replace("/\[quote\](.*?)\[\/quote\]/is",">$1\n\n", $Text);
    	$Text = preg_replace("/\[quote=(.*?)\](.*?)\[\/quote\]/is",">$2\n\n", $Text);
    
    	// Images
    
    	// html5 video and audio
    
    	$Text = preg_replace("/\[video\](.*?)\[\/video\]/", '$1', $Text);
    
    	$Text = preg_replace("/\[audio\](.*?)\[\/audio\]/", '$1', $Text);
    
    //	$Text = preg_replace("/\[iframe\](.*?)\[\/iframe\]/", '<iframe src="$1" width="425" height="350"><a href="$1">$1</a></iframe>', $Text);
    
    	// [img=widthxheight]image source[/img]
    //	$Text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/", '<img src="$3" style="height:{$2}px; width:{$1}px;" >', $Text);
    
    	$Text = preg_replace("/\[youtube\]https?:\/\/www.youtube.com\/watch\?v\=(.*?)\[\/youtube\]/ism",'http://www.youtube.com/watch?v=$1',$Text); 
    	$Text = preg_replace("/\[youtube\]https?:\/\/www.youtube.com\/embed\/(.*?)\[\/youtube\]/ism",'http://www.youtube.com/watch?v=$1',$Text); 
    	$Text = preg_replace("/\[youtube\]https?:\/\/youtu.be\/(.*?)\[\/youtube\]/ism",'http://www.youtube.com/watch?v=$1',$Text); 
    	$Text = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism", 'http://www.youtube.com/watch?v=$1', $Text);
    
    	$Text = preg_replace("/\[vimeo\]https?:\/\/player.vimeo.com\/video\/([0-9]+)(.*?)\[\/vimeo\]/ism",'http://vimeo.com/$1',$Text); 
    	$Text = preg_replace("/\[vimeo\]https?:\/\/vimeo.com\/([0-9]+)(.*?)\[\/vimeo\]/ism",'http://vimeo.com/$1',$Text); 
    	$Text = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism", 'http://vimeo.com/$1',$Text);
    
    
    	$Text = str_replace('[nosmile]','',$Text);
    
    	// oembed tag
    	//	$Text = oembed_bbcode2html($Text);
    
    	// If we found an event earlier, strip out all the event code and replace with a reformatted version.
    
    	if(x($ev,'start')) {
    
    		$sub = format_event_diaspora($ev);
    
    		$Text = preg_replace("/\[event\-summary\](.*?)\[\/event\-summary\]/is",'',$Text);
    		$Text = preg_replace("/\[event\-description\](.*?)\[\/event\-description\]/is",'',$Text);
    		$Text = preg_replace("/\[event\-start\](.*?)\[\/event\-start\]/is",$sub,$Text);
    		$Text = preg_replace("/\[event\-finish\](.*?)\[\/event\-finish\]/is",'',$Text);
    		$Text = preg_replace("/\[event\-location\](.*?)\[\/event\-location\]/is",'',$Text);
    		$Text = preg_replace("/\[event\-adjust\](.*?)\[\/event\-adjust\]/is",'',$Text);
    	}
    
    	$Text = preg_replace("/\<(.*?)(src|href)=(.*?)\&amp\;(.*?)\>/ism",'<$1$2=$3&$4>',$Text);
    
    	$Text = preg_replace_callback('/\[(.*?)\]\((.*?)\)/ism','unescape_underscores_in_links',$Text);
    
    */
    // Remove any leading or trailing whitespace, as this will mess up
    // the Diaspora signature verification and cause the item to disappear
    $Text = trim($Text);
    call_hooks('bb2diaspora', $Text);
    return $Text;
}
    $user = (isset($_POST['user']) and !empty($_POST['user'])) ? trim($_POST['user']) : NULL;
    if (!in_array($user, $valid_users)) {
        throw new Exception('You do not have access to use this web service.');
    }
    $operation = (isset($_POST['operation']) and !empty($_POST['operation'])) ? trim($_POST['operation']) : NULL;
    if (!in_array($operation, array('markdown', 'markdownify'))) {
        throw new Exception('An invalid operation was requested of this service.');
    }
    $content = (isset($_POST['content']) and !empty($_POST['content'])) ? stripslashes(trim($_POST['content'])) : NULL;
    if (empty($content)) {
        throw new Exception('There was no content provided in which to apply this service.');
    }
    if ($operation == 'markdown') {
        $response['result'] = Markdown($content);
    } elseif ($operation == 'markdownify') {
        $markdownify = new Markdownify();
        $response['result'] = $markdownify->parseString($content);
    } else {
        throw new Exception('An unknown error occured while trying to use this service.');
    }
} catch (Exception $e) {
    $response['status'] = 'error';
    $response['message'] = $e->getMessage();
}
$benchmark_finish = microtime(TRUE);
$response['benchmark'] = number_format(($benchmark_finish - $benchmark_start) * 1000, 2) . ' ms';
$response['timestamp'] = date('Y-m-d H:i:s');
$output = json_encode($response);
if ($fp = @fopen('markdown_service.log', 'a')) {
    $response['user'] = array_search($user, $valid_users);
    $log = json_encode($response);
Exemple #7
-1
 protected static function initialize()
 {
     if (self::$initialized) {
         return;
     }
     self::$initialized = TRUE;
     # we don't have to do this every time
     $search = array();
     $replace = array();
     foreach (self::$escapeInText as $s => $r) {
         array_push($search, '#(?<!\\\\)' . $s . '#U');
         array_push($replace, $r);
     }
     self::$escapeInText = array('search' => $search, 'replace' => $replace);
 }
Exemple #8
-1
<?php
require('config.php');
require('markdownify/markdownify_extra.php');
require('curl_github.php');
$md = new Markdownify(FALSE,FALSE,FALSE);
$doc = new DOMDocument();
$doc->load($issuesXML);
$issues = $doc->getElementsByTagName('item');
$issueCount = $issues->length;
for ($i=$issues->length-1; $i>=0; $i--) {
  $issue = array('labels'=>array());
  foreach ($issues->item($i)->childNodes as $node) {
    if ($node->nodeName == 'comments') {
      if (trim($node->textContent)) $issue[$node->nodeName] = $node->childNodes;
    } elseif ($node->nodeName =='attachments') {
      if ($node->childNodes->length > 1) $issue['attachments'] = $node->childNodes;
    } elseif ($node->nodeName == 'component') {
      $issue['labels'][] = sanitizeLabel($node->nodeValue);
    } else {
      $issue[$node->nodeName] = trim($node->nodeValue);
    }
    if ($node->nodeName == 'status') {
      $issue['statusid'] = $node->attributes->getNamedItem('id')->value;
    }
  }
  $resolved = ($issue['statusid'] != 1 && $issue['statusid'] != 3);
  
  $json = array();
  $json['title'] = sprintf('[%s] %s', $issue['key'], $issue['summary']);
  
  $json['labels'] = $issue['labels'];
 /**
  * Convert data
  *
  * @param   string  $data
  * @return  string
  */
 public function convert($data)
 {
     // markdownify doesn't like attrs
     $md = new Markdownify();
     return $md->parseString($data);
 }
/**
 * Transformer un mail HTML en mail Texte proprement :
 * - les tableaux de mise en page sont utilis�s pour structurer le mail texte
 * - le reste du HTML est markdownifie car c'est un format texte lisible et conventionnel
 *
 * @param string $html
 * @return string
 */
function facteur_mail_html2text($html){
	// nettoyer les balises de mise en page html
	$html = preg_replace(",</(td|th)>,Uims","<br/>",$html);
	$html = preg_replace(",</(table)>,Uims","@@@hr@@@",$html);
	$html = preg_replace(",</?(html|body|table|td|th|tbody|thead|center|article|section|span)[^>]*>,Uims","\n\n",$html);

	// commentaires html et conditionnels
	$html = preg_replace(",<!--.*-->,Uims","\n",$html);
	$html = preg_replace(",<!\[.*\]>,Uims","\n",$html);

	$html = preg_replace(",<(/?)(div|tr|caption)([^>]*>),Uims","<\\1p>",$html);
	$html = preg_replace(",(<p>\s*)+,ims","<p>",$html);
	$html = preg_replace(",<br/?>\s*</p>,ims","</p>",$html);
	$html = preg_replace(",</p>\s*<br/?>,ims","</p>",$html);
	$html = preg_replace(",(</p>\s*(@@@hr@@@)?\s*)+,ims","</p>\\2",$html);
	$html = preg_replace(",(<p>\s*</p>),ims","",$html);

	// succession @@@hr@@@<hr> et <hr>@@@hr@@@
	$html = preg_replace(",@@@hr@@@\s*(<[^>]*>\s*)?<hr[^>]*>,ims","@@@hr@@@\n",$html);
	$html = preg_replace(",<hr[^>]*>\s*(<[^>]*>\s*)?@@@hr@@@,ims","\n@@@hr@@@",$html);

	$html = preg_replace(",<textarea[^>]*spip_cadre[^>]*>(.*)</textarea>,Uims","<code>\n\\1\n</code>",$html);

	// vider le contenu de qqunes :
	$html = preg_replace(",<head[^>]*>.*</head>,Uims","\n",$html);

	// Liens :
	// Nettoyage des liens des notes de bas de page
	$html = preg_replace("@<a href=\"#n(b|h)[0-9]+-[0-9]+\" name=\"n(b|h)[0-9]+-[0-9]+\" class=\"spip_note\">([0-9]+)</a>@", "\\3", $html);
	// Supprimer tous les liens internes
	$html = preg_replace("/\<a href=['\"]#(.*?)['\"][^>]*>(.*?)<\/a>/ims","\\2", $html);
	// Remplace tous les liens
	preg_match_all("/\<a href=['\"](.*?)['\"][^>]*>(.*?)<\/a>/ims", $html,$matches,PREG_SET_ORDER);
	$prelinks = $postlinks = array();
	if (!function_exists('url_absolue'))
		include_spip('inc/filtres');
	foreach ($matches as $k => $match){
		$link = "@@@link$k@@@";
		$url = str_replace("&amp;","&",$match[1]);
		if ($match[2]==$match[1] OR $match[2]==$url){
			// si le texte est l'url :
			$prelinks[$match[0]] = "$link";
		}
		else {
			// texte + url
			$prelinks[$match[0]] = $match[2] . " ($link)";
		}
		// passer l'url en absolu dans le texte sinon elle n'est pas clicable ni utilisable
		$postlinks[$link] = url_absolue($url);
	}
	$html = str_replace(array_keys($prelinks), array_values($prelinks),$html);

	// les images par leur alt ?
	// au moins les puces
	$html = preg_replace(',<img\s[^>]*alt="-"[^>]*>,Uims','-',$html);
	// les autres
	$html = preg_replace(',<img\s[^>]*alt=[\'"]([^\'"]*)[\'"][^>]*>,Uims',"\\1",$html);
	// on vire celles sans alt
	$html = preg_replace(",</?(img)[^>]*>,Uims","\n",$html);

	// espaces
	$html = str_replace("&nbsp;"," ",$html);
	$html = preg_replace(",<p>\s+,ims","<p>",$html);

	#return $html;
	include_spip("lib/markdownify/markdownify");
	$parser = new Markdownify('inline',false,false);
	$texte = $parser->parseString($html);

	$texte = str_replace(array_keys($postlinks), array_values($postlinks),$texte);


	// trim et sauts de ligne en trop ou pas assez
	$texte = trim($texte);
	$texte = str_replace("<br />\n","\n",$texte);
	$texte = preg_replace(",(@@@hr@@@\s*)+\Z,ims","",$texte);
	$texte = preg_replace(",(@@@hr@@@\s*\n)+,ims","\n\n\n".str_pad("-",75,"-")."\n\n\n",$texte);
	$texte = preg_replace(",(\n#+\s),ims","\n\n\\1",$texte);
	$texte = preg_replace(",(\n\s*)(\n\s*)+(\n)+,ims","\n\n\n",$texte);


	// <p> et </p> restants
	$texte = str_replace(array("<p>","</p>"),array("",""),$texte);

	// entites restantes ? (dans du code...)
	include_spip('inc/charsets');
	$texte = unicode2charset($texte);
	$texte = str_replace(array('&#039;', '&#034;'),array("'",'"'), $texte);


	// Faire des lignes de 75 caracteres maximum
	return trim(wordwrap($texte));
}
Exemple #11
-1
if (!empty($_POST['input'])) {
    include 'markdownify_extra.php';
    if (!isset($_POST['leap'])) {
        $leap = MDFY_LINKS_EACH_PARAGRAPH;
    } else {
        $leap = $_POST['leap'];
    }
    if (!isset($_POST['keepHTML'])) {
        $keephtml = MDFY_KEEPHTML;
    } else {
        $keephtml = $_POST['keepHTML'];
    }
    if (!empty($_POST['extra'])) {
        $md = new Markdownify_Extra($leap, MDFY_BODYWIDTH, $keephtml);
    } else {
        $md = new Markdownify($leap, MDFY_BODYWIDTH, $keephtml);
    }
    if (ini_get('magic_quotes_gpc')) {
        $_POST['input'] = stripslashes($_POST['input']);
    }
    $output = $md->parseString($_POST['input']);
} else {
    $_POST['input'] = '';
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
		<title>HTML to Markdown Converter</title>
	</head>
Exemple #12
-1
                        	<tr>
                                <td>转换之前日志内容</td>
                                <td>升级前0.9版前,所有日志内容都保存的是HTML代码,该功能可以把HTML代码转换成markdown格式。</td>
                                <td><button id="act2" name="btnExe" type="submit" class="btn-s">开始执行</button></td>
                            </tr>
                         </tbody>
                    </table>
                <?php 
$action = isset($_GET['action']) ? $_GET['action'] : null;
if ($action != null) {
    $db = Typecho_Db::get();
    $sql = $db->select()->from('table.contents')->where('table.contents.type = ?', 'post')->order('table.contents.created', Typecho_Db::SORT_ASC);
    $content = $db->fetchAll($sql);
    foreach ($content as $one) {
        if (substr($one['text'], 0, 15) != '<!--markdown-->') {
            $markdownify = new Markdownify();
            if ($action == 'act1') {
                $sql = $db->update('table.contents')->rows(array('text' => '<!--markdown-->' . $one['text']))->where('cid = ?', $one['cid']);
            } else {
                if ($action == 'act2') {
                    $one['text'] = $markdownify->parseString($one['text']);
                    $sql = $db->update('table.contents')->rows(array('text' => '<!--markdown-->' . $one['text']))->where('cid = ?', $one['cid']);
                }
            }
            $db->query($sql);
        }
    }
    ?>
				<div class="message success popup" style="position: absolute; top: 36px; display: block;">
					<ul>
						<li>好了,执行完了,我也不知道是不是全部成功了,你自己去看看吧!</li>
Exemple #13
-1
 public function markdownify(Silex\Application $app, Request $request)
 {
     $html = $request->request->get('html');
     if (isHtml($html)) {
         require_once __DIR__ . '/../../../classes/markdownify/markdownify_extra.php';
         $markdown = new \Markdownify(false, 80, false);
         $output = $markdown->parseString($html);
     } else {
         $output = $html;
     }
     return $output;
 }
Exemple #14
-1
<?php

$html = "\n\n    <h1>Sed ne, dum huic obsequor, vobis molestus sim.</h1>\n\n<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cur ipse Pythagoras et Aegyptum lustravit et Persarum magos adiit? Eam tum adesse, cum dolor omnis absit; Quae diligentissime contra Aristonem dicuntur a Chryippo. <a href='http://loripsum.net/' target='_blank'>Scisse enim te quis coarguere possit?</a> </p>\n\n<p>Non dolere, inquam, istud quam vim habeat postea videro; A quibus propter discendi cupiditatem videmus ultimas terras esse peragratas. Nam et complectitur verbis, quod vult, et dicit plane, quod intellegam; Indicant pueri, in quibus ut in speculis natura cernitur. Sin dicit obscurari quaedam nec apparere, quia valde parva sint, nos quoque concedimus; <b>Quis hoc dicit?</b> Maximas vero virtutes iacere omnis necesse est voluptate dominante. <i>Equidem, sed audistine modo de Carneade?</i> Sin dicit obscurari quaedam nec apparere, quia valde parva sint, nos quoque concedimus; </p>\n\n<p><a href='http://loripsum.net/' target='_blank'>Easdemne res?</a> <a href='http://loripsum.net/' target='_blank'>Hoc non est positum in nostra actione.</a> Quam ob rem tandem, inquit, non satisfacit? Eam si varietatem diceres, intellegerem, ut etiam non dicente te intellego; Si enim ad populum me vocas, eum. Ne in odium veniam, si amicum destitero tueri. Te ipsum, dignissimum maioribus tuis, voluptasne induxit, ut adolescentulus eriperes P. <i>Confecta res esset.</i> </p>\n\n<h2>Non quaero, quid dicat, sed quid convenienter possit rationi et sententiae suae dicere.</h2>\n\n<p>Magno hic ingenio, sed res se tamen sic habet, ut nimis imperiosi philosophi sit vetare meminisse. Esse enim quam vellet iniquus iustus poterat inpune. <b>Quorum altera prosunt, nocent altera.</b> Deinde disputat, quod cuiusque generis animantium statui deceat extremum. Paulum, cum regem Persem captum adduceret, eodem flumine invectio? Nihil opus est exemplis hoc facere longius. Sic consequentibus vestris sublatis prima tolluntur. Nam memini etiam quae nolo, oblivisci non possum quae volo. Diodorus, eius auditor, adiungit ad honestatem vacuitatem doloris. </p>\n\n<ol>\n\t<li>Num igitur utiliorem tibi hunc Triarium putas esse posse, quam si tua sint Puteolis granaria?</li>\n\t<li>Oratio me istius philosophi non offendit;</li>\n\t<li>Mihi quidem Homerus huius modi quiddam vidisse videatur in iis, quae de Sirenum cantibus finxerit.</li>\n\t<li>Quicquid porro animo cernimus, id omne oritur a sensibus;</li>\n\t<li>Materiam vero rerum et copiam apud hos exilem, apud illos uberrimam reperiemus.</li>\n</ol>\n\n\n<p>Sine ea igitur iucunde negat posse se vivere? Age nunc isti doceant, vel tu potius quis enim ista melius? Hoc mihi cum tuo fratre convenit. Sed erat aequius Triarium aliquid de dissensione nostra iudicare. At Zeno eum non beatum modo, sed etiam divitem dicere ausus est. Nihil illinc huc pervenit. Ita graviter et severe voluptatem secrevit a bono. </p>\n\n<ul>\n\t<li>Quod cum accidisset ut alter alterum necopinato videremus, surrexit statim.</li>\n\t<li>In his igitur partibus duabus nihil erat, quod Zeno commutare gestiret.</li>\n\t<li>De ingenio eius in his disputationibus, non de moribus quaeritur.</li>\n\t<li>Ergo, si semel tristior effectus est, hilara vita amissa est?</li>\n</ul>\n\n\n<p>Duo enim genera quae erant, fecit tria. <a href='http://loripsum.net/' target='_blank'>Maximus dolor, inquit, brevis est.</a> Nos paucis ad haec additis finem faciamus aliquando; <a href='http://loripsum.net/' target='_blank'>Memini me adesse P.</a> Omnia contraria, quos etiam insanos esse vultis. </p>\n\n<p>Cum audissem Antiochum, Brute, ut solebam, cum M. Eadem nunc mea adversum te oratio est. <i>Si quidem, inquit, tollerem, sed relinquo.</i> At iste non dolendi status non vocatur voluptas. Iubet igitur nos Pythius Apollo noscere nosmet ipsos. Itaque hic ipse iam pridem est reiectus; An potest cupiditas finiri? Utilitatis causa amicitia est quaesita. Minime vero, inquit ille, consentit. Suo enim quisque studio maxime ducitur. Nihilne est in his rebus, quod dignum libero aut indignum esse ducamus? </p>\n\n<p>Duo Reges: constructio interrete. Si alia sentit, inquam, alia loquitur, numquam intellegam quid sentiat; An, partus ancillae sitne in fructu habendus, disseretur inter principes civitatis, P. At quicum ioca seria, ut dicitur, quicum arcana, quicum occulta omnia? </p>\n\n<blockquote cite='http://loripsum.net'>\n    Idemne potest esse dies saepius, qui semel fuit?\n</blockquote>\n";
include 'markdownify_extra.php';
$md = new Markdownify(false, 90, false);
$output = $md->parseString($html);
echo nl2br(htmlentities($output));
Exemple #15
-1
 /**
  * parse a HTML string, clean up footnotes prior
  *
  * @param string $HTML input
  * @return string Markdown formatted output
  */
 function parseString($html)
 {
     /** TODO: custom markdown-extra options, e.g. titles & classes **/
     # <sup id="fnref:..."><a href"#fn..." rel="footnote">...</a></sup>
     # => <fnref target="..." />
     $html = preg_replace('@<sup id="fnref:([^"]+)">\\s*<a href="#fn:\\1" rel="footnote">\\s*\\d+\\s*</a>\\s*</sup>@Us', '<fnref target="$1" />', $html);
     # <div class="footnotes">
     # <hr />
     # <ol>
     #
     # <li id="fn:...">...</li>
     # ...
     #
     # </ol>
     # </div>
     # =>
     # <footnotes>
     #   <fn name="...">...</fn>
     #   ...
     # </footnotes>
     $html = preg_replace_callback('#<div class="footnotes">\\s*<hr />\\s*<ol>\\s*(.+)\\s*</ol>\\s*</div>#Us', array(&$this, '_makeFootnotes'), $html);
     return parent::parseString($html);
 }
Exemple #16
-1
function bb2diaspora($Text, $preserve_nl = false, $fordiaspora = true)
{
    // Re-enabling the converter again.
    // The bbcode parser now handles youtube-links (and the other stuff) correctly.
    // Additionally the html code is now fixed so that lists are now working.
    /**
     * Transform #tags, strip off the [url] and replace spaces with underscore
     */
    $Text = preg_replace_callback('/#\\[([zu])rl\\=(\\w+.*?)\\](\\w+.*?)\\[\\/[(zu)]rl\\]/i', create_function('$match', 'return \'#\'. str_replace(\' \', \'_\', $match[3]);'), $Text);
    $Text = preg_replace('/#\\^\\[([zu])rl\\=(\\w+.*?)\\](\\w+.*?)\\[\\/([zu])rl\\]/i', '[$1rl=$2]$3[/$4rl]', $Text);
    $Text = preg_replace_callback('/\\@\\!?\\[([zu])rl\\=(\\w+.*?)\\](\\w+.*?)\\[\\/([zu])rl\\]/i', 'bb2dmention_callback', $Text);
    // Converting images with size parameters to simple images. Markdown doesn't know it.
    $Text = preg_replace("/\\[img\\=([0-9]*)x([0-9]*)\\](.*?)\\[\\/img\\]/ism", '[img]$3[/img]', $Text);
    // the following was added on 10-January-2012 due to an inability of Diaspora's
    // new javascript markdown processor to handle links with images as the link "text"
    // It is not optimal and may be removed if this ability is restored in the future
    //if ($fordiaspora)
    //	$Text = preg_replace("/\[url\=([^\[\]]*)\]\s*\[img\](.*?)\[\/img\]\s*\[\/url\]/ism",
    //				"[url]$1[/url]\n[img]$2[/img]", $Text);
    // Convert it to HTML - don't try oembed
    $Text = bbcode($Text, $preserve_nl, false);
    // Now convert HTML to Markdown
    $md = new Markdownify(false, false, false);
    $Text = $md->parseString($Text);
    // If the text going into bbcode() has a plain URL in it, i.e.
    // with no [url] tags around it, it will come out of parseString()
    // looking like: <http://url.com>, which gets removed by strip_tags().
    // So take off the angle brackets of any such URL
    $Text = preg_replace("/<http(.*?)>/is", "http\$1", $Text);
    // Remove all unconverted tags
    $Text = strip_tags($Text);
    // Remove any leading or trailing whitespace, as this will mess up
    // the Diaspora signature verification and cause the item to disappear
    $Text = trim($Text);
    call_hooks('bb2diaspora', $Text);
    return $Text;
}
 static function markdownify($string)
 {
     require_once EXTENSIONS . '/xmlimporter/lib/markdownify/markdownify_extra.php';
     $markdownify = new Markdownify(true, MDFY_BODYWIDTH, false);
     $markdown = $markdownify->parseString($string);
     $markdown = htmlspecialchars($markdown, ENT_NOQUOTES, 'UTF-8');
     return $markdown;
 }
Exemple #18
-19
 public function parseString($html, $options = array())
 {
     if ($this->settings['engine'] == 'extra') {
         $Parser = new Markdownify_Extra();
     } else {
         $Parser = new Markdownify();
     }
     return $Parser->parseString($html);
 }