Merge pull request #4883 from totten/master-cs4
[civicrm-core.git] / CRM / Financial / BAO / ExportFormat.php
CommitLineData
03e04002 1<?php
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
03e04002 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
03e04002 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
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
03e04002 32 * $Id$
33 *
34 */
35
36/**
37 * Base class for Export Formats
38 * Create a subclass for a specific format.
39 * @see http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+Specifications+-++Batches#CiviAccountsSpecifications-Batches-%C2%A0Overviewofimplementation
40 */
41
42class CRM_Financial_BAO_ExportFormat {
43
44 /*
45 * Array of data which the individual export formats will output in the desired format
46 */
47 protected $_exportParams;
48
49 /*
50 * smarty template
51 */
52 static protected $_template;
53
54 /**
100fef9d 55 * Class constructor
03e04002 56 */
00be9182 57 public function __construct() {
481a74f4 58 if (!isset(self::$_template)) {
03e04002 59 self::$_template = CRM_Core_Smarty::singleton();
60 }
61 }
62
63 // Override to assemble the appropriate subset of financial data for the specific export format
e0ef6999 64 /**
100fef9d 65 * @param array $exportParams
e0ef6999
EM
66 *
67 * @return mixed
68 */
00be9182 69 public function export($exportParams) {
03e04002 70 $this->_exportParams = $exportParams;
71 return $exportParams;
72 }
73
e0ef6999
EM
74 /**
75 * @param null $fileName
76 */
00be9182 77 public function output($fileName = NULL) {
03e04002 78 switch ($this->getFileExtension()) {
79 case 'csv':
80 self::createActivityExport($this->_batchIds, $fileName);
045f52a3 81 break;
03e04002 82
83 case 'iif':
232624b1 84 $tplFile = $this->getHookedTemplateFileName();
f4114c3e 85 $out = self::getTemplate()->fetch($tplFile);
03e04002 86 $fileName = $this->putFile($out);
87 self::createActivityExport($this->_batchIds, $fileName);
045f52a3 88 break;
03e04002 89 }
90 }
91
e0ef6999
EM
92 /**
93 * @return string
94 */
00be9182 95 public function getMimeType() {
03e04002 96 return 'text/plain';
97 }
98
e0ef6999
EM
99 /**
100 * @return string
101 */
00be9182 102 public function getFileExtension() {
03e04002 103 return 'txt';
104 }
105
106 // Override this if appropriate
e0ef6999
EM
107 /**
108 * @return null
109 */
00be9182 110 public function getTemplateFileName() {
045f52a3 111 return NULL;
03e04002 112 }
113
e0ef6999
EM
114 /**
115 * @return object
116 */
00be9182 117 public static function &getTemplate() {
03e04002 118 return self::$_template;
119 }
120
e0ef6999
EM
121 /**
122 * @param $var
123 * @param null $value
124 */
00be9182 125 public function assign($var, $value = NULL) {
03e04002 126 self::$_template->assign($var, $value);
127 }
128
129 /*
130 * This gets called for every item of data being compiled before being sent to the exporter for output.
131 *
132 * Depending on the output format might want to override this, e.g. for IIF tabs need to be escaped etc,
133 * but for CSV it doesn't make sense because php has built in csv output functions.
134 */
e0ef6999
EM
135 /**
136 * @param $s
137 * @param string $type
138 *
139 * @return null
140 */
00be9182 141 public static function format($s, $type = 'string') {
03e04002 142 if (!empty($s)) {
143 return $s;
144 }
145 else {
146 return NULL;
147 }
148 }
149
00be9182 150 public function initiateDownload() {
03e04002 151 $config = CRM_Core_Config::singleton();
152 //zip files if more than one.
045f52a3 153 if (count($this->_downloadFile) > 1) {
f4114c3e 154 $zip = $config->customFileUploadDir . 'Financial_Transactions_' . date('YmdHis') . '.zip';
03e04002 155 $result = $this->createZip($this->_downloadFile, $zip, TRUE);
156 if ($result) {
157 header('Content-Type: application/zip');
f4114c3e 158 header('Content-Disposition: attachment; filename=' . CRM_Utils_File::cleanFileName(basename($zip)));
03e04002 159 header('Content-Length: ' . filesize($zip));
160 ob_clean();
161 flush();
f4114c3e 162 readfile($config->customFileUploadDir . CRM_Utils_File::cleanFileName(basename($zip)));
03e04002 163 unlink($zip); //delete the zip to avoid clutter.
164 CRM_Utils_System::civiExit();
165 }
166 }
167 else {
f4114c3e
PN
168 header('Content-Type: text/plain');
169 header('Content-Disposition: attachment; filename=' . CRM_Utils_File::cleanFileName(basename($this->_downloadFile[0])));
03e04002 170 header('Content-Length: ' . filesize($this->_downloadFile[0]));
171 ob_clean();
172 flush();
f4114c3e 173 readfile($config->customFileUploadDir . CRM_Utils_File::cleanFileName(basename($this->_downloadFile[0])));
03e04002 174 CRM_Utils_System::civiExit();
175 }
176 }
177
e0ef6999
EM
178 /**
179 * @param $batchIds
100fef9d 180 * @param string $fileName
e0ef6999
EM
181 *
182 * @throws CRM_Core_Exception
183 */
00be9182 184 public static function createActivityExport($batchIds, $fileName) {
03e04002 185 $session = CRM_Core_Session::singleton();
186 $values = array();
187 $params = array('id' => $batchIds);
188 CRM_Batch_BAO_Batch::retrieve($params, $values);
189 $createdBy = CRM_Contact_BAO_Contact::displayName($values['created_id']);
190 $modifiedBy = CRM_Contact_BAO_Contact::displayName($values['modified_id']);
191
192 $values['payment_instrument_id'] = '';
193 if (isset($values['payment_instrument_id'])) {
194 $paymentInstrument = array_flip(CRM_Contribute_PseudoConstant::paymentInstrument('label'));
195 $values['payment_instrument_id'] = array_search($values['payment_instrument_id'], $paymentInstrument);
196 }
ffa40ba9 197 $details = '<p>' . ts('Record:') . ' ' . $values['title'] . '</p><p>' . ts('Description:') . '</p><p>' . ts('Created By:') . " $createdBy" . '</p><p>' . ts('Created Date:') . ' ' . $values['created_date'] . '</p><p>' . ts('Last Modified By:') . ' ' . $modifiedBy . '</p><p>' . ts('Payment Instrument:') . ' ' . $values['payment_instrument_id'] . '</p>';
03e04002 198 $subject = '';
a7488080 199 if (!empty($values['total'])) {
86bfa4f6 200 $subject .= ts('Total') . '[' . CRM_Utils_Money::format($values['total']) . '],';
03e04002 201 }
a7488080 202 if (!empty($values['item_count'])) {
86bfa4f6 203 $subject .= ' ' . ts('Count') . '[' . $values['item_count'] . '],';
03e04002 204 }
205
206 //create activity.
86bfa4f6 207 $subject .= ' ' . ts('Batch') . '[' . $values['title'] . ']';
03e04002 208 $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
209 $activityParams = array(
210 'activity_type_id' => array_search('Export Accounting Batch', $activityTypes),
211 'subject' => $subject,
212 'status_id' => 2,
213 'activity_date_time' => date('YmdHis'),
214 'source_contact_id' => $session->get('userID'),
215 'source_record_id' => $values['id'],
216 'target_contact_id' => $session->get('userID'),
217 'details' => $details,
045f52a3 218 'attachFile_1' => array(
03e04002 219 'uri' => $fileName,
220 'type' => 'text/csv',
221 'location' => $fileName,
222 'upload_date' => date('YmdHis'),
223 ),
224 );
225
226 CRM_Activity_BAO_Activity::create($activityParams);
227 }
228
e0ef6999
EM
229 /**
230 * @param array $files
231 * @param null $destination
232 * @param bool $overwrite
233 *
234 * @return bool
235 */
00be9182 236 public function createZip($files = array(), $destination = NULL, $overwrite = FALSE) {
03e04002 237 //if the zip file already exists and overwrite is false, return false
238 if (file_exists($destination) && !$overwrite) {
239 return FALSE;
240 }
241 $valid_files = array();
242 if (is_array($files)) {
243 foreach ($files as $file) {
244 //make sure the file exists
245 if (file_exists($file)) {
246 $validFiles[] = $file;
247 }
248 }
249 }
250 if (count($validFiles)) {
251 $zip = new ZipArchive();
045f52a3 252 if ($zip->open($destination, $overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== TRUE) {
03e04002 253 return FALSE;
254 }
255 foreach ($validFiles as $file) {
256 $zip->addFile($file, CRM_Utils_File::cleanFileName(basename($file)));
257 }
258 $zip->close();
259 return file_exists($destination);
260 }
261 else {
045f52a3
TO
262 return FALSE;
263 }
03e04002 264 }
232624b1 265}