Merge pull request #20093 from larssandergreen/mailings-AB-test-improvements
[civicrm-core.git] / CRM / Core / BAO / File.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * BAO object for crm_log table
20 */
21 class CRM_Core_BAO_File extends CRM_Core_DAO_File {
22
23 public static $_signableFields = ['entityTable', 'entityID', 'fileID'];
24
25 /**
26 * If there is no setting configured on the admin screens, maximum number
27 * of attachments to try to process when given a list of attachments to
28 * process.
29 */
30 const DEFAULT_MAX_ATTACHMENTS_BACKEND = 100;
31
32 /**
33 * Takes an associative array and creates a File object.
34 *
35 * @param array $params
36 * (reference ) an assoc array of name/value pairs.
37 *
38 * @return CRM_Core_BAO_File
39 */
40 public static function create($params) {
41 $fileDAO = new CRM_Core_DAO_File();
42
43 $op = empty($params['id']) ? 'create' : 'edit';
44
45 CRM_Utils_Hook::pre($op, 'File', CRM_Utils_Array::value('id', $params), $params);
46
47 $fileDAO->copyValues($params);
48
49 if (empty($params['id']) && empty($params['created_id'])) {
50 $fileDAO->created_id = CRM_Core_Session::getLoggedInContactID();
51 }
52
53 $fileDAO->save();
54
55 CRM_Utils_Hook::post($op, 'File', $fileDAO->id, $fileDAO);
56
57 return $fileDAO;
58 }
59
60 /**
61 * @param int $fileID
62 * @param int $entityID
63 *
64 * @return array
65 */
66 public static function path($fileID, $entityID) {
67 $entityFileDAO = new CRM_Core_DAO_EntityFile();
68 $entityFileDAO->entity_id = $entityID;
69 $entityFileDAO->file_id = $fileID;
70
71 if ($entityFileDAO->find(TRUE)) {
72 $fileDAO = new CRM_Core_DAO_File();
73 $fileDAO->id = $fileID;
74 if ($fileDAO->find(TRUE)) {
75 $config = CRM_Core_Config::singleton();
76 $path = $config->customFileUploadDir . $fileDAO->uri;
77
78 if (file_exists($path) && is_readable($path)) {
79 return [$path, $fileDAO->mime_type];
80 }
81 }
82 }
83
84 return [NULL, NULL];
85 }
86
87 /**
88 * @param string $data
89 * @param int $fileTypeID
90 * @param string $entityTable
91 * @param int $entityID
92 * @param string|false $entitySubtype
93 * @param bool $overwrite
94 * @param null|array $fileParams
95 * @param string $uploadName
96 * @param string $mimeType
97 *
98 * @throws Exception
99 */
100 public static function filePostProcess(
101 $data,
102 $fileTypeID,
103 $entityTable,
104 $entityID,
105 $entitySubtype = FALSE,
106 $overwrite = TRUE,
107 $fileParams = NULL,
108 $uploadName = 'uploadFile',
109 $mimeType = NULL
110 ) {
111 if (!$mimeType) {
112 CRM_Core_Error::statusBounce(ts('Mime Type is now a required parameter for file upload'));
113 }
114
115 $config = CRM_Core_Config::singleton();
116
117 $path = explode('/', $data);
118 $filename = $path[count($path) - 1];
119
120 // rename this file to go into the secure directory
121 if ($entitySubtype) {
122 $directoryName = $config->customFileUploadDir . $entitySubtype . DIRECTORY_SEPARATOR . $entityID;
123 }
124 else {
125 $directoryName = $config->customFileUploadDir;
126 }
127
128 CRM_Utils_File::createDir($directoryName);
129
130 if (!rename($data, $directoryName . DIRECTORY_SEPARATOR . $filename)) {
131 CRM_Core_Error::statusBounce(ts('Could not move custom file to custom upload directory'));
132 }
133
134 // to get id's
135 if ($overwrite && $fileTypeID) {
136 list($sql, $params) = self::sql($entityTable, $entityID, $fileTypeID);
137 }
138 else {
139 list($sql, $params) = self::sql($entityTable, $entityID, 0);
140 }
141
142 $dao = CRM_Core_DAO::executeQuery($sql, $params);
143 $dao->fetch();
144
145 $fileDAO = new CRM_Core_DAO_File();
146 $op = 'create';
147 if (isset($dao->cfID) && $dao->cfID) {
148 $op = 'edit';
149 $fileDAO->id = $dao->cfID;
150 unlink($directoryName . DIRECTORY_SEPARATOR . $dao->uri);
151 }
152
153 if (!empty($fileParams)) {
154 $fileDAO->copyValues($fileParams);
155 }
156
157 $fileDAO->uri = $filename;
158 $fileDAO->mime_type = $mimeType;
159 $fileDAO->file_type_id = $fileTypeID;
160 $fileDAO->upload_date = date('YmdHis');
161 $fileDAO->save();
162
163 // need to add/update civicrm_entity_file
164 $entityFileDAO = new CRM_Core_DAO_EntityFile();
165 if (isset($dao->cefID) && $dao->cefID) {
166 $entityFileDAO->id = $dao->cefID;
167 }
168 $entityFileDAO->entity_table = $entityTable;
169 $entityFileDAO->entity_id = $entityID;
170 $entityFileDAO->file_id = $fileDAO->id;
171 $entityFileDAO->save();
172
173 //save static tags
174 if (!empty($fileParams['tag'])) {
175 CRM_Core_BAO_EntityTag::create($fileParams['tag'], 'civicrm_file', $entityFileDAO->id);
176 }
177
178 //save free tags
179 if (isset($fileParams['attachment_taglist']) && !empty($fileParams['attachment_taglist'])) {
180 CRM_Core_Form_Tag::postProcess($fileParams['attachment_taglist'], $entityFileDAO->id, 'civicrm_file');
181 }
182
183 // lets call the post hook here so attachments code can do the right stuff
184 CRM_Utils_Hook::post($op, 'File', $fileDAO->id, $fileDAO);
185 }
186
187 /**
188 * A static function wrapper that deletes the various objects.
189 *
190 * Objects are those hat are connected to a file object (i.e. file, entityFile and customValue.
191 *
192 * @param int $fileID
193 * @param int $entityID
194 * @param int $fieldID
195 *
196 * @throws \Exception
197 */
198 public static function deleteFileReferences($fileID, $entityID, $fieldID) {
199 $fileDAO = new CRM_Core_DAO_File();
200 $fileDAO->id = $fileID;
201 if (!$fileDAO->find(TRUE)) {
202 throw new CRM_Core_Exception(ts('File not found'));
203 }
204
205 // lets call a pre hook before the delete, so attachments hooks can get the info before things
206 // disappear
207 CRM_Utils_Hook::pre('delete', 'File', $fileID, $fileDAO);
208
209 // get the table and column name
210 list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField::getTableColumnGroup($fieldID);
211
212 $entityFileDAO = new CRM_Core_DAO_EntityFile();
213 $entityFileDAO->file_id = $fileID;
214 $entityFileDAO->entity_id = $entityID;
215 $entityFileDAO->entity_table = $tableName;
216
217 if (!$entityFileDAO->find(TRUE)) {
218 throw new CRM_Core_Exception(sprintf('No record found for given file ID - %d and entity ID - %d', $fileID, $entityID));
219 }
220
221 $entityFileDAO->delete();
222 $fileDAO->delete();
223
224 // also set the value to null of the table and column
225 $query = "UPDATE $tableName SET $columnName = null WHERE $columnName = %1";
226 $params = [1 => [$fileID, 'Integer']];
227 CRM_Core_DAO::executeQuery($query, $params);
228 }
229
230 /**
231 * The $useWhere is used so that the signature matches the parent class
232 *
233 * public function delete($useWhere = FALSE) {
234 * list($fileID, $entityID, $fieldID) = func_get_args();
235 *
236 * self::deleteFileReferences($fileID, $entityID, $fieldID);
237 * } */
238
239 /**
240 * Delete all the files and associated object associated with this combination.
241 *
242 * @param string $entityTable
243 * @param int $entityID
244 * @param int $fileTypeID
245 * @param int $fileID
246 *
247 * @return bool
248 * Was file deleted?
249 */
250 public static function deleteEntityFile($entityTable, $entityID, $fileTypeID = NULL, $fileID = NULL) {
251 $isDeleted = FALSE;
252 if (empty($entityTable) || empty($entityID)) {
253 return $isDeleted;
254 }
255
256 $config = CRM_Core_Config::singleton();
257
258 list($sql, $params) = self::sql($entityTable, $entityID, $fileTypeID, $fileID);
259 $dao = CRM_Core_DAO::executeQuery($sql, $params);
260
261 $cfIDs = [];
262 $cefIDs = [];
263 while ($dao->fetch()) {
264 $cfIDs[$dao->cfID] = $dao->uri;
265 $cefIDs[] = $dao->cefID;
266 }
267
268 if (!empty($cefIDs)) {
269 $cefIDs = implode(',', $cefIDs);
270 $sql = "DELETE FROM civicrm_entity_file where id IN ( $cefIDs )";
271 CRM_Core_DAO::executeQuery($sql);
272 $isDeleted = TRUE;
273 }
274
275 if (!empty($cfIDs)) {
276 // Delete file only if there no any entity using this file.
277 $deleteFiles = [];
278 foreach ($cfIDs as $fId => $fUri) {
279 //delete tags from entity tag table
280 $tagParams = [
281 'entity_table' => 'civicrm_file',
282 'entity_id' => $fId,
283 ];
284
285 CRM_Core_BAO_EntityTag::del($tagParams);
286
287 if (!CRM_Core_DAO::getFieldValue('CRM_Core_DAO_EntityFile', $fId, 'id', 'file_id')) {
288 unlink($config->customFileUploadDir . DIRECTORY_SEPARATOR . $fUri);
289 $deleteFiles[$fId] = $fId;
290 }
291 }
292
293 if (!empty($deleteFiles)) {
294 $deleteFiles = implode(',', $deleteFiles);
295 $sql = "DELETE FROM civicrm_file where id IN ( $deleteFiles )";
296 CRM_Core_DAO::executeQuery($sql);
297 }
298 $isDeleted = TRUE;
299 }
300 return $isDeleted;
301 }
302
303 /**
304 * Get all the files and associated object associated with this combination.
305 *
306 * @param string $entityTable
307 * @param int $entityID
308 * @param bool $addDeleteArgs
309 *
310 * @return array|null
311 */
312 public static function getEntityFile($entityTable, $entityID, $addDeleteArgs = FALSE) {
313 if (empty($entityTable) || !$entityID) {
314 $results = NULL;
315 return $results;
316 }
317
318 $config = CRM_Core_Config::singleton();
319
320 list($sql, $params) = self::sql($entityTable, $entityID, NULL);
321 $dao = CRM_Core_DAO::executeQuery($sql, $params);
322 $results = [];
323 while ($dao->fetch()) {
324 $fileHash = self::generateFileHash($dao->entity_id, $dao->cfID);
325 $result['fileID'] = $dao->cfID;
326 $result['entityID'] = $dao->cefID;
327 $result['mime_type'] = $dao->mime_type;
328 $result['fileName'] = $dao->uri;
329 $result['description'] = $dao->description;
330 $result['cleanName'] = CRM_Utils_File::cleanFileName($dao->uri);
331 $result['fullPath'] = $config->customFileUploadDir . DIRECTORY_SEPARATOR . $dao->uri;
332 $result['url'] = CRM_Utils_System::url('civicrm/file', "reset=1&id={$dao->cfID}&eid={$dao->entity_id}&fcs={$fileHash}");
333 $result['href'] = "<a href=\"{$result['url']}\">{$result['cleanName']}</a>";
334 $result['tag'] = CRM_Core_BAO_EntityTag::getTag($dao->cfID, 'civicrm_file');
335 $result['icon'] = CRM_Utils_File::getIconFromMimeType($dao->mime_type);
336 if ($addDeleteArgs) {
337 $result['deleteURLArgs'] = self::deleteURLArgs($dao->entity_table, $dao->entity_id, $dao->cfID);
338 }
339 $results[$dao->cfID] = $result;
340 }
341
342 //fix tag names
343 $tags = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', ['onlyActive' => FALSE]);
344
345 foreach ($results as &$values) {
346 if (!empty($values['tag'])) {
347 $tagNames = [];
348 foreach ($values['tag'] as $tid) {
349 $tagNames[] = $tags[$tid];
350 }
351 $values['tag'] = implode(', ', $tagNames);
352 }
353 else {
354 $values['tag'] = '';
355 }
356 }
357
358 return $results;
359 }
360
361 /**
362 * @param string $entityTable
363 * Table-name or "*" (to reference files directly by file-id).
364 * @param int $entityID
365 * @param int $fileTypeID
366 * @param int $fileID
367 *
368 * @return array
369 */
370 public static function sql($entityTable, $entityID, $fileTypeID = NULL, $fileID = NULL) {
371 if ($entityTable == '*') {
372 // $entityID is the ID of a specific file
373 $sql = "
374 SELECT CF.id as cfID,
375 CF.uri as uri,
376 CF.mime_type as mime_type,
377 CF.description as description,
378 CEF.id as cefID,
379 CEF.entity_table as entity_table,
380 CEF.entity_id as entity_id
381 FROM civicrm_file AS CF
382 LEFT JOIN civicrm_entity_file AS CEF ON ( CEF.file_id = CF.id )
383 WHERE CF.id = %2";
384
385 }
386 else {
387 $sql = "
388 SELECT CF.id as cfID,
389 CF.uri as uri,
390 CF.mime_type as mime_type,
391 CF.description as description,
392 CEF.id as cefID,
393 CEF.entity_table as entity_table,
394 CEF.entity_id as entity_id
395 FROM civicrm_file AS CF
396 LEFT JOIN civicrm_entity_file AS CEF ON ( CEF.file_id = CF.id )
397 WHERE CEF.entity_table = %1
398 AND CEF.entity_id = %2";
399 }
400
401 $params = [
402 1 => [$entityTable, 'String'],
403 2 => [$entityID, 'Integer'],
404 ];
405
406 if ($fileTypeID !== NULL) {
407 $sql .= " AND CF.file_type_id = %3";
408 $params[3] = [$fileTypeID, 'Integer'];
409 }
410
411 if ($fileID !== NULL) {
412 $sql .= " AND CF.id = %4";
413 $params[4] = [$fileID, 'Integer'];
414 }
415
416 return [$sql, $params];
417 }
418
419 /**
420 * @param CRM_Core_Form $form
421 * @param string $entityTable
422 * @param int $entityID
423 * @param null $numAttachments
424 * @param bool $ajaxDelete
425 */
426 public static function buildAttachment(&$form, $entityTable, $entityID = NULL, $numAttachments = NULL, $ajaxDelete = FALSE) {
427
428 if (!$numAttachments) {
429 $numAttachments = Civi::settings()->get('max_attachments');
430 }
431 // Assign maxAttachments count to template for help message
432 $form->assign('maxAttachments', $numAttachments);
433
434 $config = CRM_Core_Config::singleton();
435 // set default max file size as 2MB
436 $maxFileSize = $config->maxFileSize ? $config->maxFileSize : 2;
437
438 $currentAttachmentInfo = self::getEntityFile($entityTable, $entityID, TRUE);
439 $totalAttachments = 0;
440 if ($currentAttachmentInfo) {
441 $totalAttachments = count($currentAttachmentInfo);
442 $form->add('checkbox', 'is_delete_attachment', ts('Delete All Attachment(s)'));
443 $form->assign('currentAttachmentInfo', $currentAttachmentInfo);
444 }
445 else {
446 $form->assign('currentAttachmentInfo', NULL);
447 }
448
449 if ($totalAttachments) {
450 if ($totalAttachments >= $numAttachments) {
451 $numAttachments = 0;
452 }
453 else {
454 $numAttachments -= $totalAttachments;
455 }
456 }
457
458 $form->assign('numAttachments', $numAttachments);
459
460 CRM_Core_BAO_Tag::getTags('civicrm_file', $tags, NULL,
461 '&nbsp;&nbsp;', TRUE);
462
463 // get tagset info
464 $parentNames = CRM_Core_BAO_Tag::getTagSet('civicrm_file');
465
466 // add attachments
467 for ($i = 1; $i <= $numAttachments; $i++) {
468 $form->addElement('file', "attachFile_$i", ts('Attach File'), 'size=30 maxlength=221');
469 $form->addUploadElement("attachFile_$i");
470 $form->setMaxFileSize($maxFileSize * 1024 * 1024);
471 $form->addRule("attachFile_$i",
472 ts('File size should be less than %1 MByte(s)',
473 [1 => $maxFileSize]
474 ),
475 'maxfilesize',
476 $maxFileSize * 1024 * 1024
477 );
478 $form->addElement('text', "attachDesc_$i", NULL, [
479 'size' => 40,
480 'maxlength' => 255,
481 'placeholder' => ts('Description'),
482 ]);
483
484 if (!empty($tags)) {
485 $form->add('select', "tag_$i", ts('Tags'), $tags, FALSE,
486 [
487 'id' => "tags_$i",
488 'multiple' => 'multiple',
489 'class' => 'huge crm-select2',
490 'placeholder' => ts('- none -'),
491 ]
492 );
493 }
494 CRM_Core_Form_Tag::buildQuickForm($form, $parentNames, 'civicrm_file', NULL, FALSE, TRUE, "file_taglist_$i");
495 }
496 }
497
498 /**
499 * Return a HTML string, separated by $separator,
500 * where each item is an anchor link to the file,
501 * with the filename as the link text.
502 *
503 * @param string $entityTable
504 * The entityTable to which the file is attached.
505 * @param int $entityID
506 * The id of the object in the above entityTable.
507 * @param string $separator
508 * The string separator where to implode the urls.
509 *
510 * @return string|null
511 * HTML list of attachment links, or null if no attachments
512 */
513 public static function attachmentInfo($entityTable, $entityID, $separator = '<br />') {
514 if (!$entityID) {
515 return NULL;
516 }
517
518 $currentAttachments = self::getEntityFile($entityTable, $entityID);
519 if (!empty($currentAttachments)) {
520 $currentAttachmentURL = [];
521 foreach ($currentAttachments as $fileID => $attach) {
522 $currentAttachmentURL[] = $attach['href'];
523 }
524 return implode($separator, $currentAttachmentURL);
525 }
526 return NULL;
527 }
528
529 /**
530 * @param $formValues
531 * @param array $params
532 * @param $entityTable
533 * @param int $entityID
534 */
535 public static function formatAttachment(
536 &$formValues,
537 &$params,
538 $entityTable,
539 $entityID = NULL
540 ) {
541
542 // delete current attachments if applicable
543 if ($entityID && !empty($formValues['is_delete_attachment'])) {
544 CRM_Core_BAO_File::deleteEntityFile($entityTable, $entityID);
545 }
546
547 $numAttachments = Civi::settings()->get('max_attachments');
548
549 // setup all attachments
550 for ($i = 1; $i <= $numAttachments; $i++) {
551 $attachName = "attachFile_$i";
552 $attachDesc = "attachDesc_$i";
553 $attachTags = "tag_$i";
554 $attachFreeTags = "file_taglist_$i";
555 if (isset($formValues[$attachName]) && !empty($formValues[$attachName])) {
556 // add static tags if selects
557 $tagParams = [];
558 if (!empty($formValues[$attachTags])) {
559 foreach ($formValues[$attachTags] as $tag) {
560 $tagParams[$tag] = 1;
561 }
562 }
563
564 // we dont care if the file is empty or not
565 // CRM-7448
566 $extraParams = [
567 'description' => $formValues[$attachDesc],
568 'tag' => $tagParams,
569 'attachment_taglist' => $formValues[$attachFreeTags] ?? [],
570 ];
571
572 CRM_Utils_File::formatFile($formValues, $attachName, $extraParams);
573
574 // set the formatted attachment attributes to $params, later used
575 // to send mail with desired attachments
576 if (!empty($formValues[$attachName])) {
577 $params[$attachName] = $formValues[$attachName];
578 }
579 }
580 }
581 }
582
583 /**
584 * @param array $params
585 * @param $entityTable
586 * @param int $entityID
587 */
588 public static function processAttachment(&$params, $entityTable, $entityID) {
589 $numAttachments = Civi::settings()->get('max_attachments_backend') ?? self::DEFAULT_MAX_ATTACHMENTS_BACKEND;
590
591 for ($i = 1; $i <= $numAttachments; $i++) {
592 if (isset($params["attachFile_$i"])) {
593 /**
594 * Moved the second condition into its own if block to avoid changing
595 * how it works if there happens to be an entry that is not an array,
596 * since we now might exit loop early via newly added break below.
597 */
598 if (is_array($params["attachFile_$i"])) {
599 self::filePostProcess(
600 $params["attachFile_$i"]['location'],
601 NULL,
602 $entityTable,
603 $entityID,
604 NULL,
605 TRUE,
606 $params["attachFile_$i"],
607 "attachFile_$i",
608 $params["attachFile_$i"]['type']
609 );
610 }
611 }
612 else {
613 /**
614 * No point looping 100 times if there aren't any more.
615 * This assumes the array is continuous and doesn't skip array keys,
616 * but (a) where would it be doing that, and (b) it would have caused
617 * problems before anyway if there were skipped keys.
618 */
619 break;
620 }
621 }
622 }
623
624 /**
625 * @return array
626 */
627 public static function uploadNames() {
628 $numAttachments = Civi::settings()->get('max_attachments');
629
630 $names = [];
631 for ($i = 1; $i <= $numAttachments; $i++) {
632 $names[] = "attachFile_{$i}";
633 }
634 $names[] = 'uploadFile';
635 return $names;
636 }
637
638 /**
639 * copy/attach an existing file to a different entity
640 * table and id.
641 *
642 * @param $oldEntityTable
643 * @param int $oldEntityId
644 * @param $newEntityTable
645 * @param int $newEntityId
646 */
647 public static function copyEntityFile($oldEntityTable, $oldEntityId, $newEntityTable, $newEntityId) {
648 $oldEntityFile = new CRM_Core_DAO_EntityFile();
649 $oldEntityFile->entity_id = $oldEntityId;
650 $oldEntityFile->entity_table = $oldEntityTable;
651 $oldEntityFile->find();
652
653 while ($oldEntityFile->fetch()) {
654 $newEntityFile = new CRM_Core_DAO_EntityFile();
655 $newEntityFile->entity_id = $newEntityId;
656 $newEntityFile->entity_table = $newEntityTable;
657 $newEntityFile->file_id = $oldEntityFile->file_id;
658 $newEntityFile->save();
659 }
660 }
661
662 /**
663 * @param $entityTable
664 * @param int $entityID
665 * @param int $fileID
666 *
667 * @return string
668 */
669 public static function deleteURLArgs($entityTable, $entityID, $fileID) {
670 $params['entityTable'] = $entityTable;
671 $params['entityID'] = $entityID;
672 $params['fileID'] = $fileID;
673
674 $signer = new CRM_Utils_Signer(CRM_Core_Key::privateKey(), self::$_signableFields);
675 $params['_sgn'] = $signer->sign($params);
676 return CRM_Utils_System::makeQueryString($params);
677 }
678
679 /**
680 * Delete a file attachment from an entity table / entity ID
681 * @throws CRM_Core_Exception
682 */
683 public static function deleteAttachment() {
684 $params = [];
685 $params['entityTable'] = CRM_Utils_Request::retrieve('entityTable', 'String', CRM_Core_DAO::$_nullObject, TRUE);
686 $params['entityID'] = CRM_Utils_Request::retrieve('entityID', 'Positive', CRM_Core_DAO::$_nullObject, TRUE);
687 $params['fileID'] = CRM_Utils_Request::retrieve('fileID', 'Positive', CRM_Core_DAO::$_nullObject, TRUE);
688
689 $signature = CRM_Utils_Request::retrieve('_sgn', 'String', CRM_Core_DAO::$_nullObject, TRUE);
690
691 $signer = new CRM_Utils_Signer(CRM_Core_Key::privateKey(), self::$_signableFields);
692 if (!$signer->validate($signature, $params)) {
693 throw new CRM_Core_Exception('Request signature is invalid');
694 }
695
696 self::deleteEntityFile($params['entityTable'], $params['entityID'], NULL, $params['fileID']);
697 }
698
699 /**
700 * Display paper icon for a file attachment -- CRM-13624
701 *
702 * @param string $entityTable
703 * The entityTable to which the file is attached. eg "civicrm_contact", "civicrm_note", "civicrm_activity".
704 * If you have the ID of a specific row in civicrm_file, use $entityTable='*'
705 * @param int $entityID
706 * The id of the object in the above entityTable.
707 *
708 * @return array|NULL
709 * list of HTML snippets; one HTML snippet for each attachment. If none found, then NULL
710 *
711 */
712 public static function paperIconAttachment($entityTable, $entityID) {
713 if (empty($entityTable) || !$entityID) {
714 $results = NULL;
715 return $results;
716 }
717 $currentAttachmentInfo = self::getEntityFile($entityTable, $entityID);
718 foreach ($currentAttachmentInfo as $fileKey => $fileValue) {
719 $fileID = $fileValue['fileID'];
720 if ($fileID) {
721 $fileType = $fileValue['mime_type'];
722 $url = $fileValue['url'];
723 $title = $fileValue['cleanName'];
724 if ($fileType == 'image/jpeg' ||
725 $fileType == 'image/pjpeg' ||
726 $fileType == 'image/gif' ||
727 $fileType == 'image/x-png' ||
728 $fileType == 'image/png'
729 ) {
730 $file_url[$fileID] = <<<HEREDOC
731 <a href="$url" class="crm-image-popup" title="$title">
732 <i class="crm-i fa-file-image-o" aria-hidden="true"></i>
733 </a>
734 HEREDOC;
735 }
736 // for non image files
737 else {
738 $file_url[$fileID] = <<<HEREDOC
739 <a href="$url" title="$title">
740 <i class="crm-i fa-paperclip" aria-hidden="true"></i>
741 </a>
742 HEREDOC;
743 }
744 }
745 }
746 if (empty($file_url)) {
747 $results = NULL;
748 }
749 else {
750 $results = $file_url;
751 }
752 return $results;
753 }
754
755 /**
756 * Get a reference to the file-search service (if one is available).
757 *
758 * @return CRM_Core_FileSearchInterface|NULL
759 */
760 public static function getSearchService() {
761 $fileSearches = [];
762 CRM_Utils_Hook::fileSearches($fileSearches);
763
764 // use the first available search
765 foreach ($fileSearches as $fileSearch) {
766 /** @var $fileSearch CRM_Core_FileSearchInterface */
767 return $fileSearch;
768 }
769 return NULL;
770 }
771
772 /**
773 * Generates an access-token for downloading a specific file.
774 *
775 * @param int $entityId entity id the file is attached to
776 * @param int $fileId file ID
777 * @param int $genTs
778 * @param int $life
779 * @return string
780 */
781 public static function generateFileHash($entityId = NULL, $fileId = NULL, $genTs = NULL, $life = NULL) {
782 // Use multiple (but stable) inputs for hash information.
783 $siteKey = CRM_Utils_Constant::value('CIVICRM_SITE_KEY');
784 if (!$siteKey) {
785 throw new \CRM_Core_Exception("Cannot generate file access token. Please set CIVICRM_SITE_KEY.");
786 }
787
788 if (!$genTs) {
789 $genTs = time();
790 }
791 if (!$life) {
792 $days = Civi::settings()->get('checksum_timeout');
793 $life = 24 * $days;
794 }
795 // Trim 8 chars off the string, make it slightly easier to find
796 // but reveals less information from the hash.
797 $cs = hash_hmac('sha256', "entity={$entityId}&file={$fileId}&life={$life}", $siteKey);
798 return "{$cs}_{$genTs}_{$life}";
799 }
800
801 /**
802 * Validate a file access token.
803 *
804 * @param string $hash
805 * @param int $entityId Entity Id the file is attached to
806 * @param int $fileId File Id
807 * @return bool
808 */
809 public static function validateFileHash($hash, $entityId, $fileId) {
810 $input = CRM_Utils_System::explode('_', $hash, 3);
811 $inputTs = $input[1] ?? NULL;
812 $inputLF = $input[2] ?? NULL;
813 $testHash = CRM_Core_BAO_File::generateFileHash($entityId, $fileId, $inputTs, $inputLF);
814 if (hash_equals($testHash, $hash)) {
815 $now = time();
816 if ($inputTs + ($inputLF * 60 * 60) >= $now) {
817 return TRUE;
818 }
819 else {
820 return FALSE;
821 }
822 }
823 return FALSE;
824 }
825
826 }