<?php

/**
  * BLOG:CMS: PHP/MySQL Personal Content Management System (CMS)
  * http://blogcms.com/
  * ----------------------------------------------------------------
  *
  * Copyright (C) 2003-2005 Radek HULÁN
  * http://hulan.cz/contact/
  *
  * ----------------------------------------------------------------
  * This program is free software; you can redistribute it and/or
  * modify it under the terms of the GNU General Public License
  * as published by the Free Software Foundation; either version 2
  * of the License, or (at your option) any later version.
**/

global $DIR_PLUGINS;
if (!is_dir($DIR_PLUGINS)) die('System is not configured properly - NP_PDF.php');
include($DIR_PLUGINS.'pdf/html2pdf.php');

define('FPDF_FONTPATH',$DIR_PLUGINS.'pdf/font/');

class NP_PDF extends NucleusPlugin {

	function getName() {	return 'PDF'; 	}
	function getAuthor()  { return 'Radek HULAN'; 	}
	function getURL() {		return 'http://hulan.cz/blog/'; }
	function getVersion() {	return '0.1'; }
	function getDescription() {
		return 'Template var to add a PDF-friendly version of your article. Use &lt;%PDF%&gt; inside your detailed (item) template';
	}
	
	function supportsFeature($feature) {
		switch($feature) {
			case 'SqlTablePrefix':
				return 1;
			default:
				return 0;
		}
	}
	
	function install() {
		$this->createOption('pdftext','Text to display as a link?','text','[PDF]');
		$this->createOption('bold','Support italics and bold text?','yesno','no');
		$this->createOption('imgembed','Support embedded images?','yesno','no');
		$this->createOption('imglinked','Support linked images?','yesno','yes');
		$this->createOption('iconvoutput','Iconv output encoding','text','cp1250');
		$this->createOption('directory','Subdirectory under media dir to create files (must end with a slash)?','text','.cache/');
		$this->createOption('delete','Delete temporary files after X minutes','text','60');
	}

  function convert($s){
    static $useiconv=2, $from, $to;
    if ($useiconv==2) {
      $from=_CHARSET;
      $to=$this->getOption('iconvoutput');
    }
    if (is_callable("iconv")) return iconv($from,$to,$s); else return $s;
  }

  function _redirect(){
    $url = "http://".serverVar('HTTP_HOST').serverVar('REQUEST_URI');
    header("Location: $url");
    $url = htmlspecialchars($url);
    die("Redirected: <a href=\"$url\">$url</a>");
  }

	function makeFileName($title) {
		$title = iso2ascii(strip_tags(trim($title)));
		preg_match_all('/[a-zA-Z0-9]+/', $title, $nt);
		return implode('-',$nt[0]);
	}

