3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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 +--------------------------------------------------------------------+
29 * "Attachment" is a pseudo-entity which represents a record in civicrm_file
30 * combined with a record in civicrm_entity_file as well as the underlying
32 * For core fields use "entity_table", for custom fields use "field_name"
35 * // Create an attachment for a core field
36 * $result = civicrm_api3('Attachment', 'create', array(
37 * 'entity_table' => 'civicrm_activity',
39 * 'name' => 'README.txt',
40 * 'mime_type' => 'text/plain',
41 * 'content' => 'Please to read the README',
43 * $attachment = $result['values'][$result['id']];
44 * echo sprintf("<a href='%s'>View %s</a>", $attachment['url'], $attachment['name']);
48 * // Create an attachment for a custom file field
49 * $result = civicrm_api3('Attachment', 'create', array(
50 * 'field_name' => 'custom_6',
52 * 'name' => 'README.txt',
53 * 'mime_type' => 'text/plain',
54 * 'content' => 'Please to read the README',
56 * $attachment = $result['values'][$result['id']];
57 * echo sprintf("<a href='%s'>View %s</a>", $attachment['url'], $attachment['name']);
61 * // Move an existing file and save as an attachment
62 * $result = civicrm_api3('Attachment', 'create', array(
63 * 'entity_table' => 'civicrm_activity',
65 * 'name' => 'README.txt',
66 * 'mime_type' => 'text/plain',
68 * 'move-file' => '/tmp/upload1a2b3c4d',
71 * $attachment = $result['values'][$result['id']];
72 * echo sprintf("<a href='%s'>View %s</a>", $attachment['url'], $attachment['name']);
76 * - File content is not returned by default. One must specify 'return => content'.
77 * - Features which deal with local file system (e.g. passing "options.move-file"
78 * or returning a "path") are only valid when executed as a local API (ie
79 * "check_permissions"==false)
81 * @package CiviCRM_APIv3
85 * Adjust metadata for "create" action.
90 function _civicrm_api3_attachment_create_spec(&$spec) {
91 $spec = array_merge($spec, _civicrm_api3_attachment_getfields());
92 $spec['name']['api.required'] = 1;
93 $spec['mime_type']['api.required'] = 1;
94 $spec['entity_id']['api.required'] = 1;
95 $spec['upload_date']['api.default'] = 'now';
99 * Create an Attachment.
101 * @param array $params
104 * @throws API_Exception validation errors
105 * @see Civi\API\Subscriber\DynamicFKAuthorization
107 function civicrm_api3_attachment_create($params) {
108 if (empty($params['id'])) {
109 // When creating we need either entity_table or field_name.
110 civicrm_api3_verify_one_mandatory($params, NULL, array('entity_table', 'field_name'));
113 $config = CRM_Core_Config
::singleton();
114 list($id, $file, $entityFile, $name, $content, $moveFile, $isTrusted, $returnContent) = _civicrm_api3_attachment_parse_params($params);
116 $fileDao = new CRM_Core_BAO_File();
117 $entityFileDao = new CRM_Core_DAO_EntityFile();
121 if (!$fileDao->find(TRUE)) {
122 throw new API_Exception("Invalid ID");
125 $entityFileDao->file_id
= $id;
126 if (!$entityFileDao->find(TRUE)) {
127 throw new API_Exception("Cannot modify orphaned file");
131 if (!$id && !is_string($content) && !is_string($moveFile)) {
132 throw new API_Exception("Mandatory key(s) missing from params array: 'id' or 'content' or 'options.move-file'");
134 if (!$isTrusted && $moveFile) {
135 throw new API_Exception("options.move-file is only supported on secure calls");
137 if (is_string($content) && is_string($moveFile)) {
138 throw new API_Exception("'content' and 'options.move-file' are mutually exclusive");
140 if ($id && !$isTrusted && isset($file['upload_date']) && $file['upload_date'] != CRM_Utils_Date
::isoToMysql($fileDao->upload_date
)) {
141 throw new API_Exception("Cannot modify upload_date" . var_export(array($file['upload_date'], $fileDao->upload_date
, CRM_Utils_Date
::isoToMysql($fileDao->upload_date
)), TRUE));
143 if ($id && $name && $name != CRM_Utils_File
::cleanFileName($fileDao->uri
)) {
144 throw new API_Exception("Cannot modify name");
147 $fileDao->copyValues($file);
149 $fileDao->uri
= CRM_Utils_File
::makeFileName($name);
153 $entityFileDao->copyValues($entityFile);
154 $entityFileDao->file_id
= $fileDao->id
;
155 $entityFileDao->save();
157 $path = $config->customFileUploadDir
. DIRECTORY_SEPARATOR
. $fileDao->uri
;
158 if (is_string($content)) {
159 file_put_contents($path, $content);
161 elseif (is_string($moveFile)) {
162 // CRM-17432 Do not use rename() since it will break file permissions.
163 // Also avoid move_uplaoded_file() because the API can use options.move-file.
164 copy($moveFile, $path);
168 // Save custom field to entity
169 if (!$id && empty($params['entity_table']) && isset($params['field_name'])) {
170 civicrm_api3('custom_value', 'create', array(
171 'entity_id' => $params['entity_id'],
172 $params['field_name'] => $fileDao->id
,
177 $fileDao->id
=> _civicrm_api3_attachment_format_result($fileDao, $entityFileDao, $returnContent, $isTrusted),
179 return civicrm_api3_create_success($result, $params, 'Attachment', 'create');
183 * Adjust metadata for get action.
188 function _civicrm_api3_attachment_get_spec(&$spec) {
189 $spec = array_merge($spec, _civicrm_api3_attachment_getfields());
195 * @param array $params
199 * @throws API_Exception validation errors
201 function civicrm_api3_attachment_get($params) {
202 list($id, $file, $entityFile, $name, $content, $moveFile, $isTrusted, $returnContent) = _civicrm_api3_attachment_parse_params($params);
204 $dao = __civicrm_api3_attachment_find($params, $id, $file, $entityFile, $isTrusted);
206 while ($dao->fetch()) {
207 $result[$dao->id
] = _civicrm_api3_attachment_format_result($dao, $dao, $returnContent, $isTrusted);
209 return civicrm_api3_create_success($result, $params, 'Attachment', 'create');
213 * Adjust metadata for Attachment delete action.
217 function _civicrm_api3_attachment_delete_spec(&$spec) {
218 unset($spec['id']['api.required']);
219 $entityFileFields = CRM_Core_DAO_EntityFile
::fields();
220 $spec['entity_table'] = $entityFileFields['entity_table'];
221 $spec['entity_table']['title'] = CRM_Utils_Array
::value('title', $spec['entity_table'], 'Entity Table') . ' (write-once)';
222 $spec['entity_id'] = $entityFileFields['entity_id'];
223 $spec['entity_id']['title'] = CRM_Utils_Array
::value('title', $spec['entity_id'], 'Entity ID') . ' (write-once)';
229 * @param array $params
232 * @throws API_Exception
234 function civicrm_api3_attachment_delete($params) {
235 if (!empty($params['id'])) {
238 elseif (!empty($params['entity_table']) && !empty($params['entity_id'])) {
242 throw new API_Exception("Mandatory key(s) missing from params array: id or entity_table+entity_table");
245 $config = CRM_Core_Config
::singleton();
246 list($id, $file, $entityFile, $name, $content, $moveFile, $isTrusted, $returnContent) = _civicrm_api3_attachment_parse_params($params);
247 $dao = __civicrm_api3_attachment_find($params, $id, $file, $entityFile, $isTrusted);
249 $filePaths = array();
251 while ($dao->fetch()) {
252 $filePaths[] = $config->customFileUploadDir
. DIRECTORY_SEPARATOR
. $dao->uri
;
253 $fileIds[] = $dao->id
;
256 if (!empty($fileIds)) {
257 $idString = implode(',', array_filter($fileIds, 'is_numeric'));
258 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_entity_file WHERE file_id in ($idString)");
259 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_file WHERE id in ($idString)");
262 // unlink is non-transactional, so we do this as the last step -- just in case the other steps produce errors
263 if (!empty($filePaths)) {
264 foreach ($filePaths as $filePath) {
270 return civicrm_api3_create_success($result, $params, 'Attachment', 'create');
274 * Attachment find helper.
276 * @param array $params
277 * @param int|null $id the user-supplied ID of the attachment record
279 * The user-supplied vales for the file (mime_type, description, upload_date).
280 * @param array $entityFile
281 * The user-supplied values of the entity-file (entity_table, entity_id).
282 * @param bool $isTrusted
284 * @return CRM_Core_DAO
285 * @throws API_Exception
287 function __civicrm_api3_attachment_find($params, $id, $file, $entityFile, $isTrusted) {
288 foreach (array('name', 'content', 'path', 'url') as $unsupportedFilter) {
289 if (!empty($params[$unsupportedFilter])) {
290 throw new API_Exception("Get by $unsupportedFilter is not currently supported");
294 $select = CRM_Utils_SQL_Select
::from('civicrm_file cf')
295 ->join('cef', 'INNER JOIN civicrm_entity_file cef ON cf.id = cef.file_id')
307 $select->where('cf.id = #id', array('#id' => $id));
309 // Recall: $file is filtered by parse_params.
310 foreach ($file as $key => $value) {
311 $select->where('cf.!field = @value', array(
316 // Recall: $entityFile is filtered by parse_params.
317 foreach ($entityFile as $key => $value) {
318 $select->where('cef.!field = @value', array(
324 // FIXME ACLs: Add any JOIN or WHERE clauses needed to enforce access-controls for the target entity.
326 // The target entity is identified by "cef.entity_table" (aka $entityFile['entity_table']) and "cef.entity_id".
328 // As a simplification, we *require* the "get" actions to filter on a single "entity_table" which should
329 // avoid the complexity of matching ACL's against multiple entity types.
332 $dao = CRM_Core_DAO
::executeQuery($select->toSQL());
337 * Attachment parsing helper.
339 * @param array $params
342 * (0 => int $id, 1 => array $file, 2 => array $entityFile, 3 => string $name, 4 => string $content,
343 * 5 => string $moveFile, 6 => $isTrusted, 7 => bool $returnContent)
344 * - array $file: whitelisted fields that can pass through directly to civicrm_file
345 * - array $entityFile: whitelisted fields that can pass through directly to civicrm_entity_file
346 * - string $name: the printable name
347 * - string $moveFile: the full path to a local file whose content should be loaded
348 * - bool $isTrusted: whether we trust the requester to do sketchy things (like moving files or reassigning entities)
349 * - bool $returnContent: whether we are expected to return the full content of the file
350 * @throws API_Exception validation errors
352 function _civicrm_api3_attachment_parse_params($params) {
353 $id = CRM_Utils_Array
::value('id', $params, NULL);
354 if ($id && !is_numeric($id)) {
355 throw new API_Exception("Malformed id");
359 foreach (array('mime_type', 'description', 'upload_date') as $field) {
360 if (array_key_exists($field, $params)) {
361 $file[$field] = $params[$field];
365 $entityFile = array();
366 foreach (array('entity_table', 'entity_id') as $field) {
367 if (array_key_exists($field, $params)) {
368 $entityFile[$field] = $params[$field];
372 if (empty($params['entity_table']) && isset($params['field_name'])) {
373 $tableInfo = CRM_Core_BAO_CustomField
::getTableColumnGroup(intval(str_replace('custom_', '', $params['field_name'])));
374 $entityFile['entity_table'] = $tableInfo[0];
378 if (array_key_exists('name', $params)) {
379 if ($params['name'] != basename($params['name']) ||
preg_match(':[/\\\\]:', $params['name'])) {
380 throw new API_Exception('Malformed name');
382 $name = $params['name'];
386 if (isset($params['content'])) {
387 $content = $params['content'];
391 if (isset($params['options']['move-file'])) {
392 $moveFile = $params['options']['move-file'];
394 elseif (isset($params['options.move-file'])) {
395 $moveFile = $params['options.move-file'];
398 $isTrusted = empty($params['check_permissions']);
400 $returns = isset($params['return']) ?
$params['return'] : array();
401 $returns = is_array($returns) ?
$returns : array($returns);
402 $returnContent = in_array('content', $returns);
404 return array($id, $file, $entityFile, $name, $content, $moveFile, $isTrusted, $returnContent);
408 * Attachment result formatting helper.
410 * @param CRM_Core_DAO_File $fileDao
411 * Maybe "File" or "File JOIN EntityFile".
412 * @param CRM_Core_DAO_EntityFile $entityFileDao
413 * Maybe "EntityFile" or "File JOIN EntityFile".
414 * @param bool $returnContent
415 * Whether to return the full content of the file.
416 * @param bool $isTrusted
417 * Whether the current request is trusted to perform file-specific operations.
421 function _civicrm_api3_attachment_format_result($fileDao, $entityFileDao, $returnContent, $isTrusted) {
422 $config = CRM_Core_Config
::singleton();
423 $path = $config->customFileUploadDir
. DIRECTORY_SEPARATOR
. $fileDao->uri
;
426 'id' => $fileDao->id
,
427 'name' => CRM_Utils_File
::cleanFileName($fileDao->uri
),
428 'mime_type' => $fileDao->mime_type
,
429 'description' => $fileDao->description
,
430 'upload_date' => is_numeric($fileDao->upload_date
) ? CRM_Utils_Date
::mysqlToIso($fileDao->upload_date
) : $fileDao->upload_date
,
431 'entity_table' => $entityFileDao->entity_table
,
432 'entity_id' => $entityFileDao->entity_id
,
433 'icon' => CRM_Utils_File
::getIconFromMimeType($fileDao->mime_type
),
435 $result['url'] = CRM_Utils_System
::url(
436 'civicrm/file', 'reset=1&id=' . $result['id'] . '&eid=' . $result['entity_id'],
443 $result['path'] = $path;
445 if ($returnContent) {
446 $result['content'] = file_get_contents($path);
452 * Attachment getfields helper.
455 * list of fields (indexed by name)
457 function _civicrm_api3_attachment_getfields() {
458 $fileFields = CRM_Core_DAO_File
::fields();
459 $entityFileFields = CRM_Core_DAO_EntityFile
::fields();
462 $spec['id'] = $fileFields['id'];
463 $spec['name'] = array(
464 'title' => 'Name (write-once)',
465 'description' => 'The logical file name (not searchable)',
466 'type' => CRM_Utils_Type
::T_STRING
,
468 $spec['field_name'] = array(
469 'title' => 'Field Name (write-once)',
470 'description' => 'Alternative to "entity_table" param - sets custom field value.',
471 'type' => CRM_Utils_Type
::T_STRING
,
473 $spec['mime_type'] = $fileFields['mime_type'];
474 $spec['description'] = $fileFields['description'];
475 $spec['upload_date'] = $fileFields['upload_date'];
476 $spec['entity_table'] = $entityFileFields['entity_table'];
477 // Would be hard to securely handle changes.
478 $spec['entity_table']['title'] = CRM_Utils_Array
::value('title', $spec['entity_table'], 'Entity Table') . ' (write-once)';
479 $spec['entity_id'] = $entityFileFields['entity_id'];
480 $spec['entity_id']['title'] = CRM_Utils_Array
::value('title', $spec['entity_id'], 'Entity ID') . ' (write-once)'; // would be hard to securely handle changes
481 $spec['url'] = array(
482 'title' => 'URL (read-only)',
483 'description' => 'URL for downloading the file (not searchable, expire-able)',
484 'type' => CRM_Utils_Type
::T_STRING
,
486 $spec['path'] = array(
487 'title' => 'Path (read-only)',
488 'description' => 'Local file path (not searchable, local-only)',
489 'type' => CRM_Utils_Type
::T_STRING
,
491 $spec['content'] = array(
492 'title' => 'Content',
493 'description' => 'File content (not searchable, not returned by default)',
494 'type' => CRM_Utils_Type
::T_STRING
,