3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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 +--------------------------------------------------------------------+
28 namespace Civi\API\Subscriber
;
31 use Symfony\Component\EventDispatcher\EventSubscriberInterface
;
34 * Given an entity which dynamically attaches itself to another entity,
35 * determine if one has permission to the other entity.
37 * Example: Suppose one tries to manipulate a File which is attached to a
38 * Mailing. DynamicFKAuthorization will enforce permissions on the File by
39 * imitating the permissions of the Mailing.
41 * Note: This enforces a constraint: all matching API calls must define
42 * "id" (e.g. for the file) or "entity_table+entity_id" or
43 * "field_name+entity_id".
45 * Note: The permission guard does not exactly authorize the request, but it
46 * may veto authorization.
48 class DynamicFKAuthorization
implements EventSubscriberInterface
{
53 public static function getSubscribedEvents() {
55 Events
::AUTHORIZE
=> array(
56 array('onApiAuthorize', Events
::W_EARLY
),
62 * @var \Civi\API\Kernel
64 * Treat as private. Marked public due to PHP 5.3-compatibility issues.
69 * @var string, the entity for which we want to manage permissions
71 protected $entityName;
74 * @var array <string> the actions for which we want to manage permissions
79 * @var string, SQL. Given a file ID, determine the entity+table it's attached to.
81 * ex: "SELECT if(cf.id,1,0) as is_valid, cef.entity_table, cef.entity_id
82 * FROM civicrm_file cf
83 * INNER JOIN civicrm_entity_file cef ON cf.id = cef.file_id
86 * Note: %1 is a parameter
87 * Note: There are three parameters
88 * - is_valid: "1" if %1 identifies an actual record; otherwise "0"
89 * - entity_table: NULL or the name of a related table
90 * - entity_id: NULL or the ID of a row in the related table
92 protected $lookupDelegateSql;
95 * @var string, SQL. Get a list of (field_name, table_name, extends) tuples.
97 * For example, one tuple might be ("custom_123", "civicrm_value_mygroup_4",
100 protected $lookupCustomFieldSql;
105 * Each item is an array(field_name => $, table_name => $, extends => $)
107 protected $lookupCustomFieldCache;
110 * @var array list of related tables for which FKs are allowed
112 protected $allowedDelegates;
115 * @param \Civi\API\Kernel $kernel
117 * @param string $entityName
118 * The entity for which we want to manage permissions (e.g. "File" or
120 * @param array $actions
121 * The actions for which we want to manage permissions (e.g. "create",
123 * @param string $lookupDelegateSql
124 * See docblock in DynamicFKAuthorization::$lookupDelegateSql.
125 * @param string $lookupCustomFieldSql
126 * See docblock in DynamicFKAuthorization::$lookupCustomFieldSql.
127 * @param array|NULL $allowedDelegates
128 * e.g. "civicrm_mailing","civicrm_activity"; NULL to allow any.
130 public function __construct($kernel, $entityName, $actions, $lookupDelegateSql, $lookupCustomFieldSql, $allowedDelegates = NULL) {
131 $this->kernel
= $kernel;
132 $this->entityName
= \CRM_Utils_String
::convertStringToCamel($entityName);
133 $this->actions
= $actions;
134 $this->lookupDelegateSql
= $lookupDelegateSql;
135 $this->lookupCustomFieldSql
= $lookupCustomFieldSql;
136 $this->allowedDelegates
= $allowedDelegates;
140 * @param \Civi\API\Event\AuthorizeEvent $event
141 * API authorization event.
142 * @throws \API_Exception
143 * @throws \Civi\API\Exception\UnauthorizedException
145 public function onApiAuthorize(\Civi\API\Event\AuthorizeEvent
$event) {
146 $apiRequest = $event->getApiRequest();
147 if ($apiRequest['version'] == 3 && \CRM_Utils_String
::convertStringToCamel($apiRequest['entity']) == $this->entityName
&& in_array(strtolower($apiRequest['action']), $this->actions
)) {
148 if (isset($apiRequest['params']['field_name'])) {
149 $fldIdx = \CRM_Utils_Array
::index(array('field_name'), $this->getCustomFields());
150 if (empty($fldIdx[$apiRequest['params']['field_name']])) {
151 throw new \
Exception("Failed to map custom field to entity table");
153 $apiRequest['params']['entity_table'] = $fldIdx[$apiRequest['params']['field_name']]['entity_table'];
154 unset($apiRequest['params']['field_name']);
158 empty($apiRequest['params']['id']) && empty($apiRequest['params']['entity_table'])
160 throw new \
API_Exception("Mandatory key(s) missing from params array: 'id' or 'entity_table'");
163 if (isset($apiRequest['params']['id'])) {
164 list($isValidId, $entityTable, $entityId) = $this->getDelegate($apiRequest['params']['id']);
165 if ($isValidId && $entityTable && $entityId) {
166 $this->authorizeDelegate($apiRequest['action'], $entityTable, $entityId, $apiRequest);
167 $this->preventReassignment($apiRequest['params']['id'], $entityTable, $entityId, $apiRequest);
170 elseif ($isValidId) {
171 throw new \
API_Exception("Failed to match record to related entity");
173 elseif (!$isValidId && strtolower($apiRequest['action']) == 'get') {
174 // The matches will be an empty set; doesn't make a difference if we
176 // To pass SyntaxConformanceTest, we won't veto "get" on empty-set.
181 if (isset($apiRequest['params']['entity_table'])) {
182 $this->authorizeDelegate(
183 $apiRequest['action'],
184 $apiRequest['params']['entity_table'],
185 \CRM_Utils_Array
::value('entity_id', $apiRequest['params'], NULL),
191 throw new \
API_Exception("Failed to run permission check");
196 * @param string $action
197 * The API action (e.g. "create").
198 * @param string $entityTable
199 * The target entity table (e.g. "civicrm_mailing").
200 * @param int|NULL $entityId
201 * The target entity ID.
202 * @param array $apiRequest
203 * The full API request.
204 * @throws \API_Exception
205 * @throws \Civi\API\Exception\UnauthorizedException
207 public function authorizeDelegate($action, $entityTable, $entityId, $apiRequest) {
208 $entity = $this->getDelegatedEntityName($entityTable);
210 throw new \
API_Exception("Failed to run permission check: Unrecognized target entity table ($entityTable)");
213 throw new \Civi\API\Exception\
UnauthorizedException("Authorization failed on ($entity): Missing entity_id");
216 if ($this->isTrusted($apiRequest)) {
221 * @var \Exception $exception
225 \CRM_Core_Transaction
::create(TRUE)->run(function($tx) use ($entity, $action, $entityId, &$exception, $self) {
226 $tx->rollback(); // Just to be safe.
230 'check_permissions' => 1,
234 $result = $self->kernel
->run($entity, $self->getDelegatedAction($action), $params);
235 if ($result['is_error'] ||
empty($result['values'])) {
236 $exception = new \Civi\API\Exception\
UnauthorizedException("Authorization failed on ($entity,$entityId)", array(
248 * If the request attempts to change the entity_table/entity_id of an
249 * existing record, then generate an error.
252 * The main record being changed.
253 * @param string $entityTable
255 * @param int $entityId
257 * @param array $apiRequest
258 * The full API request.
259 * @throws \API_Exception
261 public function preventReassignment($fileId, $entityTable, $entityId, $apiRequest) {
262 if (strtolower($apiRequest['action']) == 'create' && $fileId && !$this->isTrusted($apiRequest)) {
263 // TODO: no change in field_name?
264 if (isset($apiRequest['params']['entity_table']) && $entityTable != $apiRequest['params']['entity_table']) {
265 throw new \
API_Exception("Cannot modify entity_table");
267 if (isset($apiRequest['params']['entity_id']) && $entityId != $apiRequest['params']['entity_id']) {
268 throw new \
API_Exception("Cannot modify entity_id");
274 * @param string $entityTable
275 * The target entity table (e.g. "civicrm_mailing" or "civicrm_activity").
276 * @return string|NULL
277 * The target entity name (e.g. "Mailing" or "Activity").
279 public function getDelegatedEntityName($entityTable) {
280 if ($this->allowedDelegates
=== NULL ||
in_array($entityTable, $this->allowedDelegates
)) {
281 $className = \CRM_Core_DAO_AllCoreTables
::getClassForTable($entityTable);
283 $entityName = \CRM_Core_DAO_AllCoreTables
::getBriefName($className);
293 * @param string $action
294 * API action name -- e.g. "create" ("When running *create* on a file...").
296 * e.g. "create" ("Check for *create* permission on the mailing to which
299 public function getDelegatedAction($action) {
302 // reading attachments requires reading the other entity
307 // creating/updating/deleting an attachment requires editing
320 * (0 => bool $isValid, 1 => string $entityTable, 2 => int $entityId)
323 public function getDelegate($id) {
324 $query = \CRM_Core_DAO
::executeQuery($this->lookupDelegateSql
, array(
325 1 => array($id, 'Positive'),
327 if ($query->fetch()) {
328 if (!preg_match('/^civicrm_value_/', $query->entity_table
)) {
329 // A normal attachment directly on its entity.
330 return array($query->is_valid
, $query->entity_table
, $query->entity_id
);
333 // Ex: Translate custom-field table ("civicrm_value_foo_4") to
334 // entity table ("civicrm_activity").
335 $tblIdx = \CRM_Utils_Array
::index(array('table_name'), $this->getCustomFields());
336 if (isset($tblIdx[$query->entity_table
])) {
337 return array($query->is_valid
, $tblIdx[$query->entity_table
]['entity_table'], $query->entity_id
);
339 throw new \
Exception('Failed to lookup entity table for custom field.');
342 return array(FALSE, NULL, NULL);
347 * @param array $apiRequest
348 * The full API request.
351 public function isTrusted($apiRequest) {
352 // isn't this redundant?
353 return empty($apiRequest['params']['check_permissions']) or $apiRequest['params']['check_permissions'] == FALSE;
358 * Each item has keys 'field_name', 'table_name', 'extends', 'entity_table'
360 public function getCustomFields() {
361 $query = \CRM_Core_DAO
::executeQuery($this->lookupCustomFieldSql
);
363 while ($query->fetch()) {
365 'field_name' => $query->field_name
,
366 'table_name' => $query->table_name
,
367 'extends' => $query->extends,
368 'entity_table' => \CRM_Core_BAO_CustomGroup
::getTableNameByEntityName($query->extends),