gencourrier en odt

This commit is contained in:
Sebastien BEAUGRAND 2010-11-09 14:38:55 +00:00
parent 4be31e27f9
commit a1566dab22
11 changed files with 7539 additions and 253 deletions

View File

@ -0,0 +1,211 @@
<?php
require 'SegmentIterator.php';
class SegmentException extends Exception
{}
/**
* Class for handling templating segments with odt files
* You need PHP 5.2 at least
* You need Zip Extension or PclZip library
* Encoding : ISO-8859-1
* Last commit by $Author: neveldo $
* Date - $Date: 2009-06-17 12:12:59 +0200 (mer., 17 juin 2009) $
* SVN Revision - $Rev: 44 $
* Id : $Id: Segment.php 44 2009-06-17 10:12:59Z neveldo $
*
* @copyright GPL License 2008 - Julien Pauli - Cyril PIERRE de GEYER - Anaska (http://www.anaska.com)
* @license http://www.gnu.org/copyleft/gpl.html GPL License
* @version 1.3
*/
class Segment implements IteratorAggregate, Countable
{
protected $xml;
protected $xmlParsed = '';
protected $name;
protected $children = array();
protected $vars = array();
protected $images = array();
protected $odf;
protected $file;
/**
* Constructor
*
* @param string $name name of the segment to construct
* @param string $xml XML tree of the segment
*/
public function __construct($name, $xml, $odf)
{
$this->name = (string) $name;
$this->xml = (string) $xml;
$this->odf = $odf;
$zipHandler = $this->odf->getConfig('ZIP_PROXY');
$this->file = new $zipHandler();
$this->_analyseChildren($this->xml);
}
/**
* Returns the name of the segment
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Does the segment have children ?
*
* @return bool
*/
public function hasChildren()
{
return $this->getIterator()->hasChildren();
}
/**
* Countable interface
*
* @return int
*/
public function count()
{
return count($this->children);
}
/**
* IteratorAggregate interface
*
* @return Iterator
*/
public function getIterator()
{
return new RecursiveIteratorIterator(new SegmentIterator($this->children), 1);
}
/**
* Replace variables of the template in the XML code
* All the children are also called
*
* @return string
*/
public function merge()
{
$this->xmlParsed .= str_replace(array_keys($this->vars), array_values($this->vars), $this->xml);
if ($this->hasChildren()) {
foreach ($this->children as $child) {
$this->xmlParsed = str_replace($child->xml, ($child->xmlParsed=="")?$child->merge():$child->xmlParsed, $this->xmlParsed);
$child->xmlParsed = '';
}
}
$reg = "/\[!--\sBEGIN\s$this->name\s--\](.*)\[!--\sEND\s$this->name\s--\]/sm";
$this->xmlParsed = preg_replace($reg, '$1', $this->xmlParsed);
$this->file->open($this->odf->getTmpfile());
foreach ($this->images as $imageKey => $imageValue) {
if ($this->file->getFromName('Pictures/' . $imageValue) === false) {
$this->file->addFile($imageKey, 'Pictures/' . $imageValue);
}
}
$this->file->close();
return $this->xmlParsed;
}
/**
* Analyse the XML code in order to find children
*
* @param string $xml
* @return Segment
*/
protected function _analyseChildren($xml)
{
// $reg2 = "#\[!--\sBEGIN\s([\S]*)\s--\](?:<\/text:p>)?(.*)(?:<text:p\s.*>)?\[!--\sEND\s(\\1)\s--\]#sm";
$reg2 = "#\[!--\sBEGIN\s([\S]*)\s--\](.*)\[!--\sEND\s(\\1)\s--\]#sm";
preg_match_all($reg2, $xml, $matches);
for ($i = 0, $size = count($matches[0]); $i < $size; $i++) {
if ($matches[1][$i] != $this->name) {
$this->children[$matches[1][$i]] = new self($matches[1][$i], $matches[0][$i], $this->odf);
} else {
$this->_analyseChildren($matches[2][$i]);
}
}
return $this;
}
/**
* Assign a template variable to replace
*
* @param string $key
* @param string $value
* @throws SegmentException
* @return Segment
*/
public function setVars($key, $value, $encode = true, $charset = 'ISO-8859')
{
if (strpos($this->xml, $this->odf->getConfig('DELIMITER_LEFT') . $key . $this->odf->getConfig('DELIMITER_RIGHT')) === false) {
throw new SegmentException("var $key not found in {$this->getName()}");
}
$value = $encode ? htmlspecialchars($value) : $value;
$value = ($charset == 'ISO-8859') ? utf8_encode($value) : $value;
$this->vars[$this->odf->getConfig('DELIMITER_LEFT') . $key . $this->odf->getConfig('DELIMITER_RIGHT')] = str_replace("\n", "<text:line-break/>", $value);
return $this;
}
/**
* Assign a template variable as a picture
*
* @param string $key name of the variable within the template
* @param string $value path to the picture
* @throws OdfException
* @return Segment
*/
public function setImage($key, $value)
{
$filename = strtok(strrchr($value, '/'), '/.');
$file = substr(strrchr($value, '/'), 1);
$size = @getimagesize($value);
if ($size === false) {
throw new OdfException("Invalid image");
}
list ($width, $height) = $size;
$width *= Odf::PIXEL_TO_CM;
$height *= Odf::PIXEL_TO_CM;
$xml = <<<IMG
<draw:frame draw:style-name="fr1" draw:name="$filename" text:anchor-type="char" svg:width="{$width}cm" svg:height="{$height}cm" draw:z-index="3"><draw:image xlink:href="Pictures/$file" xlink:type="simple" xlink:show="embed" xlink:actuate="onLoad"/></draw:frame>
IMG;
$this->images[$value] = $file;
$this->setVars($key, $xml, false);
return $this;
}
/**
* Shortcut to retrieve a child
*
* @param string $prop
* @return Segment
* @throws SegmentException
*/
public function __get($prop)
{
if (array_key_exists($prop, $this->children)) {
return $this->children[$prop];
} else {
throw new SegmentException('child ' . $prop . ' does not exist');
}
}
/**
* Proxy for setVars
*
* @param string $meth
* @param array $args
* @return Segment
*/
public function __call($meth, $args)
{
try {
return $this->setVars($meth, $args[0]);
} catch (SegmentException $e) {
throw new SegmentException("method $meth nor var $meth exist");
}
}
/**
* Returns the parsed XML
*
* @return string
*/
public function getXmlParsed()
{
return $this->xmlParsed;
}
}
?>

