commiting uncommited changes on live site
[weblabels.fsf.org.git] / crm.fsf.org / 20131203 / files / sites / all / modules-new / civicrm / api / v3 / Attachment.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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 * "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
31 * file content.
32 * For core fields use "entity_table", for custom fields use "field_name"
33 *
34 * @code
35 * // Create an attachment for a core field
36 * $result = civicrm_api3('Attachment', 'create', array(
37 * 'entity_table' => 'civicrm_activity',
38 * 'entity_id' => 123,
39 * 'name' => 'README.txt',
40 * 'mime_type' => 'text/plain',
41 * 'content' => 'Please to read the README',
42 * ));
43 * $attachment = $result['values'][$result['id']];
44 * echo sprintf("<a href='%s'>View %s</a>", $attachment['url'], $attachment['name']);
45 * @endcode
46 *
47 * @code
48 * // Create an attachment for a custom file field
49 * $result = civicrm_api3('Attachment', 'create', array(
50 * 'field_name' => 'custom_6',
51 * 'entity_id' => 123,
52 * 'name' => 'README.txt',
53 * 'mime_type' => 'text/plain',
54 * 'content' => 'Please to read the README',
55 * ));
56 * $attachment = $result['values'][$result['id']];
57 * echo sprintf("<a href='%s'>View %s</a>", $attachment['url'], $attachment['name']);
58 * @endcode
59 *
60 * @code
61 * // Move an existing file and save as an attachment
62 * $result = civicrm_api3('Attachment', 'create', array(
63 * 'entity_table' => 'civicrm_activity',
64 * 'entity_id' => 123,
65 * 'name' => 'README.txt',
66 * 'mime_type' => 'text/plain',
67 * 'options' => array(
68 * 'move-file' => '/tmp/upload1a2b3c4d',
69 * ),
70 * ));
71 * $attachment = $result['values'][$result['id']];
72 * echo sprintf("<a href='%s'>View %s</a>", $attachment['url'], $attachment['name']);
73 * @endcode
74 *
75 * Notes:
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)
80 *
81 * @package CiviCRM_APIv3
82 */
83
84 /**
85 * Adjust metadata for "create" action.
86 *
87 * @param array $spec
88 * List of fields.
89 */
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';
96 }
97
98 /**
99 * Create an Attachment.
100 *
101 * @param array $params
102 *
103 * @return array
104 * @throws API_Exception validation errors
105 * @see Civi\API\Subscriber\DynamicFKAuthorization
106 */
107 function civicrm_api3_attachment_create($params) {
108
109 if (empty($params['id'])) {
110 // When creating we need either entity_table or field_name
111 civicrm_api3_verify_one_mandatory($params, NULL, array('entity_table', 'field_name'));
112 }
113
114 $config = CRM_Core_Config::singleton();
115 list($id, $file, $entityFile, $name, $content, $moveFile, $isTrusted, $returnContent) = _civicrm_api3_attachment_parse_params($params);
116
117 $fileDao = new CRM_Core_BAO_File();
118 $entityFileDao = new CRM_Core_DAO_EntityFile();
119
120 if ($id) {
121 $fileDao->id = $id;
122 if (!$fileDao->find(TRUE)) {
123 throw new API_Exception("Invalid ID");
124 }
125
126 $entityFileDao->file_id = $id;
127 if (!$entityFileDao->find(TRUE)) {
128 throw new API_Exception("Cannot modify orphaned file");
129 }
130 }
131
132 if (!$id && !is_string($content) && !is_string($moveFile)) {
133 throw new API_Exception("Mandatory key(s) missing from params array: 'id' or 'content' or 'options.move-file'");
134 }
135 if (!$isTrusted && $moveFile) {
136 throw new API_Exception("options.move-file is only supported on secure calls");
137 }
138 if (is_string($content) && is_string($moveFile)) {
139 throw new API_Exception("'content' and 'options.move-file' are mutually exclusive");
140 }
141 if ($id && !$isTrusted && isset($file['upload_date']) && $file['upload_date'] != CRM_Utils_Date::isoToMysql($fileDao->upload_date)) {
142 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 }
144 if ($id && $name && $name != CRM_Utils_File::cleanFileName($fileDao->uri)) {
145 throw new API_Exception("Cannot modify name");
146 }
147
148 $fileDao->copyValues($file);
149 if (!$id) {
150 $fileDao->uri = CRM_Utils_File::makeFileName($name);
151 }
152 $fileDao->save();
153
154 $entityFileDao->copyValues($entityFile);
155 $entityFileDao->file_id = $fileDao->id;
156 $entityFileDao->save();
157
158 $path = $config->customFileUploadDir . DIRECTORY_SEPARATOR . $fileDao->uri;
159 if (is_string($content)) {
160 file_put_contents($path, $content);
161 }
162 elseif (is_string($moveFile)) {
163 rename($moveFile, $path);
164 }
165
166 // Save custom field to entity
167 if (!$id && empty($params['entity_table']) && isset($params['field_name'])) {
168 civicrm_api3('custom_value', 'create', array(
169 'entity_id' => $params['entity_id'],
170 $params['field_name'] => $fileDao->id,
171 ));
172 }
173
174 $result = array(
175 $fileDao->id => _civicrm_api3_attachment_format_result($fileDao, $entityFileDao, $returnContent, $isTrusted),
176 );
177 return civicrm_api3_create_success($result, $params, 'Attachment', 'create');
178 }
179
180 /**
181 * Adjust metadata for get action.
182 *
183 * @param array $spec
184 * List of fields.
185 */
186 function _civicrm_api3_attachment_get_spec(&$spec) {
187 $spec = array_merge($spec, _civicrm_api3_attachment_getfields());
188 }
189
190 /**
191 * Get Attachment.
192 *
193 * @param array $params
194 *
195 * @return array
196 * per APIv3
197 * @throws API_Exception validation errors
198 */
199 function civicrm_api3_attachment_get($params) {
200 list($id, $file, $entityFile, $name, $content, $moveFile, $isTrusted, $returnContent) = _civicrm_api3_attachment_parse_params($params);
201
202 $dao = __civicrm_api3_attachment_find($params, $id, $file, $entityFile, $isTrusted);
203 $result = array();
204 while ($dao->fetch()) {
205 $result[$dao->id] = _civicrm_api3_attachment_format_result($dao, $dao, $returnContent, $isTrusted);
206 }
207 return civicrm_api3_create_success($result, $params, 'Attachment', 'create');
208 }
209
210 /**
211 * Adjust metadata for Attachment delete action.
212 *
213 * @param $spec
214 */
215 function _civicrm_api3_attachment_delete_spec(&$spec) {
216 unset($spec['id']['api.required']);
217 $entityFileFields = CRM_Core_DAO_EntityFile::fields();
218 $spec['entity_table'] = $entityFileFields['entity_table'];
219 $spec['entity_table']['title'] = CRM_Utils_Array::value('title', $spec['entity_table'], 'Entity Table') . ' (write-once)';
220 $spec['entity_id'] = $entityFileFields['entity_id'];
221 $spec['entity_id']['title'] = CRM_Utils_Array::value('title', $spec['entity_id'], 'Entity ID') . ' (write-once)';
222 }
223
224 /**
225 * Delete Attachment.
226 *
227 * @param array $params
228 *
229 * @return array
230 * @throws API_Exception
231 */
232 function civicrm_api3_attachment_delete($params) {
233 if (!empty($params['id'])) {
234 // ok
235 }
236 elseif (!empty($params['entity_table']) && !empty($params['entity_id'])) {
237 // ok
238 }
239 else {
240 throw new API_Exception("Mandatory key(s) missing from params array: id or entity_table+entity_table");
241 }
242
243 $config = CRM_Core_Config::singleton();
244 list($id, $file, $entityFile, $name, $content, $moveFile, $isTrusted, $returnContent) = _civicrm_api3_attachment_parse_params($params);
245 $dao = __civicrm_api3_attachment_find($params, $id, $file, $entityFile, $isTrusted);
246
247 $filePaths = array();
248 $fileIds = array();
249 while ($dao->fetch()) {
250 $filePaths[] = $config->customFileUploadDir . DIRECTORY_SEPARATOR . $dao->uri;
251 $fileIds[] = $dao->id;
252 }
253
254 if (!empty($fileIds)) {
255 $idString = implode(',', array_filter($fileIds, 'is_numeric'));
256 CRM_Core_DAO::executeQuery("DELETE FROM civicrm_entity_file WHERE file_id in ($idString)");
257 CRM_Core_DAO::executeQuery("DELETE FROM civicrm_file WHERE id in ($idString)");
258 }
259
260 // unlink is non-transactional, so we do this as the last step -- just in case the other steps produce errors
261 if (!empty($filePaths)) {
262 foreach ($filePaths as $filePath) {
263 unlink($filePath);
264 }
265 }
266
267 $result = array();
268 return civicrm_api3_create_success($result, $params, 'Attachment', 'create');
269 }
270
271 /**
272 * Attachment find helper.
273 *
274 * @param array $params
275 * @param int|null $id the user-supplied ID of the attachment record
276 * @param array $file
277 * The user-supplied vales for the file (mime_type, description, upload_date).
278 * @param array $entityFile
279 * The user-supplied values of the entity-file (entity_table, entity_id).
280 * @param bool $isTrusted
281 *
282 * @return CRM_Core_DAO
283 * @throws API_Exception
284 */
285 function __civicrm_api3_attachment_find($params, $id, $file, $entityFile, $isTrusted) {
286 foreach (array('name', 'content', 'path', 'url') as $unsupportedFilter) {
287 if (!empty($params[$unsupportedFilter])) {
288 throw new API_Exception("Get by $unsupportedFilter is not currently supported");
289 }
290 }
291
292 $select = CRM_Utils_SQL_Select::from('civicrm_file cf')
293 ->join('cef', 'INNER JOIN civicrm_entity_file cef ON cf.id = cef.file_id')
294 ->select(array(
295 'cf.id',
296 'cf.uri',
297 'cf.mime_type',
298 'cf.description',
299 'cf.upload_date',
300 'cef.entity_table',
301 'cef.entity_id',
302 ));
303
304 if ($id) {
305 $select->where('cf.id = #id', array('#id' => $id));
306 }
307 // Recall: $file is filtered by parse_params.
308 foreach ($file as $key => $value) {
309 $select->where('cf.!field = @value', array(
310 '!field' => $key,
311 '@value' => $value,
312 ));
313 }
314 // Recall: $entityFile is filtered by parse_params.
315 foreach ($entityFile as $key => $value) {
316 $select->where('cef.!field = @value', array(
317 '!field' => $key,
318 '@value' => $value,
319 ));
320 }
321 if (!$isTrusted) {
322 // FIXME ACLs: Add any JOIN or WHERE clauses needed to enforce access-controls for the target entity.
323 //
324 // The target entity is identified by "cef.entity_table" (aka $entityFile['entity_table']) and "cef.entity_id".
325 //
326 // As a simplification, we *require* the "get" actions to filter on a single "entity_table" which should
327 // avoid the complexity of matching ACL's against multiple entity types.
328 }
329
330 $dao = CRM_Core_DAO::executeQuery($select->toSQL());
331 return $dao;
332 }
333
334 /**
335 * Attachment parsing helper.
336 *
337 * @param array $params
338 *
339 * @return array
340 * (0 => int $id, 1 => array $file, 2 => array $entityFile, 3 => string $name, 4 => string $content,
341 * 5 => string $moveFile, 6 => $isTrusted, 7 => bool $returnContent)
342 * - array $file: whitelisted fields that can pass through directly to civicrm_file
343 * - array $entityFile: whitelisted fields that can pass through directly to civicrm_entity_file
344 * - string $name: the printable name
345 * - string $moveFile: the full path to a local file whose content should be loaded
346 * - bool $isTrusted: whether we trust the requester to do sketchy things (like moving files or reassigning entities)
347 * - bool $returnContent: whether we are expected to return the full content of the file
348 * @throws API_Exception validation errors
349 */
350 function _civicrm_api3_attachment_parse_params($params) {
351 $id = CRM_Utils_Array::value('id', $params, NULL);
352 if ($id && !is_numeric($id)) {
353 throw new API_Exception("Malformed id");
354 }
355
356 $file = array();
357 foreach (array('mime_type', 'description', 'upload_date') as $field) {
358 if (array_key_exists($field, $params)) {
359 $file[$field] = $params[$field];
360 }
361 }
362
363 $entityFile = array();
364 foreach (array('entity_table', 'entity_id') as $field) {
365 if (array_key_exists($field, $params)) {
366 $entityFile[$field] = $params[$field];
367 }
368 }
369
370 if (empty($params['entity_table']) && isset($params['field_name'])) {
371 $tableInfo = CRM_Core_BAO_CustomField::getTableColumnGroup(intval(str_replace('custom_', '', $params['field_name'])));
372 $entityFile['entity_table'] = $tableInfo[0];
373 }
374
375 $name = NULL;
376 if (array_key_exists('name', $params)) {
377 if ($params['name'] != basename($params['name']) || preg_match(':[/\\\\]:', $params['name'])) {
378 throw new API_Exception('Malformed name');
379 }
380 $name = $params['name'];
381 }
382
383 $content = NULL;
384 if (isset($params['content'])) {
385 $content = $params['content'];
386 }
387
388 $moveFile = NULL;
389 if (isset($params['options']['move-file'])) {
390 $moveFile = $params['options']['move-file'];
391 }
392 elseif (isset($params['options.move-file'])) {
393 $moveFile = $params['options.move-file'];
394 }
395
396 $isTrusted = empty($params['check_permissions']);
397
398 $returns = isset($params['return']) ? $params['return'] : array();
399 $returns = is_array($returns) ? $returns : array($returns);
400 $returnContent = in_array('content', $returns);
401
402 return array($id, $file, $entityFile, $name, $content, $moveFile, $isTrusted, $returnContent);
403 }
404
405 /**
406 * Attachment result formatting helper.
407 *
408 * @param CRM_Core_DAO_File $fileDao
409 * Maybe "File" or "File JOIN EntityFile".
410 * @param CRM_Core_DAO_EntityFile $entityFileDao
411 * Maybe "EntityFile" or "File JOIN EntityFile".
412 * @param bool $returnContent
413 * Whether to return the full content of the file.
414 * @param bool $isTrusted
415 * Whether the current request is trusted to perform file-specific operations.
416 *
417 * @return array
418 */
419 function _civicrm_api3_attachment_format_result($fileDao, $entityFileDao, $returnContent, $isTrusted) {
420 $config = CRM_Core_Config::singleton();
421 $path = $config->customFileUploadDir . DIRECTORY_SEPARATOR . $fileDao->uri;
422
423 $result = array(
424 'id' => $fileDao->id,
425 'name' => CRM_Utils_File::cleanFileName($fileDao->uri),
426 'mime_type' => $fileDao->mime_type,
427 'description' => $fileDao->description,
428 'upload_date' => is_numeric($fileDao->upload_date) ? CRM_Utils_Date::mysqlToIso($fileDao->upload_date) : $fileDao->upload_date,
429 'entity_table' => $entityFileDao->entity_table,
430 'entity_id' => $entityFileDao->entity_id,
431 );
432 $result['url'] = CRM_Utils_System::url(
433 'civicrm/file', 'reset=1&id=' . $result['id'] . '&eid=' . $result['entity_id'],
434 TRUE,
435 NULL,
436 FALSE,
437 TRUE
438 );
439 if ($isTrusted) {
440 $result['path'] = $path;
441 }
442 if ($returnContent) {
443 $result['content'] = file_get_contents($path);
444 }
445 return $result;
446 }
447
448 /**
449 * Attachment getfields helper.
450 *
451 * @return array
452 * list of fields (indexed by name)
453 */
454 function _civicrm_api3_attachment_getfields() {
455 $fileFields = CRM_Core_DAO_File::fields();
456 $entityFileFields = CRM_Core_DAO_EntityFile::fields();
457
458 $spec = array();
459 $spec['id'] = $fileFields['id'];
460 $spec['name'] = array(
461 'title' => 'Name (write-once)',
462 'description' => 'The logical file name (not searchable)',
463 'type' => CRM_Utils_Type::T_STRING,
464 );
465 $spec['field_name'] = array(
466 'title' => 'Field Name (write-once)',
467 'description' => 'Alternative to "entity_table" param - sets custom field value.',
468 'type' => CRM_Utils_Type::T_STRING,
469 );
470 $spec['mime_type'] = $fileFields['mime_type'];
471 $spec['description'] = $fileFields['description'];
472 $spec['upload_date'] = $fileFields['upload_date'];
473 $spec['entity_table'] = $entityFileFields['entity_table'];
474 // Would be hard to securely handle changes.
475 $spec['entity_table']['title'] = CRM_Utils_Array::value('title', $spec['entity_table'], 'Entity Table') . ' (write-once)';
476 $spec['entity_id'] = $entityFileFields['entity_id'];
477 $spec['entity_id']['title'] = CRM_Utils_Array::value('title', $spec['entity_id'], 'Entity ID') . ' (write-once)'; // would be hard to securely handle changes
478 $spec['url'] = array(
479 'title' => 'URL (read-only)',
480 'description' => 'URL for downloading the file (not searchable, expire-able)',
481 'type' => CRM_Utils_Type::T_STRING,
482 );
483 $spec['path'] = array(
484 'title' => 'Path (read-only)',
485 'description' => 'Local file path (not searchable, local-only)',
486 'type' => CRM_Utils_Type::T_STRING,
487 );
488 $spec['content'] = array(
489 'title' => 'Content',
490 'description' => 'File content (not searchable, not returned by default)',
491 'type' => CRM_Utils_Type::T_STRING,
492 );
493
494 return $spec;
495 }