Merge pull request #11838 from mfb/ses-smtp-support
[civicrm-core.git] / CRM / Core / BAO / File.php
CommitLineData
6a488035 1<?php
0c56e4c8
TO
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
0c56e4c8 5 +--------------------------------------------------------------------+
8c9251b3 6 | Copyright CiviCRM LLC (c) 2004-2018 |
0c56e4c8
TO
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
0c56e4c8
TO
27
28/**
29 *
30 * @package CRM
8c9251b3 31 * @copyright CiviCRM LLC (c) 2004-2018
0c56e4c8
TO
32 * $Id$
33 *
6a488035
TO
34 */
35
0c56e4c8
TO
36/**
37 * BAO object for crm_log table
38 */
39class CRM_Core_BAO_File extends CRM_Core_DAO_File {
40
41 static $_signableFields = array('entityTable', 'entityID', 'fileID');
42
ae2c7e00 43 /**
44 * Takes an associative array and creates a File object.
45 *
46 * @param array $params
47 * (reference ) an assoc array of name/value pairs.
48 *
49 * @return CRM_Core_BAO_File
50 */
51 public static function create($params) {
52 $fileDAO = new CRM_Core_DAO_File();
53
54 $op = empty($params['id']) ? 'create' : 'edit';
55
56 CRM_Utils_Hook::pre($op, 'File', CRM_Utils_Array::value('id', $params), $params);
57
58 $fileDAO->copyValues($params);
59
60 if (empty($params['id']) && empty($params['created_id'])) {
61 $fileDAO->created_id = CRM_Core_Session::getLoggedInContactID();
62 }
63
64 $fileDAO->save();
65
66 CRM_Utils_Hook::post($op, 'File', $fileDAO->id, $fileDAO);
67
68 return $fileDAO;
69 }
70
0c56e4c8 71 /**
100fef9d
CW
72 * @param int $fileID
73 * @param int $entityID
0c56e4c8
TO
74 * @param null $entityTable
75 *
76 * @return array
77 */
00be9182 78 public static function path($fileID, $entityID, $entityTable = NULL) {
0c56e4c8
TO
79 $entityFileDAO = new CRM_Core_DAO_EntityFile();
80 if ($entityTable) {
81 $entityFileDAO->entity_table = $entityTable;
82 }
83 $entityFileDAO->entity_id = $entityID;
84 $entityFileDAO->file_id = $fileID;
85
86 if ($entityFileDAO->find(TRUE)) {
87 $fileDAO = new CRM_Core_DAO_File();
88 $fileDAO->id = $fileID;
89 if ($fileDAO->find(TRUE)) {
90 $config = CRM_Core_Config::singleton();
91 $path = $config->customFileUploadDir . $fileDAO->uri;
92
93 if (file_exists($path) && is_readable($path)) {
94 return array($path, $fileDAO->mime_type);
95 }
96 }
97 }
98
99 return array(NULL, NULL);
100 }
101
102
103 /**
104 * @param $data
100fef9d 105 * @param int $fileTypeID
0c56e4c8 106 * @param $entityTable
100fef9d 107 * @param int $entityID
0c56e4c8
TO
108 * @param $entitySubtype
109 * @param bool $overwrite
75fd1335 110 * @param null|array $fileParams
0c56e4c8
TO
111 * @param string $uploadName
112 * @param null $mimeType
113 *
114 * @throws Exception
115 */
ae5ffbb7 116 public static function filePostProcess(
0c56e4c8
TO
117 $data,
118 $fileTypeID,
119 $entityTable,
120 $entityID,
121 $entitySubtype,
122 $overwrite = TRUE,
123 $fileParams = NULL,
124 $uploadName = 'uploadFile',
125 $mimeType = NULL
126 ) {
127 if (!$mimeType) {
b93376a8 128 CRM_Core_Error::statusBounce(ts('Mime Type is now a required parameter for file upload'));
0c56e4c8
TO
129 }
130
131 $config = CRM_Core_Config::singleton();
132
133 $path = explode('/', $data);
134 $filename = $path[count($path) - 1];
135
136 // rename this file to go into the secure directory
137 if ($entitySubtype) {
138 $directoryName = $config->customFileUploadDir . $entitySubtype . DIRECTORY_SEPARATOR . $entityID;
139 }
140 else {
141 $directoryName = $config->customFileUploadDir;
142 }
143
144 CRM_Utils_File::createDir($directoryName);
145
146 if (!rename($data, $directoryName . DIRECTORY_SEPARATOR . $filename)) {
b93376a8 147 CRM_Core_Error::statusBounce(ts('Could not move custom file to custom upload directory'));
0c56e4c8
TO
148 }
149
150 // to get id's
151 if ($overwrite && $fileTypeID) {
152 list($sql, $params) = self::sql($entityTable, $entityID, $fileTypeID);
153 }
154 else {
155 list($sql, $params) = self::sql($entityTable, $entityID, 0);
156 }
157
158 $dao = CRM_Core_DAO::executeQuery($sql, $params);
159 $dao->fetch();
160
161 $fileDAO = new CRM_Core_DAO_File();
162 $op = 'create';
163 if (isset($dao->cfID) && $dao->cfID) {
164 $op = 'edit';
165 $fileDAO->id = $dao->cfID;
166 unlink($directoryName . DIRECTORY_SEPARATOR . $dao->uri);
167 }
168
169 if (!empty($fileParams)) {
170 $fileDAO->copyValues($fileParams);
171 }
172
173 $fileDAO->uri = $filename;
174 $fileDAO->mime_type = $mimeType;
175 $fileDAO->file_type_id = $fileTypeID;
77ca21d6 176 $fileDAO->upload_date = date('YmdHis');
0c56e4c8
TO
177 $fileDAO->save();
178
179 // need to add/update civicrm_entity_file
180 $entityFileDAO = new CRM_Core_DAO_EntityFile();
181 if (isset($dao->cefID) && $dao->cefID) {
182 $entityFileDAO->id = $dao->cefID;
183 }
184 $entityFileDAO->entity_table = $entityTable;
185 $entityFileDAO->entity_id = $entityID;
186 $entityFileDAO->file_id = $fileDAO->id;
187 $entityFileDAO->save();
188
189 //save static tags
190 if (!empty($fileParams['tag'])) {
191 CRM_Core_BAO_EntityTag::create($fileParams['tag'], 'civicrm_file', $entityFileDAO->id);
192 }
193
194 //save free tags
195 if (isset($fileParams['attachment_taglist']) && !empty($fileParams['attachment_taglist'])) {
1273d77c 196 CRM_Core_Form_Tag::postProcess($fileParams['attachment_taglist'], $entityFileDAO->id, 'civicrm_file');
0c56e4c8
TO
197 }
198
199 // lets call the post hook here so attachments code can do the right stuff
200 CRM_Utils_Hook::post($op, 'File', $fileDAO->id, $fileDAO);
201 }
202
203 /**
ad37ac8e 204 * A static function wrapper that deletes the various objects.
205 *
206 * Objects are those hat are connected to a file object (i.e. file, entityFile and customValue.
207 *
208 * @param int $fileID
209 * @param int $entityID
210 * @param int $fieldID
211 *
212 * @throws \Exception
0c56e4c8
TO
213 */
214 public static function deleteFileReferences($fileID, $entityID, $fieldID) {
215 $fileDAO = new CRM_Core_DAO_File();
216 $fileDAO->id = $fileID;
217 if (!$fileDAO->find(TRUE)) {
218 CRM_Core_Error::fatal();
219 }
220
221 // lets call a pre hook before the delete, so attachments hooks can get the info before things
222 // disappear
223 CRM_Utils_Hook::pre('delete', 'File', $fileID, $fileDAO);
224
225 // get the table and column name
226 list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField::getTableColumnGroup($fieldID);
227
228 $entityFileDAO = new CRM_Core_DAO_EntityFile();
229 $entityFileDAO->file_id = $fileID;
230 $entityFileDAO->entity_id = $entityID;
231 $entityFileDAO->entity_table = $tableName;
232
233 if (!$entityFileDAO->find(TRUE)) {
ecdae719 234 CRM_Core_Error::fatal(sprintf('No record found for given file ID - %d and entity ID - %d', $fileID, $entityID));
0c56e4c8
TO
235 }
236
237 $entityFileDAO->delete();
238 $fileDAO->delete();
239
240 // also set the value to null of the table and column
241 $query = "UPDATE $tableName SET $columnName = null WHERE $columnName = %1";
242 $params = array(1 => array($fileID, 'Integer'));
243 CRM_Core_DAO::executeQuery($query, $params);
244 }
245
246 /**
247 * The $useWhere is used so that the signature matches the parent class
0527cd81 248 *
353ffa53
TO
249 * public function delete($useWhere = FALSE) {
250 * list($fileID, $entityID, $fieldID) = func_get_args();
251 *
252 * self::deleteFileReferences($fileID, $entityID, $fieldID);
253 * } */
0c56e4c8
TO
254
255 /**
ad37ac8e 256 * Delete all the files and associated object associated with this combination.
257 *
258 * @param string $entityTable
259 * @param int $entityID
260 * @param int $fileTypeID
261 * @param int $fileID
262 *
7b8bc7a1
SB
263 * @return bool
264 * Was file deleted?
0c56e4c8 265 */
00be9182 266 public static function deleteEntityFile($entityTable, $entityID, $fileTypeID = NULL, $fileID = NULL) {
7b8bc7a1 267 $isDeleted = FALSE;
0c56e4c8 268 if (empty($entityTable) || empty($entityID)) {
7b8bc7a1 269 return $isDeleted;
0c56e4c8
TO
270 }
271
272 $config = CRM_Core_Config::singleton();
273
274 list($sql, $params) = self::sql($entityTable, $entityID, $fileTypeID, $fileID);
275 $dao = CRM_Core_DAO::executeQuery($sql, $params);
276
277 $cfIDs = array();
278 $cefIDs = array();
279 while ($dao->fetch()) {
280 $cfIDs[$dao->cfID] = $dao->uri;
281 $cefIDs[] = $dao->cefID;
282 }
283
284 if (!empty($cefIDs)) {
285 $cefIDs = implode(',', $cefIDs);
286 $sql = "DELETE FROM civicrm_entity_file where id IN ( $cefIDs )";
287 CRM_Core_DAO::executeQuery($sql);
7b8bc7a1 288 $isDeleted = TRUE;
0c56e4c8
TO
289 }
290
291 if (!empty($cfIDs)) {
292 // Delete file only if there no any entity using this file.
293 $deleteFiles = array();
294 foreach ($cfIDs as $fId => $fUri) {
295 //delete tags from entity tag table
296 $tagParams = array(
297 'entity_table' => 'civicrm_file',
21dfd5f5 298 'entity_id' => $fId,
0c56e4c8
TO
299 );
300
301 CRM_Core_BAO_EntityTag::del($tagParams);
302
303 if (!CRM_Core_DAO::getFieldValue('CRM_Core_DAO_EntityFile', $fId, 'id', 'file_id')) {
304 unlink($config->customFileUploadDir . DIRECTORY_SEPARATOR . $fUri);
305 $deleteFiles[$fId] = $fId;
306 }
307 }
308
309 if (!empty($deleteFiles)) {
310 $deleteFiles = implode(',', $deleteFiles);
311 $sql = "DELETE FROM civicrm_file where id IN ( $deleteFiles )";
312 CRM_Core_DAO::executeQuery($sql);
313 }
7b8bc7a1 314 $isDeleted = TRUE;
0c56e4c8 315 }
7b8bc7a1 316 return $isDeleted;
0c56e4c8
TO
317 }
318
319 /**
ad37ac8e 320 * Get all the files and associated object associated with this combination.
321 *
322 * @param string $entityTable
323 * @param int $entityID
324 * @param bool $addDeleteArgs
325 *
326 * @return array|null
0c56e4c8 327 */
00be9182 328 public static function getEntityFile($entityTable, $entityID, $addDeleteArgs = FALSE) {
0c56e4c8
TO
329 if (empty($entityTable) || !$entityID) {
330 $results = NULL;
331 return $results;
332 }
333
334 $config = CRM_Core_Config::singleton();
335
336 list($sql, $params) = self::sql($entityTable, $entityID, NULL);
337 $dao = CRM_Core_DAO::executeQuery($sql, $params);
338 $results = array();
339 while ($dao->fetch()) {
340 $result['fileID'] = $dao->cfID;
341 $result['entityID'] = $dao->cefID;
342 $result['mime_type'] = $dao->mime_type;
343 $result['fileName'] = $dao->uri;
344 $result['description'] = $dao->description;
345 $result['cleanName'] = CRM_Utils_File::cleanFileName($dao->uri);
346 $result['fullPath'] = $config->customFileUploadDir . DIRECTORY_SEPARATOR . $dao->uri;
06faabfa 347 $result['url'] = CRM_Utils_System::url('civicrm/file', "reset=1&id={$dao->cfID}&eid={$dao->entity_id}");
0c56e4c8
TO
348 $result['href'] = "<a href=\"{$result['url']}\">{$result['cleanName']}</a>";
349 $result['tag'] = CRM_Core_BAO_EntityTag::getTag($dao->cfID, 'civicrm_file');
30a0455f 350 $result['icon'] = CRM_Utils_File::getIconFromMimeType($dao->mime_type);
0c56e4c8 351 if ($addDeleteArgs) {
06faabfa 352 $result['deleteURLArgs'] = self::deleteURLArgs($dao->entity_table, $dao->entity_id, $dao->cfID);
0c56e4c8
TO
353 }
354 $results[$dao->cfID] = $result;
355 }
356
357 //fix tag names
358 $tags = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
359
360 foreach ($results as &$values) {
361 if (!empty($values['tag'])) {
362 $tagNames = array();
363 foreach ($values['tag'] as $tid) {
364 $tagNames[] = $tags[$tid];
365 }
366 $values['tag'] = implode(', ', $tagNames);
367 }
368 else {
369 $values['tag'] = '';
370 }
371 }
372
373 $dao->free();
374 return $results;
375 }
376
377 /**
6a0b768e
TO
378 * @param string $entityTable
379 * Table-name or "*" (to reference files directly by file-id).
06faabfa 380 * @param int $entityID
100fef9d
CW
381 * @param int $fileTypeID
382 * @param int $fileID
0c56e4c8
TO
383 *
384 * @return array
385 */
00be9182 386 public static function sql($entityTable, $entityID, $fileTypeID = NULL, $fileID = NULL) {
06faabfa
TO
387 if ($entityTable == '*') {
388 // $entityID is the ID of a specific file
389 $sql = "
390SELECT CF.id as cfID,
391 CF.uri as uri,
392 CF.mime_type as mime_type,
393 CF.description as description,
394 CEF.id as cefID,
395 CEF.entity_table as entity_table,
396 CEF.entity_id as entity_id
397FROM civicrm_file AS CF
398LEFT JOIN civicrm_entity_file AS CEF ON ( CEF.file_id = CF.id )
399WHERE CF.id = %2";
400
0db6c3e1
TO
401 }
402 else {
06faabfa 403 $sql = "
0c56e4c8 404SELECT CF.id as cfID,
6a488035
TO
405 CF.uri as uri,
406 CF.mime_type as mime_type,
407 CF.description as description,
06faabfa
TO
408 CEF.id as cefID,
409 CEF.entity_table as entity_table,
410 CEF.entity_id as entity_id
0c56e4c8
TO
411FROM civicrm_file AS CF
412LEFT JOIN civicrm_entity_file AS CEF ON ( CEF.file_id = CF.id )
413WHERE CEF.entity_table = %1
414AND CEF.entity_id = %2";
06faabfa 415 }
0c56e4c8
TO
416
417 $params = array(
418 1 => array($entityTable, 'String'),
419 2 => array($entityID, 'Integer'),
420 );
421
422 if ($fileTypeID !== NULL) {
423 $sql .= " AND CF.file_type_id = %3";
424 $params[3] = array($fileTypeID, 'Integer');
425 }
426
427 if ($fileID !== NULL) {
428 $sql .= " AND CF.id = %4";
429 $params[4] = array($fileID, 'Integer');
430 }
431
432 return array($sql, $params);
433 }
434
435 /**
75fd1335
TO
436 * @param CRM_Core_Form $form
437 * @param string $entityTable
100fef9d 438 * @param int $entityID
0c56e4c8
TO
439 * @param null $numAttachments
440 * @param bool $ajaxDelete
441 */
00be9182 442 public static function buildAttachment(&$form, $entityTable, $entityID = NULL, $numAttachments = NULL, $ajaxDelete = FALSE) {
0c56e4c8
TO
443
444 if (!$numAttachments) {
aaffa79f 445 $numAttachments = Civi::settings()->get('max_attachments');
0c56e4c8
TO
446 }
447 // Assign maxAttachments count to template for help message
448 $form->assign('maxAttachments', $numAttachments);
449
450 $config = CRM_Core_Config::singleton();
451 // set default max file size as 2MB
452 $maxFileSize = $config->maxFileSize ? $config->maxFileSize : 2;
453
454 $currentAttachmentInfo = self::getEntityFile($entityTable, $entityID, TRUE);
455 $totalAttachments = 0;
456 if ($currentAttachmentInfo) {
457 $totalAttachments = count($currentAttachmentInfo);
458 $form->add('checkbox', 'is_delete_attachment', ts('Delete All Attachment(s)'));
459 $form->assign('currentAttachmentInfo', $currentAttachmentInfo);
460 }
461 else {
462 $form->assign('currentAttachmentInfo', NULL);
463 }
464
465 if ($totalAttachments) {
466 if ($totalAttachments >= $numAttachments) {
467 $numAttachments = 0;
468 }
469 else {
470 $numAttachments -= $totalAttachments;
471 }
472 }
473
474 $form->assign('numAttachments', $numAttachments);
475
e0f9d6a2 476 CRM_Core_BAO_Tag::getTags('civicrm_file', $tags, NULL,
477 '&nbsp;&nbsp;', TRUE);
0c56e4c8
TO
478
479 // get tagset info
480 $parentNames = CRM_Core_BAO_Tag::getTagSet('civicrm_file');
481
482 // add attachments
483 for ($i = 1; $i <= $numAttachments; $i++) {
d00e9ef0 484 $form->addElement('file', "attachFile_$i", ts('Attach File'), 'size=30 maxlength=221');
0c56e4c8
TO
485 $form->addUploadElement("attachFile_$i");
486 $form->setMaxFileSize($maxFileSize * 1024 * 1024);
487 $form->addRule("attachFile_$i",
488 ts('File size should be less than %1 MByte(s)',
489 array(1 => $maxFileSize)
490 ),
491 'maxfilesize',
492 $maxFileSize * 1024 * 1024
493 );
494 $form->addElement('text', "attachDesc_$i", NULL, array(
495 'size' => 40,
496 'maxlength' => 255,
21dfd5f5 497 'placeholder' => ts('Description'),
0c56e4c8
TO
498 ));
499
500 if (!empty($tags)) {
501 $form->add('select', "tag_$i", ts('Tags'), $tags, FALSE,
502 array(
503 'id' => "tags_$i",
504 'multiple' => 'multiple',
505 'class' => 'huge crm-select2',
21dfd5f5 506 'placeholder' => ts('- none -'),
0c56e4c8
TO
507 )
508 );
509 }
510 CRM_Core_Form_Tag::buildQuickForm($form, $parentNames, 'civicrm_file', NULL, FALSE, TRUE, "file_taglist_$i");
511 }
512 }
513
514 /**
100fef9d 515 * Return a clean url string and the number of attachment for a
0c56e4c8
TO
516 * given entityTable, entityID
517 *
5a4f6742
CW
518 * @param string $entityTable
519 * The entityTable to which the file is attached.
520 * @param int $entityID
521 * The id of the object in the above entityTable.
522 * @param string $separator
523 * The string separator where to implode the urls.
0c56e4c8 524 *
a6c01b45
CW
525 * @return array
526 * An array with 2 elements. The string and the number of attachments
0c56e4c8 527 */
00be9182 528 public static function attachmentInfo($entityTable, $entityID, $separator = '<br />') {
0c56e4c8
TO
529 if (!$entityID) {
530 return NULL;
531 }
532
533 $currentAttachments = self::getEntityFile($entityTable, $entityID);
534 if (!empty($currentAttachments)) {
535 $currentAttachmentURL = array();
536 foreach ($currentAttachments as $fileID => $attach) {
537 $currentAttachmentURL[] = $attach['href'];
538 }
539 return implode($separator, $currentAttachmentURL);
540 }
541 return NULL;
542 }
543
544 /**
545 * @param $formValues
c490a46a 546 * @param array $params
0c56e4c8 547 * @param $entityTable
100fef9d 548 * @param int $entityID
0c56e4c8 549 */
ae5ffbb7 550 public static function formatAttachment(
0c56e4c8
TO
551 &$formValues,
552 &$params,
553 $entityTable,
554 $entityID = NULL
555 ) {
556
557 // delete current attachments if applicable
558 if ($entityID && !empty($formValues['is_delete_attachment'])) {
559 CRM_Core_BAO_File::deleteEntityFile($entityTable, $entityID);
560 }
561
aaffa79f 562 $numAttachments = Civi::settings()->get('max_attachments');
0c56e4c8 563
0c56e4c8
TO
564 // setup all attachments
565 for ($i = 1; $i <= $numAttachments; $i++) {
566 $attachName = "attachFile_$i";
567 $attachDesc = "attachDesc_$i";
568 $attachTags = "tag_$i";
569 $attachFreeTags = "file_taglist_$i";
570 if (isset($formValues[$attachName]) && !empty($formValues[$attachName])) {
571 // add static tags if selects
572 $tagParams = array();
573 if (!empty($formValues[$attachTags])) {
574 foreach ($formValues[$attachTags] as $tag) {
575 $tagParams[$tag] = 1;
576 }
577 }
578
579 // we dont care if the file is empty or not
580 // CRM-7448
90a73810 581 $extraParams = array(
0c56e4c8 582 'description' => $formValues[$attachDesc],
0c56e4c8 583 'tag' => $tagParams,
21dfd5f5 584 'attachment_taglist' => CRM_Utils_Array::value($attachFreeTags, $formValues, array()),
0c56e4c8
TO
585 );
586
90a73810 587 CRM_Utils_File::formatFile($formValues, $attachName, $extraParams);
cde03305 588
589 // set the formatted attachment attributes to $params, later used by
590 // CRM_Activity_BAO_Activity::sendEmail(...) to send mail with desired attachments
591 if (!empty($formValues[$attachName])) {
592 $params[$attachName] = $formValues[$attachName];
593 }
0c56e4c8
TO
594 }
595 }
596 }
597
598 /**
c490a46a 599 * @param array $params
0c56e4c8 600 * @param $entityTable
100fef9d 601 * @param int $entityID
0c56e4c8 602 */
00be9182 603 public static function processAttachment(&$params, $entityTable, $entityID) {
aaffa79f 604 $numAttachments = Civi::settings()->get('max_attachments');
0c56e4c8
TO
605
606 for ($i = 1; $i <= $numAttachments; $i++) {
607 if (
608 isset($params["attachFile_$i"]) &&
609 is_array($params["attachFile_$i"])
610 ) {
611 self::filePostProcess(
612 $params["attachFile_$i"]['location'],
613 NULL,
614 $entityTable,
615 $entityID,
616 NULL,
617 TRUE,
618 $params["attachFile_$i"],
619 "attachFile_$i",
620 $params["attachFile_$i"]['type']
621 );
622 }
623 }
624 }
625
626 /**
627 * @return array
628 */
00be9182 629 public static function uploadNames() {
aaffa79f 630 $numAttachments = Civi::settings()->get('max_attachments');
0c56e4c8
TO
631
632 $names = array();
633 for ($i = 1; $i <= $numAttachments; $i++) {
634 $names[] = "attachFile_{$i}";
635 }
636 $names[] = 'uploadFile';
637 return $names;
638 }
639
d424ffde 640 /**
c490a46a 641 * copy/attach an existing file to a different entity
0c56e4c8 642 * table and id.
d424ffde 643 *
0c56e4c8 644 * @param $oldEntityTable
100fef9d 645 * @param int $oldEntityId
0c56e4c8 646 * @param $newEntityTable
100fef9d 647 * @param int $newEntityId
0c56e4c8 648 */
00be9182 649 public static function copyEntityFile($oldEntityTable, $oldEntityId, $newEntityTable, $newEntityId) {
6a488035
TO
650 $oldEntityFile = new CRM_Core_DAO_EntityFile();
651 $oldEntityFile->entity_id = $oldEntityId;
652 $oldEntityFile->entity_table = $oldEntityTable;
653 $oldEntityFile->find();
654
655 while ($oldEntityFile->fetch()) {
656 $newEntityFile = new CRM_Core_DAO_EntityFile();
657 $newEntityFile->entity_id = $newEntityId;
658 $newEntityFile->entity_table = $newEntityTable;
659 $newEntityFile->file_id = $oldEntityFile->file_id;
660 $newEntityFile->save();
661 }
662 }
663
0c56e4c8
TO
664 /**
665 * @param $entityTable
100fef9d
CW
666 * @param int $entityID
667 * @param int $fileID
0c56e4c8
TO
668 *
669 * @return string
670 */
00be9182 671 public static function deleteURLArgs($entityTable, $entityID, $fileID) {
6a488035 672 $params['entityTable'] = $entityTable;
0c56e4c8
TO
673 $params['entityID'] = $entityID;
674 $params['fileID'] = $fileID;
6a488035
TO
675
676 $signer = new CRM_Utils_Signer(CRM_Core_Key::privateKey(), self::$_signableFields);
677 $params['_sgn'] = $signer->sign($params);
678 return CRM_Utils_System::makeQueryString($params);
679 }
680
681 /**
100fef9d 682 * Delete a file attachment from an entity table / entity ID
6a488035 683 *
6a488035 684 */
00be9182 685 public static function deleteAttachment() {
0c56e4c8
TO
686 $params = array();
687 $params['entityTable'] = CRM_Utils_Request::retrieve('entityTable', 'String', CRM_Core_DAO::$_nullObject, TRUE);
688 $params['entityID'] = CRM_Utils_Request::retrieve('entityID', 'Positive', CRM_Core_DAO::$_nullObject, TRUE);
689 $params['fileID'] = CRM_Utils_Request::retrieve('fileID', 'Positive', CRM_Core_DAO::$_nullObject, TRUE);
6a488035 690
0c56e4c8 691 $signature = CRM_Utils_Request::retrieve('_sgn', 'String', CRM_Core_DAO::$_nullObject, TRUE);
6a488035
TO
692
693 $signer = new CRM_Utils_Signer(CRM_Core_Key::privateKey(), self::$_signableFields);
0c56e4c8 694 if (!$signer->validate($signature, $params)) {
6a488035
TO
695 CRM_Core_Error::fatal('Request signature is invalid');
696 }
697
33d245c8 698 self::deleteEntityFile($params['entityTable'], $params['entityID'], NULL, $params['fileID']);
6a488035
TO
699 }
700
6a488035 701
34f51a07 702 /**
100fef9d 703 * Display paper icon for a file attachment -- CRM-13624
34f51a07 704 *
5a4f6742
CW
705 * @param string $entityTable
706 * The entityTable to which the file is attached. eg "civicrm_contact", "civicrm_note", "civicrm_activity".
06faabfa 707 * If you have the ID of a specific row in civicrm_file, use $entityTable='*'
5a4f6742
CW
708 * @param int $entityID
709 * The id of the object in the above entityTable.
1a7ab71e 710 *
72b3a70c
CW
711 * @return array|NULL
712 * list of HTML snippets; one HTML snippet for each attachment. If none found, then NULL
1a7ab71e 713 *
34f51a07 714 */
00be9182 715 public static function paperIconAttachment($entityTable, $entityID) {
0c56e4c8
TO
716 if (empty($entityTable) || !$entityID) {
717 $results = NULL;
718 return $results;
719 }
720 $currentAttachmentInfo = self::getEntityFile($entityTable, $entityID);
721 foreach ($currentAttachmentInfo as $fileKey => $fileValue) {
34f51a07 722 $fileID = $fileValue['fileID'];
0c56e4c8 723 if ($fileID) {
b9773de0
CW
724 $fileType = $fileValue['mime_type'];
725 $url = $fileValue['url'];
726 $title = $fileValue['cleanName'];
34f51a07 727 if ($fileType == 'image/jpeg' ||
0c56e4c8
TO
728 $fileType == 'image/pjpeg' ||
729 $fileType == 'image/gif' ||
730 $fileType == 'image/x-png' ||
731 $fileType == 'image/png'
732 ) {
34f51a07 733 $file_url[$fileID] = "
b9773de0
CW
734 <a href='$url' class='crm-image-popup' title='$title'>
735 <i class='crm-i fa-file-image-o'></i>
34f51a07 736 </a>";
34f51a07 737 }
b9773de0 738 // for non image files
34f51a07 739 else {
b9773de0
CW
740 $file_url[$fileID] = "
741 <a href='$url' title='$title'>
742 <i class='crm-i fa-paperclip'></i>
743 </a>";
34f51a07
N
744 }
745 }
746 }
0c56e4c8
TO
747 if (empty($file_url)) {
748 $results = NULL;
34f51a07
N
749 }
750 else {
0c56e4c8 751 $results = $file_url;
34f51a07
N
752 }
753 return $results;
754 }
6cccc6d4
TO
755
756 /**
757 * Get a reference to the file-search service (if one is available).
758 *
759 * @return CRM_Core_FileSearchInterface|NULL
760 */
00be9182 761 public static function getSearchService() {
6cccc6d4
TO
762 $fileSearches = array();
763 CRM_Utils_Hook::fileSearches($fileSearches);
764
765 // use the first available search
766 foreach ($fileSearches as $fileSearch) {
767 /** @var $fileSearch CRM_Core_FileSearchInterface */
768 return $fileSearch;
769 }
770 return NULL;
771 }
96025800 772
b2aaa85e 773}