View File

@ -0,0 +1,56 @@
<?php
/**
* Segments iterator
* You need PHP 5.2 at least
* You need Zip Extension or PclZip library
* Encoding : ISO-8859-1
* Last commit by $Author: neveldo $
* Date - $Date: 2009-06-17 11:11:57 +0200 (mer., 17 juin 2009) $
* SVN Revision - $Rev: 42 $
* Id : $Id: SegmentIterator.php 42 2009-06-17 09:11:57Z neveldo $
*
* @copyright GPL License 2008 - Julien Pauli - Cyril PIERRE de GEYER - Anaska (http://www.anaska.com)
* @license http://www.gnu.org/copyleft/gpl.html GPL License
* @version 1.3
*/
class SegmentIterator implements RecursiveIterator
{
private $ref;
private $key;
public function __construct(array $ref)
{
$this->ref = $ref;
$this->key = 0;
$this->keys = array_keys($this->ref);
}
public function hasChildren()
{
return $this->valid() && $this->current() instanceof Segment;
}
public function current()
{
return $this->ref[$this->keys[$this->key]];
}
function getChildren()
{
return new self($this->current()->children);
}
public function key()
{
return $this->key;
}
public function valid()
{
return array_key_exists($this->key, $this->keys);
}
public function rewind()
{
$this->key = 0;
}
public function next()
{
$this->key ++;
}
}
?>

View File

