5 * Contains \Drupal\filefield_sources\Plugin\FilefieldSource\Attach.
8 namespace Drupal\filefield_sources\Plugin\FilefieldSource;
10 use Drupal\Core\Form\FormStateInterface;
11 use Drupal\filefield_sources\FilefieldSourceInterface;
12 use Drupal\Core\Field\WidgetInterface;
13 use Drupal\Component\Utility\NestedArray;
14 use Drupal\Core\Site\Settings;
15 use Drupal\Core\Template\Attribute;
18 * A FileField source plugin to allow use of files within a server directory.
22 * name = @Translation("File attach from server directory"),
23 * label = @Translation("File attach"),
24 * description = @Translation("Select a file from a directory on the server."),
28 class Attach implements FilefieldSourceInterface {
33 public static function value(array &$element, &$input, FormStateInterface $form_state) {
34 if (!empty($input['filefield_attach']['filename'])) {
35 $instance = entity_load('field_config', $element['#entity_type'] . '.' . $element['#bundle'] . '.' . $element['#field_name']);
36 $filepath = $input['filefield_attach']['filename'];
38 // Check that the destination is writable.
39 $directory = $element['#upload_location'];
40 $mode = Settings::get('file_chmod_directory', FILE_CHMOD_DIRECTORY);
42 // This first chmod check is for other systems such as S3, which don't
43 // work with file_prepare_directory().
44 if (!drupal_chmod($directory, $mode) && !file_prepare_directory($directory, FILE_CREATE_DIRECTORY)) {
45 \Drupal::logger('filefield_sources')->log(E_NOTICE, 'File %file could not be copied, because the destination directory %destination is not configured correctly.', array(
47 '%destination' => drupal_realpath($directory),
49 drupal_set_message(t('The specified file %file could not be copied, because the destination directory is not properly configured. This may be caused by a problem with file or directory permissions. More information is available in the system log.', array('%file' => $filepath)), 'error');
53 // Clean up the file name extensions and transliterate.
54 $original_filepath = $filepath;
55 $new_filepath = filefield_sources_clean_filename($filepath, $instance->getSetting('file_extensions'));
56 rename($filepath, $new_filepath);
57 $filepath = $new_filepath;
59 // Run all the normal validations, minus file size restrictions.
60 $validators = $element['#upload_validators'];
61 if (isset($validators['file_validate_size'])) {
62 unset($validators['file_validate_size']);
65 // Save the file to the new location.
66 if ($file = filefield_sources_save_file($filepath, $validators, $directory)) {
67 if (!in_array($file->id(), $input['fids'])) {
68 $input['fids'][] = $file->id();
71 // Delete the original file if "moving" the file instead of copying.
72 if ($element['#filefield_sources_settings']['source_attach']['attach_mode'] !== FILEFIELD_SOURCE_ATTACH_MODE_COPY) {
77 // Restore the original file name if the file still exists.
78 if (file_exists($filepath) && $filepath != $original_filepath) {
79 rename($filepath, $original_filepath);
82 $input['filefield_attach']['filename'] = '';
89 public static function process(array &$element, FormStateInterface $form_state, array &$complete_form) {
90 $settings = $element['#filefield_sources_settings']['source_attach'];
91 $field_name = $element['#field_name'];
92 $instance = entity_load('field_config', $element['#entity_type'] . '.' . $element['#bundle'] . '.' . $field_name);
94 $element['filefield_attach'] = array(
96 '#theme' => 'filefield_sources_element',
97 '#source_id' => 'attach',
98 // Required for proper theming.
99 '#filefield_source' => TRUE,
102 $path = static::getDirectory($settings);
103 $options = static::getAttachOptions($path, $instance->getSetting('file_extensions'));
105 // If we have built this element before, append the list of options that we
106 // had previously. This allows files to be deleted after copying them and
107 // still be considered a valid option during the validation and submit.
108 $triggering_element = $form_state->getTriggeringElement();
114 if (!isset($triggering_element) && $form_state->has($property)) {
115 $attach_options = $form_state->get($property);
116 $options = $options + $attach_options;
118 // On initial form build and rebuilds after processing input, save the
119 // original list of options so they can be restored in the line above.
121 $form_state->set(array('filefield_sources', $field_name, 'attach_options'), $options);
124 $description = t('This method may be used to attach files that exceed the file size limit. Files may be attached from the %directory directory on the server, usually uploaded through FTP.', array('%directory' => realpath($path)));
127 if ($options === FALSE || empty($settings['path'])) {
128 $attach_message = t('A file attach directory could not be located.');
129 $attach_description = t('Please check your settings for the %field field.', array('%field' => $instance->getLabel()));
131 elseif (!count($options)) {
132 $attach_message = t('There currently are no files to attach.');
133 $attach_description = $description;
136 if (isset($attach_message)) {
137 $element['filefield_attach']['attach_message'] = array(
138 '#markup' => $attach_message,
140 $element['filefield_attach']['#description'] = $attach_description;
143 $validators = $element['#upload_validators'];
144 if (isset($validators['file_validate_size'])) {
145 unset($validators['file_validate_size']);
147 $description .= '<br />' . filefield_sources_element_validation_help($validators);
148 $element['filefield_attach']['filename'] = array(
150 '#options' => $options,
152 $element['filefield_attach']['#description'] = $description;
154 $class = '\Drupal\file\Element\ManagedFile';
156 'callback' => [$class, 'uploadAjaxCallback'],
159 'element_parents' => implode('/', $element['#array_parents']),
162 'wrapper' => $element['upload_button']['#ajax']['wrapper'],
165 $element['filefield_attach']['attach'] = [
166 '#name' => implode('_', $element['#parents']) . '_attach',
168 '#value' => t('Attach'),
170 '#submit' => ['filefield_sources_field_submit'],
171 '#limit_validation_errors' => [$element['#parents']],
172 '#ajax' => $ajax_settings,
179 * Theme the output of the attach element.
181 public static function element($variables) {
182 $element = $variables['element'];
183 if (isset($element['attach_message'])) {
184 $output = $element['attach_message']['#markup'];
186 elseif (isset($element['filename'])) {
187 // Get rendered options.
188 $options = form_select_options($element['filename']);
190 foreach ($options as $key => $value) {
191 $option_output .= '<option value=' . $value["value"] . '>' . $value["label"] . '</option>';
193 // Get rendered select.
194 $size = !empty($element['filename']['#size']) ? ' size="' . $element['filename']['#size'] . '"' : '';
195 $element['filename']['#attributes']['class'][] = 'form-select';
196 $multiple = !empty($element['#multiple']);
197 $output = '<select name="' . $element['filename']['#name'] . '' . ($multiple ? '[]' : '') . '"' . ($multiple ? ' multiple="multiple" ' : '') . new Attribute($element['filename']['#attributes']) . ' id="' . $element['filename']['#id'] . '" ' . $size . '>' . $option_output . '</select>';
200 $output .= drupal_render($element['attach']);
201 $element['#children'] = $output;
202 $element['#theme_wrappers'] = array('form_element');
203 return '<div class="filefield-source filefield-source-attach clear-block">' . drupal_render($element) . '</div>';
207 * Get directory from settings.
209 * @param array $settings
210 * Attach source's settings.
211 * @param object $account
212 * User to replace token.
215 * Path that contains files to attach.
217 protected static function getDirectory(array $settings, $account = NULL) {
218 $account = isset($account) ? $account : \Drupal::currentUser();
219 $path = $settings['path'];
220 $absolute = !empty($settings['absolute']);
222 // Replace user level tokens.
223 // Node level tokens require a lot of complexity like temporary storage
224 // locations when values don't exist. See the filefield_paths module.
225 if (\Drupal::moduleHandler()->moduleExists('token')) {
226 $token = \Drupal::token();
227 $path = $token->replace($path, array('user' => $account));
230 return $absolute ? $path : file_default_scheme() . '://' . $path;
234 * Get attach options.
236 * @param string $path
237 * Path to scan files.
238 * @param string $extensions
239 * Path to scan files.
244 protected static function getAttachOptions($path, $extensions = FALSE) {
245 if (!file_prepare_directory($path, FILE_CREATE_DIRECTORY)) {
246 drupal_set_message(t('Specified file attach path %path must exist or be writable.', array('%path' => $path)), 'error');
251 $pattern = !empty($extensions) ? '/\.(' . strtr($extensions, ' ', '|') . ')$/' : '/.*/';
252 $files = file_scan_directory($path, $pattern);
255 $options = array('' => t('-- Select file --'));
256 foreach ($files as $file) {
257 $options[$file->uri] = str_replace($path . '/', '', $file->uri);
259 natcasesort($options);
266 * Implements hook_filefield_source_settings().
268 public static function settings(WidgetInterface $plugin) {
269 $settings = $plugin->getThirdPartySetting('filefield_sources', 'filefield_sources', array(
270 'source_attach' => array(
271 'path' => FILEFIELD_SOURCE_ATTACH_DEFAULT_PATH,
272 'absolute' => FILEFIELD_SOURCE_ATTACH_RELATIVE,
273 'attach_mode' => FILEFIELD_SOURCE_ATTACH_MODE_MOVE,
277 $return['source_attach'] = array(
278 '#title' => t('File attach settings'),
279 '#type' => 'details',
280 '#description' => t('File attach allows for selecting a file from a directory on the server, commonly used in combination with FTP.') . ' <strong>' . t('This file source will ignore file size checking when used.') . '</strong>',
281 '#element_validate' => array(array(get_called_class(), 'filePathValidate')),
284 $return['source_attach']['path'] = array(
285 '#type' => 'textfield',
286 '#title' => t('File attach path'),
287 '#default_value' => $settings['source_attach']['path'],
290 '#description' => t('The directory within the <em>File attach location</em> that will contain attachable files.'),
292 if (\Drupal::moduleHandler()->moduleExists('token')) {
293 $return['source_attach']['tokens'] = array(
294 '#theme' => 'token_tree',
295 '#token_types' => array('user'),
298 $return['source_attach']['absolute'] = array(
300 '#title' => t('File attach location'),
302 FILEFIELD_SOURCE_ATTACH_RELATIVE => t('Within the files directory'),
303 FILEFIELD_SOURCE_ATTACH_ABSOLUTE => t('Absolute server path'),
305 '#default_value' => $settings['source_attach']['absolute'],
306 '#description' => t('The <em>File attach path</em> may be with the files directory (%file_directory) or from the root of your server. If an absolute path is used and it does not start with a "/" your path will be relative to your site directory: %realpath.', array('%file_directory' => drupal_realpath(file_default_scheme() . '://'), '%realpath' => realpath('./'))),
308 $return['source_attach']['attach_mode'] = array(
310 '#title' => t('Attach method'),
312 FILEFIELD_SOURCE_ATTACH_MODE_MOVE => t('Move the file directly to the final location'),
313 FILEFIELD_SOURCE_ATTACH_MODE_COPY => t('Leave a copy of the file in the attach directory'),
315 '#default_value' => isset($settings['source_attach']['attach_mode']) ? $settings['source_attach']['attach_mode'] : 'move',
322 * Validate file path.
324 * @param array $element
326 * @param \Drupal\Core\Form\FormStateInterface $form_state
328 * @param array $complete_form
331 public static function filePathValidate(array &$element, FormStateInterface $form_state, array &$complete_form) {
332 $parents = $element['#parents'];
334 $input_exists = FALSE;
336 // Get input of the whole parent element.
337 $input = NestedArray::getValue($form_state->getValues(), $parents, $input_exists);
339 // Only validate if this source is enabled.
340 if (!$input['sources']['attach']) {
344 // Strip slashes from the end of the file path.
345 $filepath = rtrim($element['path']['#value'], '\\/');
346 $form_state->setValueForElement($element['path'], $filepath);
347 $filepath = static::getDirectory($input['source_attach']);
349 // Check that the directory exists and is writable.
350 if (!file_prepare_directory($filepath, FILE_CREATE_DIRECTORY)) {
351 $form_state->setError($element['path'], t('Specified file attach path %path must exist or be writable.', array('%path' => $filepath)));