Merge pull request #2326 from eileenmcnaughton/CRM-14069
[civicrm-core.git] / CRM / Core / BAO / File.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2014
32 * $Id$
33 *
34 */
35
36 /**
37 * BAO object for crm_log table
38 */
39 class CRM_Core_BAO_File extends CRM_Core_DAO_File {
40
41 static $_signableFields = array('entityTable', 'entityID', 'fileID');
42
43 /**
44 * @param $fileID
45 * @param $entityID
46 * @param null $entityTable
47 *
48 * @return array
49 */
50 static function path($fileID, $entityID, $entityTable = NULL) {
51 $entityFileDAO = new CRM_Core_DAO_EntityFile();
52 if ($entityTable) {
53 $entityFileDAO->entity_table = $entityTable;
54 }
55 $entityFileDAO->entity_id = $entityID;
56 $entityFileDAO->file_id = $fileID;
57
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;
64
65 if (file_exists($path) && is_readable($path)) {
66 return array($path, $fileDAO->mime_type);
67 }
68 }
69 }
70
71 return array(NULL, NULL);
72 }
73
74
75 /**
76 * @param $data
77 * @param $fileTypeID
78 * @param $entityTable
79 * @param $entityID
80 * @param $entitySubtype
81 * @param bool $overwrite
82 * @param null $fileParams
83 * @param string $uploadName
84 * @param null $mimeType
85 *
86 * @throws Exception
87 */
88 static function filePostProcess(
89 $data,
90 $fileTypeID,
91 $entityTable,
92 $entityID,
93 $entitySubtype,
94 $overwrite = TRUE,
95 $fileParams = NULL,
96 $uploadName = 'uploadFile',
97 $mimeType = null
98 ) {
99 if (!$mimeType) {
100 CRM_Core_Error::fatal(ts('Mime Type is now a required parameter'));
101 }
102
103 $config = CRM_Core_Config::singleton();
104
105 $path = explode('/', $data);
106 $filename = $path[count($path) - 1];
107
108 // rename this file to go into the secure directory
109 if ($entitySubtype) {
110 $directoryName = $config->customFileUploadDir . $entitySubtype . DIRECTORY_SEPARATOR . $entityID;
111 }
112 else {
113 $directoryName = $config->customFileUploadDir;
114 }
115
116 CRM_Utils_File::createDir($directoryName);
117
118 if (!rename($data, $directoryName . DIRECTORY_SEPARATOR . $filename)) {
119 CRM_Core_Error::fatal(ts('Could not move custom file to custom upload directory'));
120 break;
121 }
122
123 // to get id's
124 if ($overwrite && $fileTypeID) {
125 list($sql, $params) = self::sql($entityTable, $entityID, $fileTypeID);
126 }
127 else {
128 list($sql, $params) = self::sql($entityTable, $entityID, 0);
129 }
130
131 $dao = CRM_Core_DAO::executeQuery($sql, $params);
132 $dao->fetch();
133
134 $fileDAO = new CRM_Core_DAO_File();
135 $op = 'create';
136 if (isset($dao->cfID) && $dao->cfID) {
137 $op = 'edit';
138 $fileDAO->id = $dao->cfID;
139 unlink($directoryName . DIRECTORY_SEPARATOR . $dao->uri);
140 }
141
142 if (!empty($fileParams)) {
143 $fileDAO->copyValues($fileParams);
144 }
145
146 $fileDAO->uri = $filename;
147 $fileDAO->mime_type = $mimeType;
148 $fileDAO->file_type_id = $fileTypeID;
149 $fileDAO->upload_date = date('Ymdhis');
150 $fileDAO->save();
151
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;
156 }
157 $entityFileDAO->entity_table = $entityTable;
158 $entityFileDAO->entity_id = $entityID;
159 $entityFileDAO->file_id = $fileDAO->id;
160 $entityFileDAO->save();
161
162 //save static tags
163 if (!empty($fileParams['tag'])) {
164 CRM_Core_BAO_EntityTag::create($fileParams['tag'], 'civicrm_file', $entityFileDAO->id);
165 }
166
167 //save free tags
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);
170 }
171
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);
174 }
175
176 /**
177 * A static function wrapper that deletes the various objects that are
178 * connected to a file object (i.e. file, entityFile and customValue
179 */
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();
185 }
186
187 // lets call a pre hook before the delete, so attachments hooks can get the info before things
188 // disappear
189 CRM_Utils_Hook::pre('delete', 'File', $fileID, $fileDAO);
190
191 // get the table and column name
192 list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField::getTableColumnGroup($fieldID);
193
194 $entityFileDAO = new CRM_Core_DAO_EntityFile();
195 $entityFileDAO->file_id = $fileID;
196 $entityFileDAO->entity_id = $entityID;
197 $entityFileDAO->entity_table = $tableName;
198
199 if (!$entityFileDAO->find(TRUE)) {
200 CRM_Core_Error::fatal();
201 }
202
203 $entityFileDAO->delete();
204 $fileDAO->delete();
205
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);
210 }
211
212 /**
213 * The $useWhere is used so that the signature matches the parent class
214 */
215 public function delete($useWhere = false) {
216 list($fileID, $entityID, $fieldID) = func_get_args();
217
218 self::deleteFileReferences($fileID, $entityID, $fieldID);
219 }
220
221 /**
222 * delete all the files and associated object associated with this
223 * combination
224 */
225 static function deleteEntityFile($entityTable, $entityID, $fileTypeID = NULL, $fileID = NULL) {
226 if (empty($entityTable) || empty($entityID)) {
227 return;
228 }
229
230 $config = CRM_Core_Config::singleton();
231
232 list($sql, $params) = self::sql($entityTable, $entityID, $fileTypeID, $fileID);
233 $dao = CRM_Core_DAO::executeQuery($sql, $params);
234
235 $cfIDs = array();
236 $cefIDs = array();
237 while ($dao->fetch()) {
238 $cfIDs[$dao->cfID] = $dao->uri;
239 $cefIDs[] = $dao->cefID;
240 }
241
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);
246 }
247
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
253 $tagParams = array(
254 'entity_table' => 'civicrm_file',
255 'entity_id' => $fId
256 );
257
258 CRM_Core_BAO_EntityTag::del($tagParams);
259
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;
263 }
264 }
265
266 if (!empty($deleteFiles)) {
267 $deleteFiles = implode(',', $deleteFiles);
268 $sql = "DELETE FROM civicrm_file where id IN ( $deleteFiles )";
269 CRM_Core_DAO::executeQuery($sql);
270 }
271 }
272 }
273
274 /**
275 * get all the files and associated object associated with this
276 * combination
277 */
278 static function getEntityFile($entityTable, $entityID, $addDeleteArgs = false) {
279 if (empty($entityTable) || !$entityID) {
280 $results = NULL;
281 return $results;
282 }
283
284 $config = CRM_Core_Config::singleton();
285
286 list($sql, $params) = self::sql($entityTable, $entityID, NULL);
287 $dao = CRM_Core_DAO::executeQuery($sql, $params);
288 $results = array();
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);
302 }
303 $results[$dao->cfID] = $result;
304 }
305
306 //fix tag names
307 $tags = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
308
309 foreach($results as &$values) {
310 if (!empty($values['tag'])) {
311 $tagNames = array();
312 foreach( $values['tag'] as $tid ) {
313 $tagNames[] = $tags[$tid];
314 }
315 $values['tag'] = implode(', ', $tagNames);
316 } else {
317 $values['tag'] = '';
318 }
319 }
320
321 $dao->free();
322 return $results;
323 }
324
325 /**
326 * @param $entityTable
327 * @param $entityID
328 * @param null $fileTypeID
329 * @param null $fileID
330 *
331 * @return array
332 */
333 static function sql($entityTable, $entityID, $fileTypeID = NULL, $fileID = NULL) {
334 $sql = "
335 SELECT CF.id as cfID,
336 CF.uri as uri,
337 CF.mime_type as mime_type,
338 CF.description as description,
339 CEF.id as cefID
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";
344
345 $params = array(
346 1 => array($entityTable, 'String'),
347 2 => array($entityID, 'Integer'),
348 );
349
350 if ($fileTypeID !== NULL) {
351 $sql .= " AND CF.file_type_id = %3";
352 $params[3] = array($fileTypeID, 'Integer');
353 }
354
355 if ($fileID !== NULL) {
356 $sql .= " AND CF.id = %4";
357 $params[4] = array($fileID, 'Integer');
358 }
359
360 return array($sql, $params);
361 }
362
363 /**
364 * @param $form
365 * @param $entityTable
366 * @param null $entityID
367 * @param null $numAttachments
368 * @param bool $ajaxDelete
369 */
370 static function buildAttachment(&$form, $entityTable, $entityID = NULL, $numAttachments = NULL, $ajaxDelete = FALSE) {
371
372 if (!$numAttachments) {
373 $numAttachments = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'max_attachments');
374 }
375 // Assign maxAttachments count to template for help message
376 $form->assign('maxAttachments', $numAttachments);
377
378 $config = CRM_Core_Config::singleton();
379 // set default max file size as 2MB
380 $maxFileSize = $config->maxFileSize ? $config->maxFileSize : 2;
381
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);
388 }
389 else {
390 $form->assign('currentAttachmentInfo', NULL);
391 }
392
393 if ( $totalAttachments ) {
394 if ($totalAttachments >= $numAttachments) {
395 $numAttachments = 0;
396 }
397 else {
398 $numAttachments -= $totalAttachments;
399 }
400 }
401
402 $form->assign('numAttachments', $numAttachments);
403
404 $tags = CRM_Core_BAO_Tag::getTags('civicrm_file');
405
406 // get tagset info
407 $parentNames = CRM_Core_BAO_Tag::getTagSet('civicrm_file');
408
409 // add attachments
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)
417 ),
418 'maxfilesize',
419 $maxFileSize * 1024 * 1024
420 );
421 $form->addElement('text', "attachDesc_$i", NULL, array('size' => 40, 'maxlength' => 255, 'placeholder' => ts('Description')));
422
423 if (!empty($tags)) {
424 $form->add('select', "tag_$i", ts('Tags'), $tags, FALSE,
425 array('id' => "tags_$i", 'multiple' => 'multiple', 'class' => 'huge crm-select2', 'placeholder' => ts('- none -'))
426 );
427 }
428 CRM_Core_Form_Tag::buildQuickForm($form, $parentNames, 'civicrm_file', NULL, FALSE, TRUE, "file_taglist_$i");
429 }
430 }
431
432 /**
433 * Function to return a clean url string and the number of attachment for a
434 * given entityTable, entityID
435 *
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
439 *
440 * @return array An array with 2 elements. The string and the number of attachments
441 * @static
442 */
443 static function attachmentInfo($entityTable, $entityID, $separator = '<br />') {
444 if (!$entityID) {
445 return NULL;
446 }
447
448 $currentAttachments = self::getEntityFile($entityTable, $entityID);
449 if (!empty($currentAttachments)) {
450 $currentAttachmentURL = array();
451 foreach ($currentAttachments as $fileID => $attach) {
452 $currentAttachmentURL[] = $attach['href'];
453 }
454 return implode($separator, $currentAttachmentURL);
455 }
456 return NULL;
457 }
458
459 /**
460 * @param $formValues
461 * @param $params
462 * @param $entityTable
463 * @param null $entityID
464 */
465 static function formatAttachment(
466 &$formValues,
467 &$params,
468 $entityTable,
469 $entityID = NULL
470 ) {
471
472 // delete current attachments if applicable
473 if ($entityID && !empty($formValues['is_delete_attachment'])) {
474 CRM_Core_BAO_File::deleteEntityFile($entityTable, $entityID);
475 }
476
477 $numAttachments = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'max_attachments');
478
479 $now = date('Ymdhis');
480
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;
493 }
494 }
495
496 // we dont care if the file is empty or not
497 // CRM-7448
498 $fileParams = array(
499 'uri' => $formValues[$attachName]['name'],
500 'type' => $formValues[$attachName]['type'],
501 'location' => $formValues[$attachName]['name'],
502 'description' => $formValues[$attachDesc],
503 'upload_date' => $now,
504 'tag' => $tagParams,
505 'attachment_taglist' => CRM_Utils_Array::value($attachFreeTags, $formValues, array())
506 );
507
508 $params[$attachName] = $fileParams;
509 }
510 }
511 }
512
513 /**
514 * @param $params
515 * @param $entityTable
516 * @param $entityID
517 */
518 static function processAttachment(&$params, $entityTable, $entityID) {
519 $numAttachments = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'max_attachments');
520
521 for ($i = 1; $i <= $numAttachments; $i++) {
522 if (
523 isset($params["attachFile_$i"]) &&
524 is_array($params["attachFile_$i"])
525 ) {
526 self::filePostProcess(
527 $params["attachFile_$i"]['location'],
528 NULL,
529 $entityTable,
530 $entityID,
531 NULL,
532 TRUE,
533 $params["attachFile_$i"],
534 "attachFile_$i",
535 $params["attachFile_$i"]['type']
536 );
537 }
538 }
539 }
540
541 /**
542 * @return array
543 */
544 static function uploadNames() {
545 $numAttachments = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'max_attachments');
546
547 $names = array();
548 for ($i = 1; $i <= $numAttachments; $i++) {
549 $names[] = "attachFile_{$i}";
550 }
551 $names[] = 'uploadFile';
552 return $names;
553 }
554
555 /*
556 * Function to copy/attach an existing file to a different entity
557 * table and id.
558 */
559 /**
560 * @param $oldEntityTable
561 * @param $oldEntityId
562 * @param $newEntityTable
563 * @param $newEntityId
564 */
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();
570
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();
577 }
578 }
579
580 /**
581 * @param $entityTable
582 * @param $entityID
583 * @param $fileID
584 *
585 * @return string
586 */
587 static function deleteURLArgs($entityTable, $entityID, $fileID) {
588 $params['entityTable'] = $entityTable;
589 $params['entityID'] = $entityID;
590 $params['fileID'] = $fileID;
591
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);
595 }
596
597 /**
598 * function to delete a file attachment from an entity table / entity ID
599 *
600 * @static
601 * @access public
602 */
603 static function deleteAttachment( ) {
604 $params = array( );
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);
608
609 $signature = CRM_Utils_Request::retrieve( '_sgn', 'String', CRM_Core_DAO::$_nullObject, TRUE);
610
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');
614 }
615
616 CRM_Core_BAO_File::deleteEntityFile($params['entityTable'], $params['entityID'], NULL, $params['fileID']);
617 }
618
619
620 /**
621 * function to display paper icon for a file attachment -- CRM-13624
622 *
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
625 *
626 * @return array|NULL list of HTML snippets; one HTML snippet for each attachment. If none found, then NULL
627 *
628 * @static
629 * @access public
630 */
631 static function paperIconAttachment( $entityTable, $entityID ) {
632 if (empty($entityTable) || !$entityID) {
633 $results = NULL;
634 return $results;
635 }
636 $currentAttachmentInfo = self::getEntityFile( $entityTable, $entityID );
637 foreach($currentAttachmentInfo as $fileKey => $fileValue) {
638 $fileID = $fileValue['fileID'];
639 $fileType = $fileValue['mime_type'];
640 $eid = $entityID;
641 if($fileID) {
642 if ($fileType == 'image/jpeg' ||
643 $fileType == 'image/pjpeg' ||
644 $fileType == 'image/gif' ||
645 $fileType == 'image/x-png' ||
646 $fileType == 'image/png'
647 ) {
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>
653 </a>";
654 // for non image files
655 }
656 else {
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>";
660 }
661 }
662 }
663 if(empty($file_url)) {
664 $results = NULL;
665 }
666 else {
667 $results = $file_url;
668 }
669 return $results;
670 }
671
672 }