@ -0,0 +1,311 @@
<?php
require 'zip/PclZipProxy.php';
require 'zip/PhpZipProxy.php';
require 'Segment.php';
class OdfException extends Exception
{}
/**
* Templating class for odt file
* You need PHP 5.2 at least
* You need Zip Extension or PclZip library
* Encoding : ISO-8859-1
* Last commit by $Author: neveldo $
* Date - $Date: 2009-06-17 11:11:57 +0200 (mer., 17 juin 2009) $
* SVN Revision - $Rev: 42 $
* Id : $Id: odf.php 42 2009-06-17 09:11:57Z neveldo $
*
* @copyright GPL License 2008 - Julien Pauli - Cyril PIERRE de GEYER - Anaska (http://www.anaska.com)
* @license http://www.gnu.org/copyleft/gpl.html GPL License
* @version 1.3
*/
class Odf
{
protected $config = array(
'ZIP_PROXY' => 'PclZipProxy',
'DELIMITER_LEFT' => '{',
'DELIMITER_RIGHT' => '}',
'PATH_TO_TMP' => null
);
protected $file;
protected $contentXml;
protected $tmpfile;
protected $images = array();
protected $vars = array();
protected $segments = array();
const PIXEL_TO_CM = 0.026458333;
/**
* Class constructor
*
* @param string $filename the name of the odt file
* @throws OdfException
*/
public function __construct($filename, $config = array())
{
if (! is_array($config)) {
throw new OdfException('Configuration data must be provided as array');
}
foreach ($config as $configKey => $configValue) {
if (array_key_exists($configKey, $this->config)) {
$this->config[$configKey] = $configValue;
}
}
if (! class_exists($this->config['ZIP_PROXY'])) {
throw new OdfException($this->config['ZIP_PROXY'] . ' class not found - check your php settings');
}
$zipHandler = $this->config['ZIP_PROXY'];
$this->file = new $zipHandler();
if ($this->file->open($filename) !== true) {
throw new OdfException("Error while Opening the file '$filename' - Check your odt file");
}
if (($this->contentXml = $this->file->getFromName('content.xml')) === false) {
throw new OdfException("Nothing to parse - check that the content.xml file is correctly formed");
}
$this->file->close();
$tmp = tempnam($this->config['PATH_TO_TMP'], md5(uniqid()));
copy($filename, $tmp);
$this->tmpfile = $tmp;
$this->_moveRowSegments();
}
/**
* Assing a template variable
*
* @param string $key name of the variable within the template
* @param string $value replacement value
* @param bool $encode if true, special XML characters are encoded
* @throws OdfException
* @return odf
*/
public function setVars($key, $value, $encode = true, $charset = 'ISO-8859')
{
if (strpos($this->contentXml, $this->config['DELIMITER_LEFT'] . $key . $this->config['DELIMITER_RIGHT']) === false) {
throw new OdfException("var $key not found in the document");
}
$value = $encode ? htmlspecialchars($value) : $value;
$value = ($charset == 'ISO-8859') ? utf8_encode($value) : $value;
$this->vars[$this->config['DELIMITER_LEFT'] . $key . $this->config['DELIMITER_RIGHT']] = str_replace("\n", "<text:line-break/>", $value);
return $this;
}
/**
* Assign a template variable as a picture
*
* @param string $key name of the variable within the template
* @param string $value path to the picture
* @throws OdfException
* @return odf
*/
public function setImage($key, $value)
{
$filename = strtok(strrchr($value, '/'), '/.');
$file = substr(strrchr($value, '/'), 1);
$size = @getimagesize($value);
if ($size === false) {
throw new OdfException("Invalid image");
}
list ($width, $height) = $size;
$width *= self::PIXEL_TO_CM;
$height *= self::PIXEL_TO_CM;
$xml = <<<IMG
<draw:frame draw:style-name="fr1" draw:name="$filename" text:anchor-type="char" svg:width="{$width}cm" svg:height="{$height}cm" draw:z-index="3"><draw:image xlink:href="Pictures/$file" xlink:type="simple" xlink:show="embed" xlink:actuate="onLoad"/></draw:frame>
IMG;
$this->images[$value] = $file;
$this->setVars($key, $xml, false);
return $this;
}
/**
* Move segment tags for lines of tables
* Called automatically within the constructor
*
* @return void
*/
private function _moveRowSegments()
{
// Search all possible rows in the document
$reg1 = "#<table:table-row[^>]*>(.*)</table:table-row>#smU";
preg_match_all($reg1, $this->contentXml, $matches);
for ($i = 0, $size = count($matches[0]); $i < $size; $i++) {
// Check if the current row contains a segment row.*
$reg2 = '#\[!--\sBEGIN\s(row.[\S]*)\s--\](.*)\[!--\sEND\s\\1\s--\]#sm';
if (preg_match($reg2, $matches[0][$i], $matches2)) {
$balise = str_replace('row.', '', $matches2[1]);
// Move segment tags around the row
$replace = array(
'[!-- BEGIN ' . $matches2[1] . ' --]' => '',
'[!-- END ' . $matches2[1] . ' --]' => '',
'<table:table-row' => '[!-- BEGIN ' . $balise . ' --]<table:table-row',
'</table:table-row>' => '</table:table-row>[!-- END ' . $balise . ' --]'
);
$replacedXML = str_replace(array_keys($replace), array_values($replace), $matches[0][$i]);
$this->contentXml = str_replace($matches[0][$i], $replacedXML, $this->contentXml);
}
}
}
/**
* Merge template variables
* Called automatically for a save
*
* @return void
*/
private function _parse()
{
$this->contentXml = str_replace(array_keys($this->vars), array_values($this->vars), $this->contentXml);
}
/**
* Add the merged segment to the document
*
* @param Segment $segment
* @throws OdfException
* @return odf
*/
public function mergeSegment(Segment $segment)
{
if (! array_key_exists($segment->getName(), $this->segments)) {
throw new OdfException($segment->getName() . 'cannot be parsed, has it been set yet ?');
}
$string = $segment->getName();
// $reg = '@<text:p[^>]*>\[!--\sBEGIN\s' . $string . '\s--\](.*)\[!--.+END\s' . $string . '\s--\]<\/text:p>@smU';
$reg = '@\[!--\sBEGIN\s' . $string . '\s--\](.*)\[!--.+END\s' . $string . '\s--\]@smU';
$this->contentXml = preg_replace($reg, $segment->getXmlParsed(), $this->contentXml);
return $this;
}
/**
* Display all the current template variables
*
* @return string
*/
public function printVars()
{
return print_r('<pre>' . print_r($this->vars, true) . '</pre>', true);
}
/**
* Display the XML content of the file from odt document
* as it is at the moment
*
* @return string
*/
public function __toString()
{
return $this->contentXml;
}
/**
* Display loop segments declared with setSegment()
*
* @return string
*/
public function printDeclaredSegments()
{
return '<pre>' . print_r(implode(' ', array_keys($this->segments)), true) . '</pre>';
}
/**
* Declare a segment in order to use it in a loop
*
* @param string $segment
* @throws OdfException
* @return Segment
*/
public function setSegment($segment)
{
if (array_key_exists($segment, $this->segments)) {
return $this->segments[$segment];
}
// $reg = "#\[!--\sBEGIN\s$segment\s--\]<\/text:p>(.*)<text:p\s.*>\[!--\sEND\s$segment\s--\]#sm";
$reg = "#\[!--\sBEGIN\s$segment\s--\](.*)\[!--\sEND\s$segment\s--\]#sm";
if (preg_match($reg, html_entity_decode($this->contentXml), $m) == 0) {
throw new OdfException("'$segment' segment not found in the document");
}
$this->segments[$segment] = new Segment($segment, $m[1], $this);
return $this->segments[$segment];
}
/**
* Save the odt file on the disk
*
* @param string $file name of the desired file
* @throws OdfException
* @return void
*/
public function saveToDisk($file = null)
{
if ($file !== null && is_string($file)) {
if (file_exists($file) && !(is_file($file) && is_writable($file))) {
throw new OdfException('Permission denied : can\'t create ' . $file);
}
$this->_save();
copy($this->tmpfile, $file);
} else {
$this->_save();
}
}
/**
* Internal save
*
* @throws OdfException
* @return void
*/
private function _save()
{
$this->file->open($this->tmpfile);
$this->_parse();
if (! $this->file->addFromString('content.xml', $this->contentXml)) {
throw new OdfException('Error during file export');
}
foreach ($this->images as $imageKey => $imageValue) {
$this->file->addFile($imageKey, 'Pictures/' . $imageValue);
}
$this->file->close(); // seems to bug on windows CLI sometimes
}
/**
* Export the file as attached file by HTTP
*
* @param string $name (optionnal)
* @throws OdfException
* @return void
*/
public function exportAsAttachedFile($name="")
{
$this->_save();
if (headers_sent($filename, $linenum)) {
throw new OdfException("headers already sent ($filename at $linenum)");
}
if( $name == "" )
{
$name = md5(uniqid()) . ".odt";
}
header('Content-type: application/vnd.oasis.opendocument.text');
header('Content-Disposition: attachment; filename="'.$name.'"');
readfile($this->tmpfile);
}
/**
* Returns a variable of configuration
*
* @return string The requested variable of configuration
*/
public function getConfig($configKey)
{
if (array_key_exists($configKey, $this->config)) {
return $this->config[$configKey];
}
return false;
}
/**
* Returns the temporary working file
*
* @return string le chemin vers le fichier temporaire de travail
*/
public function getTmpfile()
{
return $this->tmpfile;
}
/**
* Delete the temporary file when the object is destroyed
*/
public function __destruct() {
if (file_exists($this->tmpfile)) {
unlink($this->tmpfile);
}
}
}
?>

View File

