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