3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
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');
46 * @param null $entityTable
50 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);
80 * @param $entitySubtype
81 * @param bool $overwrite
82 * @param null|array $fileParams
83 * @param string $uploadName
84 * @param null $mimeType
88 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
224 static function deleteEntityFile($entityTable, $entityID, $fileTypeID = NULL, $fileID = NULL) {
225 if (empty($entityTable) ||
empty($entityID)) {
229 $config = CRM_Core_Config
::singleton();
231 list($sql, $params) = self
::sql($entityTable, $entityID, $fileTypeID, $fileID);
232 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
236 while ($dao->fetch()) {
237 $cfIDs[$dao->cfID
] = $dao->uri
;
238 $cefIDs[] = $dao->cefID
;
241 if (!empty($cefIDs)) {
242 $cefIDs = implode(',', $cefIDs);
243 $sql = "DELETE FROM civicrm_entity_file where id IN ( $cefIDs )";
244 CRM_Core_DAO
::executeQuery($sql);
247 if (!empty($cfIDs)) {
248 // Delete file only if there no any entity using this file.
249 $deleteFiles = array();
250 foreach ($cfIDs as $fId => $fUri) {
251 //delete tags from entity tag table
253 'entity_table' => 'civicrm_file',
257 CRM_Core_BAO_EntityTag
::del($tagParams);
259 if (!CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile', $fId, 'id', 'file_id')) {
260 unlink($config->customFileUploadDir
. DIRECTORY_SEPARATOR
. $fUri);
261 $deleteFiles[$fId] = $fId;
265 if (!empty($deleteFiles)) {
266 $deleteFiles = implode(',', $deleteFiles);
267 $sql = "DELETE FROM civicrm_file where id IN ( $deleteFiles )";
268 CRM_Core_DAO
::executeQuery($sql);
274 * get all the files and associated object associated with this
277 static function getEntityFile($entityTable, $entityID, $addDeleteArgs = FALSE) {
278 if (empty($entityTable) ||
!$entityID) {
283 $config = CRM_Core_Config
::singleton();
285 list($sql, $params) = self
::sql($entityTable, $entityID, NULL);
286 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
288 while ($dao->fetch()) {
289 $result['fileID'] = $dao->cfID
;
290 $result['entityID'] = $dao->cefID
;
291 $result['mime_type'] = $dao->mime_type
;
292 $result['fileName'] = $dao->uri
;
293 $result['description'] = $dao->description
;
294 $result['cleanName'] = CRM_Utils_File
::cleanFileName($dao->uri
);
295 $result['fullPath'] = $config->customFileUploadDir
. DIRECTORY_SEPARATOR
. $dao->uri
;
296 $result['url'] = CRM_Utils_System
::url('civicrm/file', "reset=1&id={$dao->cfID}&eid={$dao->entity_id}");
297 $result['href'] = "<a href=\"{$result['url']}\">{$result['cleanName']}</a>";
298 $result['tag'] = CRM_Core_BAO_EntityTag
::getTag($dao->cfID
, 'civicrm_file');
299 if ($addDeleteArgs) {
300 $result['deleteURLArgs'] = self
::deleteURLArgs($dao->entity_table
, $dao->entity_id
, $dao->cfID
);
302 $results[$dao->cfID
] = $result;
306 $tags = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
308 foreach ($results as &$values) {
309 if (!empty($values['tag'])) {
311 foreach ($values['tag'] as $tid) {
312 $tagNames[] = $tags[$tid];
314 $values['tag'] = implode(', ', $tagNames);
326 * @param string $entityTable table-name or "*" (to reference files directly by file-id)
327 * @param int $entityID
328 * @param null $fileTypeID
329 * @param null $fileID
333 static function sql($entityTable, $entityID, $fileTypeID = NULL, $fileID = NULL) {
334 if ($entityTable == '*') {
335 // $entityID is the ID of a specific file
337 SELECT CF.id as cfID,
339 CF.mime_type as mime_type,
340 CF.description as description,
342 CEF.entity_table as entity_table,
343 CEF.entity_id as entity_id
344 FROM civicrm_file AS CF
345 LEFT JOIN civicrm_entity_file AS CEF ON ( CEF.file_id = CF.id )
350 SELECT CF.id as cfID,
352 CF.mime_type as mime_type,
353 CF.description as description,
355 CEF.entity_table as entity_table,
356 CEF.entity_id as entity_id
357 FROM civicrm_file AS CF
358 LEFT JOIN civicrm_entity_file AS CEF ON ( CEF.file_id = CF.id )
359 WHERE CEF.entity_table = %1
360 AND CEF.entity_id = %2";
364 1 => array($entityTable, 'String'),
365 2 => array($entityID, 'Integer'),
368 if ($fileTypeID !== NULL) {
369 $sql .= " AND CF.file_type_id = %3";
370 $params[3] = array($fileTypeID, 'Integer');
373 if ($fileID !== NULL) {
374 $sql .= " AND CF.id = %4";
375 $params[4] = array($fileID, 'Integer');
378 return array($sql, $params);
382 * @param CRM_Core_Form $form
383 * @param string $entityTable
384 * @param null $entityID
385 * @param null $numAttachments
386 * @param bool $ajaxDelete
388 static function buildAttachment(&$form, $entityTable, $entityID = NULL, $numAttachments = NULL, $ajaxDelete = FALSE) {
390 if (!$numAttachments) {
391 $numAttachments = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'max_attachments');
393 // Assign maxAttachments count to template for help message
394 $form->assign('maxAttachments', $numAttachments);
396 $config = CRM_Core_Config
::singleton();
397 // set default max file size as 2MB
398 $maxFileSize = $config->maxFileSize ?
$config->maxFileSize
: 2;
400 $currentAttachmentInfo = self
::getEntityFile($entityTable, $entityID, TRUE);
401 $totalAttachments = 0;
402 if ($currentAttachmentInfo) {
403 $totalAttachments = count($currentAttachmentInfo);
404 $form->add('checkbox', 'is_delete_attachment', ts('Delete All Attachment(s)'));
405 $form->assign('currentAttachmentInfo', $currentAttachmentInfo);
408 $form->assign('currentAttachmentInfo', NULL);
411 if ($totalAttachments) {
412 if ($totalAttachments >= $numAttachments) {
416 $numAttachments -= $totalAttachments;
420 $form->assign('numAttachments', $numAttachments);
422 $tags = CRM_Core_BAO_Tag
::getTags('civicrm_file');
425 $parentNames = CRM_Core_BAO_Tag
::getTagSet('civicrm_file');
428 for ($i = 1; $i <= $numAttachments; $i++
) {
429 $form->addElement('file', "attachFile_$i", ts('Attach File'), 'size=30 maxlength=60');
430 $form->addUploadElement("attachFile_$i");
431 $form->setMaxFileSize($maxFileSize * 1024 * 1024);
432 $form->addRule("attachFile_$i",
433 ts('File size should be less than %1 MByte(s)',
434 array(1 => $maxFileSize)
437 $maxFileSize * 1024 * 1024
439 $form->addElement('text', "attachDesc_$i", NULL, array(
442 'placeholder' => ts('Description')
446 $form->add('select', "tag_$i", ts('Tags'), $tags, FALSE,
449 'multiple' => 'multiple',
450 'class' => 'huge crm-select2',
451 'placeholder' => ts('- none -')
455 CRM_Core_Form_Tag
::buildQuickForm($form, $parentNames, 'civicrm_file', NULL, FALSE, TRUE, "file_taglist_$i");
460 * Function to return a clean url string and the number of attachment for a
461 * given entityTable, entityID
463 * @param $entityTable string The entityTable to which the file is attached
464 * @param $entityID int The id of the object in the above entityTable
465 * @param $separator string The string separator where to implode the urls
467 * @return array An array with 2 elements. The string and the number of attachments
470 static function attachmentInfo($entityTable, $entityID, $separator = '<br />') {
475 $currentAttachments = self
::getEntityFile($entityTable, $entityID);
476 if (!empty($currentAttachments)) {
477 $currentAttachmentURL = array();
478 foreach ($currentAttachments as $fileID => $attach) {
479 $currentAttachmentURL[] = $attach['href'];
481 return implode($separator, $currentAttachmentURL);
489 * @param $entityTable
490 * @param null $entityID
492 static function formatAttachment(
499 // delete current attachments if applicable
500 if ($entityID && !empty($formValues['is_delete_attachment'])) {
501 CRM_Core_BAO_File
::deleteEntityFile($entityTable, $entityID);
504 $numAttachments = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'max_attachments');
506 $now = date('Ymdhis');
508 // setup all attachments
509 for ($i = 1; $i <= $numAttachments; $i++
) {
510 $attachName = "attachFile_$i";
511 $attachDesc = "attachDesc_$i";
512 $attachTags = "tag_$i";
513 $attachFreeTags = "file_taglist_$i";
514 if (isset($formValues[$attachName]) && !empty($formValues[$attachName])) {
515 // add static tags if selects
516 $tagParams = array();
517 if (!empty($formValues[$attachTags])) {
518 foreach ($formValues[$attachTags] as $tag) {
519 $tagParams[$tag] = 1;
523 // we dont care if the file is empty or not
526 'uri' => $formValues[$attachName]['name'],
527 'type' => $formValues[$attachName]['type'],
528 'location' => $formValues[$attachName]['name'],
529 'description' => $formValues[$attachDesc],
530 'upload_date' => $now,
532 'attachment_taglist' => CRM_Utils_Array
::value($attachFreeTags, $formValues, array())
535 $params[$attachName] = $fileParams;
542 * @param $entityTable
545 static function processAttachment(&$params, $entityTable, $entityID) {
546 $numAttachments = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'max_attachments');
548 for ($i = 1; $i <= $numAttachments; $i++
) {
550 isset($params["attachFile_$i"]) &&
551 is_array($params["attachFile_$i"])
553 self
::filePostProcess(
554 $params["attachFile_$i"]['location'],
560 $params["attachFile_$i"],
562 $params["attachFile_$i"]['type']
571 static function uploadNames() {
572 $numAttachments = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'max_attachments');
575 for ($i = 1; $i <= $numAttachments; $i++
) {
576 $names[] = "attachFile_{$i}";
578 $names[] = 'uploadFile';
583 * Function to copy/attach an existing file to a different entity
587 * @param $oldEntityTable
588 * @param $oldEntityId
589 * @param $newEntityTable
590 * @param $newEntityId
592 static function copyEntityFile($oldEntityTable, $oldEntityId, $newEntityTable, $newEntityId) {
593 $oldEntityFile = new CRM_Core_DAO_EntityFile();
594 $oldEntityFile->entity_id
= $oldEntityId;
595 $oldEntityFile->entity_table
= $oldEntityTable;
596 $oldEntityFile->find();
598 while ($oldEntityFile->fetch()) {
599 $newEntityFile = new CRM_Core_DAO_EntityFile();
600 $newEntityFile->entity_id
= $newEntityId;
601 $newEntityFile->entity_table
= $newEntityTable;
602 $newEntityFile->file_id
= $oldEntityFile->file_id
;
603 $newEntityFile->save();
608 * @param $entityTable
614 static function deleteURLArgs($entityTable, $entityID, $fileID) {
615 $params['entityTable'] = $entityTable;
616 $params['entityID'] = $entityID;
617 $params['fileID'] = $fileID;
619 $signer = new CRM_Utils_Signer(CRM_Core_Key
::privateKey(), self
::$_signableFields);
620 $params['_sgn'] = $signer->sign($params);
621 return CRM_Utils_System
::makeQueryString($params);
625 * function to delete a file attachment from an entity table / entity ID
630 static function deleteAttachment() {
632 $params['entityTable'] = CRM_Utils_Request
::retrieve('entityTable', 'String', CRM_Core_DAO
::$_nullObject, TRUE);
633 $params['entityID'] = CRM_Utils_Request
::retrieve('entityID', 'Positive', CRM_Core_DAO
::$_nullObject, TRUE);
634 $params['fileID'] = CRM_Utils_Request
::retrieve('fileID', 'Positive', CRM_Core_DAO
::$_nullObject, TRUE);
636 $signature = CRM_Utils_Request
::retrieve('_sgn', 'String', CRM_Core_DAO
::$_nullObject, TRUE);
638 $signer = new CRM_Utils_Signer(CRM_Core_Key
::privateKey(), self
::$_signableFields);
639 if (!$signer->validate($signature, $params)) {
640 CRM_Core_Error
::fatal('Request signature is invalid');
643 CRM_Core_BAO_File
::deleteEntityFile($params['entityTable'], $params['entityID'], NULL, $params['fileID']);
648 * function to display paper icon for a file attachment -- CRM-13624
650 * @param $entityTable string The entityTable to which the file is attached. eg "civicrm_contact", "civicrm_note", "civicrm_activity"
651 * If you have the ID of a specific row in civicrm_file, use $entityTable='*'
652 * @param $entityID int The id of the object in the above entityTable
654 * @return array|NULL list of HTML snippets; one HTML snippet for each attachment. If none found, then NULL
659 static function paperIconAttachment($entityTable, $entityID) {
660 if (empty($entityTable) ||
!$entityID) {
664 $currentAttachmentInfo = self
::getEntityFile($entityTable, $entityID);
665 foreach ($currentAttachmentInfo as $fileKey => $fileValue) {
666 $fileID = $fileValue['fileID'];
667 $fileType = $fileValue['mime_type'];
670 if ($fileType == 'image/jpeg' ||
671 $fileType == 'image/pjpeg' ||
672 $fileType == 'image/gif' ||
673 $fileType == 'image/x-png' ||
674 $fileType == 'image/png'
676 $url = $fileValue['url'];
677 $alt = $fileValue['cleanName'];
678 $file_url[$fileID] = "
679 <a href=\"$url\" class='crm-image-popup'>
680 <div class='icon paper-icon' title=\"$alt\" alt=\"$alt\"></div>
682 // for non image files
685 $url = $fileValue['url'];
686 $alt = $fileValue['cleanName'];
687 $file_url[$fileID] = "<a href=\"$url\"><div class='icon paper-icon' title=\"$alt\" alt=\"$alt\"></div></a>";
691 if (empty($file_url)) {
695 $results = $file_url;
701 * Get a reference to the file-search service (if one is available).
703 * @return CRM_Core_FileSearchInterface|NULL
705 static function getSearchService() {
706 $fileSearches = array();
707 CRM_Utils_Hook
::fileSearches($fileSearches);
709 // use the first available search
710 foreach ($fileSearches as $fileSearch) {
711 /** @var $fileSearch CRM_Core_FileSearchInterface */