3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
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');
45 * @param int $entityID
46 * @param null $entityTable
50 public static function path($fileID, $entityID, $entityTable = NULL) {
51 $entityFileDAO = new CRM_Core_DAO_EntityFile();
53 $entityFileDAO->entity_table
= $entityTable;
55 $entityFileDAO->entity_id
= $entityID;
56 $entityFileDAO->file_id
= $fileID;
58 if ($entityFileDAO->find(TRUE)) {
59 $fileDAO = new CRM_Core_DAO_File();
60 $fileDAO->id
= $fileID;
61 if ($fileDAO->find(TRUE)) {
62 $config = CRM_Core_Config
::singleton();
63 $path = $config->customFileUploadDir
. $fileDAO->uri
;
65 if (file_exists($path) && is_readable($path)) {
66 return array($path, $fileDAO->mime_type
);
71 return array(NULL, NULL);
77 * @param int $fileTypeID
79 * @param int $entityID
80 * @param $entitySubtype
81 * @param bool $overwrite
82 * @param null|array $fileParams
83 * @param string $uploadName
84 * @param null $mimeType
88 public static function filePostProcess(
96 $uploadName = 'uploadFile',
100 CRM_Core_Error
::fatal(ts('Mime Type is now a required parameter'));
103 $config = CRM_Core_Config
::singleton();
105 $path = explode('/', $data);
106 $filename = $path[count($path) - 1];
108 // rename this file to go into the secure directory
109 if ($entitySubtype) {
110 $directoryName = $config->customFileUploadDir
. $entitySubtype . DIRECTORY_SEPARATOR
. $entityID;
113 $directoryName = $config->customFileUploadDir
;
116 CRM_Utils_File
::createDir($directoryName);
118 if (!rename($data, $directoryName . DIRECTORY_SEPARATOR
. $filename)) {
119 CRM_Core_Error
::fatal(ts('Could not move custom file to custom upload directory'));
123 if ($overwrite && $fileTypeID) {
124 list($sql, $params) = self
::sql($entityTable, $entityID, $fileTypeID);
127 list($sql, $params) = self
::sql($entityTable, $entityID, 0);
130 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
133 $fileDAO = new CRM_Core_DAO_File();
135 if (isset($dao->cfID
) && $dao->cfID
) {
137 $fileDAO->id
= $dao->cfID
;
138 unlink($directoryName . DIRECTORY_SEPARATOR
. $dao->uri
);
141 if (!empty($fileParams)) {
142 $fileDAO->copyValues($fileParams);
145 $fileDAO->uri
= $filename;
146 $fileDAO->mime_type
= $mimeType;
147 $fileDAO->file_type_id
= $fileTypeID;
148 $fileDAO->upload_date
= date('Ymdhis');
151 // need to add/update civicrm_entity_file
152 $entityFileDAO = new CRM_Core_DAO_EntityFile();
153 if (isset($dao->cefID
) && $dao->cefID
) {
154 $entityFileDAO->id
= $dao->cefID
;
156 $entityFileDAO->entity_table
= $entityTable;
157 $entityFileDAO->entity_id
= $entityID;
158 $entityFileDAO->file_id
= $fileDAO->id
;
159 $entityFileDAO->save();
162 if (!empty($fileParams['tag'])) {
163 CRM_Core_BAO_EntityTag
::create($fileParams['tag'], 'civicrm_file', $entityFileDAO->id
);
167 if (isset($fileParams['attachment_taglist']) && !empty($fileParams['attachment_taglist'])) {
168 CRM_Core_Form_Tag
::postProcess($fileParams['attachment_taglist'], $entityFileDAO->id
, 'civicrm_file', CRM_Core_DAO
::$_nullObject);
171 // lets call the post hook here so attachments code can do the right stuff
172 CRM_Utils_Hook
::post($op, 'File', $fileDAO->id
, $fileDAO);
176 * A static function wrapper that deletes the various objects that are
177 * connected to a file object (i.e. file, entityFile and customValue
179 public static function deleteFileReferences($fileID, $entityID, $fieldID) {
180 $fileDAO = new CRM_Core_DAO_File();
181 $fileDAO->id
= $fileID;
182 if (!$fileDAO->find(TRUE)) {
183 CRM_Core_Error
::fatal();
186 // lets call a pre hook before the delete, so attachments hooks can get the info before things
188 CRM_Utils_Hook
::pre('delete', 'File', $fileID, $fileDAO);
190 // get the table and column name
191 list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField
::getTableColumnGroup($fieldID);
193 $entityFileDAO = new CRM_Core_DAO_EntityFile();
194 $entityFileDAO->file_id
= $fileID;
195 $entityFileDAO->entity_id
= $entityID;
196 $entityFileDAO->entity_table
= $tableName;
198 if (!$entityFileDAO->find(TRUE)) {
199 CRM_Core_Error
::fatal();
202 $entityFileDAO->delete();
205 // also set the value to null of the table and column
206 $query = "UPDATE $tableName SET $columnName = null WHERE $columnName = %1";
207 $params = array(1 => array($fileID, 'Integer'));
208 CRM_Core_DAO
::executeQuery($query, $params);
212 * The $useWhere is used so that the signature matches the parent class
214 * public function delete($useWhere = FALSE) {
215 * list($fileID, $entityID, $fieldID) = func_get_args();
217 * self::deleteFileReferences($fileID, $entityID, $fieldID);
221 * Delete all the files and associated object associated with this
226 public static function deleteEntityFile($entityTable, $entityID, $fileTypeID = NULL, $fileID = NULL) {
228 if (empty($entityTable) ||
empty($entityID)) {
232 $config = CRM_Core_Config
::singleton();
234 list($sql, $params) = self
::sql($entityTable, $entityID, $fileTypeID, $fileID);
235 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
239 while ($dao->fetch()) {
240 $cfIDs[$dao->cfID
] = $dao->uri
;
241 $cefIDs[] = $dao->cefID
;
244 if (!empty($cefIDs)) {
245 $cefIDs = implode(',', $cefIDs);
246 $sql = "DELETE FROM civicrm_entity_file where id IN ( $cefIDs )";
247 CRM_Core_DAO
::executeQuery($sql);
251 if (!empty($cfIDs)) {
252 // Delete file only if there no any entity using this file.
253 $deleteFiles = array();
254 foreach ($cfIDs as $fId => $fUri) {
255 //delete tags from entity tag table
257 'entity_table' => 'civicrm_file',
261 CRM_Core_BAO_EntityTag
::del($tagParams);
263 if (!CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile', $fId, 'id', 'file_id')) {
264 unlink($config->customFileUploadDir
. DIRECTORY_SEPARATOR
. $fUri);
265 $deleteFiles[$fId] = $fId;
269 if (!empty($deleteFiles)) {
270 $deleteFiles = implode(',', $deleteFiles);
271 $sql = "DELETE FROM civicrm_file where id IN ( $deleteFiles )";
272 CRM_Core_DAO
::executeQuery($sql);
280 * Get all the files and associated object associated with this
283 public static function getEntityFile($entityTable, $entityID, $addDeleteArgs = FALSE) {
284 if (empty($entityTable) ||
!$entityID) {
289 $config = CRM_Core_Config
::singleton();
291 list($sql, $params) = self
::sql($entityTable, $entityID, NULL);
292 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
294 while ($dao->fetch()) {
295 $result['fileID'] = $dao->cfID
;
296 $result['entityID'] = $dao->cefID
;
297 $result['mime_type'] = $dao->mime_type
;
298 $result['fileName'] = $dao->uri
;
299 $result['description'] = $dao->description
;
300 $result['cleanName'] = CRM_Utils_File
::cleanFileName($dao->uri
);
301 $result['fullPath'] = $config->customFileUploadDir
. DIRECTORY_SEPARATOR
. $dao->uri
;
302 $result['url'] = CRM_Utils_System
::url('civicrm/file', "reset=1&id={$dao->cfID}&eid={$dao->entity_id}");
303 $result['href'] = "<a href=\"{$result['url']}\">{$result['cleanName']}</a>";
304 $result['tag'] = CRM_Core_BAO_EntityTag
::getTag($dao->cfID
, 'civicrm_file');
305 if ($addDeleteArgs) {
306 $result['deleteURLArgs'] = self
::deleteURLArgs($dao->entity_table
, $dao->entity_id
, $dao->cfID
);
308 $results[$dao->cfID
] = $result;
312 $tags = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
314 foreach ($results as &$values) {
315 if (!empty($values['tag'])) {
317 foreach ($values['tag'] as $tid) {
318 $tagNames[] = $tags[$tid];
320 $values['tag'] = implode(', ', $tagNames);
332 * @param string $entityTable
333 * Table-name or "*" (to reference files directly by file-id).
334 * @param int $entityID
335 * @param int $fileTypeID
340 public static function sql($entityTable, $entityID, $fileTypeID = NULL, $fileID = NULL) {
341 if ($entityTable == '*') {
342 // $entityID is the ID of a specific file
344 SELECT CF.id as cfID,
346 CF.mime_type as mime_type,
347 CF.description as description,
349 CEF.entity_table as entity_table,
350 CEF.entity_id as entity_id
351 FROM civicrm_file AS CF
352 LEFT JOIN civicrm_entity_file AS CEF ON ( CEF.file_id = CF.id )
358 SELECT CF.id as cfID,
360 CF.mime_type as mime_type,
361 CF.description as description,
363 CEF.entity_table as entity_table,
364 CEF.entity_id as entity_id
365 FROM civicrm_file AS CF
366 LEFT JOIN civicrm_entity_file AS CEF ON ( CEF.file_id = CF.id )
367 WHERE CEF.entity_table = %1
368 AND CEF.entity_id = %2";
372 1 => array($entityTable, 'String'),
373 2 => array($entityID, 'Integer'),
376 if ($fileTypeID !== NULL) {
377 $sql .= " AND CF.file_type_id = %3";
378 $params[3] = array($fileTypeID, 'Integer');
381 if ($fileID !== NULL) {
382 $sql .= " AND CF.id = %4";
383 $params[4] = array($fileID, 'Integer');
386 return array($sql, $params);
390 * @param CRM_Core_Form $form
391 * @param string $entityTable
392 * @param int $entityID
393 * @param null $numAttachments
394 * @param bool $ajaxDelete
396 public static function buildAttachment(&$form, $entityTable, $entityID = NULL, $numAttachments = NULL, $ajaxDelete = FALSE) {
398 if (!$numAttachments) {
399 $numAttachments = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'max_attachments');
401 // Assign maxAttachments count to template for help message
402 $form->assign('maxAttachments', $numAttachments);
404 $config = CRM_Core_Config
::singleton();
405 // set default max file size as 2MB
406 $maxFileSize = $config->maxFileSize ?
$config->maxFileSize
: 2;
408 $currentAttachmentInfo = self
::getEntityFile($entityTable, $entityID, TRUE);
409 $totalAttachments = 0;
410 if ($currentAttachmentInfo) {
411 $totalAttachments = count($currentAttachmentInfo);
412 $form->add('checkbox', 'is_delete_attachment', ts('Delete All Attachment(s)'));
413 $form->assign('currentAttachmentInfo', $currentAttachmentInfo);
416 $form->assign('currentAttachmentInfo', NULL);
419 if ($totalAttachments) {
420 if ($totalAttachments >= $numAttachments) {
424 $numAttachments -= $totalAttachments;
428 $form->assign('numAttachments', $numAttachments);
430 CRM_Core_BAO_Tag
::getTags('civicrm_file', $tags, NULL,
431 ' ', TRUE);
434 $parentNames = CRM_Core_BAO_Tag
::getTagSet('civicrm_file');
437 for ($i = 1; $i <= $numAttachments; $i++
) {
438 $form->addElement('file', "attachFile_$i", ts('Attach File'), 'size=30 maxlength=60');
439 $form->addUploadElement("attachFile_$i");
440 $form->setMaxFileSize($maxFileSize * 1024 * 1024);
441 $form->addRule("attachFile_$i",
442 ts('File size should be less than %1 MByte(s)',
443 array(1 => $maxFileSize)
446 $maxFileSize * 1024 * 1024
448 $form->addElement('text', "attachDesc_$i", NULL, array(
451 'placeholder' => ts('Description'),
455 $form->add('select', "tag_$i", ts('Tags'), $tags, FALSE,
458 'multiple' => 'multiple',
459 'class' => 'huge crm-select2',
460 'placeholder' => ts('- none -'),
464 CRM_Core_Form_Tag
::buildQuickForm($form, $parentNames, 'civicrm_file', NULL, FALSE, TRUE, "file_taglist_$i");
469 * Return a clean url string and the number of attachment for a
470 * given entityTable, entityID
472 * @param string $entityTable
473 * The entityTable to which the file is attached.
474 * @param int $entityID
475 * The id of the object in the above entityTable.
476 * @param string $separator
477 * The string separator where to implode the urls.
480 * An array with 2 elements. The string and the number of attachments
482 public static function attachmentInfo($entityTable, $entityID, $separator = '<br />') {
487 $currentAttachments = self
::getEntityFile($entityTable, $entityID);
488 if (!empty($currentAttachments)) {
489 $currentAttachmentURL = array();
490 foreach ($currentAttachments as $fileID => $attach) {
491 $currentAttachmentURL[] = $attach['href'];
493 return implode($separator, $currentAttachmentURL);
500 * @param array $params
501 * @param $entityTable
502 * @param int $entityID
504 public static function formatAttachment(
511 // delete current attachments if applicable
512 if ($entityID && !empty($formValues['is_delete_attachment'])) {
513 CRM_Core_BAO_File
::deleteEntityFile($entityTable, $entityID);
516 $numAttachments = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'max_attachments');
518 $now = date('Ymdhis');
520 // setup all attachments
521 for ($i = 1; $i <= $numAttachments; $i++
) {
522 $attachName = "attachFile_$i";
523 $attachDesc = "attachDesc_$i";
524 $attachTags = "tag_$i";
525 $attachFreeTags = "file_taglist_$i";
526 if (isset($formValues[$attachName]) && !empty($formValues[$attachName])) {
527 // add static tags if selects
528 $tagParams = array();
529 if (!empty($formValues[$attachTags])) {
530 foreach ($formValues[$attachTags] as $tag) {
531 $tagParams[$tag] = 1;
535 // we dont care if the file is empty or not
538 'uri' => $formValues[$attachName]['name'],
539 'type' => $formValues[$attachName]['type'],
540 'location' => $formValues[$attachName]['name'],
541 'description' => $formValues[$attachDesc],
542 'upload_date' => $now,
544 'attachment_taglist' => CRM_Utils_Array
::value($attachFreeTags, $formValues, array()),
547 $params[$attachName] = $fileParams;
553 * @param array $params
554 * @param $entityTable
555 * @param int $entityID
557 public static function processAttachment(&$params, $entityTable, $entityID) {
558 $numAttachments = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'max_attachments');
560 for ($i = 1; $i <= $numAttachments; $i++
) {
562 isset($params["attachFile_$i"]) &&
563 is_array($params["attachFile_$i"])
565 self
::filePostProcess(
566 $params["attachFile_$i"]['location'],
572 $params["attachFile_$i"],
574 $params["attachFile_$i"]['type']
583 public static function uploadNames() {
584 $numAttachments = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'max_attachments');
587 for ($i = 1; $i <= $numAttachments; $i++
) {
588 $names[] = "attachFile_{$i}";
590 $names[] = 'uploadFile';
595 * copy/attach an existing file to a different entity
598 * @param $oldEntityTable
599 * @param int $oldEntityId
600 * @param $newEntityTable
601 * @param int $newEntityId
603 public static function copyEntityFile($oldEntityTable, $oldEntityId, $newEntityTable, $newEntityId) {
604 $oldEntityFile = new CRM_Core_DAO_EntityFile();
605 $oldEntityFile->entity_id
= $oldEntityId;
606 $oldEntityFile->entity_table
= $oldEntityTable;
607 $oldEntityFile->find();
609 while ($oldEntityFile->fetch()) {
610 $newEntityFile = new CRM_Core_DAO_EntityFile();
611 $newEntityFile->entity_id
= $newEntityId;
612 $newEntityFile->entity_table
= $newEntityTable;
613 $newEntityFile->file_id
= $oldEntityFile->file_id
;
614 $newEntityFile->save();
619 * @param $entityTable
620 * @param int $entityID
625 public static function deleteURLArgs($entityTable, $entityID, $fileID) {
626 $params['entityTable'] = $entityTable;
627 $params['entityID'] = $entityID;
628 $params['fileID'] = $fileID;
630 $signer = new CRM_Utils_Signer(CRM_Core_Key
::privateKey(), self
::$_signableFields);
631 $params['_sgn'] = $signer->sign($params);
632 return CRM_Utils_System
::makeQueryString($params);
636 * Delete a file attachment from an entity table / entity ID
639 public static function deleteAttachment() {
641 $params['entityTable'] = CRM_Utils_Request
::retrieve('entityTable', 'String', CRM_Core_DAO
::$_nullObject, TRUE);
642 $params['entityID'] = CRM_Utils_Request
::retrieve('entityID', 'Positive', CRM_Core_DAO
::$_nullObject, TRUE);
643 $params['fileID'] = CRM_Utils_Request
::retrieve('fileID', 'Positive', CRM_Core_DAO
::$_nullObject, TRUE);
645 $signature = CRM_Utils_Request
::retrieve('_sgn', 'String', CRM_Core_DAO
::$_nullObject, TRUE);
647 $signer = new CRM_Utils_Signer(CRM_Core_Key
::privateKey(), self
::$_signableFields);
648 if (!$signer->validate($signature, $params)) {
649 CRM_Core_Error
::fatal('Request signature is invalid');
652 CRM_Core_BAO_File
::deleteEntityFile($params['entityTable'], $params['entityID'], NULL, $params['fileID']);
657 * Display paper icon for a file attachment -- CRM-13624
659 * @param string $entityTable
660 * The entityTable to which the file is attached. eg "civicrm_contact", "civicrm_note", "civicrm_activity".
661 * If you have the ID of a specific row in civicrm_file, use $entityTable='*'
662 * @param int $entityID
663 * The id of the object in the above entityTable.
666 * list of HTML snippets; one HTML snippet for each attachment. If none found, then NULL
669 public static function paperIconAttachment($entityTable, $entityID) {
670 if (empty($entityTable) ||
!$entityID) {
674 $currentAttachmentInfo = self
::getEntityFile($entityTable, $entityID);
675 foreach ($currentAttachmentInfo as $fileKey => $fileValue) {
676 $fileID = $fileValue['fileID'];
677 $fileType = $fileValue['mime_type'];
679 if ($fileType == 'image/jpeg' ||
680 $fileType == 'image/pjpeg' ||
681 $fileType == 'image/gif' ||
682 $fileType == 'image/x-png' ||
683 $fileType == 'image/png'
685 $url = $fileValue['url'];
686 $alt = $fileValue['cleanName'];
687 $file_url[$fileID] = "
688 <a href=\"$url\" class='crm-image-popup'>
689 <div class='icon paper-icon' title=\"$alt\" alt=\"$alt\"></div>
691 // for non image files
694 $url = $fileValue['url'];
695 $alt = $fileValue['cleanName'];
696 $file_url[$fileID] = "<a href=\"$url\"><div class='icon paper-icon' title=\"$alt\" alt=\"$alt\"></div></a>";
700 if (empty($file_url)) {
704 $results = $file_url;
710 * Get a reference to the file-search service (if one is available).
712 * @return CRM_Core_FileSearchInterface|NULL
714 public static function getSearchService() {
715 $fileSearches = array();
716 CRM_Utils_Hook
::fileSearches($fileSearches);
718 // use the first available search
719 foreach ($fileSearches as $fileSearch) {
720 /** @var $fileSearch CRM_Core_FileSearchInterface */