/pdf/code/trunk/administrator/components/com_artofpdf/models/pdf.php
PHP | 490 lines | 230 code | 72 blank | 188 comment | 20 complexity | 0f57d178fbc83998c5228aaf344bd4b2 MD5 | raw file
- <?php
- /**
- * @version $Id: pdf.php 385 2010-11-03 09:01:13Z eddieajau $
- * @package NewLifeInIT
- * @subpackage com_artofpdf
- * @copyright Copyright 2010 New Life in IT Pty Ltd. All rights reserved.
- * @license GNU General Public License version 2 or later.
- * @link http://www.theartofjoomla.com
- */
- // No direct access
- defined('_JEXEC') or die;
- juimport('joomla.application.component.modeladmin');
- juimport('joomla.database.databasequery');
- /**
- * Pdf model.
- *
- * @package NewLifeInIT
- * @subpackage com_artofpdf
- * @since 1.0
- */
- class ArtofPdfModelPdf extends JModelAdmin
- {
- /**
- * Adds the Table of Contents to the PDF document.
- *
- * @param TCPDF $doc
- * @param JObject $params
- *
- * @return void
- * @since 1.0
- */
- protected static function addPdfToc(TCPDF $doc, JObject $params)
- {
- // add a new page for TOC
- $doc->addTOCPage();
- // write the TOC title and/or other elements on the TOC page
- //$doc->SetFont('times', 'B', 16);
- $doc->SetFont('helvetica', '', 16);
- $doc->MultiCell(0, 0, JText::_('COM_ARTOFPDF_PDF_TABLE_OF_CONTENTS'), 0, 'C', 0, 1, '', '', true, 0);
- $doc->Ln();
- //$doc->SetFont('helvetica', '', 10);
- // define styles for various bookmark levels
- $bookmark_templates = array();
- /*
- * The key of the $bookmark_templates array represent the bookmark level (from 0 to n).
- * The following templates will be replaced with proper content:
- * #TOC_DESCRIPTION# this will be replaced with the bookmark description;
- * #TOC_PAGE_NUMBER# this will be replaced with page number.
- *
- * NOTES:
- * If you want to align the page number on the right you have to use a monospaced font like courier, otherwise you can left align using any font type.
- * The following is just an example, you can get various styles by combining various HTML elements.
- */
- // A monospaced font for the page number is mandatory to get the right alignment
- $bookmark_templates[0] = '<table border="0" cellpadding="0" cellspacing="0"><tr><td width="165mm"><span style="font-weight:bold;font-size:12pt;color:black;">#TOC_DESCRIPTION#</span></td><td width="15mm"><span style="font-weight:bold;font-size:12pt;color:black;" align="right">#TOC_PAGE_NUMBER#</span></td></tr></table>';
- $bookmark_templates[1] = '<table border="0" cellpadding="0" cellspacing="0"><tr><td width="5mm"> </td><td width="160mm"><span style="font-size:11pt;color:#6a1a41;">#TOC_DESCRIPTION#</span></td><td width="15mm"><span style="font-weight:bold;font-size:11pt;color:#6a1a41;" align="right">#TOC_PAGE_NUMBER#</span></td></tr></table>';
- $bookmark_templates[2] = '<table border="0" cellpadding="0" cellspacing="0"><tr><td width="10mm"> </td><td width="155mm"><span style="font-size:10pt;color:#666666;"><i>#TOC_DESCRIPTION#</i></span></td><td width="15mm"><span style="font-weight:bold;font-size:10pt;color:#666666;" align="right">#TOC_PAGE_NUMBER#</span></td></tr></table>';
- $bookmark_templates[3] = '<table border="0" cellpadding="0" cellspacing="0"><tr><td width="15mm"> </td><td width="150mm"><span style="font-size:10pt;color:#666666;"><i>#TOC_DESCRIPTION#</i></span></td><td width="15mm"><span style="font-weight:bold;font-size:10pt;color:#666666;" align="right">#TOC_PAGE_NUMBER#</span></td></tr></table>';
- // add other bookmark level templates here ...
- // add table of content at page 1
- // (check the example n. 45 for a text-only TOC
- $doc->addHTMLTOC($page=1, $toc_name='INDEX', $bookmark_templates, $correct_align=true);
- // end of TOC page
- $doc->endTOCPage();
- }
- /**
- * Gets the basic PDF document.
- *
- * @param JObject $params
- *
- * @return TCPDF
- * @since 1.0
- */
- protected static function &getPdfDocument(JObject $params)
- {
- // Initialise variables.
- $user = JFactory::getUser();
- // Initialiase the PDF engine.
- self::initPdfEngine();
- // Create and prepare the PDF document.
- $doc = new TCPDF(
- $params->get('page_orientation', 'P'),
- $params->get('unit', 'mm'),
- $params->get('page_format', 'A4'),
- true, // Unicode
- 'UTF-8',
- $params->get('disk_cache', false)
- );
- $doc->SetMargins(
- $params->get('margin_left', 15),
- $params->get('margin_top', 27),
- $params->get('margin_right', 15)
- );
- $doc->SetAutoPageBreak(
- true, // Automode on or off
- $params->get('margin_bottom', 25)
- );
- $doc->SetHeaderMargin(
- $params->get('margin_header', 5)
- );
- $doc->SetFooterMargin(
- $params->get('margin_footer', 10)
- );
- $doc->setImageScale(
- $params->get('image_scale_ratio', 4)
- );
- $doc->SetCreator(
- $params->get('creator', $user->get('name', 'Joomla!'))
- );
- // TODO Optionally turn off headers
- // $doc->setPrintHeader(false);
- // $doc->setPrintFooter(false);
- $doc->SetHeaderData(
- $params->get('logo'),
- $params->get('logo_width', 0),
- $params->get('header_title'),
- $params->get('header_string')
- );
- $lang = JFactory::getLanguage();
- $doc->setRTL($lang->isRTL());
- //$doc->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
- $doc->SetFont(
- 'helvetica', // Family
- '', // Style
- 8 // Size
- );
- $doc->setHeaderFont(
- array(
- 'helvetica', // Family
- '', // Style
- 6 // Size
- )
- );
- $doc->setFooterFont(
- array(
- 'helvetica', // Family
- '', // Style
- 6 // Size
- )
- );
- return $doc;
- }
- /**
- * Once only initialiasation PDF settings.
- *
- * @return void
- */
- protected static function initPdfEngine()
- {
- static $done;
- if ($done) {
- return;
- }
- // Configure manually.
- define('K_TCPDF_EXTERNAL_CONFIG', true);
- define('K_PATH_MAIN', JPATH_COMPONENT_ADMINISTRATOR.'/libraries/tcpdf');
- define('K_PATH_URL', JPATH_BASE);
- define('K_PATH_FONTS', K_PATH_MAIN.'/fonts/');
- define('K_PATH_CACHE', K_PATH_MAIN.'/cache');
- define('K_PATH_URL_CACHE', K_PATH_URL.'/cache');
- define('K_PATH_IMAGES', K_PATH_MAIN.'/images');
- define('K_BLANK_IMAGE', K_PATH_IMAGES.'/_blank.png');
- define('K_CELL_HEIGHT_RATIO', 1.25);
- define('K_TITLE_MAGNIFICATION', 1.3);
- define('K_SMALL_RATIO', 2/3);
- define('HEAD_MAGNIFICATION', 1.1);
- // Include dependancies.
- juimport('tcpdf.tcpdf');
- }
- /**
- * Parse the bookmarks in a buffer.
- *
- * @param TCPDF $doc The PDF document.
- * @param string $text The text to parse.
- * @param object $pdf The PDF data object.
- *
- * @return void
- * @since 1.0
- */
- protected static function parseBookmarks(TCPDF $doc, $text, $pdf)
- {
- // Find any bookmarks in the page.
- $regex = '#<!--BOOKMARK(\d)(.*)-->#U';
- // Find the bookmark comments.
- $matches = array();
- preg_match_all($regex, $text, $matches, PREG_SET_ORDER);
- if (!empty($matches)) {
- // Split the text around the bookmark.
- $parts = preg_split($regex, $text);
- foreach ($parts as $n => $part)
- {
- if (trim($part) == '') {
- continue;
- }
- if (isset($matches[$n-1])) {
- $doc->Bookmark($matches[$n-1][2], $matches[$n-1][1], 0);
- }
- else {
- $doc->Bookmark(JText::sprintf('COM_ARTOFPDF_PDF_BOOKMARK_N', $n), 0, 0);
- }
- if ($pdf->style) {
- $part = '<style>'.$pdf->style.'</style>'.$part;
- }
- $doc->WriteHTML($part, true, false, true, true, '');
- }
- }
- // No bookmarks to just add the text.
- else {
- if ($pdf->style) {
- $text = '<style>'.$pdf->style.'</style>'.$text;
- }
- $doc->WriteHTML($text, true, false, true, true, '');
- }
- }
- /**
- * Parse the pages in a buffer.
- *
- * @param TCPDF $doc The PDF document.
- * @param string $text The text to parse.
- * @param object $pdf The PDF data object.
- *
- * @return void
- * @since 1.0
- */
- protected static function parsePages(TCPDF $doc, $text, $pdf)
- {
- // Explode the buffer on the new page marker.
- $pages = explode('<!--NEWPAGE-->', $text);
- foreach ($pages as $page)
- {
- if (trim($page) == '') {
- continue;
- }
- $doc->AddPage();
- self::parseBookmarks($doc, $page, $pdf);
- }
- }
- /**
- * Method to test whether a record can be deleted.
- *
- * @param object $record A record object.
- *
- * @return boolean True if allowed to delete the record. Defaults to the permission set in the component.
- * @since 1.0
- */
- protected function canDelete($record)
- {
- return true;
- }
- /**
- * Method to test whether a record can be deleted.
- *
- * @param object $record A record object.
- *
- * @return boolean True if allowed to change the state of the record. Defaults to the permission set in the component.
- * @since 1.0
- */
- protected function canEditState($record)
- {
- return true;
- }
- /**
- * Method to duplicate PDF's.
- *
- * @param array An array of primary key IDs.
- *
- * @return boolean True if successful.
- * @throws Exception
- */
- public function duplicate(&$pks)
- {
- // Initialise variables.
- $user = JFactory::getUser();
- $db = $this->getDbo();
- // Access checks.
- // if (!$user->authorise('core.create', 'com_artofpdf')) {
- // throw new Exception(JText::_('JERROR_CORE_CREATE_NOT_PERMITTED'));
- // }
- $table = $this->getTable();
- foreach ($pks as $pk)
- {
- if ($table->load($pk, true)) {
- // Reset the id to create a new record.
- $table->id = 0;
- // Alter the title.
- $m = null;
- if (preg_match('#\((\d+)\)$#', $table->title, $m)) {
- $table->title = preg_replace('#\(\d+\)$#', '('.($m[1] + 1).')', $table->title);
- }
- else {
- $table->title .= ' (2)';
- }
- if (!$table->check() || !$table->store()) {
- throw new Exception($table->getError());
- }
- }
- else {
- throw new Exception($table->getError());
- }
- }
- return true;
- }
- /**
- * Method to get a Pdf.
- *
- * @param integer An optional id of the object to get, otherwise the id from the model state is used.
- * @return mixed Category data object on success, false on failure.
- * @since 1.6
- */
- public function getItem($pk = null)
- {
- if ($result = parent::getItem($pk)) {
- $result->params->loadSetupFile(dirname(__FILE__).'/forms/pdf.xml');
- /*
- // Convert the created and modified dates to local user time for display in the form.
- jimport('joomla.utilities.date');
- $tz = new DateTimeZone(JFactory::getApplication()->getCfg('offset'));
- if (intval($result->created_time)) {
- $date = new JDate($result->created_time);
- $date->setTimezone($tz);
- $result->created_time = $date->toMySQL(true);
- } else {
- $result->created_time = null;
- }
- if (intval($result->modified_time)) {
- $date = new JDate($result->modified_time);
- $date->setTimezone($tz);
- $result->modified_time = $date->toMySQL(true);
- } else {
- $result->modified_time = null;
- }
- */
- }
- return $result;
- }
- /**
- * Returns a reference to the a Table object, always creating it.
- *
- * @param type $type The table type to instantiate
- * @param string $prefix A prefix for the table class name.
- * @param array $config Configuration array for model.
- *
- * @return JTable A database object
- * @since 1.0
- */
- public function getTable($type = 'Pdf', $prefix = 'ArtofPdfTable', $config = array())
- {
- return JTable::getInstance($type, $prefix, $config);
- }
- /**
- * Make the PDF.
- *
- * Note: This method is inspired by the JDocumentPdf class and other examples from the TCPDF site.
- *
- * @param object $pdf
- * @param string $html
- *
- * @return boolean
- * @since 1.0
- */
- public function make(&$pdf, &$buffer)
- {
- // Initialise variables.
- $user = JFactory::getUser();
- $pdf->params->def('header_title', $pdf->title);
- $doc = self::getPdfDocument($pdf->params);
- $doc->SetTitle(
- $pdf->title
- );
- $doc->SetSubject(
- $pdf->subject
- );
- $doc->SetKeywords(
- $pdf->keywords
- );
- // PHP doesn't handle relative paths if soft links are involved to this component.
- // TODO Add optional switch for this.
- if (strpos($buffer, '<img') !== false) {
- $regex = "#(<img\s[^>]*src\s*=\s*['\"]?)(images/)([^>]*?>)#is";
- $replace = '$1'.JPATH_ROOT.'/$2$3';
- $buffer = preg_replace($regex, $replace, $buffer);
- }
- // if ($pdf->style) {
- // $buffer = '<style>'.$pdf->style.'</style>'.$buffer;
- // }
- self::parsePages($doc, $buffer, $pdf);
- self::addPdfToc($doc, $pdf->params);
- //Close and output PDF document
- $doc->Output(JPATH_SITE.'/tmp/'.$pdf->title.'.pdf', 'F');
- jimport('joomla.filesystem.file');
- JFile::write(JPATH_SITE.'/tmp/'.$pdf->title.'.html', '<html><body>'.$buffer.'</html></body>');
- // Update the build stamp.
- jimport('joomla.utilities.date');
- $db = $this->getDbo();
- $query = new JDatabaseQuery;
- $now = new JDate;
- $query->update('#__artof_pdfs');
- $query->set('`build_time` = '.$db->quote($now->toMySQL()));
- $query->where('`id` = '.(int) $pdf->id);
- $db->setQuery((string) $query);
- if (!$db->query()) {
- throw new Exception($db->getErrorMsg());
- }
- }
- /**
- * Prepare and sanitise the table prior to saving.
- *
- * @param JTable $table The table object for the record.
- *
- * @return boolean True if successful, otherwise false and the error is set.
- * @since 1.0
- */
- protected function prepareTable($table)
- {
- }
- }