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 $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'));
124 if ($overwrite && $fileTypeID) {
125 list($sql, $params) = self
::sql($entityTable, $entityID, $fileTypeID);
128 list($sql, $params) = self
::sql($entityTable, $entityID, 0);
131 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
134 $fileDAO = new CRM_Core_DAO_File();
136 if (isset($dao->cfID
) && $dao->cfID
) {
138 $fileDAO->id
= $dao->cfID
;
139 unlink($directoryName . DIRECTORY_SEPARATOR
. $dao->uri
);
142 if (!empty($fileParams)) {
143 $fileDAO->copyValues($fileParams);
146 $fileDAO->uri
= $filename;
147 $fileDAO->mime_type
= $mimeType;
148 $fileDAO->file_type_id
= $fileTypeID;
149 $fileDAO->upload_date
= date('Ymdhis');
152 // need to add/update civicrm_entity_file
153 $entityFileDAO = new CRM_Core_DAO_EntityFile();
154 if (isset($dao->cefID
) && $dao->cefID
) {
155 $entityFileDAO->id
= $dao->cefID
;
157 $entityFileDAO->entity_table
= $entityTable;
158 $entityFileDAO->entity_id
= $entityID;
159 $entityFileDAO->file_id
= $fileDAO->id
;
160 $entityFileDAO->save();
163 if (!empty($fileParams['tag'])) {
164 CRM_Core_BAO_EntityTag
::create($fileParams['tag'], 'civicrm_file', $entityFileDAO->id
);
168 if (isset($fileParams['attachment_taglist']) && !empty($fileParams['attachment_taglist'])) {
169 CRM_Core_Form_Tag
::postProcess($fileParams['attachment_taglist'], $entityFileDAO->id
, 'civicrm_file', CRM_Core_DAO
::$_nullObject);
172 // lets call the post hook here so attachments code can do the right stuff
173 CRM_Utils_Hook
::post($op, 'File', $fileDAO->id
, $fileDAO);
177 * A static function wrapper that deletes the various objects that are
178 * connected to a file object (i.e. file, entityFile and customValue
180 public static function deleteFileReferences($fileID, $entityID, $fieldID) {
181 $fileDAO = new CRM_Core_DAO_File();
182 $fileDAO->id
= $fileID;
183 if (!$fileDAO->find(TRUE)) {
184 CRM_Core_Error
::fatal();
187 // lets call a pre hook before the delete, so attachments hooks can get the info before things
189 CRM_Utils_Hook
::pre('delete', 'File', $fileID, $fileDAO);
191 // get the table and column name
192 list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField
::getTableColumnGroup($fieldID);
194 $entityFileDAO = new CRM_Core_DAO_EntityFile();
195 $entityFileDAO->file_id
= $fileID;
196 $entityFileDAO->entity_id
= $entityID;
197 $entityFileDAO->entity_table
= $tableName;
199 if (!$entityFileDAO->find(TRUE)) {
200 CRM_Core_Error
::fatal();
203 $entityFileDAO->delete();
206 // also set the value to null of the table and column
207 $query = "UPDATE $tableName SET $columnName = null WHERE $columnName = %1";
208 $params = array(1 => array($fileID, 'Integer'));
209 CRM_Core_DAO
::executeQuery($query, $params);
213 * The $useWhere is used so that the signature matches the parent class
215 public function delete($useWhere = false) {
216 list($fileID, $entityID, $fieldID) = func_get_args();
218 self
::deleteFileReferences($fileID, $entityID, $fieldID);
222 * delete all the files and associated object associated with this
225 static function deleteEntityFile($entityTable, $entityID, $fileTypeID = NULL, $fileID = NULL) {
226 if (empty($entityTable) ||
empty($entityID)) {
230 $config = CRM_Core_Config
::singleton();
232 list($sql, $params) = self
::sql($entityTable, $entityID, $fileTypeID, $fileID);
233 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
237 while ($dao->fetch()) {
238 $cfIDs[$dao->cfID
] = $dao->uri
;
239 $cefIDs[] = $dao->cefID
;
242 if (!empty($cefIDs)) {
243 $cefIDs = implode(',', $cefIDs);
244 $sql = "DELETE FROM civicrm_entity_file where id IN ( $cefIDs )";
245 CRM_Core_DAO
::executeQuery($sql);
248 if (!empty($cfIDs)) {
249 // Delete file only if there no any entity using this file.
250 $deleteFiles = array();
251 foreach ($cfIDs as $fId => $fUri) {
252 //delete tags from entity tag table
254 'entity_table' => 'civicrm_file',
258 CRM_Core_BAO_EntityTag
::del($tagParams);
260 if (!CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile', $fId, 'id', 'file_id')) {
261 unlink($config->customFileUploadDir
. DIRECTORY_SEPARATOR
. $fUri);
262 $deleteFiles[$fId] = $fId;
266 if (!empty($deleteFiles)) {
267 $deleteFiles = implode(',', $deleteFiles);
268 $sql = "DELETE FROM civicrm_file where id IN ( $deleteFiles )";
269 CRM_Core_DAO
::executeQuery($sql);
275 * get all the files and associated object associated with this
278 static function getEntityFile($entityTable, $entityID, $addDeleteArgs = false) {
279 if (empty($entityTable) ||
!$entityID) {
284 $config = CRM_Core_Config
::singleton();
286 list($sql, $params) = self
::sql($entityTable, $entityID, NULL);
287 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
289 while ($dao->fetch()) {
290 $result['fileID'] = $dao->cfID
;
291 $result['entityID'] = $dao->cefID
;
292 $result['mime_type'] = $dao->mime_type
;
293 $result['fileName'] = $dao->uri
;
294 $result['description'] = $dao->description
;
295 $result['cleanName'] = CRM_Utils_File
::cleanFileName($dao->uri
);
296 $result['fullPath'] = $config->customFileUploadDir
. DIRECTORY_SEPARATOR
. $dao->uri
;
297 $result['url'] = CRM_Utils_System
::url('civicrm/file', "reset=1&id={$dao->cfID}&eid={$entityID}");
298 $result['href'] = "<a href=\"{$result['url']}\">{$result['cleanName']}</a>";
299 $result['tag'] = CRM_Core_BAO_EntityTag
::getTag($dao->cfID
, 'civicrm_file');
300 if ($addDeleteArgs) {
301 $result['deleteURLArgs'] = self
::deleteURLArgs($entityTable, $entityID, $dao->cfID
);
303 $results[$dao->cfID
] = $result;
307 $tags = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
309 foreach($results as &$values) {
310 if (!empty($values['tag'])) {
312 foreach( $values['tag'] as $tid ) {
313 $tagNames[] = $tags[$tid];
315 $values['tag'] = implode(', ', $tagNames);
326 * @param $entityTable
328 * @param null $fileTypeID
329 * @param null $fileID
333 static function sql($entityTable, $entityID, $fileTypeID = NULL, $fileID = NULL) {
335 SELECT CF.id as cfID,
337 CF.mime_type as mime_type,
338 CF.description as description,
340 FROM civicrm_file AS CF
341 LEFT JOIN civicrm_entity_file AS CEF ON ( CEF.file_id = CF.id )
342 WHERE CEF.entity_table = %1
343 AND CEF.entity_id = %2";
346 1 => array($entityTable, 'String'),
347 2 => array($entityID, 'Integer'),
350 if ($fileTypeID !== NULL) {
351 $sql .= " AND CF.file_type_id = %3";
352 $params[3] = array($fileTypeID, 'Integer');
355 if ($fileID !== NULL) {
356 $sql .= " AND CF.id = %4";
357 $params[4] = array($fileID, 'Integer');
360 return array($sql, $params);
365 * @param $entityTable
366 * @param null $entityID
367 * @param null $numAttachments
368 * @param bool $ajaxDelete
370 static function buildAttachment(&$form, $entityTable, $entityID = NULL, $numAttachments = NULL, $ajaxDelete = FALSE) {
372 if (!$numAttachments) {
373 $numAttachments = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'max_attachments');
375 // Assign maxAttachments count to template for help message
376 $form->assign('maxAttachments', $numAttachments);
378 $config = CRM_Core_Config
::singleton();
379 // set default max file size as 2MB
380 $maxFileSize = $config->maxFileSize ?
$config->maxFileSize
: 2;
382 $currentAttachmentInfo = self
::getEntityFile($entityTable, $entityID, TRUE);
383 $totalAttachments = 0;
384 if ($currentAttachmentInfo) {
385 $totalAttachments = count($currentAttachmentInfo);
386 $form->add('checkbox', 'is_delete_attachment', ts('Delete All Attachment(s)'));
387 $form->assign('currentAttachmentInfo', $currentAttachmentInfo);
390 $form->assign('currentAttachmentInfo', NULL);
393 if ( $totalAttachments ) {
394 if ($totalAttachments >= $numAttachments) {
398 $numAttachments -= $totalAttachments;
402 $form->assign('numAttachments', $numAttachments);
404 $tags = CRM_Core_BAO_Tag
::getTags('civicrm_file');
407 $parentNames = CRM_Core_BAO_Tag
::getTagSet('civicrm_file');
410 for ($i = 1; $i <= $numAttachments; $i++
) {
411 $form->addElement('file', "attachFile_$i", ts('Attach File'), 'size=30 maxlength=60');
412 $form->addUploadElement("attachFile_$i");
413 $form->setMaxFileSize($maxFileSize * 1024 * 1024);
414 $form->addRule("attachFile_$i",
415 ts('File size should be less than %1 MByte(s)',
416 array(1 => $maxFileSize)
419 $maxFileSize * 1024 * 1024
421 $form->addElement('text', "attachDesc_$i", NULL, array('size' => 40, 'maxlength' => 255, 'placeholder' => ts('Description')));
424 $form->add('select', "tag_$i", ts('Tags'), $tags, FALSE,
425 array('id' => "tags_$i", 'multiple' => 'multiple', 'class' => 'huge crm-select2', 'placeholder' => ts('- none -'))
428 CRM_Core_Form_Tag
::buildQuickForm($form, $parentNames, 'civicrm_file', NULL, FALSE, TRUE, "file_taglist_$i");
433 * Function to return a clean url string and the number of attachment for a
434 * given entityTable, entityID
436 * @param $entityTable string The entityTable to which the file is attached
437 * @param $entityID int The id of the object in the above entityTable
438 * @param $separator string The string separator where to implode the urls
440 * @return array An array with 2 elements. The string and the number of attachments
443 static function attachmentInfo($entityTable, $entityID, $separator = '<br />') {
448 $currentAttachments = self
::getEntityFile($entityTable, $entityID);
449 if (!empty($currentAttachments)) {
450 $currentAttachmentURL = array();
451 foreach ($currentAttachments as $fileID => $attach) {
452 $currentAttachmentURL[] = $attach['href'];
454 return implode($separator, $currentAttachmentURL);
462 * @param $entityTable
463 * @param null $entityID
465 static function formatAttachment(
472 // delete current attachments if applicable
473 if ($entityID && !empty($formValues['is_delete_attachment'])) {
474 CRM_Core_BAO_File
::deleteEntityFile($entityTable, $entityID);
477 $numAttachments = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'max_attachments');
479 $now = date('Ymdhis');
481 // setup all attachments
482 for ($i = 1; $i <= $numAttachments; $i++
) {
483 $attachName = "attachFile_$i";
484 $attachDesc = "attachDesc_$i";
485 $attachTags = "tag_$i";
486 $attachFreeTags = "file_taglist_$i";
487 if (isset($formValues[$attachName]) && !empty($formValues[$attachName])) {
488 // add static tags if selects
489 $tagParams = array();
490 if (!empty($formValues[$attachTags])) {
491 foreach ($formValues[$attachTags] as $tag) {
492 $tagParams[$tag] = 1;
496 // we dont care if the file is empty or not
499 'uri' => $formValues[$attachName]['name'],
500 'type' => $formValues[$attachName]['type'],
501 'location' => $formValues[$attachName]['name'],
502 'description' => $formValues[$attachDesc],
503 'upload_date' => $now,
505 'attachment_taglist' => CRM_Utils_Array
::value($attachFreeTags, $formValues, array())
508 $params[$attachName] = $fileParams;
515 * @param $entityTable
518 static function processAttachment(&$params, $entityTable, $entityID) {
519 $numAttachments = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'max_attachments');
521 for ($i = 1; $i <= $numAttachments; $i++
) {
523 isset($params["attachFile_$i"]) &&
524 is_array($params["attachFile_$i"])
526 self
::filePostProcess(
527 $params["attachFile_$i"]['location'],
533 $params["attachFile_$i"],
535 $params["attachFile_$i"]['type']
544 static function uploadNames() {
545 $numAttachments = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'max_attachments');
548 for ($i = 1; $i <= $numAttachments; $i++
) {
549 $names[] = "attachFile_{$i}";
551 $names[] = 'uploadFile';
556 * Function to copy/attach an existing file to a different entity
560 * @param $oldEntityTable
561 * @param $oldEntityId
562 * @param $newEntityTable
563 * @param $newEntityId
565 static function copyEntityFile($oldEntityTable, $oldEntityId, $newEntityTable, $newEntityId) {
566 $oldEntityFile = new CRM_Core_DAO_EntityFile();
567 $oldEntityFile->entity_id
= $oldEntityId;
568 $oldEntityFile->entity_table
= $oldEntityTable;
569 $oldEntityFile->find();
571 while ($oldEntityFile->fetch()) {
572 $newEntityFile = new CRM_Core_DAO_EntityFile();
573 $newEntityFile->entity_id
= $newEntityId;
574 $newEntityFile->entity_table
= $newEntityTable;
575 $newEntityFile->file_id
= $oldEntityFile->file_id
;
576 $newEntityFile->save();
581 * @param $entityTable
587 static function deleteURLArgs($entityTable, $entityID, $fileID) {
588 $params['entityTable'] = $entityTable;
589 $params['entityID'] = $entityID;
590 $params['fileID'] = $fileID;
592 $signer = new CRM_Utils_Signer(CRM_Core_Key
::privateKey(), self
::$_signableFields);
593 $params['_sgn'] = $signer->sign($params);
594 return CRM_Utils_System
::makeQueryString($params);
598 * function to delete a file attachment from an entity table / entity ID
603 static function deleteAttachment( ) {
605 $params['entityTable'] = CRM_Utils_Request
::retrieve( 'entityTable', 'String' , CRM_Core_DAO
::$_nullObject, TRUE);
606 $params['entityID'] = CRM_Utils_Request
::retrieve( 'entityID' , 'Positive', CRM_Core_DAO
::$_nullObject, TRUE);
607 $params['fileID'] = CRM_Utils_Request
::retrieve( 'fileID' , 'Positive', CRM_Core_DAO
::$_nullObject, TRUE);
609 $signature = CRM_Utils_Request
::retrieve( '_sgn', 'String', CRM_Core_DAO
::$_nullObject, TRUE);
611 $signer = new CRM_Utils_Signer(CRM_Core_Key
::privateKey(), self
::$_signableFields);
612 if (! $signer->validate($signature, $params)) {
613 CRM_Core_Error
::fatal('Request signature is invalid');
616 CRM_Core_BAO_File
::deleteEntityFile($params['entityTable'], $params['entityID'], NULL, $params['fileID']);
621 * function to display paper icon for a file attachment -- CRM-13624
623 * @param $entityTable string The entityTable to which the file is attached. eg "civicrm_contact", "civicrm_note", "civicrm_activity"
624 * @param $entityID int The id of the object in the above entityTable
626 * @return array|NULL list of HTML snippets; one HTML snippet for each attachment. If none found, then NULL
631 static function paperIconAttachment( $entityTable, $entityID ) {
632 if (empty($entityTable) ||
!$entityID) {
636 $currentAttachmentInfo = self
::getEntityFile( $entityTable, $entityID );
637 foreach($currentAttachmentInfo as $fileKey => $fileValue) {
638 $fileID = $fileValue['fileID'];
639 $fileType = $fileValue['mime_type'];
642 if ($fileType == 'image/jpeg' ||
643 $fileType == 'image/pjpeg' ||
644 $fileType == 'image/gif' ||
645 $fileType == 'image/x-png' ||
646 $fileType == 'image/png'
648 $url = $fileValue['url'];
649 $alt = $fileValue['cleanName'];
650 $file_url[$fileID] = "
651 <a href=\"$url\" class='crm-image-popup'>
652 <div class='icon paper-icon' title=\"$alt\" alt=\"$alt\"></div>
654 // for non image files
657 $url = $fileValue['url'];
658 $alt = $fileValue['cleanName'];
659 $file_url[$fileID] = "<a href=\"$url\"><div class='icon paper-icon' title=\"$alt\" alt=\"$alt\"></div></a>";
663 if(empty($file_url)) {
667 $results = $file_url;