@ -0,0 +1,182 @@
<?php
require_once 'pclzip/pclzip.lib.php';
require_once 'ZipInterface.php';
class PclZipProxyException extends Exception
{ }
/**
* Proxy class for the PclZip library
* You need PHP 5.2 at least
* You need Zip Extension or PclZip library
* Encoding : ISO-8859-1
* Last commit by $Author: neveldo $
* Date - $Date: 2009-05-29 10:05:11 +0200 (ven., 29 mai 2009) $
* SVN Revision - $Rev: 28 $
* Id : $Id: odf.php 28 2009-05-29 08:05:11Z neveldo $
*
* @copyright GPL License 2008 - Julien Pauli - Cyril PIERRE de GEYER - Anaska (http://www.anaska.com)
* @license http://www.gnu.org/copyleft/gpl.html GPL License
* @version 1.3
*/
class PclZipProxy implements ZipInterface
{
const TMP_DIR = '/tmp/odtphp';
protected $openned = false;
protected $filename;
protected $pclzip;
/**
* Class constructor
*
* @throws PclZipProxyException
*/
public function __construct()
{
if (! class_exists('PclZip')) {
throw new PclZipProxyException('PclZip class not loaded - PclZip library
is required for using PclZipProxy'); ;
}
}
/**
* Open a Zip archive
*
* @param string $filename the name of the archive to open
* @return true if openning has succeeded
*/
public function open($filename)
{
if (true === $this->openned) {
$this->close();
}
if (!file_exists(self::TMP_DIR)) {
mkdir(self::TMP_DIR);
}
$this->filename = $filename;
$this->pclzip = new PclZip($this->filename);
$this->openned = true;
return true;
}
/**
* Retrieve the content of a file within the archive from its name
*
* @param string $name the name of the file to extract
* @return the content of the file in a string
*/
public function getFromName($name)
{
if (false === $this->openned) {
return false;
}
$name = preg_replace("/(?:\.|\/)*(.*)/", "\\1", $name);
$extraction = $this->pclzip->extract(PCLZIP_OPT_BY_NAME, $name,
PCLZIP_OPT_EXTRACT_AS_STRING);
if (!empty($extraction)) {
return $extraction[0]['content'];
}
return false;
}
/**
* Add a file within the archive from a string
*
* @param string $localname the local path to the file in the archive
* @param string $contents the content of the file
* @return true if the file has been successful added
*/
public function addFromString($localname, $contents)
{
if (false === $this->openned) {
return false;
}
if (file_exists($this->filename) && !is_writable($this->filename)) {
return false;
}
$localname = preg_replace("/(?:\.|\/)*(.*)/", "\\1", $localname);
$localpath = dirname($localname);
$tmpfilename = self::TMP_DIR . '/' . basename($localname);
if (false !== file_put_contents($tmpfilename, $contents)) {
$this->pclzip->delete(PCLZIP_OPT_BY_NAME, $localname);
$add = $this->pclzip->add($tmpfilename,
PCLZIP_OPT_REMOVE_PATH, self::TMP_DIR,
PCLZIP_OPT_ADD_PATH, $localpath);
unlink($tmpfilename);
if (!empty($add)) {
return true;
}
}
return false;
}
/**
* Add a file within the archive from a file
*
* @param string $filename the path to the file we want to add
* @param string $localname the local path to the file in the archive
* @return true if the file has been successful added
*/
public function addFile($filename, $localname = null)
{
if (false === $this->openned) {
return false;
}
if ((file_exists($this->filename) && !is_writable($this->filename))
|| !file_exists($filename)) {
return false;
}
if (isSet($localname)) {
$localname = preg_replace("/(?:\.|\/)*(.*)/", "\\1", $localname);
$localpath = dirname($localname);
$tmpfilename = self::TMP_DIR . '/' . basename($localname);
} else {
$localname = basename($filename);
$tmpfilename = self::TMP_DIR . '/' . $localname;
$localpath = '';
}
if (file_exists($filename)) {
copy($filename, $tmpfilename);
$this->pclzip->delete(PCLZIP_OPT_BY_NAME, $localname);
$this->pclzip->add($tmpfilename,
PCLZIP_OPT_REMOVE_PATH, self::TMP_DIR,
PCLZIP_OPT_ADD_PATH, $localpath);
unlink($tmpfilename);
return true;
}
return false;
}
/**
* Close the Zip archive
* @return true
*/
public function close()
{
if (false === $this->openned) {
return false;
}
$this->pclzip = $this->filename = null;
$this->openned = false;
if (file_exists(self::TMP_DIR)) {
$this->_rrmdir(self::TMP_DIR);
rmdir(self::TMP_DIR);
}
return true;
}
/**
* Empty the temporary working directory recursively
* @param $dir the temporary working directory
* @return void
*/
private function _rrmdir($dir)
{
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if ($file != '.' && $file != '..') {
if (is_dir($dir . '/' . $file)) {
$this->_rrmdir($dir . '/' . $file);
rmdir($dir . '/' . $file);
} else {
unlink($dir . '/' . $file);
}
}
}
closedir($handle);
}
}
}
?>

View File

