/** * Sets widget file id values by validating and processing the submitted data. * Runs before processor callbacks. */ public static function setWidgetValue($element, &$input, FormStateInterface $form_state) { if (empty($input['imce_paths'])) { return; } $paths = $input['imce_paths']; $input['imce_paths'] = ''; // Remove excess data. $paths = array_unique(array_filter(explode(':', $paths))); if (isset($element['#cardinality']) && $element['#cardinality'] > -1) { $paths = array_slice($paths, 0, $element['#cardinality']); } // Check if paths are accessible by the current user with Imce. if (!($paths = Imce::accessFilePaths($paths, \Drupal::currentUser(), $element['#scheme']))) { return; } // Validate paths as file entities. $file_usage = \Drupal::service('file.usage'); $errors = array(); foreach ($paths as $path) { // Get entity by uri $file = Imce::getFileEntity($element['#scheme'] . '://' . $path, TRUE); if ($new_errors = file_validate($file, $element['#upload_validators'])) { $errors = array_merge($errors, $new_errors); } else { // Save the file record. if ($file->isNew()) { $file->save(); } if ($fid = $file->id()) { // Make sure the file has usage otherwise it will be denied. if (!$file_usage->listUsage($file)) { $file_usage->add($file, 'imce', 'file', $fid); } $input['fids'][] = $fid; } } } // Set error messages. if ($errors) { $errors = array_unique($errors); if (count($errors) > 1) { $errors = array('#theme' => 'item_list', '#items' => $errors); $message = \Drupal::service('renderer')->render($errors); } else { $message = array_pop($errors); } // May break the widget flow if set as a form error. drupal_set_message($message, 'error'); } }
/** * Checks if a file uri is accessible by a user with Imce. */ public static function accessFileUri($uri, AccountProxyInterface $user = NULL) { list($scheme, $path) = explode('://', $uri, 2); return $scheme && $path && Imce::accessFilePaths(array($path), $user, $scheme); }