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