@ -0,0 +1,96 @@
<?php
require_once 'ZipInterface.php';
class PhpZipProxyException extends Exception
{ }
/**
* Proxy class for the PHP Zip Extension
* You need PHP 5.2 at least
* You need Zip Extension or PclZip library
* Encoding : ISO-8859-1
* Last commit by $Author: neveldo $
* Date - $Date: 2009-05-29 10:05:11 +0200 (ven., 29 mai 2009) $
* SVN Revision - $Rev: 28 $
* Id : $Id: odf.php 28 2009-05-29 08:05:11Z neveldo $
*
* @copyright GPL License 2008 - Julien Pauli - Cyril PIERRE de GEYER - Anaska (http://www.anaska.com)
* @license http://www.gnu.org/copyleft/gpl.html GPL License
* @version 1.3
*/
class PhpZipProxy implements ZipInterface
{
protected $zipArchive;
protected $filename;
/**
* Class constructor
*
* @throws PhpZipProxyException
*/
public function __construct()
{
if (! class_exists('ZipArchive')) {
throw new PhpZipProxyException('Zip extension not loaded - check your php settings, PHP5.2 minimum with zip extension
is required for using PhpZipProxy'); ;
}
$this->zipArchive = new ZipArchive();
}
/**
* Open a Zip archive
*
* @param string $filename the name of the archive to open
* @return true if openning has succeeded
*/
public function open($filename)
{
$this->filename = $filename;
return $this->zipArchive->open($filename, ZIPARCHIVE::CREATE);
}
/**
* Retrieve the content of a file within the archive from its name
*
* @param string $name the name of the file to extract
* @return the content of the file in a string
*/
public function getFromName($name)
{
return $this->zipArchive->getFromName($name);
}
/**
* Add a file within the archive from a string
*
* @param string $localname the local path to the file in the archive
* @param string $contents the content of the file
* @return true if the file has been successful added
*/
public function addFromString($localname, $contents)
{
if (file_exists($this->filename) && !is_writable($this->filename)) {
return false;
}
return $this->zipArchive->addFromString($localname, $contents);
}
/**
* Add a file within the archive from a file
*
* @param string $filename the path to the file we want to add
* @param string $localname the local path to the file in the archive
* @return true if the file has been successful added
*/
public function addFile($filename, $localname = null)
{
if ((file_exists($this->filename) && !is_writable($this->filename))
|| !file_exists($filename)) {
return false;
}
return $this->zipArchive->addFile($filename, $localname);
}
/**
* Close the Zip archive
* @return true
*/
public function close()
{
return $this->zipArchive->close();
}
}
?>

View File

@ -0,0 +1,54 @@
<?php
/**
* Interface for Zip libraries used in odtPHP
* You need PHP 5.2 at least
* You need Zip Extension or PclZip library
* Encoding : ISO-8859-1
* Last commit by $Author: neveldo $
* Date - $Date: 2009-05-29 10:05:11 +0200 (ven., 29 mai 2009) $
* SVN Revision - $Rev: 28 $
* Id : $Id: odf.php 28 2009-05-29 08:05:11Z neveldo $
*
* @copyright GPL License 2008 - Julien Pauli - Cyril PIERRE de GEYER - Anaska (http://www.anaska.com)
* @license http://www.gnu.org/copyleft/gpl.html GPL License
* @version 1.3
*/
interface ZipInterface
{
/**
* Open a Zip archive
*
* @param string $filename the name of the archive to open
* @return true if openning has succeeded
*/
public function open($filename);
/**
* Retrieve the content of a file within the archive from its name
*
* @param string $name the name of the file to extract
* @return the content of the file in a string
*/
public function getFromName($name);
/**
* Add a file within the archive from a string
*
* @param string $localname the local path to the file in the archive
* @param string $contents the content of the file
* @return true if the file has been successful added
*/
public function addFromString($localname, $contents);
/**
* Add a file within the archive from a file
*
* @param string $filename the path to the file we want to add
* @param string $localname the local path to the file in the archive
* @return true if the file has been successful added
*/
public function addFile($filename, $localname = null);
/**
* Close the Zip archive
* @return true
*/
public function close();
}
?>

View File

@ -0,0 +1,182 @@
<?php
require_once 'pclzip/pclzip.lib.php';
require_once 'ZipInterface.php';
class PclZipProxyException extends Exception
{ }
/**
* Proxy class for the PclZip library
* You need PHP 5.2 at least
* You need Zip Extension or PclZip library
* Encoding : ISO-8859-1
* Last commit by $Author: neveldo $
* Date - $Date: 2009-05-29 10:05:11 +0200 (ven., 29 mai 2009) $
* SVN Revision - $Rev: 28 $
* Id : $Id: odf.php 28 2009-05-29 08:05:11Z neveldo $
*
* @copyright GPL License 2008 - Julien Pauli - Cyril PIERRE de GEYER - Anaska (http://www.anaska.com)
* @license http://www.gnu.org/copyleft/gpl.html GPL License
* @version 1.3
*/
class PclZipProxy implements ZipInterface
{
const TMP_DIR = './tmp';
protected $openned = false;
protected $filename;
protected $pclzip;
/**
* Class constructor
*
* @throws PclZipProxyException
*/
public function __construct()
{
if (! class_exists('PclZip')) {
throw new PclZipProxyException('PclZip class not loaded - PclZip library
is required for using PclZipProxy'); ;
}
}
/**
* Open a Zip archive
*
* @param string $filename the name of the archive to open
* @return true if openning has succeeded
*/
public function open($filename)
{
if (true === $this->openned) {
$this->close();
}
if (!file_exists(self::TMP_DIR)) {
mkdir(self::TMP_DIR);
}
$this->filename = $filename;
$this->pclzip = new PclZip($this->filename);
$this->openned = true;
return true;
}
/**
* Retrieve the content of a file within the archive from its name
*
* @param string $name the name of the file to extract
* @return the content of the file in a string
*/
public function getFromName($name)
{
if (false === $this->openned) {
return false;
}
$name = preg_replace("/(?:\.|\/)*(.*)/", "\\1", $name);
$extraction = $this->pclzip->extract(PCLZIP_OPT_BY_NAME, $name,
PCLZIP_OPT_EXTRACT_AS_STRING);
if (!empty($extraction)) {
return $extraction[0]['content'];
}
return false;
}
/**
* Add a file within the archive from a string
*
* @param string $localname the local path to the file in the archive
* @param string $contents the content of the file
* @return true if the file has been successful added
*/
public function addFromString($localname, $contents)
{
if (false === $this->openned) {
return false;
}
if (file_exists($this->filename) && !is_writable($this->filename)) {
return false;
}
$localname = preg_replace("/(?:\.|\/)*(.*)/", "\\1", $localname);
$localpath = dirname($localname);
$tmpfilename = self::TMP_DIR . '/' . basename($localname);
if (false !== file_put_contents($tmpfilename, $contents)) {
$this->pclzip->delete(PCLZIP_OPT_BY_NAME, $localname);
$add = $this->pclzip->add($tmpfilename,
PCLZIP_OPT_REMOVE_PATH, self::TMP_DIR,
PCLZIP_OPT_ADD_PATH, $localpath);
unlink($tmpfilename);
if (!empty($add)) {
return true;
}
}
return false;
}
/**
* Add a file within the archive from a file
*
* @param string $filename the path to the file we want to add
* @param string $localname the local path to the file in the archive
* @return true if the file has been successful added
*/
public function addFile($filename, $localname = null)
{
if (false === $this->openned) {
return false;
}
if ((file_exists($this->filename) && !is_writable($this->filename))
|| !file_exists($filename)) {
return false;
}
if (isSet($localname)) {
$localname = preg_replace("/(?:\.|\/)*(.*)/", "\\1", $localname);
$localpath = dirname($localname);
$tmpfilename = self::TMP_DIR . '/' . basename($localname);
} else {
$localname = basename($filename);
$tmpfilename = self::TMP_DIR . '/' . $localname;
$localpath = '';
}
if (file_exists($filename)) {
copy($filename, $tmpfilename);
$this->pclzip->delete(PCLZIP_OPT_BY_NAME, $localname);
$this->pclzip->add($tmpfilename,
PCLZIP_OPT_REMOVE_PATH, self::TMP_DIR,
PCLZIP_OPT_ADD_PATH, $localpath);
unlink($tmpfilename);
return true;
}
return false;
}
/**
* Close the Zip archive
* @return true
*/
public function close()
{
if (false === $this->openned) {
return false;
}
$this->pclzip = $this->filename = null;
$this->openned = false;
if (file_exists(self::TMP_DIR)) {
$this->_rrmdir(self::TMP_DIR);
rmdir(self::TMP_DIR);
}
return true;
}
/**
* Empty the temporary working directory recursively
* @param $dir the temporary working directory
* @return void
*/
private function _rrmdir($dir)
{
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if ($file != '.' && $file != '..') {
if (is_dir($dir . '/' . $file)) {
$this->_rrmdir($dir . '/' . $file);
rmdir($dir . '/' . $file);
} else {
unlink($dir . '/' . $file);
}
}
}
closedir($handle);
}
}
}
?>

