Merge pull request #13987 from seamuslee001/new_coder_pcp_pledge_profile_queue_report
[civicrm-core.git] / CRM / Utils / PDF / Document.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2019
32 */
33
34 require_once 'TbsZip/tbszip.php';
35
36 /**
37 * Class CRM_Utils_PDF_Document.
38 */
39 class CRM_Utils_PDF_Document {
40
41 public static $ooxmlMap = [
42 'docx' => [
43 'dataFile' => 'word/document.xml',
44 'startTag' => '<w:body>',
45 'pageBreak' => '<w:p><w:pPr><w:pStyle w:val="Normal"/><w:rPr></w:rPr></w:pPr><w:r><w:rPr></w:rPr></w:r><w:r><w:br w:type="page"/></w:r></w:p>',
46 'endTag' => '</w:body></w:document>',
47 ],
48 'odt' => [
49 'dataFile' => 'content.xml',
50 'startTag' => '<office:body>',
51 'pageBreak' => '<text:p text:style-name="Standard"></text:p>',
52 'endTag' => '</office:body></office:document-content>',
53 ],
54 ];
55
56 /**
57 * Convert html to a Doc file.
58 *
59 * @param array $pages
60 * List of HTML snippets.
61 * @param string $fileName
62 * The logical filename to return to client.
63 * Ex: "HelloWorld.odt".
64 * @param array|int $format
65 */
66 public static function html2doc($pages, $fileName, $format = []) {
67 if (is_array($format)) {
68 // PDF Page Format parameters passed in - merge with defaults
69 $format += CRM_Core_BAO_PdfFormat::getDefaultValues();
70 }
71 else {
72 // PDF Page Format ID passed in
73 $format = CRM_Core_BAO_PdfFormat::getById($format);
74 }
75 $paperSize = CRM_Core_BAO_PaperSize::getByName($format['paper_size']);
76
77 $metric = CRM_Core_BAO_PdfFormat::getValue('metric', $format);
78 $pageStyle = [
79 'orientation' => CRM_Core_BAO_PdfFormat::getValue('orientation', $format),
80 'pageSizeW' => self::toTwip($paperSize['width'], $paperSize['metric']),
81 'pageSizeH' => self::toTwip($paperSize['height'], $paperSize['metric']),
82 'marginTop' => self::toTwip(CRM_Core_BAO_PdfFormat::getValue('margin_top', $format), $metric),
83 'marginRight' => self::toTwip(CRM_Core_BAO_PdfFormat::getValue('margin_right', $format), $metric),
84 'marginBottom' => self::toTwip(CRM_Core_BAO_PdfFormat::getValue('margin_bottom', $format), $metric),
85 'marginLeft' => self::toTwip(CRM_Core_BAO_PdfFormat::getValue('margin_left', $format), $metric),
86 ];
87
88 $ext = pathinfo($fileName, PATHINFO_EXTENSION);
89
90 $phpWord = new \PhpOffice\PhpWord\PhpWord();
91
92 $phpWord->getDocInfo()
93 ->setCreator(CRM_Core_DAO::getFieldValue('CRM_Contact_BAO_Contact', CRM_Core_Session::getLoggedInContactID(), 'display_name'));
94
95 foreach ((array) $pages as $page => $html) {
96 $section = $phpWord->addSection($pageStyle + ['breakType' => 'nextPage']);
97 \PhpOffice\PhpWord\Shared\Html::addHtml($section, $html);
98 }
99
100 self::printDoc($phpWord, $ext, $fileName);
101 }
102
103 /**
104 * @param object|string $phpWord
105 * @param string $ext
106 * File extension/type.
107 * Ex: docx, odt, html.
108 * @param string $fileName
109 * The logical filename to return to client.
110 * Ex: "HelloWorld.odt".
111 * Alternatively, a full path of a file to display. This seems sketchy.
112 * Ex: "/var/lib/data/HelloWorld.odt".
113 */
114 public static function printDoc($phpWord, $ext, $fileName) {
115 $formats = [
116 'docx' => 'Word2007',
117 'odt' => 'ODText',
118 'html' => 'HTML',
119 // todo
120 'pdf' => 'PDF',
121 ];
122
123 if (realpath($fileName)) {
124 $phpWord = \PhpOffice\PhpWord\IOFactory::load($fileName, $formats[$ext]);
125 }
126
127 //CRM-20015
128 \PhpOffice\PhpWord\Settings::setOutputEscapingEnabled(TRUE);
129 $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, $formats[$ext]);
130
131 CRM_Utils_System::setHttpHeader('Content-Type', "application/$ext");
132 CRM_Utils_System::setHttpHeader('Content-Disposition', 'attachment; filename="' . $fileName . '"');
133 $objWriter->save("php://output");
134 }
135
136 /**
137 * @param $value
138 * @param $metric
139 * @return int
140 */
141 public static function toTwip($value, $metric) {
142 $point = CRM_Utils_PDF_Utils::convertMetric($value, $metric, 'pt');
143 return \PhpOffice\PhpWord\Shared\Converter::pointToTwip($point);
144 }
145
146 /**
147 * @param array $path docx/odt file path
148 * @param string $type File type
149 *
150 * @return array
151 * Return extracted content of document in HTML and document type
152 */
153 public static function docReader($path, $type) {
154 $type = array_search($type, CRM_Core_SelectValues::documentApplicationType());
155 $fileType = ($type == 'docx') ? 'Word2007' : 'ODText';
156
157 $phpWord = \PhpOffice\PhpWord\IOFactory::load($path, $fileType);
158 $phpWordHTML = new \PhpOffice\PhpWord\Writer\HTML($phpWord);
159
160 // return the html content for tokenreplacment and eventually used for document download
161 return [$phpWordHTML->getWriterPart('Body')->write(), $type];
162 }
163
164 /**
165 * Extract content of docx/odt file
166 *
167 * @param string $filePath Document file path
168 * @param string $docType File type of document
169 *
170 * @return array
171 * [string, clsTbsZip]
172 */
173 public static function unzipDoc($filePath, $docType) {
174 $dataFile = self::$ooxmlMap[$docType]['dataFile'];
175
176 $zip = new clsTbsZip();
177 $zip->Open($filePath);
178 $content = $zip->FileRead($dataFile);
179
180 return [$content, $zip];
181 }
182
183 /**
184 * Modify contents of docx/odt file(s) and later merged into one final document
185 *
186 * @param array $contents
187 * Content of formatted/token-replaced document.
188 * List of HTML snippets.
189 * @param string $fileName
190 * The logical filename to return to client.
191 * Ex: "HelloWorld.odt".
192 * @param string $docType
193 * Document type e.g. odt/docx
194 * @param clsTbsZip $zip
195 * Zip archive
196 * @param bool $returnFinalContent
197 * Return the content of file document as a string used in unit test
198 *
199 * @return string
200 */
201 public static function printDocuments($contents, $fileName, $docType, $zip, $returnFinalContent = FALSE) {
202 $dataMap = self::$ooxmlMap[$docType];
203
204 $finalContent = $zip->FileRead($dataMap['dataFile']);
205
206 // token-replaced document contents of each contact will be merged into final document
207 foreach ($contents as $key => $content) {
208 if ($key == 0) {
209 $finalContent = $content;
210 continue;
211 }
212
213 // 1. fetch the start position of document body
214 // 2. later fetch only the body part starting from position $start
215 // 3. replace closing body tag with pageBreak
216 // 4. append the $content to the finalContent
217 $start = strpos($content, $dataMap['startTag']);
218 $content = substr($content, $start);
219 $content = str_replace($dataMap['startTag'], $dataMap['pageBreak'], $content);
220 $finalContent = str_replace($dataMap['endTag'], $content, $finalContent);
221 }
222
223 if ($returnFinalContent) {
224 return $finalContent;
225 }
226
227 // Replace the loaded document file content located at $filePath with $finaContent
228 $zip->FileReplace($dataMap['dataFile'], $finalContent, TBSZIP_STRING);
229
230 $zip->Flush(TBSZIP_DOWNLOAD, $fileName);
231 }
232
233 }