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