3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
37 * BAO object for crm_log table
39 class CRM_Core_BAO_File
extends CRM_Core_DAO_File
{
41 public static $_signableFields = ['entityTable', 'entityID', 'fileID'];
44 * If there is no setting configured on the admin screens, maximum number
45 * of attachments to try to process when given a list of attachments to
48 const DEFAULT_MAX_ATTACHMENTS_BACKEND
= 100;
51 * Takes an associative array and creates a File object.
53 * @param array $params
54 * (reference ) an assoc array of name/value pairs.
56 * @return CRM_Core_BAO_File
58 public static function create($params) {
59 $fileDAO = new CRM_Core_DAO_File();
61 $op = empty($params['id']) ?
'create' : 'edit';
63 CRM_Utils_Hook
::pre($op, 'File', CRM_Utils_Array
::value('id', $params), $params);
65 $fileDAO->copyValues($params);
67 if (empty($params['id']) && empty($params['created_id'])) {
68 $fileDAO->created_id
= CRM_Core_Session
::getLoggedInContactID();
73 CRM_Utils_Hook
::post($op, 'File', $fileDAO->id
, $fileDAO);
80 * @param int $entityID
84 public static function path($fileID, $entityID) {
85 $entityFileDAO = new CRM_Core_DAO_EntityFile();
86 $entityFileDAO->entity_id
= $entityID;
87 $entityFileDAO->file_id
= $fileID;
89 if ($entityFileDAO->find(TRUE)) {
90 $fileDAO = new CRM_Core_DAO_File();
91 $fileDAO->id
= $fileID;
92 if ($fileDAO->find(TRUE)) {
93 $config = CRM_Core_Config
::singleton();
94 $path = $config->customFileUploadDir
. $fileDAO->uri
;
96 if (file_exists($path) && is_readable($path)) {
97 return [$path, $fileDAO->mime_type
];
107 * @param int $fileTypeID
108 * @param $entityTable
109 * @param int $entityID
110 * @param $entitySubtype
111 * @param bool $overwrite
112 * @param null|array $fileParams
113 * @param string $uploadName
114 * @param null $mimeType
118 public static function filePostProcess(
126 $uploadName = 'uploadFile',
130 CRM_Core_Error
::statusBounce(ts('Mime Type is now a required parameter for file upload'));
133 $config = CRM_Core_Config
::singleton();
135 $path = explode('/', $data);
136 $filename = $path[count($path) - 1];
138 // rename this file to go into the secure directory
139 if ($entitySubtype) {
140 $directoryName = $config->customFileUploadDir
. $entitySubtype . DIRECTORY_SEPARATOR
. $entityID;
143 $directoryName = $config->customFileUploadDir
;
146 CRM_Utils_File
::createDir($directoryName);
148 if (!rename($data, $directoryName . DIRECTORY_SEPARATOR
. $filename)) {
149 CRM_Core_Error
::statusBounce(ts('Could not move custom file to custom upload directory'));
153 if ($overwrite && $fileTypeID) {
154 list($sql, $params) = self
::sql($entityTable, $entityID, $fileTypeID);
157 list($sql, $params) = self
::sql($entityTable, $entityID, 0);
160 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
163 $fileDAO = new CRM_Core_DAO_File();
165 if (isset($dao->cfID
) && $dao->cfID
) {
167 $fileDAO->id
= $dao->cfID
;
168 unlink($directoryName . DIRECTORY_SEPARATOR
. $dao->uri
);
171 if (!empty($fileParams)) {
172 $fileDAO->copyValues($fileParams);
175 $fileDAO->uri
= $filename;
176 $fileDAO->mime_type
= $mimeType;
177 $fileDAO->file_type_id
= $fileTypeID;
178 $fileDAO->upload_date
= date('YmdHis');
181 // need to add/update civicrm_entity_file
182 $entityFileDAO = new CRM_Core_DAO_EntityFile();
183 if (isset($dao->cefID
) && $dao->cefID
) {
184 $entityFileDAO->id
= $dao->cefID
;
186 $entityFileDAO->entity_table
= $entityTable;
187 $entityFileDAO->entity_id
= $entityID;
188 $entityFileDAO->file_id
= $fileDAO->id
;
189 $entityFileDAO->save();
192 if (!empty($fileParams['tag'])) {
193 CRM_Core_BAO_EntityTag
::create($fileParams['tag'], 'civicrm_file', $entityFileDAO->id
);
197 if (isset($fileParams['attachment_taglist']) && !empty($fileParams['attachment_taglist'])) {
198 CRM_Core_Form_Tag
::postProcess($fileParams['attachment_taglist'], $entityFileDAO->id
, 'civicrm_file');
201 // lets call the post hook here so attachments code can do the right stuff
202 CRM_Utils_Hook
::post($op, 'File', $fileDAO->id
, $fileDAO);
206 * A static function wrapper that deletes the various objects.
208 * Objects are those hat are connected to a file object (i.e. file, entityFile and customValue.
211 * @param int $entityID
212 * @param int $fieldID
216 public static function deleteFileReferences($fileID, $entityID, $fieldID) {
217 $fileDAO = new CRM_Core_DAO_File();
218 $fileDAO->id
= $fileID;
219 if (!$fileDAO->find(TRUE)) {
220 throw new CRM_Core_Exception(ts('File not found'));
223 // lets call a pre hook before the delete, so attachments hooks can get the info before things
225 CRM_Utils_Hook
::pre('delete', 'File', $fileID, $fileDAO);
227 // get the table and column name
228 list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField
::getTableColumnGroup($fieldID);
230 $entityFileDAO = new CRM_Core_DAO_EntityFile();
231 $entityFileDAO->file_id
= $fileID;
232 $entityFileDAO->entity_id
= $entityID;
233 $entityFileDAO->entity_table
= $tableName;
235 if (!$entityFileDAO->find(TRUE)) {
236 throw new CRM_Core_Exception(sprintf('No record found for given file ID - %d and entity ID - %d', $fileID, $entityID));
239 $entityFileDAO->delete();
242 // also set the value to null of the table and column
243 $query = "UPDATE $tableName SET $columnName = null WHERE $columnName = %1";
244 $params = [1 => [$fileID, 'Integer']];
245 CRM_Core_DAO
::executeQuery($query, $params);
249 * The $useWhere is used so that the signature matches the parent class
251 * public function delete($useWhere = FALSE) {
252 * list($fileID, $entityID, $fieldID) = func_get_args();
254 * self::deleteFileReferences($fileID, $entityID, $fieldID);
258 * Delete all the files and associated object associated with this combination.
260 * @param string $entityTable
261 * @param int $entityID
262 * @param int $fileTypeID
268 public static function deleteEntityFile($entityTable, $entityID, $fileTypeID = NULL, $fileID = NULL) {
270 if (empty($entityTable) ||
empty($entityID)) {
274 $config = CRM_Core_Config
::singleton();
276 list($sql, $params) = self
::sql($entityTable, $entityID, $fileTypeID, $fileID);
277 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
281 while ($dao->fetch()) {
282 $cfIDs[$dao->cfID
] = $dao->uri
;
283 $cefIDs[] = $dao->cefID
;
286 if (!empty($cefIDs)) {
287 $cefIDs = implode(',', $cefIDs);
288 $sql = "DELETE FROM civicrm_entity_file where id IN ( $cefIDs )";
289 CRM_Core_DAO
::executeQuery($sql);
293 if (!empty($cfIDs)) {
294 // Delete file only if there no any entity using this file.
296 foreach ($cfIDs as $fId => $fUri) {
297 //delete tags from entity tag table
299 'entity_table' => 'civicrm_file',
303 CRM_Core_BAO_EntityTag
::del($tagParams);
305 if (!CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile', $fId, 'id', 'file_id')) {
306 unlink($config->customFileUploadDir
. DIRECTORY_SEPARATOR
. $fUri);
307 $deleteFiles[$fId] = $fId;
311 if (!empty($deleteFiles)) {
312 $deleteFiles = implode(',', $deleteFiles);
313 $sql = "DELETE FROM civicrm_file where id IN ( $deleteFiles )";
314 CRM_Core_DAO
::executeQuery($sql);
322 * Get all the files and associated object associated with this combination.
324 * @param string $entityTable
325 * @param int $entityID
326 * @param bool $addDeleteArgs
330 public static function getEntityFile($entityTable, $entityID, $addDeleteArgs = FALSE) {
331 if (empty($entityTable) ||
!$entityID) {
336 $config = CRM_Core_Config
::singleton();
338 list($sql, $params) = self
::sql($entityTable, $entityID, NULL);
339 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
341 while ($dao->fetch()) {
342 $fileHash = self
::generateFileHash($dao->entity_id
, $dao->cfID
);
343 $result['fileID'] = $dao->cfID
;
344 $result['entityID'] = $dao->cefID
;
345 $result['mime_type'] = $dao->mime_type
;
346 $result['fileName'] = $dao->uri
;
347 $result['description'] = $dao->description
;
348 $result['cleanName'] = CRM_Utils_File
::cleanFileName($dao->uri
);
349 $result['fullPath'] = $config->customFileUploadDir
. DIRECTORY_SEPARATOR
. $dao->uri
;
350 $result['url'] = CRM_Utils_System
::url('civicrm/file', "reset=1&id={$dao->cfID}&eid={$dao->entity_id}&fcs={$fileHash}");
351 $result['href'] = "<a href=\"{$result['url']}\">{$result['cleanName']}</a>";
352 $result['tag'] = CRM_Core_BAO_EntityTag
::getTag($dao->cfID
, 'civicrm_file');
353 $result['icon'] = CRM_Utils_File
::getIconFromMimeType($dao->mime_type
);
354 if ($addDeleteArgs) {
355 $result['deleteURLArgs'] = self
::deleteURLArgs($dao->entity_table
, $dao->entity_id
, $dao->cfID
);
357 $results[$dao->cfID
] = $result;
361 $tags = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_EntityTag', 'tag_id', ['onlyActive' => FALSE]);
363 foreach ($results as &$values) {
364 if (!empty($values['tag'])) {
366 foreach ($values['tag'] as $tid) {
367 $tagNames[] = $tags[$tid];
369 $values['tag'] = implode(', ', $tagNames);
380 * @param string $entityTable
381 * Table-name or "*" (to reference files directly by file-id).
382 * @param int $entityID
383 * @param int $fileTypeID
388 public static function sql($entityTable, $entityID, $fileTypeID = NULL, $fileID = NULL) {
389 if ($entityTable == '*') {
390 // $entityID is the ID of a specific file
392 SELECT CF.id as cfID,
394 CF.mime_type as mime_type,
395 CF.description as description,
397 CEF.entity_table as entity_table,
398 CEF.entity_id as entity_id
399 FROM civicrm_file AS CF
400 LEFT JOIN civicrm_entity_file AS CEF ON ( CEF.file_id = CF.id )
406 SELECT CF.id as cfID,
408 CF.mime_type as mime_type,
409 CF.description as description,
411 CEF.entity_table as entity_table,
412 CEF.entity_id as entity_id
413 FROM civicrm_file AS CF
414 LEFT JOIN civicrm_entity_file AS CEF ON ( CEF.file_id = CF.id )
415 WHERE CEF.entity_table = %1
416 AND CEF.entity_id = %2";
420 1 => [$entityTable, 'String'],
421 2 => [$entityID, 'Integer'],
424 if ($fileTypeID !== NULL) {
425 $sql .= " AND CF.file_type_id = %3";
426 $params[3] = [$fileTypeID, 'Integer'];
429 if ($fileID !== NULL) {
430 $sql .= " AND CF.id = %4";
431 $params[4] = [$fileID, 'Integer'];
434 return [$sql, $params];
438 * @param CRM_Core_Form $form
439 * @param string $entityTable
440 * @param int $entityID
441 * @param null $numAttachments
442 * @param bool $ajaxDelete
444 public static function buildAttachment(&$form, $entityTable, $entityID = NULL, $numAttachments = NULL, $ajaxDelete = FALSE) {
446 if (!$numAttachments) {
447 $numAttachments = Civi
::settings()->get('max_attachments');
449 // Assign maxAttachments count to template for help message
450 $form->assign('maxAttachments', $numAttachments);
452 $config = CRM_Core_Config
::singleton();
453 // set default max file size as 2MB
454 $maxFileSize = $config->maxFileSize ?
$config->maxFileSize
: 2;
456 $currentAttachmentInfo = self
::getEntityFile($entityTable, $entityID, TRUE);
457 $totalAttachments = 0;
458 if ($currentAttachmentInfo) {
459 $totalAttachments = count($currentAttachmentInfo);
460 $form->add('checkbox', 'is_delete_attachment', ts('Delete All Attachment(s)'));
461 $form->assign('currentAttachmentInfo', $currentAttachmentInfo);
464 $form->assign('currentAttachmentInfo', NULL);
467 if ($totalAttachments) {
468 if ($totalAttachments >= $numAttachments) {
472 $numAttachments -= $totalAttachments;
476 $form->assign('numAttachments', $numAttachments);
478 CRM_Core_BAO_Tag
::getTags('civicrm_file', $tags, NULL,
479 ' ', TRUE);
482 $parentNames = CRM_Core_BAO_Tag
::getTagSet('civicrm_file');
485 for ($i = 1; $i <= $numAttachments; $i++
) {
486 $form->addElement('file', "attachFile_$i", ts('Attach File'), 'size=30 maxlength=221');
487 $form->addUploadElement("attachFile_$i");
488 $form->setMaxFileSize($maxFileSize * 1024 * 1024);
489 $form->addRule("attachFile_$i",
490 ts('File size should be less than %1 MByte(s)',
494 $maxFileSize * 1024 * 1024
496 $form->addElement('text', "attachDesc_$i", NULL, [
499 'placeholder' => ts('Description'),
503 $form->add('select', "tag_$i", ts('Tags'), $tags, FALSE,
506 'multiple' => 'multiple',
507 'class' => 'huge crm-select2',
508 'placeholder' => ts('- none -'),
512 CRM_Core_Form_Tag
::buildQuickForm($form, $parentNames, 'civicrm_file', NULL, FALSE, TRUE, "file_taglist_$i");
517 * Return a clean url string and the number of attachment for a
518 * given entityTable, entityID
520 * @param string $entityTable
521 * The entityTable to which the file is attached.
522 * @param int $entityID
523 * The id of the object in the above entityTable.
524 * @param string $separator
525 * The string separator where to implode the urls.
528 * An array with 2 elements. The string and the number of attachments
530 public static function attachmentInfo($entityTable, $entityID, $separator = '<br />') {
535 $currentAttachments = self
::getEntityFile($entityTable, $entityID);
536 if (!empty($currentAttachments)) {
537 $currentAttachmentURL = [];
538 foreach ($currentAttachments as $fileID => $attach) {
539 $currentAttachmentURL[] = $attach['href'];
541 return implode($separator, $currentAttachmentURL);
548 * @param array $params
549 * @param $entityTable
550 * @param int $entityID
552 public static function formatAttachment(
559 // delete current attachments if applicable
560 if ($entityID && !empty($formValues['is_delete_attachment'])) {
561 CRM_Core_BAO_File
::deleteEntityFile($entityTable, $entityID);
564 $numAttachments = Civi
::settings()->get('max_attachments');
566 // setup all attachments
567 for ($i = 1; $i <= $numAttachments; $i++
) {
568 $attachName = "attachFile_$i";
569 $attachDesc = "attachDesc_$i";
570 $attachTags = "tag_$i";
571 $attachFreeTags = "file_taglist_$i";
572 if (isset($formValues[$attachName]) && !empty($formValues[$attachName])) {
573 // add static tags if selects
575 if (!empty($formValues[$attachTags])) {
576 foreach ($formValues[$attachTags] as $tag) {
577 $tagParams[$tag] = 1;
581 // we dont care if the file is empty or not
584 'description' => $formValues[$attachDesc],
586 'attachment_taglist' => CRM_Utils_Array
::value($attachFreeTags, $formValues, []),
589 CRM_Utils_File
::formatFile($formValues, $attachName, $extraParams);
591 // set the formatted attachment attributes to $params, later used by
592 // CRM_Activity_BAO_Activity::sendEmail(...) to send mail with desired attachments
593 if (!empty($formValues[$attachName])) {
594 $params[$attachName] = $formValues[$attachName];
601 * @param array $params
602 * @param $entityTable
603 * @param int $entityID
605 public static function processAttachment(&$params, $entityTable, $entityID) {
606 $numAttachments = Civi
::settings()->get('max_attachments_backend') ?? self
::DEFAULT_MAX_ATTACHMENTS_BACKEND
;
608 for ($i = 1; $i <= $numAttachments; $i++
) {
609 if (isset($params["attachFile_$i"])) {
611 * Moved the second condition into its own if block to avoid changing
612 * how it works if there happens to be an entry that is not an array,
613 * since we now might exit loop early via newly added break below.
615 if (is_array($params["attachFile_$i"])) {
616 self
::filePostProcess(
617 $params["attachFile_$i"]['location'],
623 $params["attachFile_$i"],
625 $params["attachFile_$i"]['type']
631 * No point looping 100 times if there aren't any more.
632 * This assumes the array is continuous and doesn't skip array keys,
633 * but (a) where would it be doing that, and (b) it would have caused
634 * problems before anyway if there were skipped keys.
644 public static function uploadNames() {
645 $numAttachments = Civi
::settings()->get('max_attachments');
648 for ($i = 1; $i <= $numAttachments; $i++
) {
649 $names[] = "attachFile_{$i}";
651 $names[] = 'uploadFile';
656 * copy/attach an existing file to a different entity
659 * @param $oldEntityTable
660 * @param int $oldEntityId
661 * @param $newEntityTable
662 * @param int $newEntityId
664 public static function copyEntityFile($oldEntityTable, $oldEntityId, $newEntityTable, $newEntityId) {
665 $oldEntityFile = new CRM_Core_DAO_EntityFile();
666 $oldEntityFile->entity_id
= $oldEntityId;
667 $oldEntityFile->entity_table
= $oldEntityTable;
668 $oldEntityFile->find();
670 while ($oldEntityFile->fetch()) {
671 $newEntityFile = new CRM_Core_DAO_EntityFile();
672 $newEntityFile->entity_id
= $newEntityId;
673 $newEntityFile->entity_table
= $newEntityTable;
674 $newEntityFile->file_id
= $oldEntityFile->file_id
;
675 $newEntityFile->save();
680 * @param $entityTable
681 * @param int $entityID
686 public static function deleteURLArgs($entityTable, $entityID, $fileID) {
687 $params['entityTable'] = $entityTable;
688 $params['entityID'] = $entityID;
689 $params['fileID'] = $fileID;
691 $signer = new CRM_Utils_Signer(CRM_Core_Key
::privateKey(), self
::$_signableFields);
692 $params['_sgn'] = $signer->sign($params);
693 return CRM_Utils_System
::makeQueryString($params);
697 * Delete a file attachment from an entity table / entity ID
700 public static function deleteAttachment() {
702 $params['entityTable'] = CRM_Utils_Request
::retrieve('entityTable', 'String', CRM_Core_DAO
::$_nullObject, TRUE);
703 $params['entityID'] = CRM_Utils_Request
::retrieve('entityID', 'Positive', CRM_Core_DAO
::$_nullObject, TRUE);
704 $params['fileID'] = CRM_Utils_Request
::retrieve('fileID', 'Positive', CRM_Core_DAO
::$_nullObject, TRUE);
706 $signature = CRM_Utils_Request
::retrieve('_sgn', 'String', CRM_Core_DAO
::$_nullObject, TRUE);
708 $signer = new CRM_Utils_Signer(CRM_Core_Key
::privateKey(), self
::$_signableFields);
709 if (!$signer->validate($signature, $params)) {
710 CRM_Core_Error
::fatal('Request signature is invalid');
713 self
::deleteEntityFile($params['entityTable'], $params['entityID'], NULL, $params['fileID']);
717 * Display paper icon for a file attachment -- CRM-13624
719 * @param string $entityTable
720 * The entityTable to which the file is attached. eg "civicrm_contact", "civicrm_note", "civicrm_activity".
721 * If you have the ID of a specific row in civicrm_file, use $entityTable='*'
722 * @param int $entityID
723 * The id of the object in the above entityTable.
726 * list of HTML snippets; one HTML snippet for each attachment. If none found, then NULL
729 public static function paperIconAttachment($entityTable, $entityID) {
730 if (empty($entityTable) ||
!$entityID) {
734 $currentAttachmentInfo = self
::getEntityFile($entityTable, $entityID);
735 foreach ($currentAttachmentInfo as $fileKey => $fileValue) {
736 $fileID = $fileValue['fileID'];
738 $fileType = $fileValue['mime_type'];
739 $url = $fileValue['url'];
740 $title = $fileValue['cleanName'];
741 if ($fileType == 'image/jpeg' ||
742 $fileType == 'image/pjpeg' ||
743 $fileType == 'image/gif' ||
744 $fileType == 'image/x-png' ||
745 $fileType == 'image/png'
747 $file_url[$fileID] = "
748 <a href='$url' class='crm-image-popup' title='$title'>
749 <i class='crm-i fa-file-image-o'></i>
752 // for non image files
754 $file_url[$fileID] = "
755 <a href='$url' title='$title'>
756 <i class='crm-i fa-paperclip'></i>
761 if (empty($file_url)) {
765 $results = $file_url;
771 * Get a reference to the file-search service (if one is available).
773 * @return CRM_Core_FileSearchInterface|NULL
775 public static function getSearchService() {
777 CRM_Utils_Hook
::fileSearches($fileSearches);
779 // use the first available search
780 foreach ($fileSearches as $fileSearch) {
781 /** @var $fileSearch CRM_Core_FileSearchInterface */
788 * Generates an access-token for downloading a specific file.
790 * @param int $entityId entity id the file is attached to
791 * @param int $fileId file ID
796 public static function generateFileHash($entityId = NULL, $fileId = NULL, $genTs = NULL, $life = NULL) {
797 // Use multiple (but stable) inputs for hash information.
798 $siteKey = CRM_Utils_Constant
::value('CIVICRM_SITE_KEY');
800 throw new \
CRM_Core_Exception("Cannot generate file access token. Please set CIVICRM_SITE_KEY.");
807 $days = Civi
::settings()->get('checksum_timeout');
810 // Trim 8 chars off the string, make it slightly easier to find
811 // but reveals less information from the hash.
812 $cs = hash_hmac('sha256', "entity={$entityId}&file={$fileId}&life={$life}", $siteKey);
813 return "{$cs}_{$genTs}_{$life}";
817 * Validate a file access token.
819 * @param string $hash
820 * @param int $entityId Entity Id the file is attached to
821 * @param int $fileId File Id
824 public static function validateFileHash($hash, $entityId, $fileId) {
825 $input = CRM_Utils_System
::explode('_', $hash, 3);
826 $inputTs = CRM_Utils_Array
::value(1, $input);
827 $inputLF = CRM_Utils_Array
::value(2, $input);
828 $testHash = CRM_Core_BAO_File
::generateFileHash($entityId, $fileId, $inputTs, $inputLF);
829 if (hash_equals($testHash, $hash)) {
831 if ($inputTs +
($inputLF * 60 * 60) >= $now) {