Merge pull request #4871 from eileenmcnaughton/CRM-15795
[civicrm-core.git] / api / v3 / Attachment.php
1 <?php
2
3 /*
4 +--------------------------------------------------------------------+
5 | CiviCRM version 4.6 |
6 +--------------------------------------------------------------------+
7 | Copyright CiviCRM LLC (c) 2004-2014 |
8 +--------------------------------------------------------------------+
9 | This file is a part of CiviCRM. |
10 | |
11 | CiviCRM is free software; you can copy, modify, and distribute it |
12 | under the terms of the GNU Affero General Public License |
13 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | |
15 | CiviCRM is distributed in the hope that it will be useful, but |
16 | WITHOUT ANY WARRANTY; without even the implied warranty of |
17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
18 | See the GNU Affero General Public License for more details. |
19 | |
20 | You should have received a copy of the GNU Affero General Public |
21 | License and the CiviCRM Licensing Exception along |
22 | with this program; if not, contact CiviCRM LLC |
23 | at info[AT]civicrm[DOT]org. If you have questions about the |
24 | GNU Affero General Public License or the licensing of CiviCRM, |
25 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
26 +--------------------------------------------------------------------+
27 */
28
29 /**
30 * "Attachment" is a pseudo-entity which represents a record in civicrm_file
31 * combined with a record in civicrm_entity_file as well as the underlying
32 * file content.
33 *
34 * @code
35 * $result = civicrm_api3('Attachment', 'create', array(
36 * 'entity_table' => 'civicrm_activity',
37 * 'entity_id' => 123,
38 * 'name' => 'README.txt',
39 * 'mime_type' => 'text/plain',
40 * 'content' => 'Please to read the README',
41 * ));
42 * $attachment = $result['values'][$result['id']];
43 * echo sprintf("<a href='%s'>View %s</a>", $attachment['url'], $attachment['name']);
44 * @endcode
45 *
46 * @code
47 * $result = civicrm_api3('Attachment', 'create', array(
48 * 'entity_table' => 'civicrm_activity',
49 * 'entity_id' => 123,
50 * 'name' => 'README.txt',
51 * 'mime_type' => 'text/plain',
52 * 'options' => array(
53 * 'move-file' => '/tmp/upload1a2b3c4d',
54 * ),
55 * ));
56 * $attachment = $result['values'][$result['id']];
57 * echo sprintf("<a href='%s'>View %s</a>", $attachment['url'], $attachment['name']);
58 * @endcode
59 *
60 * Notes:
61 * - File content is not returned by default. One must specify 'return => content'.
62 * - Features which deal with local file system (e.g. passing "options.move-file"
63 * or returning a "path") are only valid when executed as a local API (ie
64 * "check_permissions"==false)
65 *
66 * @package CiviCRM_APIv3
67 * @subpackage API_Attachment
68 * @copyright CiviCRM LLC (c) 2004-2014
69 * $Id: $
70 *
71 */
72
73 /**
74 * Adjust metadata for "create" action
75 *
76 * @param array $spec
77 * List of fields.
78 */
79 function _civicrm_api3_attachment_create_spec(&$spec) {
80 $spec = array_merge($spec, _civicrm_api3_attachment_getfields());
81 $spec['name']['api.required'] = 1;
82 $spec['mime_type']['api.required'] = 1;
83 $spec['entity_table']['api.required'] = 1;
84 $spec['entity_id']['api.required'] = 1;
85 $spec['upload_date']['api.default'] = 'now';
86 }
87
88 /**
89 * Create an attachment
90 *
91 * @param array $params
92 * @return array of newly created file property values.
93 * @access public
94 * @throws API_Exception validation errors
95 */
96 function civicrm_api3_attachment_create($params) {
97 $config = CRM_Core_Config::singleton();
98 list($id, $file, $entityFile, $name, $content, $moveFile, $isTrusted, $returnContent) = _civicrm_api3_attachment_parse_params($params);
99
100 $fileDao = new CRM_Core_BAO_File();
101 $entityFileDao = new CRM_Core_DAO_EntityFile();
102
103 if ($id) {
104 $fileDao->id = $id;
105 if (!$fileDao->find(TRUE)) {
106 throw new API_Exception("Invalid ID");
107 }
108
109 $entityFileDao->file_id = $id;
110 if (!$entityFileDao->find(TRUE)) {
111 throw new API_Exception("Cannot modify orphaned file");
112 }
113 }
114
115 if (!$id && !is_string($content) && !is_string($moveFile)) {
116 throw new API_Exception("Mandatory key(s) missing from params array: 'id' or 'content' or 'options.move-file'");
117 }
118 if (!$isTrusted && $moveFile) {
119 throw new API_Exception("options.move-file is only supported on secure calls");
120 }
121 if (is_string($content) && is_string($moveFile)) {
122 throw new API_Exception("'content' and 'options.move-file' are mutually exclusive");
123 }
124 if ($id && !$isTrusted && isset($file['upload_date']) && $file['upload_date'] != CRM_Utils_Date::isoToMysql($fileDao->upload_date)) {
125 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));
126 }
127 if ($id && $name && $name != CRM_Utils_File::cleanFileName($fileDao->uri)) {
128 throw new API_Exception("Cannot modify name");
129 }
130
131 $fileDao->copyValues($file);
132 if (!$id) {
133 $fileDao->uri = CRM_Utils_File::makeFileName($name);
134 }
135 $fileDao->save();
136
137 $entityFileDao->copyValues($entityFile);
138 $entityFileDao->file_id = $fileDao->id;
139 $entityFileDao->save();
140
141 $path = $config->customFileUploadDir . DIRECTORY_SEPARATOR . $fileDao->uri;
142 if (is_string($content)) {
143 file_put_contents($path, $content);
144 }
145 elseif (is_string($moveFile)) {
146 rename($moveFile, $path);
147 }
148
149 $result = array(
150 $fileDao->id => _civicrm_api3_attachment_format_result($fileDao, $entityFileDao, $returnContent, $isTrusted)
151 );
152 return civicrm_api3_create_success($result, $params, 'Attachment', 'create');
153 }
154
155 /**
156 * Adjust metadata for "create" action
157 *
158 * @param array $spec
159 * List of fields.
160 */
161 function _civicrm_api3_attachment_get_spec(&$spec) {
162 $spec = array_merge($spec, _civicrm_api3_attachment_getfields());
163 }
164
165 /**
166 * @param array $params
167 * @return array per APIv3
168 * @throws API_Exception validation errors
169 */
170 function civicrm_api3_attachment_get($params) {
171 list($id, $file, $entityFile, $name, $content, $moveFile, $isTrusted, $returnContent) = _civicrm_api3_attachment_parse_params($params);
172
173 $dao = __civicrm_api3_attachment_find($params, $id, $file, $entityFile, $isTrusted);
174 $result = array();
175 while ($dao->fetch()) {
176 $result[$dao->id] = _civicrm_api3_attachment_format_result($dao, $dao, $returnContent, $isTrusted);
177 }
178 return civicrm_api3_create_success($result, $params, 'Attachment', 'create');
179 }
180
181 function _civicrm_api3_attachment_delete_spec(&$spec) {
182 unset($spec['id']['api.required']);
183 $entityFileFields = CRM_Core_DAO_EntityFile::fields();
184 $spec['entity_table'] = $entityFileFields['entity_table'];
185 $spec['entity_table']['title'] = CRM_Utils_Array::value('title', $spec['entity_table'], 'Entity Table') . ' (write-once)';
186 $spec['entity_id'] = $entityFileFields['entity_id'];
187 $spec['entity_id']['title'] = CRM_Utils_Array::value('title', $spec['entity_id'], 'Entity ID') . ' (write-once)';
188 }
189
190 /**
191 * @param $params
192 * @return array
193 * @throws API_Exception
194 */
195 function civicrm_api3_attachment_delete($params) {
196 if (!empty($params['id'])) {
197 // ok
198 }
199 elseif (!empty($params['entity_table']) && !empty($params['entity_id'])) {
200 // ok
201 }
202 else {
203 throw new API_Exception("Mandatory key(s) missing from params array: id or entity_table+entity_table");
204 }
205
206 $config = CRM_Core_Config::singleton();
207 list($id, $file, $entityFile, $name, $content, $moveFile, $isTrusted, $returnContent) = _civicrm_api3_attachment_parse_params($params);
208 $dao = __civicrm_api3_attachment_find($params, $id, $file, $entityFile, $isTrusted);
209
210 $filePaths = array();
211 $fileIds = array();
212 while ($dao->fetch()) {
213 $filePaths[] = $config->customFileUploadDir . DIRECTORY_SEPARATOR . $dao->uri;
214 $fileIds[] = $dao->id;
215 }
216
217 if (!empty($fileIds)) {
218 $idString = implode(',', array_filter($fileIds, 'is_numeric'));
219 CRM_Core_DAO::executeQuery("DELETE FROM civicrm_entity_file WHERE file_id in ($idString)");
220 CRM_Core_DAO::executeQuery("DELETE FROM civicrm_file WHERE id in ($idString)");
221 }
222
223 // unlink is non-transactional, so we do this as the last step -- just in case the other steps produce errors
224 if (!empty($filePaths)) {
225 foreach ($filePaths as $filePath) {
226 unlink($filePath);
227 }
228 }
229
230 $result = array();
231 return civicrm_api3_create_success($result, $params, 'Attachment', 'create');
232 }
233
234 /**
235 * @param array $params
236 * @param int|null $id the user-supplied ID of the attachment record
237 * @param array $file
238 * The user-supplied vales for the file (mime_type, description, upload_date).
239 * @param array $entityFile
240 * The user-supllied values of the entity-file (entity_table, entity_id).
241 * @param bool $isTrusted
242 * @return CRM_Core_DAO
243 * @throws API_Exception
244 */
245 function __civicrm_api3_attachment_find($params, $id, $file, $entityFile, $isTrusted) {
246 foreach (array('name', 'content', 'path', 'url') as $unsupportedFilter) {
247 if (!empty($params[$unsupportedFilter])) {
248 throw new API_Exception("Get by $unsupportedFilter is not currently supported");
249 }
250 }
251
252 $select = CRM_Utils_SQL_Select::from('civicrm_file cf')
253 ->join('cef', 'INNER JOIN civicrm_entity_file cef ON cf.id = cef.file_id')
254 ->select(array(
255 'cf.id',
256 'cf.uri',
257 'cf.mime_type',
258 'cf.description',
259 'cf.upload_date',
260 'cef.entity_table',
261 'cef.entity_id',
262 ));
263
264 if ($id) {
265 $select->where('cf.id = #id', array('#id' => $id));
266 }
267 // recall: $file is filtered by parse_params
268 foreach ($file as $key => $value) {
269 $select->where('cf.!field = @value', array(
270 '!field' => $key,
271 '@value' => $value,
272 ));
273 }
274 // recall: $entityFile is filtered by parse_params
275 foreach ($entityFile as $key => $value) {
276 $select->where('cef.!field = @value', array(
277 '!field' => $key,
278 '@value' => $value,
279 ));
280 }
281 if (!$isTrusted) {
282 // FIXME ACLs: Add any JOIN or WHERE clauses needed to enforce access-controls for the target entity.
283 //
284 // The target entity is identified by "cef.entity_table" (aka $entityFile['entity_table']) and "cef.entity_id".
285 //
286 // As a simplification, we *require* the "get" actions to filter on a single "entity_table" which should
287 // avoid the complexity of matching ACL's against multiple entity types.
288 }
289
290 $dao = CRM_Core_DAO::executeQuery($select->toSQL());
291 return $dao;
292 }
293
294 /**
295 * @param array $params
296 * @return array (0 => int $id, 1 => array $file, 2 => array $entityFile, 3 => string $name, 4 => string $content, 5 => string $moveFile, 6 => $isTrusted, 7 => bool $returnContent)
297 * - array $file: whitelisted fields that can pass through directly to civicrm_file
298 * - array $entityFile: whitelisted fields that can pass through directly to civicrm_entity_file
299 * - string $name: the printable name
300 * - string $moveFile: the full path to a local file whose content should be loaded
301 * - bool $isTrusted: whether we trust the requester to do sketchy things (like moving files or reassigning entities)
302 * - bool $returnContent: whether we are expected to return the full content of the file
303 * @throws API_Exception validation errors
304 */
305 function _civicrm_api3_attachment_parse_params($params) {
306 $id = CRM_Utils_Array::value('id', $params, NULL);
307 if ($id && !is_numeric($id)) {
308 throw new API_Exception("Malformed id");
309 }
310
311 $file = array();
312 foreach (array('mime_type', 'description', 'upload_date') as $field) {
313 if (array_key_exists($field, $params)) {
314 $file[$field] = $params[$field];
315 }
316 }
317
318 $entityFile = array();
319 foreach (array('entity_table', 'entity_id') as $field) {
320 if (array_key_exists($field, $params)) {
321 $entityFile[$field] = $params[$field];
322 }
323 }
324
325 $name = NULL;
326 if (array_key_exists('name', $params)) {
327 if ($params['name'] != basename($params['name']) || preg_match(':[/\\\\]:', $params['name'])) {
328 throw new API_Exception('Malformed name');
329 }
330 $name = $params['name'];
331 }
332
333 $content = NULL;
334 if (isset($params['content'])) {
335 $content = $params['content'];
336 }
337
338 $moveFile = NULL;
339 if (isset($params['options']['move-file'])) {
340 $moveFile = $params['options']['move-file'];
341 }
342 elseif (isset($params['options.move-file'])) {
343 $moveFile = $params['options.move-file'];
344 }
345
346 $isTrusted = empty($params['check_permissions']);
347
348 $returns = isset($params['return']) ? $params['return'] : array();
349 $returns = is_array($returns) ? $returns : array($returns);
350 $returnContent = in_array('content', $returns);
351
352 return array($id, $file, $entityFile, $name, $content, $moveFile, $isTrusted, $returnContent);
353 }
354
355 /**
356 * @param CRM_Core_DAO_File $fileDao
357 * Maybe "File" or "File JOIN EntityFile".
358 * @param CRM_Core_DAO_EntityFile $entityFileDao
359 * Maybe "EntityFile" or "File JOIN EntityFile".
360 * @param bool $returnContent
361 * Whether to return the full content of the file.
362 * @param bool $isTrusted
363 * Whether the current request is trusted to perform file-specific operations.
364 * @return array
365 */
366 function _civicrm_api3_attachment_format_result($fileDao, $entityFileDao, $returnContent, $isTrusted) {
367 $config = CRM_Core_Config::singleton();
368 $path = $config->customFileUploadDir . DIRECTORY_SEPARATOR . $fileDao->uri;
369
370 $result = array(
371 'id' => $fileDao->id,
372 'name' => CRM_Utils_File::cleanFileName($fileDao->uri),
373 'mime_type' => $fileDao->mime_type,
374 'description' => $fileDao->description,
375 'upload_date' => is_numeric($fileDao->upload_date) ? CRM_Utils_Date::mysqlToIso($fileDao->upload_date) : $fileDao->upload_date,
376 'entity_table' => $entityFileDao->entity_table,
377 'entity_id' => $entityFileDao->entity_id,
378 );
379 $result['url'] = CRM_Utils_System::url(
380 'civicrm/file', 'reset=1&id=' . $result['id'] . '&eid=' . $result['entity_id'],
381 TRUE,
382 NULL,
383 FALSE,
384 TRUE
385 );
386 if ($isTrusted) {
387 $result['path'] = $path;
388 }
389 if ($returnContent) {
390 $result['content'] = file_get_contents($path);
391 }
392 return $result;
393 }
394
395 /**
396 * @return array list of fields (indexed by name)
397 */
398 function _civicrm_api3_attachment_getfields() {
399 $fileFields = CRM_Core_DAO_File::fields();
400 $entityFileFields = CRM_Core_DAO_EntityFile::fields();
401
402 $spec = array();
403 $spec['id'] = $fileFields['id'];
404 $spec['name'] = array(
405 'title' => 'Name (write-once)',
406 'description' => 'The logical file name (not searchable)',
407 'type' => CRM_Utils_Type::T_STRING,
408 );
409 $spec['mime_type'] = $fileFields['mime_type'];
410 $spec['description'] = $fileFields['description'];
411 $spec['upload_date'] = $fileFields['upload_date'];
412 $spec['entity_table'] = $entityFileFields['entity_table'];
413 $spec['entity_table']['title'] = CRM_Utils_Array::value('title', $spec['entity_table'], 'Entity Table') . ' (write-once)'; // would be hard to securely handle changes
414 $spec['entity_id'] = $entityFileFields['entity_id'];
415 $spec['entity_id']['title'] = CRM_Utils_Array::value('title', $spec['entity_id'], 'Entity ID') . ' (write-once)'; // would be hard to securely handle changes
416 $spec['url'] = array(
417 'title' => 'URL (read-only)',
418 'description' => 'URL for downloading the file (not searchable, expire-able)',
419 'type' => CRM_Utils_Type::T_STRING,
420 );
421 $spec['path'] = array(
422 'title' => 'Path (read-only)',
423 'description' => 'Local file path (not searchable, local-only)',
424 'type' => CRM_Utils_Type::T_STRING,
425 );
426 $spec['content'] = array(
427 'title' => 'Content',
428 'description' => 'File content (not searchable, not returned by default)',
429 'type' => CRM_Utils_Type::T_STRING,
430 );
431
432 return $spec;
433 }