foldershare-8.x-1.2/src/Plugin/FolderShareCommand/UploadFiles.php

src/Plugin/FolderShareCommand/UploadFiles.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
<?php
 
namespace Drupal\foldershare\Plugin\FolderShareCommand;
 
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element\File;
 
use Drupal\foldershare\Constants;
use Drupal\foldershare\ManageFilenameExtensions;
use Drupal\foldershare\Settings;
use Drupal\foldershare\Entity\FolderShare;
 
/**
 * Defines a command plugin to upload files for a folder.
 *
 * The command uploads files and adds them to the parent folder.
 *
 * Configuration parameters:
 * - 'parentId': the parent folder, if any.
 *
 * @ingroup foldershare
 *
 * @FolderShareCommand(
 *  id              = "foldersharecommand_upload_files",
 *  label           = @Translation("Upload"),
 *  menuNameDefault = @Translation("Upload..."),
 *  menuName        = @Translation("Upload..."),
 *  description     = @Translation("Upload files to this location."),
 *  category        = "import & export",
 *  weight          = 10,
 *  specialHandling = {
 *    "upload",
 *  },
 *  parentConstraints = {
 *    "kinds"   = {
 *      "rootlist",
 *      "folder",
 *    },
 *    "access"  = "create",
 *  },
 *  selectionConstraints = {
 *    "types"   = {
 *      "none",
 *    },
 *  },
 * )
 */
class UploadFiles extends FolderShareCommandBase {
 
  /*--------------------------------------------------------------------
   *
   * Configuration form.
   *
   *--------------------------------------------------------------------*/
 
  /**
   * {@inheritdoc}
   */
  public function hasConfigurationForm() {
    // A configuration form is only needed if there are no uploaded
    // files already available.  Check.
    $configuration = $this->getConfiguration();
    if (empty($configuration) === TRUE) {
      // No command configuration? Need a form.
      return TRUE;
    }
 
    if (empty($configuration['uploadClass']) === TRUE) {
      // No command upload class specified? Need a form.
      return TRUE;
    }
 
    $uploadClass = $configuration['uploadClass'];
    $pendingFiles = \Drupal::request()->files->get('files', []);
    if (isset($pendingFiles[$uploadClass]) === FALSE) {
      // No pending files? Need a form.
      return TRUE;
    }
 
    foreach ($pendingFiles[$uploadClass] as $fileInfo) {
      if ($fileInfo !== NULL) {
        // At least one good pending file. No form.
        return FALSE;
      }
    }
 
    // No good pending files. Need a form.
    return TRUE;
  }
 
  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(
    array $form,
    FormStateInterface $formState) {
 
    // Build a form to prompt for files to upload.
    $uploadClass = Constants::MODULE . '-command-upload';
 
    $configuration = $this->getConfiguration();
    $configuration['uploadClass'] = $uploadClass;
    $this->setConfiguration($configuration);
 
    // Provide a file field. Browsers automatically add a button to
    // invoke a platform-specific file dialog to select files.
    $form[$uploadClass] = [
      '#type'        => 'file',
      '#multiple'    => TRUE,
      '#description' => t(
        "Select one or more @kinds to upload.",
        [
          '@kinds'  => FolderShare::translateKinds(FolderShare::FILE_KIND),
        ]),
      '#process'   => [
        [
          get_class($this),
          'processFileField',
        ],
      ],
    ];
 
    return $form;
  }
 
  /**
   * Process the file field in the view UI form to add extension handling.
   *
   * The 'file' field directs the browser to prompt the user for one or
   * more files to upload. This prompt is done using the browser's own
   * file dialog. When this module's list of allowed file extensions has
   * been set, and this function is added as a processing function for
   * the 'file' field, it adds the extensions to the list of allowed
   * values used by the browser's file dialog.
   *
   * @param mixed $element
   *   The form element to process.
   * @param Drupal\Core\Form\FormStateInterface $formState
   *   The current form state.
   * @param mixed $completeForm
   *   The full form.
   */
  public static function processFileField(
    &$element,
    FormStateInterface $formState,
    &$completeForm) {
 
    // Let the file field handle the '#multiple' flag, etc.
    File::processFile($element, $formState, $completeForm);
 
    // Get the list of allowed file extensions for FolderShare files.
    $extensions = ManageFilenameExtensions::getAllowedNameExtensions();
 
    // If there are extensions, add them to the form element.
    if (empty($extensions) === FALSE) {
      // The extensions list is space separated without leading dots. But
      // we need comma separated with dots. Map one to the other.
      $list = [];
      foreach (mb_split(' ', $extensions) as $ext) {
        $list[] = '.' . $ext;
      }
 
      $element['#attributes']['accept'] = implode(',', $list);
    }
 
    return $element;
  }
 
  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(
    array &$form,
    FormStateInterface $formState) {
 
    $this->execute();
  }
 
  /*--------------------------------------------------------------------
   *
   * Execute.
   *
   *--------------------------------------------------------------------*/
 
  /**
   * {@inheritdoc}
   */
  public function execute() {
 
    // Get the parent, if any.
    $parent = $this->getParent();
 
    // Attach the uploaded files to the parent. PHP has already uploaded
    // the files. It remains to convert the files to File objects, then
    // wrap them with FolderShare entities and add them to the parent folder.
    $configuration = $this->getConfiguration();
    $uploadClass = $configuration['uploadClass'];
 
    try {
      if ($parent === NULL) {
        $results = FolderShare::addUploadFilesToRoot($uploadClass);
      }
      else {
        $results = $parent->addUploadFiles($uploadClass);
      }
    }
    catch (\Exception $e) {
      \Drupal::messenger()->addMessage($e->getMessage(), 'error');
    }
 
    // Report success or errors. The returned array mixes File objects
    // with string objects containing error messages. The objects are
    // in the same order as the original list of uploaded files.
    //
    // Below, we sweep through the returned array and post
    // error messages, if any.
    $nUploaded = 0;
    $firstItem = NULL;
    foreach ($results as $entry) {
      if (is_string($entry) === TRUE) {
        // This file had an upload error.
        \Drupal::messenger()->addMessage($entry, 'error');
      }
      else {
        if ($nUploaded === 0) {
          $firstItem = $entry;
        }
 
        $nUploaded++;
      }
    }
 
    if (Settings::getCommandNormalCompletionReportEnable() === TRUE) {
      // Report on results, if any.
      if ($nUploaded === 1) {
        // Single file. There may have been other files that had errors though.
        $name = $firstItem->getFilename();
        \Drupal::messenger()->addMessage(
          t(
            "The @kind '@name' has been uploaded.",
            [
              '@kind' => FolderShare::translateKind(FolderShare::FILE_KIND),
              '@name' => $name,
            ]),
          'status');
      }
      elseif ($nUploaded > 1) {
        // Multiple files. There may have been other files that had errors tho.
        \Drupal::messenger()->addMessage(
          t(
            "@number @kinds have been uploaded.",
            [
              '@number' => $nUploaded,
              '@kinds'  => FolderShare::translateKinds(FolderShare::FILE_KIND),
            ]),
          'status');
      }
    }
  }
 
}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc