<?php ////////////////////////////////////////////////////////////// // Génération d'un courrier ODT sur base d'un formulaire // // // // Laurent Lefèvre - http://www.cybermonde.org // // // ////////////////////////////////////////////////////////////// // Source : https://github.com/cybermonde/odtphp // inclure la librairie require_once '../library/Odf.php'; // modèle de base $odf = new odf("formulaire_template.odt"); // si rien n'a été posté on propose le formulaire if (!$_POST) { ?> <!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"> <head> <title>Formulaire vers ODT</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <style type="text/css"> </style> </head> <body> <form id="monformulaire" method="POST" action="formulaire.php"> <p> <input type="radio" id="invite" name="invite" value="Madame" checked />Mme <input type="radio" id="invite" name="invite" value="Monsieur" />M. </p> <p>
<?php session_start(); require_once '../library/odf.php'; $odf = new odf("new.odt"); if ($_SERVER['REQUEST_METHOD'] == 'POST') { // Assigning Form data to variables. $name = $_POST["sal"]; $firstName = $_POST["fname"]; $middleName = $_POST["mname"]; $lastName = $_POST["lname"]; $institute = $_POST["ins"]; $city = $_POST["city"]; $state = $_POST["state"]; $_SESSION['name'] = $name; $_SESSION['fname'] = $firstName; $_SESSION['mname'] = $middleName; $_SESSION['lname'] = $lastName; $_SESSION['ins'] = $institute; $_SESSION['city'] = $city; $_SESSION['state'] = $state; //assigning image name to variable photo. $photo = $_FILES["file"]["name"]; $_SESSION['photo'] = $photo; /*************************************** Image Validation********************************************/ $url = "<meta http-equiv='Refresh' content='1; URL=option.php?var=manual'>"; if ($_FILES["file"]["type"] == "image/gif" || $_FILES["file"]["type"] == "image/jpeg" || $_FILES["file"]["type"] == "image/jpg" || $_FILES["file"]["type"] == "image/pjpeg" || $_FILES["file"]["type"] == "image/x-png" || $_FILES["file"]["type"] == "image/png") { if ($_FILES["file"]["size"] > 400144) { echo "<center><h1>Image Size Exceeded...</h1></center>"; sleep(2); echo $url;
<?php require_once '../library/odf.php'; $sel = $_GET["cert"]; //Represents Selection $odf = new odf("odt/{$sel}.odt"); if ($_SERVER['REQUEST_METHOD'] == 'POST') { /* storing data from html form to php variables*/ $insName = $_POST["in"]; $aidedStatus = $_POST["as"]; $insTagline = $_POST["it"]; $affilliation = $_POST["a"]; $event = $_POST["e"]; $topic = $_POST["t"]; $sign1 = $_POST["s1"]; $sign2 = $_POST["s2"]; $sign3 = $_POST["s3"]; $des1 = $_POST["d1"]; $des2 = $_POST["d2"]; $des3 = $_POST["d3"]; $odf->setvars('College', $insName); $odf->setvars('status', $aidedStatus); $odf->setvars('tagline', $insTagline); $odf->setvars('other', $affilliation); $odf->setvars('event', $event); $odf->setvars('topic', $topic); $odf->setvars('sign1', $sign1); $odf->setvars('sign2', $sign2); $odf->setvars('sign3', $sign3); $odf->setvars('d1', $des1); $odf->setvars('d2', $des2);
/** * Function to build a document on disk using the generic odt module. * * @param Commande $object Object source to build document * @param Translate $outputlangs Lang output object * @param string $srctemplatepath Full path of source filename for generator using a template file * @return int 1 if OK, <=0 if KO */ function write_file($object, $outputlangs, $srctemplatepath) { global $user, $langs, $conf, $mysoc, $hookmanager; if (empty($srctemplatepath)) { dol_syslog("doc_generic_odt::write_file parameter srctemplatepath empty", LOG_WARNING); return -1; } if (!is_object($outputlangs)) { $outputlangs = $langs; } $sav_charset_output = $outputlangs->charset_output; $outputlangs->charset_output = 'UTF-8'; $outputlangs->load("main"); $outputlangs->load("dict"); $outputlangs->load("companies"); $outputlangs->load("projects"); if ($conf->projet->dir_output) { // If $object is id instead of object if (!is_object($object)) { $id = $object; $object = new Task($this->db); $result = $object->fetch($id); if ($result < 0) { dol_print_error($this->db, $object->error); return -1; } } $project = new Project($this->db); $project->fetch($object->fk_project); $dir = $conf->projet->dir_output . "/" . $project->ref . "/"; $objectref = dol_sanitizeFileName($object->ref); if (!preg_match('/specimen/i', $objectref)) { $dir .= "/" . $objectref; } $file = $dir . "/" . $objectref . ".odt"; if (!file_exists($dir)) { print '$dir' . $dir; if (dol_mkdir($dir) < 0) { $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); return -1; } } if (file_exists($dir)) { //print "srctemplatepath=".$srctemplatepath; // Src filename $newfile = basename($srctemplatepath); $newfiletmp = preg_replace('/\\.(ods|odt)/i', '', $newfile); $newfiletmp = preg_replace('/template_/i', '', $newfiletmp); $newfiletmp = preg_replace('/modele_/i', '', $newfiletmp); $newfiletmp = $objectref . '_' . $newfiletmp; //$file=$dir.'/'.$newfiletmp.'.'.dol_print_date(dol_now(),'%Y%m%d%H%M%S').'.odt'; $file = $dir . '/' . $newfiletmp . '.odt'; //print "newdir=".$dir; //print "newfile=".$newfile; //print "file=".$file; //print "conf->societe->dir_temp=".$conf->societe->dir_temp; dol_mkdir($conf->projet->dir_temp); $socobject = $object->thirdparty; // Make substitution $substitutionarray = array('__FROM_NAME__' => $this->emetteur->name, '__FROM_EMAIL__' => $this->emetteur->email); complete_substitutions_array($substitutionarray, $langs, $object); // Open and load template require_once ODTPHP_PATH . 'odf.php'; try { $odfHandler = new odf($srctemplatepath, array('PATH_TO_TMP' => $conf->projet->dir_temp, 'ZIP_PROXY' => 'PclZipProxy', 'DELIMITER_LEFT' => '{', 'DELIMITER_RIGHT' => '}')); } catch (Exception $e) { $this->error = $e->getMessage(); return -1; } // After construction $odfHandler->contentXml contains content and // [!-- BEGIN row.lines --]*[!-- END row.lines --] has been replaced by // [!-- BEGIN lines --]*[!-- END lines --] //print html_entity_decode($odfHandler->__toString()); //print exit; // Make substitutions into odt of user info $array_user = $this->get_substitutionarray_user($user, $outputlangs); $array_soc = $this->get_substitutionarray_mysoc($mysoc, $outputlangs); $array_thirdparty = $this->get_substitutionarray_thirdparty($socobject, $outputlangs); $array_objet = $this->get_substitutionarray_object($project, $outputlangs); $array_other = $this->get_substitutionarray_other($outputlangs); $tmparray = array_merge($array_user, $array_soc, $array_thirdparty, $array_objet, $array_other); complete_substitutions_array($tmparray, $outputlangs, $object); foreach ($tmparray as $key => $value) { try { if (preg_match('/logo$/', $key)) { if (file_exists($value)) { $odfHandler->setImage($key, $value); } else { $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8'); } } else { $odfHandler->setVars($key, $value, true, 'UTF-8'); } } catch (OdfException $e) { } } // Replace tags of lines for tasks try { // Security check $socid = 0; if (!empty($project->fk_soc)) { $socid = $project->fk_soc; } $tmparray = $this->get_substitutionarray_tasks($object, $outputlangs); complete_substitutions_array($tmparray, $outputlangs, $object); foreach ($tmparray as $key => $val) { try { $odfHandler->setVars($key, $val, true, 'UTF-8'); } catch (OdfException $e) { } catch (SegmentException $e) { } } // Replace tags of lines for contacts task $sourcearray = array('internal', 'external'); $contact_arrray = array(); foreach ($sourcearray as $source) { $contact_temp = $object->liste_contact(-1, $source); if (is_array($contact_temp) && count($contact_temp) > 0) { $contact_arrray = array_merge($contact_arrray, $contact_temp); } } if (is_array($contact_arrray) && count($contact_arrray) > 0) { $listlinestaskres = $odfHandler->setSegment('tasksressources'); foreach ($contact_arrray as $contact) { if ($contact['source'] == 'internal') { $objectdetail = new User($this->db); $objectdetail->fetch($contact['id']); $contact['socname'] = $mysoc->name; } elseif ($contact['source'] == 'external') { $objectdetail = new Contact($this->db); $objectdetail->fetch($contact['id']); $soc = new Societe($this->db); $soc->fetch($contact['socid']); $contact['socname'] = $soc->name; } $contact['fullname'] = $objectdetail->getFullName($outputlangs, 1); $tmparray = $this->get_substitutionarray_tasksressource($contact, $outputlangs); foreach ($tmparray as $key => $val) { try { $listlinestaskres->setVars($key, $val, true, 'UTF-8'); } catch (OdfException $e) { } catch (SegmentException $e) { } } $listlinestaskres->merge(); } $odfHandler->mergeSegment($listlinestaskres); } //Time ressources $sql = "SELECT t.rowid, t.task_date, t.task_duration, t.fk_user, t.note"; $sql .= ", u.name, u.firstname"; $sql .= " FROM " . MAIN_DB_PREFIX . "projet_task_time as t"; $sql .= " , " . MAIN_DB_PREFIX . "user as u"; $sql .= " WHERE t.fk_task =" . $object->id; $sql .= " AND t.fk_user = u.rowid"; $sql .= " ORDER BY t.task_date DESC"; $resql = $this->db->query($sql); if ($resql) { $num = $this->db->num_rows($resql); $i = 0; $tasks = array(); $listlinestasktime = $odfHandler->setSegment('taskstimes'); while ($i < $num) { $row = $this->db->fetch_array($resql); if (!empty($row['fk_user'])) { $objectdetail = new User($this->db); $objectdetail->fetch($row['fk_user']); $row['fullcivname'] = $objectdetail->getFullName($outputlangs, 1); } else { $row['fullcivname'] = ''; } $tmparray = $this->get_substitutionarray_taskstime($row, $outputlangs); foreach ($tmparray as $key => $val) { try { $listlinestasktime->setVars($key, $val, true, 'UTF-8'); } catch (OdfException $e) { } catch (SegmentException $e) { } } $listlinestasktime->merge(); $i++; } $this->db->free($resql); $odfHandler->mergeSegment($listlinestasktime); } // Replace tags of project files $listtasksfiles = $odfHandler->setSegment('tasksfiles'); $upload_dir = $conf->projet->dir_output . '/' . dol_sanitizeFileName($project->ref) . '/' . dol_sanitizeFileName($object->ref); $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\\.meta|_preview\\.png)$', 'name', SORT_ASC, 1); foreach ($filearray as $filedetail) { $tmparray = $this->get_substitutionarray_task_file($filedetail, $outputlangs); //dol_syslog(get_class($this).'::main $tmparray'.var_export($tmparray,true)); foreach ($tmparray as $key => $val) { try { $listtasksfiles->setVars($key, $val, true, 'UTF-8'); } catch (OdfException $e) { } catch (SegmentException $e) { } } $listtasksfiles->merge(); } //$listlines->merge(); $odfHandler->mergeSegment($listtasksfiles); } catch (OdfException $e) { $this->error = $e->getMessage(); dol_syslog($this->error, LOG_WARNING); return -1; } // Replace tags of project files try { $listlines = $odfHandler->setSegment('projectfiles'); $upload_dir = $conf->projet->dir_output . '/' . dol_sanitizeFileName($object->ref); $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\\.meta|_preview\\.png)$', 'name', SORT_ASC, 1); foreach ($filearray as $filedetail) { //dol_syslog(get_class($this).'::main $filedetail'.var_export($filedetail,true)); $tmparray = $this->get_substitutionarray_project_file($filedetail, $outputlangs); foreach ($tmparray as $key => $val) { try { $listlines->setVars($key, $val, true, 'UTF-8'); } catch (OdfException $e) { } catch (SegmentException $e) { } } $listlines->merge(); } $odfHandler->mergeSegment($listlines); } catch (OdfException $e) { $this->error = $e->getMessage(); dol_syslog($this->error, LOG_WARNING); return -1; } // Replace tags of lines for contacts $sourcearray = array('internal', 'external'); $contact_arrray = array(); foreach ($sourcearray as $source) { $contact_temp = $project->liste_contact(-1, $source); if (is_array($contact_temp) && count($contact_temp) > 0) { $contact_arrray = array_merge($contact_arrray, $contact_temp); } } if (is_array($contact_arrray) && count($contact_arrray) > 0) { try { $listlines = $odfHandler->setSegment('projectcontacts'); foreach ($contact_arrray as $contact) { if ($contact['source'] == 'internal') { $objectdetail = new User($this->db); $objectdetail->fetch($contact['id']); $contact['socname'] = $mysoc->name; } elseif ($contact['source'] == 'external') { $objectdetail = new Contact($this->db); $objectdetail->fetch($contact['id']); $soc = new Societe($this->db); $soc->fetch($contact['socid']); $contact['socname'] = $soc->name; } $contact['fullname'] = $objectdetail->getFullName($outputlangs, 1); $tmparray = $this->get_substitutionarray_project_contacts($contact, $outputlangs); foreach ($tmparray as $key => $val) { try { $listlines->setVars($key, $val, true, 'UTF-8'); } catch (OdfException $e) { } catch (SegmentException $e) { } } $listlines->merge(); } $odfHandler->mergeSegment($listlines); } catch (OdfException $e) { $this->error = $e->getMessage(); dol_syslog($this->error, LOG_WARNING); return -1; } } // Call the beforeODTSave hook $parameters = array('odfHandler' => &$odfHandler, 'file' => $file, 'object' => $object, 'outputlangs' => $outputlangs); $reshook = $hookmanager->executeHooks('beforeODTSave', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks // Write new file if (!empty($conf->global->MAIN_ODT_AS_PDF)) { try { $odfHandler->exportAsAttachedPDF($file); } catch (Exception $e) { $this->error = $e->getMessage(); return -1; } } else { try { $odfHandler->saveToDisk($file); } catch (Exception $e) { $this->error = $e->getMessage(); return -1; } } $reshook = $hookmanager->executeHooks('afterODTCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks if (!empty($conf->global->MAIN_UMASK)) { @chmod($file, octdec($conf->global->MAIN_UMASK)); } $odfHandler = null; // Destroy object return 1; // Success } else { $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); return -1; } } return -1; }
echo $url; exit; } else { $csvtoken = strtok($csv, "."); while ($csvtoken != false) { $ext = $csvtoken; $csvtoken = strtok("."); } if ($ext != "csv") { echo "<center><h2>Invalid File Format for .csv file...</h2></center>"; echo $url; exit; } move_uploaded_file($_FILES["file"]["tmp_name"], $_FILES["file"]["name"]); } $odf = new odf("new.odt"); $file = $_FILES["photo"]["name"]; if ($file == NULL) { echo "<center><h2>No compressed file selected for images<h2></center>"; echo $url; exit; } move_uploaded_file($_FILES["photo"]["tmp_name"], $_FILES["photo"]["name"]); $token = strtok($file, "."); while ($token != false) { $new = $token; $token = strtok("."); } if ($new == "gz") { //echo "tar.gz file"; exec("tar -zxvf {$file}");
/** * * @param IssueSelection $iSel * @param type $projectid * @param type $odtTemplate * @return string filepath complete path to generated ODT file */ private function generateODT(IssueSelection $iSel, $projectid, $odtTemplate) { self::$logger->debug("genProjectODT(): project {$projectid} template {$odtTemplate}"); $project = ProjectCache::getInstance()->getProject($projectid); $odf = new odf($odtTemplate); try { $odf->setVars('today', date('Y-m-d')); } catch (Exception $e) { } try { $odf->setVars('selectionName', $project->getName()); } catch (Exception $e) { } try { $session_user = UserCache::getInstance()->getUser($this->session_userid); $odf->setVars('sessionUser', $session_user->getRealname()); } catch (Exception $e) { } $issueList = $iSel->getIssueList(); if (self::$logger->isDebugEnabled()) { self::$logger->debug("nb issues = " . count($issueList)); } $q_id = 0; try { $issueSegment = $odf->setSegment('issueSelection'); } catch (Exception $e) { self::$logger->error("generateODT: TAG 'issueSelection'"); self::$logger->error("generateODT: " + $e->getMessage()); return "FAILED: error on segment 'issueSelection'."; } if (self::$logger->isDebugEnabled()) { self::$logger->debug('XML=' . $issueSegment->getXml()); } foreach ($issueList as $issue) { $q_id += 1; if (0 == $issue->getHandlerId()) { $userName = T_('unknown'); } else { $user = UserCache::getInstance()->getUser($issue->getHandlerId()); $userName = utf8_decode($user->getRealname()); if (empty($userName)) { $userName = "******" . $issue->getHandlerId(); } } if (self::$logger->isDebugEnabled()) { self::$logger->debug("issue " . $issue->getId() . ": handlerName = " . $userName); } if (0 == $issue->getReporterId()) { $reporterName = T_('unknown'); } else { $reporter = UserCache::getInstance()->getUser($issue->getReporterId()); $reporterName = utf8_decode($reporter->getRealname()); if (empty($reporterName)) { $reporterName = "user_" . $issue->getReporterId(); } } if (self::$logger->isDebugEnabled()) { self::$logger->debug("issue " . $issue->getId() . ": reporterName = " . $reporterName); } // add issue try { $issueSegment->setVars('q_id', $q_id); } catch (Exception $e) { } try { $issueSegment->setVars('bugId', $issue->getId()); } catch (Exception $e) { $this->logException($e); } try { $issueSegment->setVars('summary', utf8_decode($issue->getSummary())); } catch (Exception $e) { $this->logException($e); } try { $issueSegment->setVars('dateSubmission', date('d/m/Y', $issue->getDateSubmission())); } catch (Exception $e) { } try { $timestamp = $issue->getLatestStatusOccurrence($issue->getBugResolvedStatusThreshold()); if (is_null($timestamp)) { $issueSegment->setVars('dateResolved', ''); } else { $issueSegment->setVars('dateResolved', date('d/m/Y', $timestamp)); } } catch (Exception $e) { } try { $timestamp = $issue->getDeadLine(); $deadline = 0 == $timestamp ? '' : date('d/m/Y', $issue->getDeadLine()); $issueSegment->setVars('deadline', $deadline); } catch (Exception $e) { $this->logException($e); } try { $issueSegment->setVars('currentStatus', Constants::$statusNames[$issue->getCurrentStatus()]); } catch (Exception $e) { } try { $issueSegment->setVars('handlerId', $userName); } catch (Exception $e) { } try { $issueSegment->setVars('reporterId', $reporterName); } catch (Exception $e) { } try { $issueSegment->setVars('reporterName', $reporterName); } catch (Exception $e) { } try { $issueSegment->setVars('description', utf8_decode($issue->getDescription())); } catch (Exception $e) { } #try { $issueSegment->setVars('description', utf8_decode(Tools::convertToUTF8($issue->getDescription()))); } catch (Exception $e) { }; try { $issueSegment->setVars('category', $issue->getCategoryName()); } catch (Exception $e) { } try { $issueSegment->setVars('severity', $issue->getSeverityName()); } catch (Exception $e) { } try { $issueSegment->setVars('status', Constants::$statusNames[$issue->getStatus()]); } catch (Exception $e) { } try { $issueSegment->setVars('extId', $issue->getTcId()); } catch (Exception $e) { } // add issueNotes $issueNotes = $issue->getIssueNoteList(); $noteId = 0; foreach ($issueNotes as $id => $issueNote) { $noteId += 1; if (self::$logger->isDebugEnabled()) { self::$logger->debug("issue " . $issue->getId() . ": note {$id} = " . $issueNote->getNote()); } $noteReporter = UserCache::getInstance()->getUser($issueNote->getReporterId()); try { $noteReporterName = utf8_decode($noteReporter->getRealname()); } catch (Exception $e) { } try { $issueSegment->bugnotes->noteId($noteId); } catch (Exception $e) { } try { $issueSegment->bugnotes->noteReporter($noteReporterName); } catch (Exception $e) { } try { $issueSegment->bugnotes->noteDateSubmission(date('d/m/Y', $issueNote->getDateSubmitted())); } catch (Exception $e) { } try { $issueSegment->bugnotes->note(utf8_decode($issueNote->getNote())); } catch (Exception $e) { } try { $issueSegment->bugnotes->merge(); } catch (Exception $e) { } } $issueSegment->merge(); } $odf->mergeSegment($issueSegment); // INFO: the following line is MANDATORY and fixes the following error: // "wrong .odt file encoding" #ob_end_clean(); #$odf->exportAsAttachedFile(); // 2nd solution : show link in page $odtFilename = basename($odtTemplate, ".odt") . '_' . $project->getName() . '_' . date('Ymd') . '.odt'; $filepath = Constants::$codevOutputDir . '/reports/' . $odtFilename; if (self::$logger->isDebugEnabled()) { self::$logger->debug("save odt file " . $filepath); } $odf->saveToDisk($filepath); return $filepath; }
<?php /** * Tutoriel file * Description : Adding a single image to the document * You need PHP 5.2 at least * You need Zip Extension or PclZip library * * @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 */ // Make sure you have Zip extension or PclZip library loaded // First : include the librairy require_once '../library/odf.php'; $odf = new odf("tutoriel2.odt"); $odf->setVars('titre', 'Anaska formation'); $message = "Anaska, leader Français de la formation informatique sur les technologies \r\nOpen Source, propose un catalogue de plus de 50 formations dont certaines préparent \r\naux certifications Linux, MySQL, PHP et PostgreSQL."; $odf->setVars('message', $message); $odf->setImage('image', './images/anaska.jpg'); // We export the file $odf->exportAsAttachedFile();
/** * Function to build a document on disk using the generic odt module. * @param object Object source to build document * @param outputlangs Lang output object * @param srctemplatepath Full path of source filename for generator using a template file * @return int 1 if OK, <=0 if KO */ function write_file($object,$outputlangs,$srctemplatepath) { global $user,$langs,$conf,$mysoc; if (empty($srctemplatepath)) { dol_syslog("doc_generic_odt::write_file parameter srctemplatepath empty", LOG_WARNING); return -1; } if (! is_object($outputlangs)) $outputlangs=$langs; $sav_charset_output=$outputlangs->charset_output; $outputlangs->charset_output='UTF-8'; $outputlangs->load("main"); $outputlangs->load("dict"); $outputlangs->load("companies"); $outputlangs->load("projects"); if ($conf->societe->dir_output) { // If $object is id instead of object if (! is_object($object)) { $id = $object; $object = new Societe($this->db); $object->fetch($id); if ($result < 0) { dol_print_error($db,$object->error); return -1; } } $objectref = dol_sanitizeFileName($object->id); $dir = $conf->societe->dir_output; if (! preg_match('/specimen/i',$objectref)) $dir.= "/" . $objectref; $file = $dir . "/" . $objectref . ".odt"; if (! file_exists($dir)) { if (create_exdir($dir) < 0) { $this->error=$langs->transnoentities("ErrorCanNotCreateDir",$dir); return -1; } } if (file_exists($dir)) { //print "srctemplatepath=".$srctemplatepath; // Src filename $newfile=basename($srctemplatepath); $newfiletmp=preg_replace('/\.odt/i','',$newfile); $file=$dir.'/'.$newfiletmp.'.'.dol_print_date(dol_now(),'%Y%m%d%H%M%S').'.odt'; //print "newdir=".$dir; //print "newfile=".$newfile; //print "file=".$file; //print "conf->societe->dir_temp=".$conf->societe->dir_temp; create_exdir($conf->societe->dir_temp); // Open and load template require_once(DOL_DOCUMENT_ROOT.'/includes/odtphp/odf.php'); $odfHandler = new odf($srctemplatepath, array( 'PATH_TO_TMP' => $conf->societe->dir_temp, 'ZIP_PROXY' => 'PclZipProxy', // PhpZipProxy or PclZipProxy. Got "bad compression method" error when using PhpZipProxy. 'DELIMITER_LEFT' => '{', 'DELIMITER_RIGHT' => '}') ); //print $odfHandler->__toString()."\n"; // Make substitutions into odt of user info $tmparray=$this->get_substitutionarray_user($user,$outputlangs); //var_dump($tmparray); exit; foreach($tmparray as $key=>$value) { try { if (preg_match('/logo$/',$key)) // Image { //var_dump($value);exit; if (file_exists($value)) $odfHandler->setImage($key, $value); else $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8'); } else // Text { //print $key.' '.$value;exit; $odfHandler->setVars($key, $value, true, 'UTF-8'); } } catch(OdfException $e) { } } // Make substitutions into odt of mysoc info $tmparray=$this->get_substitutionarray_mysoc($mysoc,$outputlangs); //var_dump($tmparray); exit; foreach($tmparray as $key=>$value) { try { if (preg_match('/logo$/',$key)) // Image { //var_dump($value);exit; if (file_exists($value)) $odfHandler->setImage($key, $value); else $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8'); } else // Text { $odfHandler->setVars($key, $value, true, 'UTF-8'); } } catch(OdfException $e) { } } // Make substitutions into odt of thirdparty + external modules $tmparray=$this->get_substitutionarray_thirdparty($object,$outputlangs); complete_substitutions_array($tmparray, $langs, $object); //var_dump($object->id); exit; foreach($tmparray as $key=>$value) { try { if (preg_match('/logo$/',$key)) // Image { if (file_exists($value)) $odfHandler->setImage($key, $value); else $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8'); } else // Text { $odfHandler->setVars($key, $value, true, 'UTF-8'); } } catch(OdfException $e) { } } // Write new file //$result=$odfHandler->exportAsAttachedFile('toto'); $odfHandler->saveToDisk($file); if (! empty($conf->global->MAIN_UMASK)) @chmod($file, octdec($conf->global->MAIN_UMASK)); $odfHandler=null; // Destroy object return 1; // Success } else { $this->error=$langs->transnoentities("ErrorCanNotCreateDir",$dir); return -1; } } return -1; }
<?php /** * Tutoriel file * Description : Odf object with configuration array * You need PHP 5.2 at least * You need Zip Extension or PclZip library * * @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 */ // Make sure you have Zip extension or PclZip library loaded // First : include the librairy require_once '../library/odf.php'; $config = array('ZIP_PROXY' => 'PhpZipProxy', 'DELIMITER_LEFT' => '#', 'DELIMITER_RIGHT' => '#'); $odf = new odf("tutoriel7.odt", $config); $odf->setVars('titre', 'PHP: Hypertext PreprocessorPHP: Hypertext Preprocessor'); $message = "PHP (sigle de PHP: Hypertext Preprocessor), est un langage de scripts libre \r\nprincipalement utilisé pour produire des pages Web dynamiques via un serveur HTTP, mais \r\npouvant également fonctionner comme n'importe quel langage interprété de façon locale, \r\nen exécutant les programmes en ligne de commande."; $odf->setVars('message', $message); // We export the file $odf->exportAsAttachedFile();
<?php /** * Tutoriel file * Description : Merging a Segment with some data * You need PHP 5.2 at least * You need Zip Extension or PclZip library * * @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 */ // Make sure you have Zip extension or PclZip library loaded // First : include the librairy require_once '../library/odf.php'; $odf = new odf("tutoriel3.odt"); $odf->setVars('titre', 'Quelques articles de l\'encyclopédie Wikipédia'); $message = "La force de cette encyclopédie en ligne réside dans son nombre important de \r\n contributeurs. Ce sont en effet des millions d'articles qui sont disponibles dans la langue \r\n de Shakespeare et des centaines de milliers d'autres dans de nombreuses langues dont \r\n le français, l'espagnol, l'italien, le turc ou encore l'allemand."; $odf->setVars('message', $message); $listeArticles = array(array('titre' => 'PHP', 'texte' => 'PHP (sigle de PHP: Hypertext Preprocessor), est un langage de scripts (...)'), array('titre' => 'MySQL', 'texte' => 'MySQL est un système de gestion de base de données (SGDB). Selon le (...)'), array('titre' => 'Apache', 'texte' => 'Apache HTTP Server, souvent appelé Apache, est un logiciel de serveur (...)')); $article = $odf->setSegment('articles'); foreach ($listeArticles as $element) { $article->titreArticle($element['titre']); $article->texteArticle($element['texte']); $article->merge(); } $odf->mergeSegment($article); // We export the file $odf->exportAsAttachedFile();
/** * Function to build a document on disk using the generic odt module. * * @param Facture $object Object source to build document * @param Translate $outputlangs Lang output object * @param string $srctemplatepath Full path of source filename for generator using a template file * @return int 1 if OK, <=0 if KO */ function write_file($object, $outputlangs, $srctemplatepath) { global $user, $langs, $conf, $mysoc; if (empty($srctemplatepath)) { dol_syslog("doc_generic_odt::write_file parameter srctemplatepath empty", LOG_WARNING); return -1; } if (!is_object($outputlangs)) { $outputlangs = $langs; } $sav_charset_output = $outputlangs->charset_output; $outputlangs->charset_output = 'UTF-8'; $outputlangs->load("main"); $outputlangs->load("dict"); $outputlangs->load("companies"); $outputlangs->load("bills"); if ($conf->facture->dir_output) { // If $object is id instead of object if (!is_object($object)) { $id = $object; $object = new Facture($this->db); $result = $object->fetch($id); if ($result < 0) { dol_print_error($this->db, $object->error); return -1; } } $dir = $conf->facture->dir_output; $objectref = dol_sanitizeFileName($object->ref); if (!preg_match('/specimen/i', $objectref)) { $dir .= "/" . $objectref; } $file = $dir . "/" . $objectref . ".odt"; if (!file_exists($dir)) { if (dol_mkdir($dir) < 0) { $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); return -1; } } if (file_exists($dir)) { //print "srctemplatepath=".$srctemplatepath;exit; // Src filename $newfile = basename($srctemplatepath); $newfiletmp = preg_replace('/\\.odt/i', '', $newfile); $newfiletmp = preg_replace('/template_/i', '', $newfiletmp); $newfiletmp = preg_replace('/modele_/i', '', $newfiletmp); $newfiletmp = $objectref . '_' . $newfiletmp; //$file=$dir.'/'.$newfiletmp.'.'.dol_print_date(dol_now(),'%Y%m%d%H%M%S').'.odt'; $file = $dir . '/' . $newfiletmp . '.odt'; //print "newdir=".$dir; //print "newfile=".$newfile; //print "file=".$file; //print "conf->societe->dir_temp=".$conf->societe->dir_temp; dol_mkdir($conf->facture->dir_temp); // If BILLING contact defined on invoice, we use it $usecontact = false; $arrayidcontact = $object->getIdContact('external', 'BILLING'); if (count($arrayidcontact) > 0) { $usecontact = true; $result = $object->fetch_contact($arrayidcontact[0]); } // Recipient name if (!empty($usecontact)) { // On peut utiliser le nom de la societe du contact if ($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT) { $socobject = $object->contact; } else { $socobject = $object->client; } } else { $socobject = $object->client; } // Make substitution $substitutionarray = array('__FROM_NAME__' => $this->emetteur->nom, '__FROM_EMAIL__' => $this->emetteur->email, '__TOTAL_TTC__' => $object->total_ttc, '__TOTAL_HT__' => $object->total_ht, '__TOTAL_VAT__' => $object->total_vat); complete_substitutions_array($substitutionarray, $langs, $object); // Line of free text $newfreetext = ''; $paramfreetext = 'FACTURE_FREE_TEXT'; if (!empty($conf->global->{$paramfreetext})) { $newfreetext = make_substitutions($conf->global->{$paramfreetext}, $substitutionarray); } // Open and load template require_once ODTPHP_PATH . 'odf.php'; $odfHandler = new odf($srctemplatepath, array('PATH_TO_TMP' => $conf->facture->dir_temp, 'ZIP_PROXY' => 'PclZipProxy', 'DELIMITER_LEFT' => '{', 'DELIMITER_RIGHT' => '}')); // After construction $odfHandler->contentXml contains content and // [!-- BEGIN row.lines --]*[!-- END row.lines --] has been replaced by // [!-- BEGIN lines --]*[!-- END lines --] //print html_entity_decode($odfHandler->__toString()); //print exit; // Make substitutions into odt of freetext try { $odfHandler->setVars('free_text', $newfreetext, true, 'UTF-8'); } catch (OdfException $e) { } // Make substitutions into odt of user info $tmparray = $this->get_substitutionarray_user($user, $outputlangs); //var_dump($tmparray); exit; foreach ($tmparray as $key => $value) { try { if (preg_match('/logo$/', $key)) { //var_dump($value);exit; if (file_exists($value)) { $odfHandler->setImage($key, $value); } else { $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8'); } } else { $odfHandler->setVars($key, $value, true, 'UTF-8'); } } catch (OdfException $e) { } } // Make substitutions into odt of mysoc $tmparray = $this->get_substitutionarray_mysoc($mysoc, $outputlangs); //var_dump($tmparray); exit; foreach ($tmparray as $key => $value) { try { if (preg_match('/logo$/', $key)) { //var_dump($value);exit; if (file_exists($value)) { $odfHandler->setImage($key, $value); } else { $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8'); } } else { $odfHandler->setVars($key, $value, true, 'UTF-8'); } } catch (OdfException $e) { } } // Make substitutions into odt of thirdparty $tmparray = $this->get_substitutionarray_thirdparty($socobject, $outputlangs); foreach ($tmparray as $key => $value) { try { if (preg_match('/logo$/', $key)) { if (file_exists($value)) { $odfHandler->setImage($key, $value); } else { $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8'); } } else { $odfHandler->setVars($key, $value, true, 'UTF-8'); } } catch (OdfException $e) { } } // Replace tags of object + external modules $tmparray = $this->get_substitutionarray_object($object, $outputlangs); complete_substitutions_array($tmparray, $outputlangs, $object); foreach ($tmparray as $key => $value) { try { if (preg_match('/logo$/', $key)) { if (file_exists($value)) { $odfHandler->setImage($key, $value); } else { $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8'); } } else { $odfHandler->setVars($key, $value, true, 'UTF-8'); } } catch (OdfException $e) { } } // Replace tags of lines try { $listlines = $odfHandler->setSegment('lines'); foreach ($object->lines as $line) { $tmparray = $this->get_substitutionarray_lines($line, $outputlangs); foreach ($tmparray as $key => $val) { try { $listlines->setVars($key, $val, true, 'UTF-8'); } catch (OdfException $e) { } catch (SegmentException $e) { } } $listlines->merge(); } $odfHandler->mergeSegment($listlines); } catch (OdfException $e) { $this->error = $e->getMessage(); dol_syslog($this->error, LOG_WARNING); return -1; } // Write new file //$result=$odfHandler->exportAsAttachedFile('toto'); $odfHandler->saveToDisk($file); if (!empty($conf->global->MAIN_UMASK)) { @chmod($file, octdec($conf->global->MAIN_UMASK)); } $odfHandler = null; // Destroy object return 1; // Success } else { $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); return -1; } } return -1; }
/** * Function to build a document on disk using the generic odt module. * * @param Societe $object Object source to build document * @param Translate $outputlangs Lang output object * @param string $srctemplatepath Full path of source filename for generator using a template file * @return int 1 if OK, <=0 if KO */ function write_file($object, $outputlangs, $srctemplatepath) { global $user, $langs, $conf, $mysoc; if (empty($srctemplatepath)) { dol_syslog("doc_generic_odt::write_file parameter srctemplatepath empty", LOG_WARNING); return -1; } if (!is_object($outputlangs)) { $outputlangs = $langs; } $sav_charset_output = $outputlangs->charset_output; $outputlangs->charset_output = 'UTF-8'; $outputlangs->load("main"); $outputlangs->load("dict"); $outputlangs->load("companies"); $outputlangs->load("projects"); if ($conf->societe->multidir_output[$object->entity]) { $dir = $conf->societe->multidir_output[$object->entity]; $objectref = dol_sanitizeFileName($object->id); if (!preg_match('/specimen/i', $objectref)) { $dir .= "/" . $objectref; } if (!file_exists($dir)) { if (dol_mkdir($dir) < 0) { $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); return -1; } } if (file_exists($dir)) { //print "srctemplatepath=".$srctemplatepath; // Src filename $newfile = basename($srctemplatepath); $newfiletmp = preg_replace('/\\.odt/i', '', $newfile); $newfiletmp = preg_replace('/template_/i', '', $newfiletmp); $newfiletmp = preg_replace('/modele_/i', '', $newfiletmp); $filename = $newfiletmp . '.' . dol_print_date(dol_now(), '%Y%m%d%H%M%S') . '.odt'; $file = $dir . '/' . $filename; $object->builddoc_filename = $filename; // For triggers //print "newdir=".$dir; //print "newfile=".$newfile; //print "file=".$file; //print "conf->societe->dir_temp=".$conf->societe->dir_temp; dol_mkdir($conf->societe->multidir_temp[$object->entity]); // Open and load template require_once ODTPHP_PATH . 'odf.php'; $odfHandler = new odf($srctemplatepath, array('PATH_TO_TMP' => $conf->societe->multidir_temp[$object->entity], 'ZIP_PROXY' => 'PclZipProxy', 'DELIMITER_LEFT' => '{', 'DELIMITER_RIGHT' => '}')); //print $odfHandler->__toString()."\n"; // Make substitutions into odt of user info $tmparray = $this->get_substitutionarray_user($user, $outputlangs); //var_dump($tmparray); exit; foreach ($tmparray as $key => $value) { try { if (preg_match('/logo$/', $key)) { //var_dump($value);exit; if (file_exists($value)) { $odfHandler->setImage($key, $value); } else { $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8'); } } else { //print $key.' '.$value;exit; $odfHandler->setVars($key, $value, true, 'UTF-8'); } } catch (OdfException $e) { // setVars failed, probably because key not found } } // Make substitutions into odt of mysoc info $tmparray = $this->get_substitutionarray_mysoc($mysoc, $outputlangs); //var_dump($tmparray); exit; foreach ($tmparray as $key => $value) { try { if (preg_match('/logo$/', $key)) { //var_dump($value);exit; if (file_exists($value)) { $odfHandler->setImage($key, $value); } else { $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8'); } } else { $odfHandler->setVars($key, $value, true, 'UTF-8'); } } catch (OdfException $e) { // setVars failed, probably because key not found } } // Make substitutions into odt of thirdparty + external modules $tmparray = $this->get_substitutionarray_thirdparty($object, $outputlangs); complete_substitutions_array($tmparray, $outputlangs, $object); //var_dump($object->id); exit; foreach ($tmparray as $key => $value) { try { if (preg_match('/logo$/', $key)) { if (file_exists($value)) { $odfHandler->setImage($key, $value); } else { $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8'); } } else { $odfHandler->setVars($key, $value, true, 'UTF-8'); } } catch (OdfException $e) { // setVars failed, probably because key not found } } // Write new file //$result=$odfHandler->exportAsAttachedFile('toto'); $odfHandler->saveToDisk($file); if (!empty($conf->global->MAIN_UMASK)) { @chmod($file, octdec($conf->global->MAIN_UMASK)); } $odfHandler = null; // Destroy object return 1; // Success } else { $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); return -1; } } $this->error = 'UnknownError'; return -1; }
/** * * @global type $logger * @param Project $project * @param type $odtTemplate * @param type $userid * @param type $session_userid */ function genProjectODT(Project $project, $odtTemplate, $session_userid, $userid = 0) { global $logger; $logger->debug("genProjectODT(): project " . $project->getName() . " template {$odtTemplate} user {$userid}"); $odf = new odf($odtTemplate); try { $odf->setVars('today', date('Y-m-d')); } catch (Exception $e) { } try { $odf->setVars('selectionName', $project->getName()); } catch (Exception $e) { } try { $session_user = UserCache::getInstance()->getUser($session_userid); $odf->setVars('sessionUser', $session_user->getRealname()); } catch (Exception $e) { } $isHideResolved = true; $issueList = $project->getIssues($userid, $isHideResolved); if ($logger->isDebugEnabled()) { $logger->debug("nb issues = " . count($issueList)); } $q_id = 0; $issueSegment = $odf->setSegment('issueSelection'); if ($logger->isDebugEnabled()) { $logger->debug('XML=' . $issueSegment->getXml()); } foreach ($issueList as $issue) { $q_id += 1; if (0 == $issue->getHandlerId()) { $userName = T_('unknown'); } else { $user = UserCache::getInstance()->getUser($issue->getHandlerId()); $userName = utf8_decode($user->getRealname()); if (empty($userName)) { $userName = "******" . $issue->getHandlerId(); } } if ($logger->isDebugEnabled()) { $logger->debug("issue " . $issue->getId() . ": handlerName = " . $userName); } if (0 == $issue->getReporterId()) { $reporterName = T_('unknown'); } else { $reporter = UserCache::getInstance()->getUser($issue->getReporterId()); $reporterName = utf8_decode($reporter->getRealname()); if (empty($reporterName)) { $reporterName = "user_" . $issue->getReporterId(); } } if ($logger->isDebugEnabled()) { $logger->debug("issue " . $issue->getId() . ": reporterName = " . $reporterName); } // add issue try { $issueSegment->setVars('q_id', $q_id); } catch (Exception $e) { $logger->error("EXCEPTION " . $e->getMessage()); $logger->error("EXCEPTION stack-trace:\n" . $e->getTraceAsString()); } try { $issueSegment->setVars('bugId', $issue->getId()); } catch (Exception $e) { $logger->error("EXCEPTION " . $e->getMessage()); $logger->error("EXCEPTION stack-trace:\n" . $e->getTraceAsString()); } try { $issueSegment->setVars('summary', utf8_decode($issue->getSummary())); } catch (Exception $e) { $logger->error("EXCEPTION " . $e->getMessage()); $logger->error("EXCEPTION stack-trace:\n" . $e->getTraceAsString()); } try { $issueSegment->setVars('dateSubmission', date('d/m/Y', $issue->getDateSubmission())); } catch (Exception $e) { $logger->error("EXCEPTION " . $e->getMessage()); $logger->error("EXCEPTION stack-trace:\n" . $e->getTraceAsString()); } try { $timestamp = $issue->getDeadLine(); $deadline = 0 == $timestamp ? '' : date('d/m/Y', $issue->getDeadLine()); $issueSegment->setVars('deadline', $deadline); } catch (Exception $e) { $logger->error("EXCEPTION " . $e->getMessage()); $logger->error("EXCEPTION stack-trace:\n" . $e->getTraceAsString()); } try { $issueSegment->setVars('currentStatus', Constants::$statusNames[$issue->getCurrentStatus()]); } catch (Exception $e) { $logger->error("EXCEPTION " . $e->getMessage()); $logger->error("EXCEPTION stack-trace:\n" . $e->getTraceAsString()); } try { $issueSegment->setVars('handlerId', $userName); } catch (Exception $e) { $logger->error("EXCEPTION " . $e->getMessage()); $logger->error("EXCEPTION stack-trace:\n" . $e->getTraceAsString()); } try { $issueSegment->setVars('reporterId', $reporterName); } catch (Exception $e) { $logger->error("EXCEPTION " . $e->getMessage()); $logger->error("EXCEPTION stack-trace:\n" . $e->getTraceAsString()); } try { $issueSegment->setVars('reporterName', $reporterName); } catch (Exception $e) { $logger->error("EXCEPTION " . $e->getMessage()); $logger->error("EXCEPTION stack-trace:\n" . $e->getTraceAsString()); } try { $issueSegment->setVars('description', utf8_decode($issue->getDescription())); } catch (Exception $e) { $logger->error("EXCEPTION " . $e->getMessage()); $logger->error("EXCEPTION stack-trace:\n" . $e->getTraceAsString()); } try { $issueSegment->setVars('category', $issue->getCategoryName()); } catch (Exception $e) { $logger->error("EXCEPTION " . $e->getMessage()); $logger->error("EXCEPTION stack-trace:\n" . $e->getTraceAsString()); } try { $issueSegment->setVars('severity', $issue->getSeverityName()); } catch (Exception $e) { $logger->error("EXCEPTION " . $e->getMessage()); $logger->error("EXCEPTION stack-trace:\n" . $e->getTraceAsString()); } try { $issueSegment->setVars('status', Constants::$statusNames[$issue->getStatus()]); } catch (Exception $e) { $logger->error("EXCEPTION " . $e->getMessage()); $logger->error("EXCEPTION stack-trace:\n" . $e->getTraceAsString()); } try { $issueSegment->setVars('extId', $issue->getTcId()); } catch (Exception $e) { $logger->error("EXCEPTION " . $e->getMessage()); $logger->error("EXCEPTION stack-trace:\n" . $e->getTraceAsString()); } // add issueNotes $issueNotes = $issue->getIssueNoteList(); $noteId = 0; foreach ($issueNotes as $id => $issueNote) { $noteId += 1; if ($logger->isDebugEnabled()) { $logger->debug("issue " . $issue->getId() . ": note {$id} = {$issueNote->note}"); } $noteReporter = UserCache::getInstance()->getUser($issueNote->reporter_id); try { $noteReporterName = utf8_decode($noteReporter->getRealname()); } catch (Exception $e) { } try { $issueSegment->bugnotes->noteId($noteId); } catch (Exception $e) { } try { $issueSegment->bugnotes->noteReporter($noteReporterName); } catch (Exception $e) { } try { $issueSegment->bugnotes->noteDateSubmission(date('d/m/Y', $issueNote->date_submitted)); } catch (Exception $e) { } try { $issueSegment->bugnotes->note(utf8_decode($issueNote->note)); } catch (Exception $e) { } try { $issueSegment->bugnotes->merge(); } catch (Exception $e) { } } $issueSegment->merge(); } $odf->mergeSegment($issueSegment); // INFO: the following line is MANDATORY and fixes the following error: // "wrong .odt file encoding" //ob_end_clean(); //$odf->exportAsAttachedFile(); $myFile = Constants::$codevOutputDir . '/reports/odtphp_test_' . time() . '.odt'; if ($logger->isDebugEnabled()) { $logger->debug("save odt file " . $myFile); } $odf->saveToDisk($myFile); echo "<br>"; echo "<br>"; echo "<span style='padding-left: 3em'><a tatget='blank' href='../include/download.php?f=" . basename($myFile) . "'>" . basename($myFile) . "</a></span>"; }
static function generateOdt($params) { global $LANG; $config = array('PATH_TO_TMP' => GLPI_DOC_DIR . '/_tmp'); if (PluginMreportingPreference::atLeastOneTemplateExists()) { $template = PluginMreportingPreference::checkPreferenceTemplateValue(Session::getLoginUserID()); $withdatas = $params[0]["withdata"]; if ($withdatas == 0) { $odf = new odf("../templates/withoutdata.odt", $config); } else { $odf = new odf("../templates/{$template}", $config); } $titre = ''; $short_classname = str_replace('PluginMreporting', '', $params[0]['class']); if (isset($LANG['plugin_mreporting'][$short_classname]['title'])) { $titre = $LANG['plugin_mreporting'][$short_classname]['title']; } $odf->setVars('titre', $titre, true, 'UTF-8'); $newpage = $odf->setSegment('newpage'); foreach ($params as $result => $page) { // Default values of parameters $title = ""; $f_name = ""; $raw_datas = array(); foreach ($page as $key => $val) { ${$key} = $val; } $datas = $raw_datas['datas']; $labels2 = array(); if (isset($raw_datas['labels2'])) { $labels2 = $raw_datas['labels2']; } $configs = PluginMreportingConfig::initConfigParams($f_name, $class); foreach ($configs as $k => $v) { ${$k} = $v; } if ($unit == '%') { $datas = PluginMreportingCommon::compileDatasForUnit($datas, $unit); } $newpage->setVars('message', $title, true, 'UTF-8'); $path = GLPI_PLUGIN_DOC_DIR . "/mreporting/" . $f_name . ".png"; if ($show_graph) { $newpage->setImage('image', $path); } else { $newpage->setVars('image', "", true, 'UTF-8'); } if ($withdatas > 0) { $simpledatas = false; //simple array if (!$labels2) { $labels2 = array(); $simpledatas = true; } if ($flip_data == true) { $labels2 = array_flip($labels2); } $types = array(); foreach ($datas as $k => $v) { if (is_array($v)) { foreach ($v as $key => $val) { if (isset($labels2[$key])) { $types[$key][$k] = $val; } } } else { $types[$k] = $v; } } if ($flip_data != true) { $tmp = $datas; $datas = $types; $types = $tmp; } //simple array if ($simpledatas) { $label = $LANG['plugin_mreporting']["export"][1]; if ($template == "word.odt") { $newpage->data0->label_0(utf8_decode($label)); $newpage->data0->merge(); } else { $newpage->csvdata->setVars('TitreCategorie', $label, true, 'UTF-8'); } if ($template == "word.odt") { foreach ($types as $label2 => $cols) { $newpage->csvdata->label1->label_1(utf8_decode($label2)); $newpage->csvdata->label1->merge(); if (!empty($unit)) { $cols = $cols . " " . $unit; } $newpage->csvdata->data1->data_1($cols); $newpage->csvdata->merge(); } } else { foreach ($types as $label2 => $cols) { if (!empty($unit)) { $cols = $cols . " " . $unit; } $newpage->csvdata->csvdata2->label_1(utf8_decode($label2)); $newpage->csvdata->csvdata2->data_1($cols); $newpage->csvdata->csvdata2->merge(); } $newpage->csvdata->merge(); } } else { if ($template == "word.odt") { foreach ($datas as $label => $val) { $newpage->data0->label_0(utf8_decode($label)); $newpage->data0->merge(); } foreach ($types as $label2 => $cols) { $newpage->csvdata->label1->label_1(utf8_decode($label2)); $newpage->csvdata->label1->merge(); foreach ($cols as $date => $nb) { if (!empty($unit)) { $nb = $nb . " " . $unit; } if (!is_array($nb)) { $newpage->csvdata->data1->data_1(utf8_decode($nb)); } $newpage->csvdata->data1->merge(); } $newpage->csvdata->merge(); } } else { foreach ($types as $label2 => $cols) { foreach ($cols as $label1 => $nb) { if (!empty($unit)) { $nb = $nb . " " . $unit; } $newpage->csvdata->setVars('TitreCategorie', $label2, true, 'UTF-8'); $newpage->csvdata->csvdata2->setVars('label_1', utf8_decode($label1), true, 'UTF-8'); if (!is_array($nb)) { $newpage->csvdata->csvdata2->setVars('data_1', utf8_decode($nb), true, 'UTF-8'); } $newpage->csvdata->csvdata2->merge(); } $newpage->csvdata->merge(); } } } } $newpage->merge(); } $odf->mergeSegment($newpage); // We export the file $odf->exportAsAttachedFile(); unset($_SESSION['glpi_plugin_mreporting_odtarray']); } }
/** * Function to build a document on disk using the generic odt module. * * @param Project $object Object source to build document * @param Translate $outputlangs Lang output object * @param string $srctemplatepath Full path of source filename for generator using a template file * @return int 1 if OK, <=0 if KO */ function write_file($object, $outputlangs, $srctemplatepath) { global $user, $langs, $conf, $mysoc, $hookmanager; if (empty($srctemplatepath)) { dol_syslog("doc_generic_odt::write_file parameter srctemplatepath empty", LOG_WARNING); return -1; } // Add odtgeneration hook if (!is_object($hookmanager)) { include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php'; $hookmanager = new HookManager($this->db); } $hookmanager->initHooks(array('odtgeneration')); global $action; if (!is_object($outputlangs)) { $outputlangs = $langs; } $sav_charset_output = $outputlangs->charset_output; $outputlangs->charset_output = 'UTF-8'; $outputlangs->load("main"); $outputlangs->load("dict"); $outputlangs->load("companies"); $outputlangs->load("projects"); if ($conf->projet->dir_output) { // If $object is id instead of object if (!is_object($object)) { $id = $object; $object = new Project($this->db); $result = $object->fetch($id); if ($result < 0) { dol_print_error($this->db, $object->error); return -1; } } $dir = $conf->projet->dir_output; $objectref = dol_sanitizeFileName($object->ref); if (!preg_match('/specimen/i', $objectref)) { $dir .= "/" . $objectref; } $file = $dir . "/" . $objectref . ".odt"; if (!file_exists($dir)) { if (dol_mkdir($dir) < 0) { $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); return -1; } } if (file_exists($dir)) { //print "srctemplatepath=".$srctemplatepath; // Src filename $newfile = basename($srctemplatepath); $newfiletmp = preg_replace('/\\.od(t|s)/i', '', $newfile); $newfiletmp = preg_replace('/template_/i', '', $newfiletmp); $newfiletmp = preg_replace('/modele_/i', '', $newfiletmp); $newfiletmp = $objectref . '_' . $newfiletmp; //$file=$dir.'/'.$newfiletmp.'.'.dol_print_date(dol_now(),'%Y%m%d%H%M%S').'.odt'; // Get extension (ods or odt) $newfileformat = substr($newfile, strrpos($newfile, '.') + 1); if (!empty($conf->global->MAIN_DOC_USE_TIMING)) { $filename = $newfiletmp . '.' . dol_print_date(dol_now(), '%Y%m%d%H%M%S') . '.' . $newfileformat; } else { $filename = $newfiletmp . '.' . $newfileformat; } $file = $dir . '/' . $filename; //print "newdir=".$dir; //print "newfile=".$newfile; //print "file=".$file; //print "conf->societe->dir_temp=".$conf->societe->dir_temp; dol_mkdir($conf->projet->dir_temp); $socobject = $object->thirdparty; // Make substitution $substitutionarray = array('__FROM_NAME__' => $this->emetteur->nom, '__FROM_EMAIL__' => $this->emetteur->email); complete_substitutions_array($substitutionarray, $langs, $object); // Open and load template require_once ODTPHP_PATH . 'odf.php'; try { $odfHandler = new odf($srctemplatepath, array('PATH_TO_TMP' => $conf->projet->dir_temp, 'ZIP_PROXY' => 'PclZipProxy', 'DELIMITER_LEFT' => '{', 'DELIMITER_RIGHT' => '}')); } catch (Exception $e) { $this->error = $e->getMessage(); return -1; } // After construction $odfHandler->contentXml contains content and // [!-- BEGIN row.lines --]*[!-- END row.lines --] has been replaced by // [!-- BEGIN lines --]*[!-- END lines --] //print html_entity_decode($odfHandler->__toString()); //print exit; // Make substitutions into odt of user info $tmparray = $this->get_substitutionarray_user($user, $outputlangs); foreach ($tmparray as $key => $value) { try { if (preg_match('/logo$/', $key)) { //var_dump($value);exit; if (file_exists($value)) { $odfHandler->setImage($key, $value); } else { $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8'); } } else { $odfHandler->setVars($key, $value, true, 'UTF-8'); } } catch (OdfException $e) { } } // Make substitutions into odt of mysoc $tmparray = $this->get_substitutionarray_mysoc($mysoc, $outputlangs); //var_dump($tmparray); exit; foreach ($tmparray as $key => $value) { try { if (preg_match('/logo$/', $key)) { //var_dump($value);exit; if (file_exists($value)) { $odfHandler->setImage($key, $value); } else { $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8'); } } else { $odfHandler->setVars($key, $value, true, 'UTF-8'); } } catch (OdfException $e) { } } // Make substitutions into odt of thirdparty $tmparray = $this->get_substitutionarray_thirdparty($socobject, $outputlangs); foreach ($tmparray as $key => $value) { try { if (preg_match('/logo$/', $key)) { if (file_exists($value)) { $odfHandler->setImage($key, $value); } else { $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8'); } } else { $odfHandler->setVars($key, $value, true, 'UTF-8'); } } catch (OdfException $e) { } } // Replace tags of object + external modules $tmparray = $this->get_substitutionarray_object($object, $outputlangs); complete_substitutions_array($tmparray, $outputlangs, $object); // Call the ODTSubstitution hook $parameters = array('file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray); $reshook = $hookmanager->executeHooks('ODTSubstitution', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks foreach ($tmparray as $key => $value) { try { if (preg_match('/logo$/', $key)) { if (file_exists($value)) { $odfHandler->setImage($key, $value); } else { $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8'); } } else { $odfHandler->setVars($key, $value, true, 'UTF-8'); } } catch (OdfException $e) { } } // Replace tags of lines for tasks try { $listlines = $odfHandler->setSegment('tasks'); $taskstatic = new Task($this->db); // Security check $socid = 0; if (!empty($object->fk_soc)) { $socid = $object->fk_soc; } $tasksarray = $taskstatic->getTasksArray(0, 0, $object->id, $socid, 0); foreach ($tasksarray as $task) { $tmparray = $this->get_substitutionarray_tasks($task, $outputlangs); //complete_substitutions_array($tmparray, $outputlangs, $object, $task, "completesubstitutionarray_lines"); foreach ($tmparray as $key => $val) { try { $listlines->setVars($key, $val, true, 'UTF-8'); } catch (OdfException $e) { } catch (SegmentException $e) { } } $taskobj = new Task($this->db); $taskobj->fetch($task->id); // Replace tags of lines for contacts task $sourcearray = array('internal', 'external'); $contact_arrray = array(); foreach ($sourcearray as $source) { $contact_temp = $taskobj->liste_contact(-1, $source); if (is_array($contact_temp) && count($contact_temp) > 0) { $contact_arrray = array_merge($contact_arrray, $contact_temp); } } if (is_array($contact_arrray) && count($contact_arrray) > 0) { $listlinestaskres = $listlines->__get('tasksressources'); foreach ($contact_arrray as $contact) { if ($contact['source'] == 'internal') { $objectdetail = new User($this->db); $objectdetail->fetch($contact['id']); $contact['socname'] = $mysoc->name; } elseif ($contact['source'] == 'external') { $objectdetail = new Contact($this->db); $objectdetail->fetch($contact['id']); $soc = new Societe($this->db); $soc->fetch($contact['socid']); $contact['socname'] = $soc->name; } $contact['fullname'] = $objectdetail->getFullName($outputlangs, 1); $tmparray = $this->get_substitutionarray_tasksressource($contact, $outputlangs); foreach ($tmparray as $key => $val) { try { $listlinestaskres->setVars($key, $val, true, 'UTF-8'); } catch (OdfException $e) { } catch (SegmentException $e) { } } $listlinestaskres->merge(); } } //Time ressources $sql = "SELECT t.rowid, t.task_date, t.task_duration, t.fk_user, t.note"; $sql .= ", u.lastname, u.firstname"; $sql .= " FROM " . MAIN_DB_PREFIX . "projet_task_time as t"; $sql .= " , " . MAIN_DB_PREFIX . "user as u"; $sql .= " WHERE t.fk_task =" . $task->id; $sql .= " AND t.fk_user = u.rowid"; $sql .= " ORDER BY t.task_date DESC"; $resql = $this->db->query($sql); if ($resql) { $num = $this->db->num_rows($resql); $i = 0; $tasks = array(); $listlinestasktime = $listlines->__get('taskstimes'); while ($i < $num) { $row = $this->db->fetch_array($resql); if (!empty($row['fk_user'])) { $objectdetail = new User($this->db); $objectdetail->fetch($row['fk_user']); $row['fullcivname'] = $objectdetail->getFullName($outputlangs, 1); } else { $row['fullcivname'] = ''; } $tmparray = $this->get_substitutionarray_taskstime($row, $outputlangs); foreach ($tmparray as $key => $val) { try { $listlinestasktime->setVars($key, $val, true, 'UTF-8'); } catch (OdfException $e) { } catch (SegmentException $e) { } } $listlinestasktime->merge(); $i++; } $this->db->free($resql); } // Replace tags of project files $listtasksfiles = $listlines->__get('tasksfiles'); $upload_dir = $conf->projet->dir_output . '/' . dol_sanitizeFileName($object->ref) . '/' . dol_sanitizeFileName($task->ref); $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\\.meta|_preview\\.png)$', 'name', SORT_ASC, 1); foreach ($filearray as $filedetail) { $tmparray = $this->get_substitutionarray_task_file($filedetail, $outputlangs); //dol_syslog(get_class($this).'::main $tmparray'.var_export($tmparray,true)); foreach ($tmparray as $key => $val) { try { $listtasksfiles->setVars($key, $val, true, 'UTF-8'); } catch (OdfException $e) { } catch (SegmentException $e) { } } $listtasksfiles->merge(); } $listlines->merge(); } $odfHandler->mergeSegment($listlines); } catch (OdfException $e) { $this->error = $e->getMessage(); dol_syslog($this->error, LOG_WARNING); return -1; } // Replace tags of project files try { $listlines = $odfHandler->setSegment('projectfiles'); $upload_dir = $conf->projet->dir_output . '/' . dol_sanitizeFileName($object->ref); $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\\.meta|_preview\\.png)$', 'name', SORT_ASC, 1); foreach ($filearray as $filedetail) { //dol_syslog(get_class($this).'::main $filedetail'.var_export($filedetail,true)); $tmparray = $this->get_substitutionarray_project_file($filedetail, $outputlangs); foreach ($tmparray as $key => $val) { try { $listlines->setVars($key, $val, true, 'UTF-8'); } catch (OdfException $e) { } catch (SegmentException $e) { } } $listlines->merge(); } $odfHandler->mergeSegment($listlines); } catch (OdfException $e) { $this->error = $e->getMessage(); dol_syslog($this->error, LOG_WARNING); return -1; } // Replace tags of lines for contacts $sourcearray = array('internal', 'external'); $contact_arrray = array(); foreach ($sourcearray as $source) { $contact_temp = $object->liste_contact(-1, $source); if (is_array($contact_temp) && count($contact_temp) > 0) { $contact_arrray = array_merge($contact_arrray, $contact_temp); } } if (is_array($contact_arrray) && count($contact_arrray) > 0) { try { $listlines = $odfHandler->setSegment('projectcontacts'); foreach ($contact_arrray as $contact) { if ($contact['source'] == 'internal') { $objectdetail = new User($this->db); $objectdetail->fetch($contact['id']); $contact['socname'] = $mysoc->name; } elseif ($contact['source'] == 'external') { $objectdetail = new Contact($this->db); $objectdetail->fetch($contact['id']); $soc = new Societe($this->db); $soc->fetch($contact['socid']); $contact['socname'] = $soc->name; } $contact['fullname'] = $objectdetail->getFullName($outputlangs, 1); $tmparray = $this->get_substitutionarray_project_contacts($contact, $outputlangs); foreach ($tmparray as $key => $val) { try { $listlines->setVars($key, $val, true, 'UTF-8'); } catch (OdfException $e) { } catch (SegmentException $e) { } } $listlines->merge(); } $odfHandler->mergeSegment($listlines); } catch (OdfException $e) { $this->error = $e->getMessage(); dol_syslog($this->error, LOG_WARNING); return -1; } } //List of referent $listofreferent = array('propal' => array('title' => "ListProposalsAssociatedProject", 'class' => 'Propal', 'table' => 'propal', 'test' => $conf->propal->enabled && $user->rights->propale->lire), 'order' => array('title' => "ListOrdersAssociatedProject", 'class' => 'Commande', 'table' => 'commande', 'test' => $conf->commande->enabled && $user->rights->commande->lire), 'invoice' => array('title' => "ListInvoicesAssociatedProject", 'class' => 'Facture', 'table' => 'facture', 'test' => $conf->facture->enabled && $user->rights->facture->lire), 'invoice_predefined' => array('title' => "ListPredefinedInvoicesAssociatedProject", 'class' => 'FactureRec', 'table' => 'facture_rec', 'test' => $conf->facture->enabled && $user->rights->facture->lire), 'order_supplier' => array('title' => "ListSupplierOrdersAssociatedProject", 'table' => 'commande_fournisseur', 'class' => 'CommandeFournisseur', 'test' => $conf->fournisseur->enabled && $user->rights->fournisseur->commande->lire), 'invoice_supplier' => array('title' => "ListSupplierInvoicesAssociatedProject", 'table' => 'facture_fourn', 'class' => 'FactureFournisseur', 'test' => $conf->fournisseur->enabled && $user->rights->fournisseur->facture->lire), 'contract' => array('title' => "ListContractAssociatedProject", 'class' => 'Contrat', 'table' => 'contrat', 'test' => $conf->contrat->enabled && $user->rights->contrat->lire), 'intervention' => array('title' => "ListFichinterAssociatedProject", 'class' => 'Fichinter', 'table' => 'fichinter', 'disableamount' => 1, 'test' => $conf->ficheinter->enabled && $user->rights->ficheinter->lire), 'trip' => array('title' => "ListTripAssociatedProject", 'class' => 'Deplacement', 'table' => 'deplacement', 'disableamount' => 1, 'test' => $conf->deplacement->enabled && $user->rights->deplacement->lire), 'agenda' => array('title' => "ListActionsAssociatedProject", 'class' => 'ActionComm', 'table' => 'actioncomm', 'disableamount' => 1, 'test' => $conf->agenda->enabled && $user->rights->agenda->allactions->lire)); //Insert reference try { $listlines = $odfHandler->setSegment('projectrefs'); foreach ($listofreferent as $keyref => $valueref) { $title = $valueref['title']; $tablename = $valueref['table']; $classname = $valueref['class']; $qualified = $valueref['test']; if ($qualified) { $elementarray = $object->get_element_list($keyref, $tablename); if (count($elementarray) > 0 && is_array($elementarray)) { $var = true; $total_ht = 0; $total_ttc = 0; $num = count($elementarray); for ($i = 0; $i < $num; $i++) { $ref_array = array(); $ref_array['type'] = $langs->trans($classname); $element = new $classname($this->db); $element->fetch($elementarray[$i]); $element->fetch_thirdparty(); //Ref object $ref_array['ref'] = $element->ref; //Date object $dateref = $element->date; if (empty($dateref)) { $dateref = $element->datep; } if (empty($dateref)) { $dateref = $element->date_contrat; } $ref_array['date'] = $dateref; //Soc object if (is_object($element->thirdparty)) { $ref_array['socname'] = $element->thirdparty->name; } else { $ref_array['socname'] = ''; } //Amount object if (empty($valueref['disableamount'])) { if (!empty($element->total_ht)) { $ref_array['amountht'] = $element->total_ht; $ref_array['amountttc'] = $element->total_ttc; } else { $ref_array['amountht'] = 0; $ref_array['amountttc'] = 0; } } else { $ref_array['amountht'] = ''; $ref_array['amountttc'] = ''; } $ref_array['status'] = $element->getLibStatut(0); $tmparray = $this->get_substitutionarray_project_reference($ref_array, $outputlangs); foreach ($tmparray as $key => $val) { try { $listlines->setVars($key, $val, true, 'UTF-8'); } catch (OdfException $e) { } catch (SegmentException $e) { } } $listlines->merge(); } } } $odfHandler->mergeSegment($listlines); } } catch (OdfException $e) { $this->error = $e->getMessage(); dol_syslog($this->error, LOG_WARNING); return -1; } // Replace labels translated $tmparray = $outputlangs->get_translations_for_substitutions(); foreach ($tmparray as $key => $value) { try { $odfHandler->setVars($key, $value, true, 'UTF-8'); } catch (OdfException $e) { } } // Call the beforeODTSave hook $parameters = array('odfHandler' => &$odfHandler, 'file' => $file, 'object' => $object, 'outputlangs' => $outputlangs); $reshook = $hookmanager->executeHooks('beforeODTSave', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks // Write new file if (!empty($conf->global->MAIN_ODT_AS_PDF)) { try { $odfHandler->exportAsAttachedPDF($file); } catch (Exception $e) { $this->error = $e->getMessage(); return -1; } } else { try { $odfHandler->saveToDisk($file); } catch (Exception $e) { $this->error = $e->getMessage(); return -1; } } if (!empty($conf->global->MAIN_UMASK)) { @chmod($file, octdec($conf->global->MAIN_UMASK)); } $odfHandler = null; // Destroy object return 1; // Success } else { $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); return -1; } } return -1; }
<?php /** * Tutoriel file * Description : Imbricating several segments * You need PHP 5.2 at least * You need Zip Extension or PclZip library * * @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 */ // Make sure you have Zip extension or PclZip library loaded // First : include the librairy require_once '../library/odf.php'; $odf = new odf("tutoriel4.odt"); $odf->setVars('titre', 'Articles disponibles :'); $categorie = $odf->setSegment('categories'); for ($j = 1; $j <= 2; $j++) { $categorie->setVars('TitreCategorie', 'Catégorie ' . $j); for ($i = 1; $i <= 3; $i++) { $categorie->articles->titreArticle('Article ' . $i); $categorie->articles->date(date('d/m/Y')); $categorie->articles->merge(); } for ($i = 1; $i <= 4; $i++) { $categorie->commentaires->texteCommentaire('Commentaire ' . $i); $categorie->commentaires->merge(); } $categorie->merge(); }
/** * Function to build a document on disk using the generic odt module. * * @param Societe $object Object source to build document * @param Translate $outputlangs Lang output object * @param string $srctemplatepath Full path of source filename for generator using a template file * @return int 1 if OK, <=0 if KO */ function write_file($object, $outputlangs, $srctemplatepath) { global $user, $langs, $conf, $mysoc; if (empty($srctemplatepath)) { dol_syslog("doc_generic_odt::write_file parameter srctemplatepath empty", LOG_WARNING); return -1; } if (!is_object($outputlangs)) { $outputlangs = $langs; } $sav_charset_output = $outputlangs->charset_output; $outputlangs->charset_output = 'UTF-8'; $outputlangs->load("main"); $outputlangs->load("dict"); $outputlangs->load("companies"); $outputlangs->load("projects"); if ($conf->contrat->dir_output) { $soc = new Societe($this->db); $soc->fetch($object->socid); $dir = $conf->contrat->dir_output; $objectref = dol_sanitizeFileName($object->ref); if (!preg_match('/specimen/i', $objectref)) { $dir .= "/" . $objectref; } if (!file_exists($dir)) { if (create_exdir($dir) < 0) { $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); return -1; } } if (file_exists($dir)) { //print "srctemplatepath=".$srctemplatepath; // Src filename $newfile = basename($srctemplatepath); $newfiletmp = preg_replace('/\\.odt/i', '', $newfile); $newfiletmp = preg_replace('/template_/i', '', $newfiletmp); $newfiletmp = preg_replace('/modele_/i', '', $newfiletmp); $file = $dir . '/' . $newfiletmp . '.' . dol_print_date(dol_now(), '%Y%m%d%H%M%S') . '.odt'; //print "newdir=".$dir; //print "newfile=".$newfile; //print "file=".$file; //print "conf->societe->dir_temp=".$conf->societe->dir_temp; create_exdir($conf->contrat->dir_temp); // If BILLING contact defined on invoice, we use it $usecontact = false; $arrayidcontact = $object->getIdContact('external', 'SALESREPSIGN'); if (count($arrayidcontact) > 0) { $usecontact = true; $result = $soc->fetch_contact($arrayidcontact[0]); } // Recipient name if (!empty($usecontact)) { // On peut utiliser le nom de la societe du contact if ($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT) { $socobject = $object->contact; } else { $socobject = $soc->client; } } else { $socobject = $soc->client; } // Make substitution $substitutionarray = array('__FROM_NAME__' => $this->emetteur->nom, '__FROM_EMAIL__' => $this->emetteur->email, '__TOTAL_TTC__' => $object->total_ttc, '__TOTAL_HT__' => $object->total_ht, '__TOTAL_VAT__' => $object->total_vat, 'date' => dol_print_date($object->date_contrat, "%d %b %Y")); complete_substitutions_array($substitutionarray, $langs, $object); // Open and load template require_once ODTPHP_PATH . 'odf.php'; $odfHandler = new odf($srctemplatepath, array('PATH_TO_TMP' => $conf->contrat->dir_temp, 'ZIP_PROXY' => 'PclZipProxy', 'DELIMITER_LEFT' => '{', 'DELIMITER_RIGHT' => '}')); //print $odfHandler->__toString()."\n"; // foreach ($substitutionarray as $key => $value) { try { if (preg_match('/logo$/', $key)) { //var_dump($value);exit; if (file_exists($value)) { $odfHandler->setImage($key, $value); } else { $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8'); } } else { //print $key.' '.$value;exit; $odfHandler->setVars($key, $value, true, 'UTF-8'); } } catch (OdfException $e) { } } // Make substitutions into odt of user info $tmparray = $this->get_substitutionarray_user($user, $outputlangs); //var_dump($tmparray); exit; foreach ($tmparray as $key => $value) { try { if (preg_match('/logo$/', $key)) { //var_dump($value);exit; if (file_exists($value)) { $odfHandler->setImage($key, $value); } else { $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8'); } } else { //print $key.' '.$value;exit; $odfHandler->setVars($key, $value, true, 'UTF-8'); } } catch (OdfException $e) { } } // Make substitutions into odt of mysoc info $tmparray = $this->get_substitutionarray_mysoc($mysoc, $outputlangs); //var_dump($tmparray); exit; foreach ($tmparray as $key => $value) { try { if (preg_match('/logo$/', $key)) { //var_dump($value);exit; if (file_exists($value)) { $odfHandler->setImage($key, $value); } else { $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8'); } } else { $odfHandler->setVars($key, $value, true, 'UTF-8'); } } catch (OdfException $e) { } } // Make substitutions into odt of thirdparty + external modules $tmparray = $this->get_substitutionarray_thirdparty($soc, $outputlangs); //complete_substitutions_array($tmparray, $langs, $object); //var_dump($object->id); exit; foreach ($tmparray as $key => $value) { try { if (preg_match('/logo$/', $key)) { if (file_exists($value)) { $odfHandler->setImage($key, $value); } else { $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8'); } } else { $odfHandler->setVars($key, $value, true, 'UTF-8'); } } catch (OdfException $e) { } } // Get extra fields for contractid include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php'; $hookmanager = new HookManager($this->db); $hookmanager->callHooks(array('contrat_extrafields')); $parameters = array('id' => $object->id); $values = $hookmanager->executeHooks('getFields', $parameters, $object, GETPOST('action')); // Note that $action and $object may have been modified by hook if (is_array($values)) { foreach ($values as $key => $value) { try { if (preg_match("/^options_/", $key)) { $var = substr($key, 8, strlen($key)); // retire options_ $odfHandler->setVars($var, $values[$key], true, 'UTF-8'); } } catch (OdfException $e) { } } } // Get extra fields for socid include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php'; $hookmanager = new HookManager($this->db); $hookmanager->callHooks(array('thirdparty_extrafields')); $parameters = array('id' => $soc->id); $values = $hookmanager->executeHooks('getFields', $parameters, $soc, GETPOST('action')); // Note that $action and $object may have been modified by hook if (is_array($values)) { foreach ($values as $key => $value) { try { if (preg_match("/^options_/", $key)) { $var = substr($key, 8, strlen($key)); // retire options_ $odfHandler->setVars($var, $values[$key], true, 'UTF-8'); } } catch (OdfException $e) { } } } // Write new file //$result=$odfHandler->exportAsAttachedFile('toto'); $odfHandler->saveToDisk($file); if (!empty($conf->global->MAIN_UMASK)) { @chmod($file, octdec($conf->global->MAIN_UMASK)); } $odfHandler = null; // Destroy object return 1; // Success } else { $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); return -1; } } return -1; }
/** * Function to build a document on disk using the generic odt module. * * @param Societe $object Object source to build document * @param Translate $outputlangs Lang output object * @param string $srctemplatepath Full path of source filename for generator using a template file * @param int $hidedetails Do not show line details * @param int $hidedesc Do not show desc * @param int $hideref Do not show ref * @return int 1 if OK, <=0 if KO */ function write_file($object, $outputlangs, $srctemplatepath, $hidedetails = 0, $hidedesc = 0, $hideref = 0) { global $user, $langs, $conf, $mysoc, $hookmanager; if (empty($srctemplatepath)) { dol_syslog("doc_generic_odt::write_file parameter srctemplatepath empty", LOG_WARNING); return -1; } // Add odtgeneration hook if (!is_object($hookmanager)) { include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php'; $hookmanager = new HookManager($this->db); } $hookmanager->initHooks(array('odtgeneration')); global $action; if (!is_object($outputlangs)) { $outputlangs = $langs; } $sav_charset_output = $outputlangs->charset_output; $outputlangs->charset_output = 'UTF-8'; $outputlangs->load("main"); $outputlangs->load("dict"); $outputlangs->load("companies"); $outputlangs->load("projects"); if ($conf->societe->multidir_output[$object->entity]) { $dir = $conf->societe->multidir_output[$object->entity]; $objectref = dol_sanitizeFileName($object->id); if (!preg_match('/specimen/i', $objectref)) { $dir .= "/" . $objectref; } if (!file_exists($dir)) { if (dol_mkdir($dir) < 0) { $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); return -1; } } if (file_exists($dir)) { //print "srctemplatepath=".$srctemplatepath; // Src filename $newfile = basename($srctemplatepath); $newfiletmp = preg_replace('/\\.od(s|t)/i', '', $newfile); $newfiletmp = preg_replace('/template_/i', '', $newfiletmp); $newfiletmp = preg_replace('/modele_/i', '', $newfiletmp); // Get extension (ods or odt) $newfileformat = substr($newfile, strrpos($newfile, '.') + 1); if (!empty($conf->global->MAIN_DOC_USE_TIMING)) { $filename = $newfiletmp . '.' . dol_print_date(dol_now(), '%Y%m%d%H%M%S') . '.' . $newfileformat; } else { $filename = $newfiletmp . '.' . $newfileformat; } $file = $dir . '/' . $filename; $object->builddoc_filename = $filename; // For triggers //print "newfileformat=".$newfileformat; //print "newdir=".$dir; //print "newfile=".$newfile; //print "file=".$file; //print "conf->societe->dir_temp=".$conf->societe->dir_temp; //exit; dol_mkdir($conf->societe->multidir_temp[$object->entity]); // Open and load template require_once ODTPHP_PATH . 'odf.php'; try { $odfHandler = new odf($srctemplatepath, array('PATH_TO_TMP' => $conf->societe->multidir_temp[$object->entity], 'ZIP_PROXY' => 'PclZipProxy', 'DELIMITER_LEFT' => '{', 'DELIMITER_RIGHT' => '}')); } catch (Exception $e) { $this->error = $e->getMessage(); return -1; } //print $odfHandler->__toString()."\n"; // Make substitutions into odt of user info $tmparray = $this->get_substitutionarray_user($user, $outputlangs); //var_dump($tmparray); exit; foreach ($tmparray as $key => $value) { try { if (preg_match('/logo$/', $key)) { //var_dump($value);exit; if (file_exists($value)) { $odfHandler->setImage($key, $value); } else { $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8'); } } else { //print $key.' '.$value;exit; $odfHandler->setVars($key, $value, true, 'UTF-8'); } } catch (OdfException $e) { // setVars failed, probably because key not found } } // Make substitutions into odt of mysoc info $tmparray = $this->get_substitutionarray_mysoc($mysoc, $outputlangs); //var_dump($tmparray); exit; foreach ($tmparray as $key => $value) { try { if (preg_match('/logo$/', $key)) { //var_dump($value);exit; if (file_exists($value)) { $odfHandler->setImage($key, $value); } else { $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8'); } } else { $odfHandler->setVars($key, $value, true, 'UTF-8'); } } catch (OdfException $e) { // setVars failed, probably because key not found } } // Replace tags of lines for contacts $contact_arrray = array(); $sql = "SELECT p.rowid"; $sql .= " FROM " . MAIN_DB_PREFIX . "socpeople as p"; $sql .= " WHERE p.fk_soc = " . $object->id; $result = $this->db->query($sql); $num = $this->db->num_rows($result); $var = true; if ($num) { $i = 0; $contactstatic = new Contact($this->db); while ($i < $num) { $obj = $this->db->fetch_object($result); $contact_arrray[$i] = $obj->rowid; $i++; } } if (is_array($contact_arrray) && count($contact_arrray) > 0) { try { $listlines = $odfHandler->setSegment('companycontacts'); foreach ($contact_arrray as $array_key => $contact_id) { $res_contact = $contactstatic->fetch($contact_id); $tmparray = $this->get_substitutionarray_contact($contactstatic, $outputlangs, 'contact'); foreach ($tmparray as $key => $val) { try { $listlines->setVars($key, $val, true, 'UTF-8'); } catch (OdfException $e) { } catch (SegmentException $e) { } } $listlines->merge(); } $odfHandler->mergeSegment($listlines); } catch (OdfException $e) { $this->error = $e->getMessage(); dol_syslog($this->error, LOG_WARNING); //return -1; } } // Make substitutions into odt of thirdparty + external modules $tmparray = $this->get_substitutionarray_thirdparty($object, $outputlangs); complete_substitutions_array($tmparray, $outputlangs, $object); // Call the ODTSubstitution hook $parameters = array('file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray); $reshook = $hookmanager->executeHooks('ODTSubstitution', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks // Replace variables into document foreach ($tmparray as $key => $value) { try { if (preg_match('/logo$/', $key)) { if (file_exists($value)) { $odfHandler->setImage($key, $value); } else { $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8'); } } else { $odfHandler->setVars($key, $value, true, 'UTF-8'); } } catch (OdfException $e) { // setVars failed, probably because key not found } } // Replace labels translated $tmparray = $outputlangs->get_translations_for_substitutions(); foreach ($tmparray as $key => $value) { try { $odfHandler->setVars($key, $value, true, 'UTF-8'); } catch (OdfException $e) { } } // Call the beforeODTSave hook $parameters = array('odfHandler' => &$odfHandler, 'file' => $file, 'object' => $object, 'outputlangs' => $outputlangs); $reshook = $hookmanager->executeHooks('beforeODTSave', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks // Write new file if (!empty($conf->global->MAIN_ODT_AS_PDF)) { try { $odfHandler->exportAsAttachedPDF($file); } catch (Exception $e) { $this->error = $e->getMessage(); return -1; } } else { try { $odfHandler->creator = $user->getFullName($outputlangs); $odfHandler->title = $object->builddoc_filename; $odfHandler->subject = $object->builddoc_filename; if (!empty($conf->global->ODT_ADD_DOLIBARR_ID)) { $odfHandler->userdefined['dol_id'] = $object->id; $odfHandler->userdefined['dol_element'] = $object->element; } $odfHandler->saveToDisk($file); } catch (Exception $e) { $this->error = $e->getMessage(); return -1; } } $reshook = $hookmanager->executeHooks('afterODTCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks if (!empty($conf->global->MAIN_UMASK)) { @chmod($file, octdec($conf->global->MAIN_UMASK)); } $odfHandler = null; // Destroy object return 1; // Success } else { $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); return -1; } } $this->error = 'UnknownError'; return -1; }
/** * Function to build a document on disk using the generic odt module. * * @param Propale $object Object source to build document * @param Translate $outputlangs Lang output object * @param string $srctemplatepath Full path of source filename for generator using a template file * @param int $hidedetails Do not show line details * @param int $hidedesc Do not show desc * @param int $hideref Do not show ref * @return int 1 if OK, <=0 if KO */ function write_file($object, $outputlangs, $srctemplatepath, $hidedetails = 0, $hidedesc = 0, $hideref = 0) { global $user, $langs, $conf, $mysoc, $hookmanager; if (empty($srctemplatepath)) { dol_syslog("doc_generic_odt::write_file parameter srctemplatepath empty", LOG_WARNING); return -1; } // Add odtgeneration hook if (!is_object($hookmanager)) { include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php'; $hookmanager = new HookManager($this->db); } $hookmanager->initHooks(array('odtgeneration')); global $action; if (!is_object($outputlangs)) { $outputlangs = $langs; } $sav_charset_output = $outputlangs->charset_output; $outputlangs->charset_output = 'UTF-8'; $outputlangs->load("main"); $outputlangs->load("dict"); $outputlangs->load("companies"); $outputlangs->load("bills"); if ($conf->supplier_proposal->dir_output) { // If $object is id instead of object if (!is_object($object)) { $id = $object; $object = new SupplierProposal($this->db); $result = $object->fetch($id); if ($result < 0) { dol_print_error($this->db, $object->error); return -1; } } $dir = $conf->supplier_proposal->dir_output; $objectref = dol_sanitizeFileName($object->ref); if (!preg_match('/specimen/i', $objectref)) { $dir .= "/" . $objectref; } $file = $dir . "/" . $objectref . ".odt"; if (!file_exists($dir)) { if (dol_mkdir($dir) < 0) { $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); return -1; } } if (file_exists($dir)) { //print "srctemplatepath=".$srctemplatepath; // Src filename $newfile = basename($srctemplatepath); $newfiletmp = preg_replace('/\\.od(t|s)/i', '', $newfile); $newfiletmp = preg_replace('/template_/i', '', $newfiletmp); $newfiletmp = preg_replace('/modele_/i', '', $newfiletmp); $newfiletmp = $objectref . '_' . $newfiletmp; // Get extension (ods or odt) $newfileformat = substr($newfile, strrpos($newfile, '.') + 1); if (!empty($conf->global->MAIN_DOC_USE_TIMING)) { $filename = $newfiletmp . '.' . dol_print_date(dol_now(), '%Y%m%d%H%M%S') . '.' . $newfileformat; } else { $filename = $newfiletmp . '.' . $newfileformat; } $file = $dir . '/' . $filename; //print "newdir=".$dir; //print "newfile=".$newfile; //print "file=".$file; //print "conf->propal->dir_temp=".$conf->propal->dir_temp; dol_mkdir($conf->supplier_proposal->dir_temp); // If BILLING contact defined on invoice, we use it $usecontact = false; $arrayidcontact = $object->getIdContact('external', 'BILLING'); if (count($arrayidcontact) > 0) { $usecontact = true; $result = $object->fetch_contact($arrayidcontact[0]); } // Recipient name if (!empty($usecontact)) { // On peut utiliser le nom de la societe du contact if (!empty($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT)) { $socobject = $object->contact; } else { $socobject = $object->client; } } else { $socobject = $object->client; } // Make substitution $substitutionarray = array('__FROM_NAME__' => $this->emetteur->name, '__FROM_EMAIL__' => $this->emetteur->email, '__TOTAL_TTC__' => $object->total_ttc, '__TOTAL_HT__' => $object->total_ht, '__TOTAL_VAT__' => $object->total_vat); complete_substitutions_array($substitutionarray, $langs, $object); // Call the ODTSubstitution hook $parameters = array('file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$substitutionarray); $reshook = $hookmanager->executeHooks('ODTSubstitution', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks // Line of free text $newfreetext = ''; $paramfreetext = 'SUPPLIER_PROPOSAL_FREE_TEXT'; if (!empty($conf->global->{$paramfreetext})) { $newfreetext = make_substitutions($conf->global->{$paramfreetext}, $substitutionarray); } // Open and load template require_once ODTPHP_PATH . 'odf.php'; try { $odfHandler = new odf($srctemplatepath, array('PATH_TO_TMP' => $conf->supplier_proposal->dir_temp, 'ZIP_PROXY' => 'PclZipProxy', 'DELIMITER_LEFT' => '{', 'DELIMITER_RIGHT' => '}')); } catch (Exception $e) { $this->error = $e->getMessage(); return -1; } // After construction $odfHandler->contentXml contains content and // [!-- BEGIN row.lines --]*[!-- END row.lines --] has been replaced by // [!-- BEGIN lines --]*[!-- END lines --] //print html_entity_decode($odfHandler->__toString()); //print exit; // Make substitutions into odt of freetext try { $odfHandler->setVars('free_text', $newfreetext, true, 'UTF-8'); } catch (OdfException $e) { } // Make substitutions into odt $array_user = $this->get_substitutionarray_user($user, $outputlangs); $array_soc = $this->get_substitutionarray_mysoc($mysoc, $outputlangs); $array_thirdparty = $this->get_substitutionarray_thirdparty($socobject, $outputlangs); $array_objet = $this->get_substitutionarray_object($object, $outputlangs); $array_other = $this->get_substitutionarray_other($outputlangs); $tmparray = array_merge($array_user, $array_soc, $array_thirdparty, $array_objet, $array_other); complete_substitutions_array($tmparray, $outputlangs, $object); // Call the ODTSubstitution hook $parameters = array('odfHandler' => &$odfHandler, 'file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray); $reshook = $hookmanager->executeHooks('ODTSubstitution', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks foreach ($tmparray as $key => $value) { try { if (preg_match('/logo$/', $key)) { if (file_exists($value)) { $odfHandler->setImage($key, $value); } else { $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8'); } } else { $odfHandler->setVars($key, $value, true, 'UTF-8'); } } catch (OdfException $e) { } } // Replace tags of lines try { $listlines = $odfHandler->setSegment('lines'); foreach ($object->lines as $line) { $tmparray = $this->get_substitutionarray_lines($line, $outputlangs); complete_substitutions_array($tmparray, $outputlangs, $object, $line, "completesubstitutionarray_lines"); // Call the ODTSubstitutionLine hook $parameters = array('odfHandler' => &$odfHandler, 'file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray, 'line' => $line); $reshook = $hookmanager->executeHooks('ODTSubstitutionLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks foreach ($tmparray as $key => $val) { try { $listlines->setVars($key, $val, true, 'UTF-8'); } catch (OdfException $e) { } catch (SegmentException $e) { } } $listlines->merge(); } $odfHandler->mergeSegment($listlines); } catch (OdfException $e) { $this->error = $e->getMessage(); dol_syslog($this->error, LOG_WARNING); return -1; } // Replace labels translated $tmparray = $outputlangs->get_translations_for_substitutions(); foreach ($tmparray as $key => $value) { try { $odfHandler->setVars($key, $value, true, 'UTF-8'); } catch (OdfException $e) { } } // Call the beforeODTSave hook $parameters = array('odfHandler' => &$odfHandler, 'file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray); $reshook = $hookmanager->executeHooks('beforeODTSave', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks // Write new file if (!empty($conf->global->MAIN_ODT_AS_PDF)) { try { $odfHandler->exportAsAttachedPDF($file); } catch (Exception $e) { $this->error = $e->getMessage(); return -1; } } else { try { $odfHandler->saveToDisk($file); } catch (Exception $e) { $this->error = $e->getMessage(); return -1; } } $parameters = array('odfHandler' => &$odfHandler, 'file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray); $reshook = $hookmanager->executeHooks('afterODTCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks if (!empty($conf->global->MAIN_UMASK)) { @chmod($file, octdec($conf->global->MAIN_UMASK)); } $odfHandler = null; // Destroy object return 1; // Success } else { $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); return -1; } } return -1; }
require_once $syslog_mod_path . 'include/common/common-Func.php'; require_once $syslog_mod_path . 'lib/odtPHP/odf.php'; require_once $centreon_path . 'www/include/common/common-Func.php'; /* * Set language */ $locale = $oreon->user->get_lang(); putenv("LANG={$locale}"); setlocale(LC_ALL, $locale); bindtextdomain("messages", $syslog_mod_path . "locale/"); bind_textdomain_codeset("messages", "UTF-8"); textdomain("messages"); /* * New ODT object */ $odf = new odf($syslog_mod_path . "include/export/odtPHP/template/syslog_events.odt"); $odf->setVars('title', _("Syslog events"), true, 'UTF-8'); $odf->setVars('from', _("From"), true, 'UTF-8'); $odf->setVars('to', _("To"), true, 'UTF-8'); /* * Build PEAR DB object */ if (isset($_GET['collector']) && $_GET['collector'] != "") { $pearSyslogDB = new SyslogDB("syslog", $_GET['collector']); } else { exit(1); } /* * Database retrieve information for Centreon-Syslog */ $cfg_syslog = getSyslogOption($_GET['collector']);