File diff suppressed because it is too large Load Diff

View File

@ -1,284 +1,180 @@
<?php
// just require TCPDF instead of FPDF
require_once 'tcpdf/tcpdf.php';
require_once 'fpdi/fpdi.php';
require_once 'dbbootstrap.php';
require_once 'infogreffe/constantes.php';
require_once 'dbbootstrap.php';
setDbConn('sdv1');
class PDF extends FPDI {
/**
* "Remembers" the template id of the imported page
*/
var $_tplIdx;
/**
* include a background template for every page
*/
function Header() {
if (is_null($this->_tplIdx)) {
$this->setSourceFile(PATH_SITE.'/includes/courrier/modele.pdf');
$this->_tplIdx = $this->importPage(1);
}
$this->useTemplate($this->_tplIdx);
}
function Footer() {}
}
define('PCLZIP_TEMPORARY_DIR', PATH_DATA.'/courrier/');
require_once 'lib/odtphp/library/odf.php';
$odf = new odf(realpath(dirname(__FILE__).'/modeleLettreGreffe.odt'));
function normaliseVoie($txt)
{
$replace_pairs = array(
'BD ' => 'BOULEVARD ',
'BVD ' => 'BOULEVARD ',
'AV ' => 'AVENUE ',
'AVE ' => 'AVENUE ',
'PL ' => 'PLACE ',
'PLA ' => 'PLACE ',
'PLAC ' => 'PLACE ',
'ESP ' => 'ESP ',
'RTE ' => 'ROUTE ',
'ST ' => 'SAINT ',
'STE ' => 'SAINTE ',
'QU ' => 'QUAI ',
);
return strtr($txt, $replace_pairs);
$replace_pairs =
array('BD ' => 'BOULEVARD ',
'BVD ' => 'BOULEVARD ',
'AV ' => 'AVENUE ',
'AVE ' => 'AVENUE ',
'PL ' => 'PLACE ',
'PLA ' => 'PLACE ',
'PLAC ' => 'PLACE ',
'ESP ' => 'ESP ',
'RTE ' => 'ROUTE ',
'ST ' => 'SAINT ',
'STE ' => 'SAINTE ',
'QU ' => 'QUAI ');
return strtr($txt, $replace_pairs);
}
setDbConn('sdv1');
$info = new StdClass;
$info->ref = $id;
$typeCommande = substr($info->ref, 0, 1);
$id = substr($info->ref, 1);
$pdfInfo = new StdClass();
$pdfInfo->ref = $id;
$typeCommande = substr($pdfInfo->ref, 0, 1);
$id = substr($pdfInfo->ref, 1);
if ($typeCommande == 'C') {
$commande = Doctrine_Query::create()
->from('Commandes')
->andWhere('idCommande = ?', $id)
->andWhere('typeCommande = ?', 'C')
->fetchOne();
if ( $typeCommande == 'C' ) {
if (preg_match('/^([0-9]{4}_).*?$/', $commande->refDocument, $matches)) {
$typeDocument = 'bilans';
} else {
$typeDocument = 'actes';
}
} else if ($typeCommande == 'K') {
$commande = Doctrine_Query::create()
->from('CommandesKbis')
->andWhere('id = ?', $id)
->andWhere('type = ?', 'C')
->fetchOne();
// => Info Commande
$q = Doctrine_Query::create()
->from('Commandes')
->where('idCommande = ?', $id)
->andWhere('typeCommande = ?', 'C');
$commande = $q->fetchOne();
if( preg_match('/^([0-9]{4}_).*?$/', $commande->refDocument, $matches) )
{
$typeDocument = 'bilans';
}
else
{
$typeDocument = 'actes';
}
} elseif ( $typeCommande == 'K'){
// => Info Commande
$q = Doctrine_Query::create()
->from('CommandesKbis')
->where('id = ?', $id)
->andWhere('type = ?', 'C');
$commande = $q->fetchOne();
$typeDocument = 'kbis';
$typeDocument = 'kbis';
}
// Identite
$siren = $commande->siren;
$O = $client->getIdentite($siren, '', false);
$etab = $O['result'];
$commune = $etab['codeCommune'];
$dept = $etab['Dept'];
$siret = $etab['Siret'];
$numRC = $etab['NumRC'];
// => Identite
$siren = $commande->siren;
$O = $client->getIdentite($siren, '', false);
$etab = $O['result'];
$codeCommune = $etab['codeCommune'];
$dept = $etab['Dept'];
$siret = $etab['Siret'];
$numRC = $etab['NumRC'];
//Adresse du tribunal de commerce
$O = $client->getListeCompetences($siret, 'tri', $dept.$codeCommune);
$competences = $O['result'];
$competence = $competences[0];
// Adresse du tribunal de commerce
$O = $client->getListeCompetences($siret, 'tri', $dept.$commune);
$competence = $O['result'][0];
$tribunalCode = $competence['Code'];
$tribunalLib = $comptence['Nom'];
if (preg_match('/(A|B|C|D)/i', $numRC))
{
$libTrib = ' RCS '.preg_replace('/(^TC |^TI |^TGIcc |^TMX )/i','',$tribunalLib);
$tribunalLib = $competence['Nom'];
if (preg_match('/(A|B|C|D)/i', $numRC)) {
$libTrib = ' RCS '.
preg_replace('/(^TC |^TI |^TGIcc |^TMX )/i', '', $tribunalLib);
} else if (preg_match('/(P)/i', $numRC)) {
$libTrib = ' RSAC '.
preg_replace('/(^TC |^TI |^TGIcc |^TMX )/i', '', $tribunalLib);
}
elseif (preg_match('/(P)/i', $numRC))
{
$libTrib = ' RSAC '.preg_replace('/(^TC |^TI |^TGIcc |^TMX )/i','',$tribunalLib);
$info->siren =
substr($siren, 0, 3).' '.
substr($siren, 3, 3).' '.
substr($siren, 6, 3);
$info->nom = $etab['Nom'];
$info->libTrib = $libTrib;
$info->adresse = $etab['Adresse'].' ';
if (empty($etab['Adresse2']) == false) {
$info->adresse .= $etab['Adresse2'].' ';
}
$info->adresse .= "\n".$etab['CP'].' '.$etab['Ville'];
$info->tribunal = $competence;
$pdfInfo->siren = substr($siren, 0, 3).' '.
substr($siren, 3, 3).' '.
substr($siren, 6, 3);
$pdfInfo->nom = $etab['Nom'];
$pdfInfo->libTrib = $libTrib;
$pdfInfo->adresse[] = $etab['Adresse'];
$pdfInfo->adresse[] = $etab['Adresse2'];
$pdfInfo->adresse[] = $etab['CP'].' '.$etab['Ville'];
// Prix
$tarifs = Doctrine_Query::create()
->from('CommandesTarifs')
->andWhere('codeTribunal = ?', $tribunalCode)
->andWhere('type = ?', $typeDocument)
->andWhere('annee = ?', date('Y'))
->execute();
$pdfInfo->tribunal = $competence;
//Prix
$q = Doctrine_Query::create()
->from('CommandesTarifs')
->where('codeTribunal = ?', $tribunalCode)
->andWhere('type = ?', $typeDocument)
->andWhere('annee = ?', date('Y'));
$tarifs = $q->execute();
$firephp->log($tarifs->toArray(),'tarifs');
if($tarifs->count()==0)
{
echo 'Pas de tarifs d&eacute;fini pour le tribunal '.
$pdfInfo->tribunal['Nom'].' ('.$tribunalCode.')';
exit;
if ($tarifs->count() == 0) {
echo 'Pas de tarifs d&eacute;fini pour le tribunal '.
$info->tribunal['Nom'].' ('.$tribunalCode.')';
exit;
}
$firephp->log($tarifs[0]->prix,'prix');
$pdfInfo->prix = number_format($tarifs[0]->prix, 2, ',', ' ');
$pdfInfo->enveloppe = $tarifs[0]->enveloppe;
$info->prix = number_format($tarifs[0]->prix, 2, ',', ' ');
$info->enveloppe = $tarifs[0]->enveloppe;
// initiate PDF
$pdf = new PDF();
// Destinataire
/*
* Définition des marges
* Left, Top et Right
* Dimension du logo d'entete :
**/
$pdf->SetMargins(25, 50, 25);
$border = 0;
// add a page
$pdf->AddPage();
$pdf->SetFont("times", "", 10);
//Position de départ
$pdf->SetY(50);
//Bloc Addresse destinataire
$txt = '';
/*
$txt.= strtr(
$pdfInfo->tribunal['Nom'],
array(
'TGI' => 'TRIBUNAL DE GRANDE INSTANCE DE',
'TI' => 'TRIBUNAL D\'INSTANCE DE',
'TC' => 'TRIBUNAL DE COMMERCE DE',
'TGIcc' => 'TRIBUNAL DE GRANDE INSTANCE A COMPETENCE COMMERCIALE DE'
)
);
$txt.= "\n";
$destinataire =
strtr($info->tribunal['Nom'],
array('TGI' => 'TRIBUNAL DE GRANDE INSTANCE DE',
'TI' => 'TRIBUNAL D\'INSTANCE DE',
'TC' => 'TRIBUNAL DE COMMERCE DE',
'TGIcc' =>
'TRIBUNAL DE GRANDE INSTANCE A COMPETENCE COMMERCIALE DE')
);
$destinataire .= "\n";
*/
$txt.= "REGISTRE DU COMMERCE - GREFFE" . "\n";
$txt.= normaliseVoie($pdfInfo->tribunal['Adr']) . "\n";
$txt.= normaliseVoie($pdfInfo->tribunal['AdrComp']) . "\n";
$txt.= $pdfInfo->tribunal['CP'] . ' ' . $pdfInfo->tribunal['Ville'] . "\n" ;
$destinataire = "REGISTRE DU COMMERCE - GREFFE\n".
normaliseVoie(trim($info->tribunal['Adr']))."\n".
normaliseVoie($info->tribunal['AdrComp'])."\n".
$info->tribunal['CP'].' '.$info->tribunal['Ville']."\n";
$largeur = 80;
$positionX = 105;
$pdf->MultiCell($largeur, 5, $txt, $border, 'L', 0, 1, $positionX);
//Bloc Lieu, date
$date = date('d/m/Y');
$txt = "Rambouillet, le $date";
$positionY = $pdf->GetY()+8;
$pdf->MultiCell($largeur, 5, $txt, $border, 'L', 0, 1, $positionX, $positionY);
//Bloc objet
$positionY = $pdf->GetY()+5;
$pdf->MultiCell(20, 5, "Objet:", $border, 'L', 0, 0, '', $positionY, true);
$pdf->MultiCell(0, 5, "Commande de document", $border, 'L', 0, 1, '', '', true);
//Bloc ref
$pdf->MultiCell(20, 5, "Réf.", $border, 'L', 0, 0, '', '', true);
$pdf->MultiCell(0, 5, $pdfInfo->ref, $border, 'L', 0, 1, '', '', true);;
//Bloc titre
$positionY = $pdf->GetY()+5;
$pdf->MultiCell(0, 5, "Madame, Monsieur,", $border, 'L', 0, 1, '', $positionY, true);
//Type de document demandé (actes ou bilans pour l'instant)
//[un Kbis / l'état d'endettement / la copie de jugement de XXX en date du XXX ]
$txt = '';
if( $typeDocument == 'bilans' )
{
$txt.= 'une copie du bilan au ';
preg_match('/^[0-9]{4}_.*?-([0-9]{8}).*?/', $commande->refDocument, $matches);
$txt.= substr($matches[1],6,2).'/'.substr($matches[1],4,2).'/'.substr($matches[1],0,4);
}
elseif( $typeDocument == 'actes' )
{
$txt.= 'une copie de l\'acte ';
$txt.= $typeActes['a'.substr($commande->refDocument,0,2)];
if( !empty($commande->libDocument) ) $txt.= ' ('.$commande->libDocument.')';
$txt.= ' en date du '.
substr($commande->refDocument,9,2).'/'.
substr($commande->refDocument,7,2).'/'.
substr($commande->refDocument,3,4);
}
elseif ($typeDocument == 'kbis' )
{
$txt.= 'un extrait RCS';
// Type de document demandé (actes ou bilans pour l'instant)
// [un Kbis / l'état d'endettement / la copie de jugement de XXX en date du XXX]
if ($typeDocument == 'bilans') {
preg_match('/^[0-9]{4}_.*?-([0-9]{8}).*?/',
$commande->refDocument, $matches);
$sujet = 'une copie du bilan au '.
substr($matches[1], 6, 2).'/'.
substr($matches[1], 4, 2).'/'.
substr($matches[1], 0, 4);
} else if ($typeDocument == 'actes') {
$sujet = 'une copie de l\'acte '.
$typeActes['a'.substr($commande->refDocument,0,2)];
if (empty($commande->libDocument) == false) {
$sujet .= ' ('.$commande->libDocument.')';
}
$sujet .= ' en date du '.
substr($commande->refDocument, 9, 2).'/'.
substr($commande->refDocument, 7, 2).'/'.
substr($commande->refDocument, 3, 4);
} else if ($typeDocument == 'kbis') {
$sujet = 'un extrait RCS';
}
$positionY = $pdf->GetY()+2;
$pdf->MultiCell(0, 5, "Je vous prie de nous faire parvenir $txt concernant la société:", $border, 'L', 0, 1, '', $positionY, true);
// Societe
$societe = $info->nom."\n".'( '.$info->siren.$info->libTrib.' )'."\n";
$societe .= normaliseVoie(htmlspecialchars_decode($info->adresse, ENT_QUOTES));
//Bloc société
$txt = '';
$txt.= $pdfInfo->nom;
$txt.= ' ( ' . $pdfInfo->siren . $pdfInfo->libTrib . ' )' . "\n";
foreach($pdfInfo->adresse as $item){
if( !empty($item) ){
$txt.= normaliseVoie(htmlspecialchars_decode($item, ENT_QUOTES)) . "\n";
}
}
$positionY = $pdf->GetY()+2;
$pdf->MultiCell(0, 5, $txt, $border, 'L', 0, 1, '', $positionY, true);
//Bloc pièce jointe
$positionY = $pdf->GetY()+5;
if($pdfInfo->enveloppe)
{
$txt = "Ci joint une enveloppe timbrée ainsi qu'un chèque d'un montant de ".
$pdfInfo->prix." euros en règlement de cette commande.";
}else{
$txt = "Ci joint un chèque d'un montant de ".
$pdfInfo->prix." euros en règlement de cette commande.";
// Piece jointe et montant
if ($info->enveloppe) {
$montant = 'Ci-joint une enveloppe timbrée ainsi qu\'un '.
'chèque d\'un montant de '.$info->prix.
' euros en règlement de cette commande.';
} else {
$montant = 'Ci-joint un chèque d\'un montant de '.$info->prix.
' euros en règlement de cette commande.';
}
$pdf->MultiCell(0, 5, $txt, $border, 'L', 0, 1, '', $positionY, true);
//Bloc intitulé adresse reception
$positionY = $pdf->GetY()+2;
$pdf->MultiCell(0, 5,
"Veuillez nous renvoyer le(s) document(s) par retour à l'adresse suivante:",
$border, 'L', 0, 1, '', $positionY, true);
//Bloc adresse s&d
$positionY = '';
$pdf->MultiCell(0, 5,
"SCORES ET DECISIONS" . "\n" .
"19 rue Clairefontaine". "\n" .
"78120 RAMBOUILLET" . "\n"
, $border, 'L', 0, 1, '', $positionY, true);
//Bloc formule politesse
$positionY = $pdf->GetY()+2;
$pdf->MultiCell(0, 5, "Dans l'attente de notre prochain échange, je vous prie de recevoir, Madame, Monsieur, l'expression de nos plus sincères salutations.", $border, 'L', 0, 1, '', $positionY, true);
$nomFichier = $siren.'-'.$pdfInfo->ref;
$file = $nomFichier.'.pdf';
$path = PATH_DATA.'/courrier/';
$pdf->Output($path.$file, 'F');
if(file_exists($path.$file))
{
$content_type = 'application/pdf';
header('Content-Transfer-Encoding: none');
header('Content-type: '.$content_type.'');
header('Content-Length: '.filesize($path.$file));
header('Content-MD5: '.base64_encode(md5_file($path.$file)));
header('Content-Disposition: attachment, filename="'.$file.'"');
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');
ini_set('zlib.output_compression','0');
echo file_get_contents($path.$file);
}
$file = $siren.'-'.$info->ref.'.odt';
$odf->setVars('destinataire', $destinataire, true, 'UTF-8');
$odf->setVars('date', date('d/m/Y'), true, 'UTF-8');
$odf->setVars('ref', $info->ref, true, 'UTF-8');
$odf->setVars('sujet', $sujet, true, 'UTF-8');
$odf->setVars('societe', $societe, true, 'UTF-8');
$odf->setVars('montant', $montant, true, 'UTF-8');
$odf->saveToDisk($path.$file);
if (file_exists($path.$file) == true) {
header('Content-Transfer-Encoding: none');
header('Content-type: application/vnd.oasis.opendocument.text');
header('Content-Length: '.filesize($path.$file));
header('Content-MD5: '.base64_encode(md5_file($path.$file)));
header('Content-Disposition: attachment, filename="'.$file.'"');
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');
ini_set('zlib.output_compression','0');
print file_get_contents($path.$file);
}

Binary file not shown.

16
includes/saisie/odtphpinst.sh Executable file
View File

@ -0,0 +1,16 @@
#!/bin/bash
cd ~/tmp
wget http://www.mirrorservice.org/sites/download.sourceforge.net/pub/\
sourceforge/o/project/od/odtphp/odtphp/odtPHP%201.0/odtphp-1.0.1.zip
cd -
cd ${0%/*}
cd ../lib
mkdir odtphp
cd odtphp
unzip ~/tmp/odtphp-1.0.1.zip -x tests/* *.svn/*
cd library/zip
cp PclZipProxy.php pPclZipProxy.php.bak
sed 's/\.\/tmp/\/tmp\/odtphp/' pPclZipProxy.php.bak > PclZipProxy.php