Further modules included.
[yaffs-website] / web / modules / contrib / filefield_sources / src / Plugin / FilefieldSource / Attach.php
1 <?php
2
3 /**
4  * @file
5  * Contains \Drupal\filefield_sources\Plugin\FilefieldSource\Attach.
6  */
7
8 namespace Drupal\filefield_sources\Plugin\FilefieldSource;
9
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;
16
17 /**
18  * A FileField source plugin to allow use of files within a server directory.
19  *
20  * @FilefieldSource(
21  *   id = "attach",
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."),
25  *   weight = 3
26  * )
27  */
28 class Attach implements FilefieldSourceInterface {
29
30   /**
31    * {@inheritdoc}
32    */
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'];
37
38       // Check that the destination is writable.
39       $directory = $element['#upload_location'];
40       $mode = Settings::get('file_chmod_directory', FILE_CHMOD_DIRECTORY);
41
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(
46           '%file' => $filepath,
47           '%destination' => drupal_realpath($directory),
48         ));
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');
50         return;
51       }
52
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;
58
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']);
63       }
64
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();
69         }
70
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) {
73           @unlink($filepath);
74         }
75       }
76
77       // Restore the original file name if the file still exists.
78       if (file_exists($filepath) && $filepath != $original_filepath) {
79         rename($filepath, $original_filepath);
80       }
81
82       $input['filefield_attach']['filename'] = '';
83     }
84   }
85
86   /**
87    * {@inheritdoc}
88    */
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);
93
94     $element['filefield_attach'] = array(
95       '#weight' => 100.5,
96       '#theme' => 'filefield_sources_element',
97       '#source_id' => 'attach',
98       // Required for proper theming.
99       '#filefield_source' => TRUE,
100     );
101
102     $path = static::getDirectory($settings);
103     $options = static::getAttachOptions($path, $instance->getSetting('file_extensions'));
104
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();
109     $property = array(
110       'filefield_sources',
111       $field_name,
112       'attach_options',
113     );
114     if (!isset($triggering_element) && $form_state->has($property)) {
115       $attach_options = $form_state->get($property);
116       $options = $options + $attach_options;
117     }
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.
120     else {
121       $form_state->set(array('filefield_sources', $field_name, 'attach_options'), $options);
122     }
123
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)));
125
126     // Error messages.
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()));
130     }
131     elseif (!count($options)) {
132       $attach_message = t('There currently are no files to attach.');
133       $attach_description = $description;
134     }
135
136     if (isset($attach_message)) {
137       $element['filefield_attach']['attach_message'] = array(
138         '#markup' => $attach_message,
139       );
140       $element['filefield_attach']['#description'] = $attach_description;
141     }
142     else {
143       $validators = $element['#upload_validators'];
144       if (isset($validators['file_validate_size'])) {
145         unset($validators['file_validate_size']);
146       }
147       $description .= '<br />' . filefield_sources_element_validation_help($validators);
148       $element['filefield_attach']['filename'] = array(
149         '#type' => 'select',
150         '#options' => $options,
151       );
152       $element['filefield_attach']['#description'] = $description;
153     }
154     $class = '\Drupal\file\Element\ManagedFile';
155     $ajax_settings = [
156       'callback' => [$class, 'uploadAjaxCallback'],
157       'options' => [
158         'query' => [
159           'element_parents' => implode('/', $element['#array_parents']),
160         ],
161       ],
162       'wrapper' => $element['upload_button']['#ajax']['wrapper'],
163       'effect' => 'fade',
164     ];
165     $element['filefield_attach']['attach'] = [
166       '#name' => implode('_', $element['#parents']) . '_attach',
167       '#type' => 'submit',
168       '#value' => t('Attach'),
169       '#validate' => [],
170       '#submit' => ['filefield_sources_field_submit'],
171       '#limit_validation_errors' => [$element['#parents']],
172       '#ajax' => $ajax_settings,
173     ];
174
175     return $element;
176   }
177
178   /**
179    * Theme the output of the attach element.
180    */
181   public static function element($variables) {
182     $element = $variables['element'];
183     if (isset($element['attach_message'])) {
184       $output = $element['attach_message']['#markup'];
185     }
186     elseif (isset($element['filename'])) {
187       // Get rendered options.
188       $options = form_select_options($element['filename']);
189       $option_output = '';
190       foreach ($options as $key => $value) {
191         $option_output .= '<option value=' . $value["value"] . '>' . $value["label"] . '</option>';
192       }
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>';
198     }
199
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>';
204   }
205
206   /**
207    * Get directory from settings.
208    *
209    * @param array $settings
210    *   Attach source's settings.
211    * @param object $account
212    *   User to replace token.
213    *
214    * @return string
215    *   Path that contains files to attach.
216    */
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']);
221
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));
228     }
229
230     return $absolute ? $path : file_default_scheme() . '://' . $path;
231   }
232
233   /**
234    * Get attach options.
235    *
236    * @param string $path
237    *   Path to scan files.
238    * @param string $extensions
239    *   Path to scan files.
240    *
241    * @return array
242    *   List of options.
243    */
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');
247       return FALSE;
248     }
249
250     $options = array();
251     $pattern = !empty($extensions) ? '/\.(' . strtr($extensions, ' ', '|') . ')$/' : '/.*/';
252     $files = file_scan_directory($path, $pattern);
253
254     if (count($files)) {
255       $options = array('' => t('-- Select file --'));
256       foreach ($files as $file) {
257         $options[$file->uri] = str_replace($path . '/', '', $file->uri);
258       }
259       natcasesort($options);
260     }
261
262     return $options;
263   }
264
265   /**
266    * Implements hook_filefield_source_settings().
267    */
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,
274       ),
275     ));
276
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')),
282       '#weight' => 3,
283     );
284     $return['source_attach']['path'] = array(
285       '#type' => 'textfield',
286       '#title' => t('File attach path'),
287       '#default_value' => $settings['source_attach']['path'],
288       '#size' => 60,
289       '#maxlength' => 128,
290       '#description' => t('The directory within the <em>File attach location</em> that will contain attachable files.'),
291     );
292     if (\Drupal::moduleHandler()->moduleExists('token')) {
293       $return['source_attach']['tokens'] = array(
294         '#theme' => 'token_tree',
295         '#token_types' => array('user'),
296       );
297     }
298     $return['source_attach']['absolute'] = array(
299       '#type' => 'radios',
300       '#title' => t('File attach location'),
301       '#options' => array(
302         FILEFIELD_SOURCE_ATTACH_RELATIVE => t('Within the files directory'),
303         FILEFIELD_SOURCE_ATTACH_ABSOLUTE => t('Absolute server path'),
304       ),
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('./'))),
307     );
308     $return['source_attach']['attach_mode'] = array(
309       '#type' => 'radios',
310       '#title' => t('Attach method'),
311       '#options' => array(
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'),
314       ),
315       '#default_value' => isset($settings['source_attach']['attach_mode']) ? $settings['source_attach']['attach_mode'] : 'move',
316     );
317
318     return $return;
319   }
320
321   /**
322    * Validate file path.
323    *
324    * @param array $element
325    *   Form element.
326    * @param \Drupal\Core\Form\FormStateInterface $form_state
327    *   Form state.
328    * @param array $complete_form
329    *   Complete form.
330    */
331   public static function filePathValidate(array &$element, FormStateInterface $form_state, array &$complete_form) {
332     $parents = $element['#parents'];
333     array_pop($parents);
334     $input_exists = FALSE;
335
336     // Get input of the whole parent element.
337     $input = NestedArray::getValue($form_state->getValues(), $parents, $input_exists);
338     if ($input_exists) {
339       // Only validate if this source is enabled.
340       if (!$input['sources']['attach']) {
341         return;
342       }
343
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']);
348
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)));
352       }
353     }
354   }
355
356 }