5830a862f879ea7e6ad7083b146529bf259a21a2
[yaffs-website] / web / modules / contrib / filefield_sources / src / Plugin / FilefieldSource / Imce.php
1 <?php
2
3 /**
4  * @file
5  * Contains \Drupal\filefield_sources\Plugin\FilefieldSource\Imce.
6  */
7
8 namespace Drupal\filefield_sources\Plugin\FilefieldSource;
9
10 use Drupal\Core\Form\FormStateInterface;
11 use Drupal\filefield_sources\FilefieldSourceInterface;
12 use Symfony\Component\Routing\Route;
13 use Drupal\Core\Field\WidgetInterface;
14
15 /**
16  * A FileField source plugin to allow referencing of files from IMCE.
17  *
18  * @FilefieldSource(
19  *   id = "imce",
20  *   name = @Translation("IMCE file browser"),
21  *   label = @Translation("File browser"),
22  *   description = @Translation("Select a file to use from a file browser."),
23  *   weight = -1
24  * )
25  */
26 class Imce implements FilefieldSourceInterface {
27
28   /**
29    * {@inheritdoc}
30    */
31   public static function value(array &$element, &$input, FormStateInterface $form_state) {
32     if (isset($input['filefield_imce']['imce_paths']) && $input['filefield_imce']['imce_paths'] != '') {
33       $instance = entity_load('field_config', $element['#entity_type'] . '.' . $element['#bundle'] . '.' . $element['#field_name']);
34       $field_settings = $instance->getSettings();
35       $scheme = $field_settings['uri_scheme'];
36       $imce_paths = explode(':', $input['filefield_imce']['imce_paths']);
37       $uris = [];
38
39       foreach ($imce_paths as $imce_path) {
40         //$wrapper = \Drupal::service('stream_wrapper_manager')->getViaScheme($scheme);
41         //$file_directory_prefix = $scheme == 'private' ? 'system/files' : $wrapper->getDirectoryPath();
42         //$uri = preg_replace('/^' . preg_quote(base_path() . $file_directory_prefix . '/', '/') . '/', $scheme . '://', $imce_path);
43         $uri = rawurldecode($scheme . '://' . $imce_path);
44         $uris[] = $uri;
45       }
46
47       // Resolve the file path to an FID.
48       $fids = db_select('file_managed', 'f')
49         ->condition('uri', $uris, 'IN')
50         ->fields('f', array('fid'))
51         ->execute()
52         ->fetchCol();
53       if ($fids) {
54         $files = file_load_multiple($fids);
55         foreach ($files as $file) {
56           if (filefield_sources_element_validate($element, $file, $form_state)) {
57             if (!in_array($file->id(), $input['fids'])) {
58               $input['fids'][] = $file->id();
59             }
60           }
61         }
62       }
63       else {
64         $form_state->setError($element, t('The selected file could not be used because the file does not exist in the database.'));
65       }
66       // No matter what happens, clear the value from the file path field.
67       $input['filefield_imce']['imce_paths'] = '';
68     }
69   }
70
71   /**
72    * {@inheritdoc}
73    */
74   public static function process(array &$element, FormStateInterface $form_state, array &$complete_form) {
75     $instance = entity_load('field_config', $element['#entity_type'] . '.' . $element['#bundle'] . '.' . $element['#field_name']);
76
77     $element['filefield_imce'] = array(
78       '#weight' => 100.5,
79       '#theme' => 'filefield_sources_element',
80       '#source_id' => 'imce',
81       // Required for proper theming.
82       '#filefield_source' => TRUE,
83       '#description' => filefield_sources_element_validation_help($element['#upload_validators']),
84     );
85
86     $imce_url = \Drupal::url('filefield_sources.imce', array(
87       'entity_type' => $element['#entity_type'],
88       'bundle_name' => $element['#bundle'],
89       'field_name' => $element['#field_name'],
90     ),
91     array(
92       'query' => array(
93         'sendto' => 'imceFileField.sendto',
94         'fieldId' => $element['#attributes']['data-drupal-selector'] . '-filefield-imce',
95       ),
96     ));
97     $element['filefield_imce']['browse'] = array(
98       '#type' => 'markup',
99       '#markup' => '<span>' . t('No file selected') . '</span> (<a class="filefield-sources-imce-browse" href="' . $imce_url . '">' . t('browse') . '</a>)',
100     );
101
102     $element['#attached']['library'][] = 'imce/drupal.imce.filefield';
103     // Set the pre-renderer to conditionally disable the elements.
104     $element['#pre_render'][] = array(get_called_class(), 'preRenderWidget');
105
106     // Path input
107     $element['filefield_imce']['imce_paths'] = array(
108       '#type' => 'hidden',
109       // Reset value to prevent consistent errors
110       '#value' => '',
111     );
112
113     $class = '\Drupal\file\Element\ManagedFile';
114     $ajax_settings = [
115       'callback' => [$class, 'uploadAjaxCallback'],
116       'options' => [
117         'query' => [
118           'element_parents' => implode('/', $element['#array_parents']),
119         ],
120       ],
121       'wrapper' => $element['upload_button']['#ajax']['wrapper'],
122       'effect' => 'fade',
123     ];
124
125     $element['filefield_imce']['imce_button'] = array(
126       '#name' => implode('_', $element['#parents']) . '_imce_select',
127       '#type' => 'submit',
128       '#value' => t('Select'),
129       '#attributes' => ['class' => ['js-hide']],
130       '#validate' => [],
131       '#submit' => ['filefield_sources_field_submit'],
132       '#limit_validation_errors' => [$element['#parents']],
133       '#ajax' => $ajax_settings,
134     );
135
136     return $element;
137   }
138
139   /**
140    * Theme the output of the imce element.
141    */
142   public static function element($variables) {
143     $element = $variables['element'];
144
145     $output = drupal_render_children($element);
146     return '<div class="filefield-source filefield-source-imce clear-block">' . $output . '</div>';
147   }
148
149   /**
150    * Define routes for Imce source.
151    *
152    * @return array
153    *   Array of routes.
154    */
155   public static function routes() {
156     $routes = array();
157
158     $routes['filefield_sources.imce'] = new Route(
159       '/file/imce/{entity_type}/{bundle_name}/{field_name}',
160       array(
161         '_controller' => '\Drupal\filefield_sources\Controller\ImceController::page',
162         '_title' => 'File Manager',
163       ),
164       array(
165         '_access_filefield_sources_field' => 'TRUE',
166       )
167     );
168
169     return $routes;
170   }
171
172   /**
173    * Implements hook_filefield_source_settings().
174    */
175   public static function settings(WidgetInterface $plugin) {
176     $settings = $plugin->getThirdPartySetting('filefield_sources', 'filefield_sources', array(
177       'source_imce' => array(
178         'imce_mode' => 0,
179       ),
180     ));
181
182     $return['source_imce'] = array(
183       '#title' => t('IMCE file browser settings'),
184       '#type' => 'details',
185       '#access' => \Drupal::moduleHandler()->moduleExists('imce'),
186     );
187
188     // $imce_admin_url = \Drupal::url('imce.admin');
189     $imce_admin_url = 'admin/config/media/imce';
190     $return['source_imce']['imce_mode'] = array(
191       '#type' => 'radios',
192       '#title' => t('File browser mode'),
193       '#options' => array(
194         0 => t('Restricted: Users can only browse the field directory. No file operations are allowed.'),
195         1 => t('Full: Browsable directories are defined by <a href=":imce-admin-url">IMCE configuration profiles</a>. File operations are allowed.', array(':imce-admin-url' => $imce_admin_url)),
196       ),
197       '#default_value' => isset($settings['source_imce']['imce_mode']) ? $settings['source_imce']['imce_mode'] : 0,
198     );
199
200     return $return;
201
202   }
203
204   /**
205    * Pre-renders widget form.
206    */
207   public static function preRenderWidget($element) {
208     // Hide elements if there is already an uploaded file.
209     if (!empty($element['#value']['fids'])) {
210       $element['filefield_imce']['imce_paths']['#access'] = FALSE;
211       $element['filefield_imce']['imce_button']['#access'] = FALSE;
212     }
213     return $element;
214   }
215
216 }