  function doAction($type) {
    global $CONF, $DIR_MEDIA;
	if (!is_dir($DIR_MEDIA)) die('System is not configured properly');
    $itemid = intRequestVar('itemid');

    $query=sql_query('select ibody as body, imore as more, ititle as title, UNIX_TIMESTAMP(itime) as time, iauthor as member from '.sql_table('item').' where inumber='.strval($itemid));
    if (!$row=sql_fetch_object($query)) $this->_redirect();

    $row->body = sql_unescape($row->body);
    $row->more = sql_unescape($row->more);

    $mquery = sql_query("SELECT mrealname FROM ".sql_table('member')." WHERE mnumber = ".$row->member);
    $member = sql_fetch_object($mquery);

    // change some tags into pseudo-tags
    $str=array(
      '[b]' => '<b>',
      '[/b]' => '</b>',
      '<br />' => '<br>',
      '<hr />' => '<hr>',
      '[i]' => '<i>',
      '[/i]' => '</i>',
      '[r]' => '<red>',
      '[/r]' => '</red>',
      '[l]' => '<blue>',
      '[/l]' => '</blue>',
      '&#8220;' => '"',
      '&#8221;' => '"',
      '&#8222;' => '"',
      '&#8230;' => '...',
      '&#8217;' => '\''
    );
	foreach ($str as $from => $to) {
	  $row->body = str_replace($from,$to,$row->body);
	  $row->more = str_replace($from,$to,$row->more);
	}
	/* images embedded */
	if ($this->getOption('imgembed')=='yes'){
	  $row->body = preg_replace('/<%image\((.*?).jpg\|(.*?)\|(.*?)\|(.*?)%>/','<img src="'.$CONF['MediaURL'].strval($row->member).'/'.'$1.jpg" width="$2" height="$3" alt="$4">',$row->body);
	  $row->more = preg_replace('/<%image\((.*?).jpg\|(.*?)\|(.*?)\|(.*?)%>/','<img src="'.$CONF['MediaURL'].strval($row->member).'/'.'$1.jpg" width="$2" height="$3" alt="$4">',$row->more);
	}
	/* images linked */
	if ($this->getOption('imglinked')=='yes'){
	  $row->body = preg_replace('/<%image\((.*?).jpg\|(.*?)\|(.*?)\|(.*?)\)%>/','<br> * <red>Linked image: <a href="'.$CONF['MediaURL'].strval($row->member).'/'.'$1.jpg">$4</a></red>',$row->body);
	  $row->more = preg_replace('/<%image\((.*?).jpg\|(.*?)\|(.*?)\|(.*?)\)%>/','<br> * <red>Linked image: <a href="'.$CONF['MediaURL'].strval($row->member).'/'.'$1.jpg">$4</a></red>',$row->more);
	}
	
	/* remove Nucleus custom tags */
	$row->body = preg_replace('/<%(.*?)%>/','',$row->body);
	$row->more = preg_replace('/<%(.*?)%>/','',$row->more);
	
	/* remove NP_Poll tags */
	$row->body = preg_replace('/\?\+\+(.*?)\+\+\?/','',$row->body);
	$row->more = preg_replace('/\?\+\+(.*?)\+\+\?/','',$row->more);
	$row->body = preg_replace('/\!\+\+(.*?)\+\+\!/','',$row->body);
	$row->more = preg_replace('/\!\+\+(.*?)\+\+\!/','',$row->more);

	$articleurl=fancyLink($itemid);
    $pdf=new PDF('P','mm','A4',$this->convert(sql_unescape($row->title)),$articleurl,false);
    $pdf->Open();
    $pdf->SetCompression(true);
    $pdf->SetCreator("BLOG:CMS :: script by Radek HULAN, http://hulan.cz/");
    $pdf->SetDisplayMode('real');
    $pdf->SetTitle($this->convert(sql_unescape($row->title)));
    $pdf->SetAuthor($this->convert($CONF['SiteName']));
    $pdf->AddPage();

    // face
    $pdf->PutMainTitle($this->convert(sql_unescape($row->title)));
    $pdf->PutMinorHeading('Article URI');
    $pdf->PutMinorTitle($articleurl,$articleurl);
    $pdf->PutMinorHeading('Author');
    $pdf->PutMinorTitle($this->convert($member->mrealname));
    $pdf->PutMinorHeading('Site URI');
    $pdf->PutMinorTitle($CONF['IndexURL'],$CONF['IndexURL']);
    $pdf->PutMinorHeading("Published: ".date("F j, Y, g:i a",$row->time));
    $pdf->PutLine();
    $pdf->Ln(10);

    // body
    $bi=($this->getOption('bold')=='yes');
    $pdf->WriteHTML($this->convert($row->body),$bi);
    $pdf->WriteHTML($this->convert($row->more),$bi);

    //save and redirect
    $filename=$this->getOption('directory').$this->makeFileName($row->title).'.pdf';
    $real=$DIR_MEDIA.$filename;
    $http=$CONF['MediaURL'].$filename;
    $pdf->Output($real);
    header("Location: $http");

    // cleanup
    $dir=$DIR_MEDIA.$this->getOption('directory');
    $files=opendir($dir);
    $minutes=intval($this->getOption('delete'));
    while ( false !== ($filename = readdir($files))) {
      if (!(strpos($filename,'.pdf')===false)){
        // delete old temp files
        $time=filectime($dir.$filename);
        if (!($time===false) && $time>0) if ($time+$minutes*60<time()) unlink($dir.$filename);
      }
    }
    // stop processing
    exit;
  }

	function doTemplateVar(&$item) {
		global $CONF;
		$url = $CONF['IndexURL'].'action.php?action=plugin&amp;name=PDF&amp;itemid='.$item->itemid;
		echo "<a href='$url'>".$this->getOption('pdftext')."</a>";
	}

}
?>