3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
37 * BAO object for crm_log table
39 class CRM_Core_BAO_File
extends CRM_Core_DAO_File
{
41 static $_signableFields = array('entityTable', 'entityID', 'fileID');
44 * Takes an associative array and creates a File object.
46 * @param array $params
47 * (reference ) an assoc array of name/value pairs.
49 * @return CRM_Core_BAO_File
51 public static function create($params) {
52 $fileDAO = new CRM_Core_DAO_File();
54 $op = empty($params['id']) ?
'create' : 'edit';
56 CRM_Utils_Hook
::pre($op, 'File', CRM_Utils_Array
::value('id', $params), $params);
58 $fileDAO->copyValues($params);
60 if (empty($params['id']) && empty($params['created_id'])) {
61 $fileDAO->created_id
= CRM_Core_Session
::getLoggedInContactID();
66 CRM_Utils_Hook
::post($op, 'File', $fileDAO->id
, $fileDAO);
73 * @param int $entityID
74 * @param null $entityTable
78 public static function path($fileID, $entityID, $entityTable = NULL) {
79 $entityFileDAO = new CRM_Core_DAO_EntityFile();
81 $entityFileDAO->entity_table
= $entityTable;
83 $entityFileDAO->entity_id
= $entityID;
84 $entityFileDAO->file_id
= $fileID;
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
;
93 if (file_exists($path) && is_readable($path)) {
94 return array($path, $fileDAO->mime_type
);
99 return array(NULL, NULL);
105 * @param int $fileTypeID
106 * @param $entityTable
107 * @param int $entityID
108 * @param $entitySubtype
109 * @param bool $overwrite
110 * @param null|array $fileParams
111 * @param string $uploadName
112 * @param null $mimeType
116 public static function filePostProcess(
124 $uploadName = 'uploadFile',
128 CRM_Core_Error
::statusBounce(ts('Mime Type is now a required parameter for file upload'));
131 $config = CRM_Core_Config
::singleton();
133 $path = explode('/', $data);
134 $filename = $path[count($path) - 1];
136 // rename this file to go into the secure directory
137 if ($entitySubtype) {
138 $directoryName = $config->customFileUploadDir
. $entitySubtype . DIRECTORY_SEPARATOR
. $entityID;
141 $directoryName = $config->customFileUploadDir
;
144 CRM_Utils_File
::createDir($directoryName);
146 if (!rename($data, $directoryName . DIRECTORY_SEPARATOR
. $filename)) {
147 CRM_Core_Error
::statusBounce(ts('Could not move custom file to custom upload directory'));
151 if ($overwrite && $fileTypeID) {
152 list($sql, $params) = self
::sql($entityTable, $entityID, $fileTypeID);
155 list($sql, $params) = self
::sql($entityTable, $entityID, 0);
158 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
161 $fileDAO = new CRM_Core_DAO_File();
163 if (isset($dao->cfID
) && $dao->cfID
) {
165 $fileDAO->id
= $dao->cfID
;
166 unlink($directoryName . DIRECTORY_SEPARATOR
. $dao->uri
);
169 if (!empty($fileParams)) {
170 $fileDAO->copyValues($fileParams);
173 $fileDAO->uri
= $filename;
174 $fileDAO->mime_type
= $mimeType;
175 $fileDAO->file_type_id
= $fileTypeID;
176 $fileDAO->upload_date
= date('YmdHis');
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
;
184 $entityFileDAO->entity_table
= $entityTable;
185 $entityFileDAO->entity_id
= $entityID;
186 $entityFileDAO->file_id
= $fileDAO->id
;
187 $entityFileDAO->save();
190 if (!empty($fileParams['tag'])) {
191 CRM_Core_BAO_EntityTag
::create($fileParams['tag'], 'civicrm_file', $entityFileDAO->id
);
195 if (isset($fileParams['attachment_taglist']) && !empty($fileParams['attachment_taglist'])) {
196 CRM_Core_Form_Tag
::postProcess($fileParams['attachment_taglist'], $entityFileDAO->id
, 'civicrm_file');
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);
204 * A static function wrapper that deletes the various objects.
206 * Objects are those hat are connected to a file object (i.e. file, entityFile and customValue.
209 * @param int $entityID
210 * @param int $fieldID
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();
221 // lets call a pre hook before the delete, so attachments hooks can get the info before things
223 CRM_Utils_Hook
::pre('delete', 'File', $fileID, $fileDAO);
225 // get the table and column name
226 list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField
::getTableColumnGroup($fieldID);
228 $entityFileDAO = new CRM_Core_DAO_EntityFile();
229 $entityFileDAO->file_id
= $fileID;
230 $entityFileDAO->entity_id
= $entityID;
231 $entityFileDAO->entity_table
= $tableName;
233 if (!$entityFileDAO->find(TRUE)) {
234 CRM_Core_Error
::fatal(sprintf('No record found for given file ID - %d and entity ID - %d', $fileID, $entityID));
237 $entityFileDAO->delete();
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);
247 * The $useWhere is used so that the signature matches the parent class
249 * public function delete($useWhere = FALSE) {
250 * list($fileID, $entityID, $fieldID) = func_get_args();
252 * self::deleteFileReferences($fileID, $entityID, $fieldID);
256 * Delete all the files and associated object associated with this combination.
258 * @param string $entityTable
259 * @param int $entityID
260 * @param int $fileTypeID
266 public static function deleteEntityFile($entityTable, $entityID, $fileTypeID = NULL, $fileID = NULL) {
268 if (empty($entityTable) ||
empty($entityID)) {
272 $config = CRM_Core_Config
::singleton();
274 list($sql, $params) = self
::sql($entityTable, $entityID, $fileTypeID, $fileID);
275 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
279 while ($dao->fetch()) {
280 $cfIDs[$dao->cfID
] = $dao->uri
;
281 $cefIDs[] = $dao->cefID
;
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);
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
297 'entity_table' => 'civicrm_file',
301 CRM_Core_BAO_EntityTag
::del($tagParams);
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;
309 if (!empty($deleteFiles)) {
310 $deleteFiles = implode(',', $deleteFiles);
311 $sql = "DELETE FROM civicrm_file where id IN ( $deleteFiles )";
312 CRM_Core_DAO
::executeQuery($sql);
320 * Get all the files and associated object associated with this combination.
322 * @param string $entityTable
323 * @param int $entityID
324 * @param bool $addDeleteArgs
328 public static function getEntityFile($entityTable, $entityID, $addDeleteArgs = FALSE) {
329 if (empty($entityTable) ||
!$entityID) {
334 $config = CRM_Core_Config
::singleton();
336 list($sql, $params) = self
::sql($entityTable, $entityID, NULL);
337 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
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
;
347 $result['url'] = CRM_Utils_System
::url('civicrm/file', "reset=1&id={$dao->cfID}&eid={$dao->entity_id}");
348 $result['href'] = "<a href=\"{$result['url']}\">{$result['cleanName']}</a>";
349 $result['tag'] = CRM_Core_BAO_EntityTag
::getTag($dao->cfID
, 'civicrm_file');
350 $result['icon'] = CRM_Utils_File
::getIconFromMimeType($dao->mime_type
);
351 if ($addDeleteArgs) {
352 $result['deleteURLArgs'] = self
::deleteURLArgs($dao->entity_table
, $dao->entity_id
, $dao->cfID
);
354 $results[$dao->cfID
] = $result;
358 $tags = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
360 foreach ($results as &$values) {
361 if (!empty($values['tag'])) {
363 foreach ($values['tag'] as $tid) {
364 $tagNames[] = $tags[$tid];
366 $values['tag'] = implode(', ', $tagNames);
378 * @param string $entityTable
379 * Table-name or "*" (to reference files directly by file-id).
380 * @param int $entityID
381 * @param int $fileTypeID
386 public static function sql($entityTable, $entityID, $fileTypeID = NULL, $fileID = NULL) {
387 if ($entityTable == '*') {
388 // $entityID is the ID of a specific file
390 SELECT CF.id as cfID,
392 CF.mime_type as mime_type,
393 CF.description as description,
395 CEF.entity_table as entity_table,
396 CEF.entity_id as entity_id
397 FROM civicrm_file AS CF
398 LEFT JOIN civicrm_entity_file AS CEF ON ( CEF.file_id = CF.id )
404 SELECT CF.id as cfID,
406 CF.mime_type as mime_type,
407 CF.description as description,
409 CEF.entity_table as entity_table,
410 CEF.entity_id as entity_id
411 FROM civicrm_file AS CF
412 LEFT JOIN civicrm_entity_file AS CEF ON ( CEF.file_id = CF.id )
413 WHERE CEF.entity_table = %1
414 AND CEF.entity_id = %2";
418 1 => array($entityTable, 'String'),
419 2 => array($entityID, 'Integer'),
422 if ($fileTypeID !== NULL) {
423 $sql .= " AND CF.file_type_id = %3";
424 $params[3] = array($fileTypeID, 'Integer');
427 if ($fileID !== NULL) {
428 $sql .= " AND CF.id = %4";
429 $params[4] = array($fileID, 'Integer');
432 return array($sql, $params);
436 * @param CRM_Core_Form $form
437 * @param string $entityTable
438 * @param int $entityID
439 * @param null $numAttachments
440 * @param bool $ajaxDelete
442 public static function buildAttachment(&$form, $entityTable, $entityID = NULL, $numAttachments = NULL, $ajaxDelete = FALSE) {
444 if (!$numAttachments) {
445 $numAttachments = Civi
::settings()->get('max_attachments');
447 // Assign maxAttachments count to template for help message
448 $form->assign('maxAttachments', $numAttachments);
450 $config = CRM_Core_Config
::singleton();
451 // set default max file size as 2MB
452 $maxFileSize = $config->maxFileSize ?
$config->maxFileSize
: 2;
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);
462 $form->assign('currentAttachmentInfo', NULL);
465 if ($totalAttachments) {
466 if ($totalAttachments >= $numAttachments) {
470 $numAttachments -= $totalAttachments;
474 $form->assign('numAttachments', $numAttachments);
476 CRM_Core_BAO_Tag
::getTags('civicrm_file', $tags, NULL,
477 ' ', TRUE);
480 $parentNames = CRM_Core_BAO_Tag
::getTagSet('civicrm_file');
483 for ($i = 1; $i <= $numAttachments; $i++
) {
484 $form->addElement('file', "attachFile_$i", ts('Attach File'), 'size=30 maxlength=221');
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)
492 $maxFileSize * 1024 * 1024
494 $form->addElement('text', "attachDesc_$i", NULL, array(
497 'placeholder' => ts('Description'),
501 $form->add('select', "tag_$i", ts('Tags'), $tags, FALSE,
504 'multiple' => 'multiple',
505 'class' => 'huge crm-select2',
506 'placeholder' => ts('- none -'),
510 CRM_Core_Form_Tag
::buildQuickForm($form, $parentNames, 'civicrm_file', NULL, FALSE, TRUE, "file_taglist_$i");
515 * Return a clean url string and the number of attachment for a
516 * given entityTable, entityID
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.
526 * An array with 2 elements. The string and the number of attachments
528 public static function attachmentInfo($entityTable, $entityID, $separator = '<br />') {
533 $currentAttachments = self
::getEntityFile($entityTable, $entityID);
534 if (!empty($currentAttachments)) {
535 $currentAttachmentURL = array();
536 foreach ($currentAttachments as $fileID => $attach) {
537 $currentAttachmentURL[] = $attach['href'];
539 return implode($separator, $currentAttachmentURL);
546 * @param array $params
547 * @param $entityTable
548 * @param int $entityID
550 public static function formatAttachment(
557 // delete current attachments if applicable
558 if ($entityID && !empty($formValues['is_delete_attachment'])) {
559 CRM_Core_BAO_File
::deleteEntityFile($entityTable, $entityID);
562 $numAttachments = Civi
::settings()->get('max_attachments');
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;
579 // we dont care if the file is empty or not
581 $extraParams = array(
582 'description' => $formValues[$attachDesc],
584 'attachment_taglist' => CRM_Utils_Array
::value($attachFreeTags, $formValues, array()),
587 CRM_Utils_File
::formatFile($formValues, $attachName, $extraParams);
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];
599 * @param array $params
600 * @param $entityTable
601 * @param int $entityID
603 public static function processAttachment(&$params, $entityTable, $entityID) {
604 $numAttachments = Civi
::settings()->get('max_attachments');
606 for ($i = 1; $i <= $numAttachments; $i++
) {
608 isset($params["attachFile_$i"]) &&
609 is_array($params["attachFile_$i"])
611 self
::filePostProcess(
612 $params["attachFile_$i"]['location'],
618 $params["attachFile_$i"],
620 $params["attachFile_$i"]['type']
629 public static function uploadNames() {
630 $numAttachments = Civi
::settings()->get('max_attachments');
633 for ($i = 1; $i <= $numAttachments; $i++
) {
634 $names[] = "attachFile_{$i}";
636 $names[] = 'uploadFile';
641 * copy/attach an existing file to a different entity
644 * @param $oldEntityTable
645 * @param int $oldEntityId
646 * @param $newEntityTable
647 * @param int $newEntityId
649 public static function copyEntityFile($oldEntityTable, $oldEntityId, $newEntityTable, $newEntityId) {
650 $oldEntityFile = new CRM_Core_DAO_EntityFile();
651 $oldEntityFile->entity_id
= $oldEntityId;
652 $oldEntityFile->entity_table
= $oldEntityTable;
653 $oldEntityFile->find();
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();
665 * @param $entityTable
666 * @param int $entityID
671 public static function deleteURLArgs($entityTable, $entityID, $fileID) {
672 $params['entityTable'] = $entityTable;
673 $params['entityID'] = $entityID;
674 $params['fileID'] = $fileID;
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);
682 * Delete a file attachment from an entity table / entity ID
685 public static function deleteAttachment() {
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);
691 $signature = CRM_Utils_Request
::retrieve('_sgn', 'String', CRM_Core_DAO
::$_nullObject, TRUE);
693 $signer = new CRM_Utils_Signer(CRM_Core_Key
::privateKey(), self
::$_signableFields);
694 if (!$signer->validate($signature, $params)) {
695 CRM_Core_Error
::fatal('Request signature is invalid');
698 self
::deleteEntityFile($params['entityTable'], $params['entityID'], NULL, $params['fileID']);
703 * Display paper icon for a file attachment -- CRM-13624
705 * @param string $entityTable
706 * The entityTable to which the file is attached. eg "civicrm_contact", "civicrm_note", "civicrm_activity".
707 * If you have the ID of a specific row in civicrm_file, use $entityTable='*'
708 * @param int $entityID
709 * The id of the object in the above entityTable.
712 * list of HTML snippets; one HTML snippet for each attachment. If none found, then NULL
715 public static function paperIconAttachment($entityTable, $entityID) {
716 if (empty($entityTable) ||
!$entityID) {
720 $currentAttachmentInfo = self
::getEntityFile($entityTable, $entityID);
721 foreach ($currentAttachmentInfo as $fileKey => $fileValue) {
722 $fileID = $fileValue['fileID'];
724 $fileType = $fileValue['mime_type'];
725 $url = $fileValue['url'];
726 $title = $fileValue['cleanName'];
727 if ($fileType == 'image/jpeg' ||
728 $fileType == 'image/pjpeg' ||
729 $fileType == 'image/gif' ||
730 $fileType == 'image/x-png' ||
731 $fileType == 'image/png'
733 $file_url[$fileID] = "
734 <a href='$url' class='crm-image-popup' title='$title'>
735 <i class='crm-i fa-file-image-o'></i>
738 // for non image files
740 $file_url[$fileID] = "
741 <a href='$url' title='$title'>
742 <i class='crm-i fa-paperclip'></i>
747 if (empty($file_url)) {
751 $results = $file_url;
757 * Get a reference to the file-search service (if one is available).
759 * @return CRM_Core_FileSearchInterface|NULL
761 public static function getSearchService() {
762 $fileSearches = array();
763 CRM_Utils_Hook
::fileSearches($fileSearches);
765 // use the first available search
766 foreach ($fileSearches as $fileSearch) {
767 /** @var $fileSearch CRM_Core_FileSearchInterface */