/** * Form constructor for the translation import screen. */ public function buildForm(array $form, FormStateInterface $form_state) { $languages = $this->languageManager->getLanguages(); // Initialize a language list to the ones available, including English if we // are to translate Drupal to English as well. $existing_languages = array(); foreach ($languages as $langcode => $language) { if (locale_is_translatable($langcode)) { $existing_languages[$langcode] = $language->getName(); } } // If we have no languages available, present the list of predefined // languages only. If we do have already added languages, set up two option // groups with the list of existing and then predefined languages. if (empty($existing_languages)) { $language_options = $this->languageManager->getStandardLanguageListWithoutConfigured(); $default = key($language_options); } else { $default = key($existing_languages); $language_options = array((string) $this->t('Existing languages') => $existing_languages, (string) $this->t('Languages not yet added') => $this->languageManager->getStandardLanguageListWithoutConfigured()); } $validators = array('file_validate_extensions' => array('po'), 'file_validate_size' => array(file_upload_max_size())); $form['file'] = array('#type' => 'file', '#title' => $this->t('Translation file'), '#description' => array('#theme' => 'file_upload_help', '#description' => $this->t('A Gettext Portable Object file.'), '#upload_validators' => $validators), '#size' => 50, '#upload_validators' => $validators, '#attributes' => array('class' => array('file-import-input'))); $form['langcode'] = array('#type' => 'select', '#title' => $this->t('Language'), '#options' => $language_options, '#default_value' => $default, '#attributes' => array('class' => array('langcode-input'))); $form['customized'] = array('#title' => $this->t('Treat imported strings as custom translations'), '#type' => 'checkbox'); $form['overwrite_options'] = array('#type' => 'container', '#tree' => TRUE); $form['overwrite_options']['not_customized'] = array('#title' => $this->t('Overwrite non-customized translations'), '#type' => 'checkbox', '#states' => array('checked' => array(':input[name="customized"]' => array('checked' => TRUE)))); $form['overwrite_options']['customized'] = array('#title' => $this->t('Overwrite existing customized translations'), '#type' => 'checkbox'); $form['actions'] = array('#type' => 'actions'); $form['actions']['submit'] = array('#type' => 'submit', '#value' => $this->t('Import')); return $form; }
public function index($theme) { $this->css('admin')->js('admin'); $form_header = $this->load->library('form')->add_rules(array('header' => array('label' => 'Image de fond', 'value' => $this->config->{'dungeon_header'}, 'type' => 'file', 'upload' => 'themes/dungeon/headers', 'info' => ' d\'image (max. ' . file_upload_max_size() / 1024 / 1024 . ' Mo)', 'check' => function ($filename, $ext) { if (!in_array($ext, array('gif', 'jpeg', 'jpg', 'png'))) { return 'Veuiller choisir un fichier d\'image'; } }, 'description' => 'Laisser vide pour utiliser l\'image par défaut du thème.'), 'repeat' => array('label' => 'Répéter l\'image', 'value' => $this->config->dungeon_header_repeat, 'values' => array('no-repeat' => 'Non', 'repeat-x' => 'Horizontalement', 'repeat-y' => 'Verticalement', 'repeat' => 'Les deux'), 'type' => 'radio', 'rules' => 'required'), 'positionX' => array('label' => 'Position', 'value' => explode(' ', $this->config->dungeon_header_position)[0], 'values' => array('left' => 'Gauche', 'center' => 'Centré', 'right' => 'Droite'), 'type' => 'radio', 'rules' => 'required'), 'positionY' => array('value' => explode(' ', $this->config->dungeon_header_position)[1], 'values' => array('top' => 'Haut', 'center' => 'Milieu', 'bottom' => 'Bas'), 'type' => 'radio', 'rules' => 'required'), 'fixed' => array('checked' => array('on' => $this->config->dungeon_header_attachment == 'fixed'), 'values' => array('on' => 'Image fixe'), 'type' => 'checkbox'), 'color' => array('label' => 'Couleur de fond', 'value' => $this->config->dungeon_header_color, 'type' => 'colorpicker', 'rules' => 'required'), 'logo' => array('label' => 'Logo du site', 'value' => $this->config->dungeon_logo, 'type' => 'file', 'upload' => 'themes/dungeon/logos', 'info' => ' d\'image (max. ' . file_upload_max_size() / 1024 / 1024 . ' Mo)', 'check' => function ($filename, $ext) { if (!in_array($ext, array('gif', 'jpeg', 'jpg', 'png'))) { return 'Veuiller choisir un fichier d\'image'; } }, 'description' => 'Le logo sera affiché dans le widget type "header", en remplacement du titre et slogan.')))->add_submit('Enregistrer')->save(); $form_background = $this->form->add_rules(array('background' => array('label' => 'Image de fond', 'value' => $this->config->dungeon_background, 'type' => 'file', 'upload' => 'themes/dungeon/backgrounds', 'info' => ' d\'image (max. ' . file_upload_max_size() / 1024 / 1024 . ' Mo)', 'check' => function ($filename, $ext) { if (!in_array($ext, array('gif', 'jpeg', 'jpg', 'png'))) { return 'Veuiller choisir un fichier d\'image'; } }, 'description' => 'Laisser vide pour utiliser l\'image par défaut du thème.'), 'repeat' => array('label' => 'Répéter l\'image', 'value' => $this->config->dungeon_background_repeat, 'values' => array('no-repeat' => 'Non', 'repeat-x' => 'Horizontalement', 'repeat-y' => 'Verticalement', 'repeat' => 'Les deux'), 'type' => 'radio', 'rules' => 'required'), 'positionX' => array('label' => 'Position', 'value' => explode(' ', $this->config->dungeon_background_position)[0], 'values' => array('left' => 'Gauche', 'center' => 'Centré', 'right' => 'Droite'), 'type' => 'radio', 'rules' => 'required'), 'positionY' => array('value' => explode(' ', $this->config->dungeon_background_position)[1], 'values' => array('top' => 'Haut', 'center' => 'Milieu', 'bottom' => 'Bas'), 'type' => 'radio', 'rules' => 'required'), 'fixed' => array('checked' => array('on' => $this->config->dungeon_background_attachment == 'fixed'), 'values' => array('on' => 'Image fixe'), 'type' => 'checkbox'), 'color' => array('label' => 'Couleur de fond', 'value' => $this->config->dungeon_background_color, 'type' => 'colorpicker', 'rules' => 'required')))->add_submit('Enregistrer')->save(); $form_settings = $this->form->add_rules(array('theme_color' => array('label' => 'Couleur du thème', 'value' => $this->config->dungeon_theme_color, 'type' => 'colorpicker', 'description' => 'Couleur générale du thème', 'rules' => 'required'), 'font_color' => array('label' => 'Couleur du texte', 'value' => $this->config->dungeon_font_color, 'type' => 'colorpicker', 'description' => 'Couleur appliquée au texte principal du thème', 'rules' => 'required'), 'font_size' => array('label' => 'Taille du texte', 'value' => $this->config->dungeon_font_size, 'values' => array('10px' => '10 px', '11px' => '11 px', '12px' => '12 px', '13px' => '13 px', '14px' => '14 px', '15px' => '15 px', '16px' => '16 px'), 'type' => 'select', 'rules' => 'required'), 'navbar' => array('checked' => array('on' => $this->config->dungeon_navbar_display), 'values' => array('on' => 'Rendre toujours visible la barre du haut'), 'type' => 'checkbox')))->add_submit('Enregistrer')->save(); $form_socials = $this->form->add_rules(array('facebook' => array('label' => 'Facebook', 'icon' => 'fa-facebook', 'value' => $this->config->dungeon_social_facebook, 'type' => 'text', 'description' => 'Indiquez l\'url complet'), 'twitter' => array('label' => 'Twitter', 'icon' => 'fa-twitter', 'value' => $this->config->dungeon_social_twitter, 'type' => 'text', 'description' => 'Indiquez l\'url complet'), 'google' => array('label' => 'Google+', 'icon' => 'fa-google-plus', 'value' => $this->config->dungeon_social_google, 'type' => 'text', 'description' => 'Indiquez l\'url complet'), 'steam' => array('label' => 'Page Steam', 'icon' => 'fa-steam', 'value' => $this->config->dungeon_social_steam, 'type' => 'text', 'description' => 'Indiquez l\'url complet'), 'twitch' => array('label' => 'Twitch', 'icon' => 'fa-twitch', 'value' => $this->config->dungeon_social_twitch, 'type' => 'text', 'description' => 'Indiquez l\'url complet'), 'dribble' => array('label' => 'Dribbble', 'icon' => 'fa-dribbble', 'value' => $this->config->dungeon_social_dribble, 'type' => 'text', 'description' => 'Indiquez l\'url complet'), 'behance' => array('label' => 'Behance', 'icon' => 'fa-behance', 'value' => $this->config->dungeon_social_behance, 'type' => 'text', 'description' => 'Indiquez l\'url complet'), 'deviantart' => array('label' => 'DeviantArt', 'icon' => 'fa-deviantart', 'value' => $this->config->dungeon_social_deviantart, 'type' => 'text', 'description' => 'Indiquez l\'url complet'), 'flickr' => array('label' => 'Flickr', 'icon' => 'fa-flickr', 'value' => $this->config->dungeon_social_flickr, 'type' => 'text', 'description' => 'Indiquez l\'url complet'), 'github' => array('label' => 'Github', 'icon' => 'fa-github', 'value' => $this->config->dungeon_social_github, 'type' => 'text', 'description' => 'Indiquez l\'url complet'), 'instagram' => array('label' => 'Instagram', 'icon' => 'fa-instagram', 'value' => $this->config->dungeon_social_instagram, 'type' => 'text', 'description' => 'Indiquez l\'url complet'), 'youtube' => array('label' => 'Youtube', 'icon' => 'fa-youtube', 'value' => $this->config->dungeon_social_youtube, 'type' => 'text', 'description' => 'Indiquez l\'url complet')))->add_submit('Enregistrer')->save(); if ($form_header->is_valid($post)) { if ($post['header']) { $this->config('dungeon_header', $post['header'], 'int'); } else { $this->db->where('name', 'dungeon_header')->delete('nf_settings'); } if ($post['logo']) { $this->config('dungeon_logo', $post['logo'], 'int'); } else { $this->db->where('name', 'dungeon_logo')->delete('nf_settings'); } $this->config('dungeon_header_repeat', $post['repeat'])->config('dungeon_header_attachment', in_array('on', $post['fixed']) ? 'fixed' : 'scroll')->config('dungeon_header_position', $post['positionX'] . ' ' . $post['positionY'])->config('dungeon_header_color', $post['color'])->config('dungeon_logo', $post['logo'], 'int'); refresh(); } else { if ($form_background->is_valid($post)) { if ($post['background']) { $this->config('dungeon_background', $post['background'], 'int'); } else { $this->db->where('name', 'dungeon_background')->delete('nf_settings'); } $this->config('dungeon_background_repeat', $post['repeat'])->config('dungeon_background_attachment', in_array('on', $post['fixed']) ? 'fixed' : 'scroll')->config('dungeon_background_position', $post['positionX'] . ' ' . $post['positionY'])->config('dungeon_background_color', $post['color']); refresh(); } else { if ($form_settings->is_valid($post)) { $this->config('dungeon_theme_color', $post['theme_color'])->config('dungeon_font_color', $post['font_color'])->config('dungeon_font_size', $post['font_size'])->config('dungeon_display', $post['display'])->config('dungeon_navbar_display', in_array('on', $post['navbar']), 'bool'); refresh(); } else { if ($form_socials->is_valid($post)) { $this->config('dungeon_social_facebook', $post['facebook'])->config('dungeon_social_twitter', $post['twitter'])->config('dungeon_social_google', $post['google'])->config('dungeon_social_steam', $post['steam'])->config('dungeon_social_twitch', $post['twitch'])->config('dungeon_social_dribble', $post['dribble'])->config('dungeon_social_behance', $post['behance'])->config('dungeon_social_deviantart', $post['deviantart'])->config('dungeon_social_flickr', $post['flickr'])->config('dungeon_social_github', $post['github'])->config('dungeon_social_instagram', $post['instagram'])->config('dungeon_social_youtube', $post['youtube']); refresh(); } } } } return new Row(new Col(new Panel(array('content' => $this->load->view('admin/menu', array('theme_name' => $theme->get_name())), 'body' => FALSE)), 'col-md-3'), new Col(new Panel(array('title' => 'Dashboard', 'icon' => 'fa-dashboard', 'content' => $this->load->view('admin/index', array('theme' => $theme, 'form_header' => $form_header->display(), 'form_background' => $form_background->display(), 'form_settings' => $form_settings->display(), 'form_socials' => $form_socials->display())))), 'col-md-9')); }
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { $form = array(); $bam = backup_migrate_get_service_object(); $form['backup_migrate_restore_upload'] = array('#title' => t('Upload a Backup File'), '#type' => 'file', '#description' => t("Upload a backup file created by Backup and Migrate. For other database or file backups please use another tool for import. Max file size: %size", array("%size" => format_size(file_upload_max_size())))); $form['source_id'] = DrupalConfigHelper::getPluginSelector($bam->sources(), $this->t('Restore To')); $conf_schema = $bam->plugins()->map('configSchema', array('operation' => 'restore')); $form += DrupalConfigHelper::buildFormFromSchema($conf_schema, $bam->plugins()->config()); $form['quickbackup']['submit'] = array('#type' => 'submit', '#value' => t('Restore now'), '#weight' => 1); return $form; }
static function registerScripts() { static $loaded = FALSE; if ($loaded) { return; } $loaded = TRUE; CRM_Core_Resources::singleton()->addSettingsFactory(function () { $config = CRM_Core_Config::singleton(); return array('PseudoConstant' => array('locationType' => CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'), 'job_hours_time' => CRM_Hrjobcontract_Page_JobContractTab::getJobHoursTime(), 'working_days' => CRM_Hrjobcontract_Page_JobContractTab::getDaysPerTime()), 'FieldOptions' => CRM_Hrjobcontract_Page_JobContractTab::getFieldOptions(), 'jobContractTabApp' => array('contactId' => CRM_Utils_Request::retrieve('cid', 'Integer'), 'domainId' => CRM_Core_Config::domainID(), 'isLogEnabled' => (bool) $config->logging, 'loggingReportId' => CRM_Report_Utils_Report::getInstanceIDForValue('logging/contact/summary'), 'currencies' => CRM_Hrjobcontract_Page_JobContractTab::getCurrencyFormats(), 'defaultCurrency' => $config->defaultCurrency, 'path' => CRM_Core_Resources::singleton()->getUrl('org.civicrm.hrjobcontract'), 'fields' => CRM_Hrjobcontract_Page_JobContractTab::getFields(), 'contractList' => CRM_Hrjobcontract_Page_JobContractTab::getContractList(), 'maxFileSize' => file_upload_max_size()), 'debug' => $config->debug); }); }
/** * {@inheritdoc} * * @param \Drupal\filter\Entity\FilterFormat $filter_format * The filter format for which this dialog corresponds. */ public function buildForm(array $form, array &$form_state, FilterFormat $filter_format = NULL) { // The default values are set directly from \Drupal::request()->request, // provided by the editor plugin opening the dialog. if (!isset($form_state['image_element'])) { $form_state['image_element'] = isset($form_state['input']['editor_object']) ? $form_state['input']['editor_object'] : array(); } $image_element = $form_state['image_element']; $form['#tree'] = TRUE; $form['#attached']['library'][] = 'editor/drupal.editor.dialog'; $form['#prefix'] = '<div id="editor-image-dialog-form">'; $form['#suffix'] = '</div>'; $editor = editor_load($filter_format->format); // Construct strings to use in the upload validators. $image_upload = $editor->getImageUploadSettings(); if (!empty($image_upload['dimensions'])) { $max_dimensions = $image_upload['dimensions']['max_width'] . 'x' . $image_upload['dimensions']['max_height']; } else { $max_dimensions = 0; } $max_filesize = min(Bytes::toInt($image_upload['max_size']), file_upload_max_size()); $existing_file = isset($image_element['data-editor-file-uuid']) ? entity_load_by_uuid('file', $image_element['data-editor-file-uuid']) : NULL; $fid = $existing_file ? $existing_file->id() : NULL; $form['fid'] = array('#title' => $this->t('Image'), '#type' => 'managed_file', '#upload_location' => $image_upload['scheme'] . '://' . $image_upload['directory'], '#default_value' => $fid ? array($fid) : NULL, '#upload_validators' => array('file_validate_extensions' => array('gif png jpg jpeg'), 'file_validate_size' => array($max_filesize), 'file_validate_image_resolution' => array($max_dimensions)), '#required' => TRUE); $form['attributes']['src'] = array('#title' => $this->t('URL'), '#type' => 'textfield', '#default_value' => isset($image_element['src']) ? $image_element['src'] : '', '#maxlength' => 2048, '#required' => TRUE); // If the editor has image uploads enabled, show a managed_file form item, // otherwise show a (file URL) text form item. if ($image_upload['status']) { $form['attributes']['src']['#access'] = FALSE; $form['attributes']['src']['#required'] = FALSE; } else { $form['fid']['#access'] = FALSE; $form['fid']['#required'] = FALSE; } $form['attributes']['alt'] = array('#title' => $this->t('Alternative text'), '#type' => 'textfield', '#required' => TRUE, '#default_value' => isset($image_element['alt']) ? $image_element['alt'] : '', '#maxlength' => 2048); $form['dimensions'] = array('#type' => 'item', '#title' => $this->t('Image size'), '#field_prefix' => '<div class="container-inline">', '#field_suffix' => '</div>'); $form['dimensions']['width'] = array('#title' => $this->t('Width'), '#title_display' => 'invisible', '#type' => 'number', '#default_value' => isset($image_element['width']) ? $image_element['width'] : '', '#size' => 8, '#maxlength' => 8, '#min' => 1, '#max' => 99999, '#placeholder' => $this->t('width'), '#field_suffix' => ' x ', '#parents' => array('attributes', 'width')); $form['dimensions']['height'] = array('#title' => $this->t('Height'), '#title_display' => 'invisible', '#type' => 'number', '#default_value' => isset($image_element['height']) ? $image_element['height'] : '', '#size' => 8, '#maxlength' => 8, '#min' => 1, '#max' => 99999, '#placeholder' => $this->t('height'), '#field_suffix' => $this->t('pixels'), '#parents' => array('attributes', 'height')); // When Drupal core's filter_caption is being used, the text editor may // offer the ability to change the alignment. if (isset($image_element['data-align'])) { $form['align'] = array('#title' => $this->t('Align'), '#type' => 'radios', '#options' => array('none' => $this->t('None'), 'left' => $this->t('Left'), 'center' => $this->t('Center'), 'right' => $this->t('Right')), '#default_value' => $image_element['data-align'] === '' ? 'none' : $image_element['data-align'], '#wrapper_attributes' => array('class' => array('container-inline')), '#attributes' => array('class' => array('container-inline')), '#parents' => array('attributes', 'data-align')); } // When Drupal core's filter_caption is being used, the text editor may // offer the ability to in-place edit the image's caption: show a toggle. if (isset($image_element['hasCaption'])) { $form['caption'] = array('#title' => $this->t('Caption'), '#type' => 'checkbox', '#default_value' => $image_element['hasCaption'] === 'true', '#parents' => array('attributes', 'hasCaption')); } $form['actions'] = array('#type' => 'actions'); $form['actions']['save_modal'] = array('#type' => 'submit', '#value' => $this->t('Save'), '#submit' => array(), '#ajax' => array('callback' => array($this, 'submitForm'), 'event' => 'click')); return $form; }
/** * Processes AJAX file uploads and deletions. * * @param \Symfony\Component\HttpFoundation\Request $request * The current request object. * * @return \Drupal\Core\Ajax\AjaxResponse * An AjaxResponse object. */ public function upload(Request $request) { $form_parents = explode('/', $request->query->get('element_parents')); $form_build_id = $request->query->get('form_build_id'); $request_form_build_id = $request->request->get('form_build_id'); if (empty($request_form_build_id) || $form_build_id !== $request_form_build_id) { // Invalid request. drupal_set_message(t('An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (@size) that this server supports.', array('@size' => format_size(file_upload_max_size()))), 'error'); $response = new AjaxResponse(); $status_messages = array('#theme' => 'status_messages'); return $response->addCommand(new ReplaceCommand(NULL, drupal_render($status_messages))); } try { /** @var $ajaxForm \Drupal\system\FileAjaxForm */ $ajaxForm = $this->getForm($request); $form = $ajaxForm->getForm(); $form_state = $ajaxForm->getFormState(); $commands = $ajaxForm->getCommands(); } catch (HttpExceptionInterface $e) { // Invalid form_build_id. drupal_set_message(t('An unrecoverable error occurred. Use of this form has expired. Try reloading the page and submitting again.'), 'error'); $response = new AjaxResponse(); $status_messages = array('#theme' => 'status_messages'); return $response->addCommand(new ReplaceCommand(NULL, drupal_render($status_messages))); } // Get the current element and count the number of files. $current_element = NestedArray::getValue($form, $form_parents); $current_file_count = isset($current_element['#file_upload_delta']) ? $current_element['#file_upload_delta'] : 0; // Process user input. $form and $form_state are modified in the process. drupal_process_form($form['#form_id'], $form, $form_state); // Retrieve the element to be rendered. $form = NestedArray::getValue($form, $form_parents); // Add the special Ajax class if a new file was added. if (isset($form['#file_upload_delta']) && $current_file_count < $form['#file_upload_delta']) { $form[$current_file_count]['#attributes']['class'][] = 'ajax-new-content'; } else { $form['#suffix'] .= '<span class="ajax-new-content"></span>'; } $status_messages = array('#theme' => 'status_messages'); $form['#prefix'] .= drupal_render($status_messages); $output = drupal_render($form); drupal_process_attached($form); $js = _drupal_add_js(); $settings = drupal_merge_js_settings($js['settings']['data']); $response = new AjaxResponse(); foreach ($commands as $command) { $response->addCommand($command, TRUE); } return $response->addCommand(new ReplaceCommand(NULL, $output, $settings)); }
/** * {@inheritdoc} */ public function form(array $form, FormStateInterface $form_state) { $imce_profile = $this->getEntity(); // Check duplication if ($this->getOperation() === 'duplicate') { $imce_profile = $imce_profile->createDuplicate(); $imce_profile->set('label', $this->t('Duplicate of @label', array('@label' => $imce_profile->label()))); $this->setEntity($imce_profile); } // Label $form['label'] = array('#type' => 'textfield', '#title' => $this->t('Name'), '#default_value' => $imce_profile->label(), '#maxlength' => 64, '#required' => TRUE, '#weight' => -20); // Id $form['id'] = array('#type' => 'machine_name', '#machine_name' => array('exists' => array(get_class($imce_profile), 'load'), 'source' => array('label')), '#default_value' => $imce_profile->id(), '#maxlength' => 32, '#required' => TRUE, '#weight' => -20); // Description $form['description'] = array('#type' => 'textfield', '#title' => $this->t('Description'), '#default_value' => $imce_profile->get('description'), '#weight' => -10); // Conf $conf = array('#tree' => TRUE); // Extensions $conf['extensions'] = array('#type' => 'textfield', '#title' => $this->t('Allowed file extensions'), '#default_value' => $imce_profile->getConf('extensions'), '#maxlength' => 255, '#description' => $this->t('Separate extensions with a space or comma and do not include the leading dot.') . ' ' . $this->t('Set to * to allow all extensions.'), '#weight' => -9); // File size $maxsize = file_upload_max_size(); $conf['maxsize'] = array('#type' => 'number', '#min' => 0, '#max' => ceil($maxsize / 1024 / 1024), '#step' => 'any', '#size' => 8, '#title' => $this->t('Maximum file size'), '#default_value' => $imce_profile->getConf('maxsize'), '#description' => $this->t('Maximum allowed file size per upload.') . ' ' . t('Your PHP settings limit the upload size to %size.', array('%size' => format_size($maxsize))), '#field_suffix' => $this->t('MB'), '#weight' => -8); // Quota $conf['quota'] = array('#type' => 'number', '#min' => 0, '#step' => 'any', '#size' => 8, '#title' => $this->t('Disk quota'), '#default_value' => $imce_profile->getConf('quota'), '#description' => $this->t('Maximum disk space that can be allocated by a user.'), '#field_suffix' => $this->t('MB'), '#weight' => -7); // Image dimensions $conf['dimensions'] = array('#type' => 'container', '#attributes' => array('class' => array('dimensions-wrapper form-item')), '#weight' => -6); $conf['dimensions']['label'] = array('#markup' => '<label>' . $this->t('Maximum image dimensions') . '</label>'); $conf['dimensions']['maxwidth'] = array('#type' => 'number', '#default_value' => $imce_profile->getConf('maxwidth'), '#maxlength' => 5, '#min' => 0, '#size' => 8, '#placeholder' => $this->t('Width'), '#field_suffix' => ' x ', '#parents' => array('conf', 'maxwidth')); $conf['dimensions']['maxheight'] = array('#type' => 'number', '#default_value' => $imce_profile->getConf('maxheight'), '#maxlength' => 5, '#min' => 0, '#size' => 8, '#placeholder' => $this->t('Height'), '#field_suffix' => $this->t('pixels'), '#parents' => array('conf', 'maxheight')); $conf['dimensions']['description'] = array('#markup' => '<div class="description">' . $this->t('Images exceeding the limit will be scaled down.') . '</div>'); // Replace method $conf['replace'] = array('#type' => 'radios', '#title' => $this->t('Upload replace method'), '#default_value' => $imce_profile->getConf('replace', FILE_EXISTS_RENAME), '#options' => array(FILE_EXISTS_RENAME => t('Keep the existing file renaming the new one'), FILE_EXISTS_REPLACE => t('Replace the existing file with the new one'), FILE_EXISTS_ERROR => t('Keep the existing file rejecting the new one')), '#description' => $this->t('Select the replace method for existing files during uploads.'), '#weight' => -5); // Folders $conf['folders'] = array('#type' => 'fieldset', '#title' => $this->t('Folders'), 'description' => array('#markup' => '<div class="description">' . $this->t('You can use user tokens in folder paths, e.g. @tokens.', array('@tokens' => '[user:uid], [user:name]')) . ' ' . $this->t('Subfolders inherit parent permissions when subfolder browsing is enabled.') . '</div>'), '#weight' => 10); $folders = $imce_profile->getConf('folders', array()); $index = 0; foreach ($folders as $folder) { $conf['folders'][] = $this->folderForm($index++, $folder); } $conf['folders'][] = $this->folderForm($index++); $conf['folders'][] = $this->folderForm($index); $form['conf'] = $conf; // Add library $form['#attached']['library'][] = 'imce/drupal.imce.admin'; // Call plugin form alterers \Drupal::service('plugin.manager.imce.plugin')->alterProfileForm($form, $form_state, $imce_profile); return parent::form($form, $form_state); }
public function index($theme) { $this->css('admin')->js('admin')->load->library('form')->add_rules(array('background' => array('label' => $this('background'), 'value' => $this->config->{'default_background'}, 'type' => 'file', 'upload' => 'themes/default/backgrounds', 'info' => i18n('file_picture', file_upload_max_size() / 1024 / 1024), 'check' => function ($filename, $ext) { if (!in_array($ext, array('gif', 'jpeg', 'jpg', 'png'))) { return i18n('select_image_file'); } }), 'repeat' => array('label' => $this('background_repeat'), 'value' => $this->config->{'default_background_repeat'}, 'values' => array('no-repeat' => $this('no'), 'repeat-x' => $this('horizontally'), 'repeat-y' => $this('vertically'), 'repeat' => $this('both')), 'type' => 'radio', 'rules' => 'required'), 'positionX' => array('label' => $this('position'), 'value' => explode(' ', $this->config->{'default_background_position'})[0], 'values' => array('left' => $this('left'), 'center' => $this('center'), 'right' => $this('right')), 'type' => 'radio', 'rules' => 'required'), 'positionY' => array('value' => explode(' ', $this->config->{'default_background_position'})[1], 'values' => array('top' => $this('top'), 'center' => $this('middle'), 'bottom' => $this('bottom')), 'type' => 'radio', 'rules' => 'required'), 'fixed' => array('value' => $this->config->{'default_background_attachment'}, 'values' => array('on' => $this('background_fixed')), 'type' => 'checkbox'), 'color' => array('label' => $this('background_color'), 'value' => $this->config->{'default_background_color'}, 'type' => 'colorpicker', 'rules' => 'required')))->add_submit($this('save')); if ($this->form->is_valid($post)) { if ($post['background']) { $this->config('default_background', $post['background'], 'int'); } else { $this->db->where('name', 'default_background')->delete('nf_settings'); } $this->config('default_background_repeat', $post['repeat'])->config('default_background_attachment', in_array('on', $post['fixed']) ? 'fixed' : 'scroll')->config('default_background_position', $post['positionX'] . ' ' . $post['positionY'])->config('default_background_color', $post['color']); refresh(); } return new Row(new Col(new Panel(array('content' => $this->load->view('admin/menu', array('theme_name' => $theme->name)), 'body' => FALSE)), 'col-md-4 col-lg-3'), new Col(new Panel(array('title' => $this('dashboard'), 'icon' => 'fa-cog', 'content' => $this->load->view('admin/index', array('theme' => $theme, 'form_background' => $this->form->display())))), 'col-md-8 col-lg-9')); }
public function _edit($gallery_id, $category_id, $image_id, $name, $published, $title, $description, $category_name, $category_title, $category_image, $category_icon) { $this->css('dropzone.min')->css('admin')->js('dropzone')->js('admin')->js('preview'); $form_album = $this->subtitle($title)->load->library('form')->add_rules('album', array('title' => $title, 'category_id' => $category_id, 'categories' => $this->model()->get_categories_list(), 'image' => $image_id, 'description' => $description, 'published' => $published, 'gallery_id' => $gallery_id))->add_submit($this('edit'))->add_back('admin/gallery.html')->save(); $form_image = $this->form->add_rules(array('image' => array('label' => $this('image'), 'type' => 'file', 'upload' => 'gallery', 'info' => $this('file_picture', file_upload_max_size() / 1024 / 1024), 'check' => function ($filename, $ext) { if (!in_array($ext, array('gif', 'jpeg', 'jpg', 'png'))) { return i18n('select_image_file'); } }, 'rules' => 'required'), 'title' => array('label' => $this('title'), 'type' => 'text'), 'description' => array('label' => $this('description'), 'type' => 'textarea')))->add_submit($this('add_image'))->save(); $gallery_table = $this->load->library('table')->add_columns(array(array('content' => function ($data, $loader) { return '<a class="thumbnail thumbnail-link" data-toggle="tooltip" title="' . $loader->lang('view') . '" data-image="' . path($data['file_id']) . '" data-title="' . $data['title'] . '" data-description="' . $data['description'] . '"><img style="max-width: 80px;" src="' . path($data['thumbnail_file_id']) . '" alt="" /></a>'; }, 'size' => TRUE), array('title' => $this('title'), 'content' => function ($data) { return $data['title']; }, 'align' => 'left', 'sort' => function ($data) { return $data['title']; }, 'search' => function ($data) { return $data['title']; }), array('title' => $this('date'), 'content' => function ($data) { return '<span data-toggle="tooltip" title="' . timetostr(NeoFrag::loader()->lang('date_time_long'), $data['date']) . '">' . time_span($data['date']) . '</span>'; }, 'align' => 'left', 'sort' => function ($data) { return $data['date']; }, 'search' => function ($data) { return $data['date']; }), array('content' => array(function ($data, $loader) { return button('gallery/image/' . $data['image_id'] . '/' . url_title($data['title']) . '.html', 'fa-eye', $loader->lang('see_image')); }, function ($data) { return button_edit('admin/gallery/image/' . $data['image_id'] . '/' . url_title($data['title']) . '.html'); }, function ($data) { return button_delete('admin/gallery/image/delete/' . $data['image_id'] . '/' . url_title($data['title']) . '.html'); }), 'align' => 'right', 'size' => TRUE)))->data($images = $this->model()->get_images($gallery_id))->no_data($this('no_images'))->save(); if ($form_album->is_valid($post)) { $this->model()->edit_gallery($gallery_id, $post['category'], $post['image'], in_array('on', $post['published']), $post['title'], $post['description'], $this->config->lang); //add_alert('success', $this('album_edited')); redirect_back('admin/gallery.html'); } else { if ($form_image->is_valid($post)) { $this->model()->add_image($post['image'], $gallery_id, $post['title'], $post['description']); //add_alert('success', $this('image_added')); refresh(); } } return new Row(new Col(new Panel(array('title' => $this('edit_album_title'), 'icon' => 'fa-photo', 'content' => $form_album->display(), 'size' => 'col-md-12 col-lg-7'))), new Col(new Panel(array('title' => $this('add_images_title'), 'icon' => 'fa-photo', 'content' => $this->load->view('upload', array('gallery_id' => $gallery_id, 'name' => $name, 'form_image' => $form_image->display())), 'footer' => $this->load->view('admin_gallery', array('images' => $images, 'gallery_table' => $gallery_table->display())), 'size' => 'col-md-12 col-lg-5')))); }
public static function ValidateFile($file) { /* check size of file is less than max file size. We have to do it this way because $_FILES[] array will be empty if a file exceeds the upload limit in php.ini. For the same reason put this check before the empty() checks. */ /* First set max file size allowed for uploading. */ if (isset($file['max_file_size']) && !empty($file['max_file_size'])) { $max_file_size = $file['max_file_size']; } else { $max_file_size = file_upload_max_size(); } if (isset($_SERVER['CONTENT_LENGTH']) && (int) $_SERVER['CONTENT_LENGTH'] > $max_file_size) { $msg[] = 'You cannot upload more than ' . round($max_file_size / 1024 / 1024, 2) . 'MB at a time.'; return $msg; } elseif ($file['file_info']['error'] === UPLOAD_ERR_NO_FILE) { $msg[] = 'Please select a file to upload.'; return $msg; } elseif (empty($file['file_info']['size'])) { $msg[] = 'The file you uploaded is empty.'; return $msg; } elseif (!preg_match('/^[0-9]+$/', $file['file_info']['size'])) { $msg[] = 'Invalid file size.'; return $msg; } /* Warn if file extension is in not array of allowable extensions. Allow devs to supply uppercase or lowercase extensions in array. */ foreach ($file['allowed_extensions'] as $extension) { $allowed_extensions_lcase[] = strtolower($extension); } if (!in_array(strtolower(pathinfo($file['file_info']['name'], PATHINFO_EXTENSION)), $allowed_extensions_lcase)) { $m = "Please upload one of the following file types: " . implode(', ', $allowed_extensions_lcase) . "."; $msg[] = $m; } $m = self::get_file_error_msg($file['file_info']['error']); if ($m !== true) { $msg[] = $m; } if (isset($msg) && count($msg) > 0) { return $msg; } else { return true; } }
/** * {@inheritdoc} * * @see editor_image_upload_settings_form() */ public function settingsForm(array $form, FormStateInterface $form_state, Editor $editor) { $editor_settings = $editor->getSettings(); $plugin_settings = !empty($editor_settings['plugins']['embridgeimage']['embridge_image_upload']) ? $editor_settings['plugins']['embridgeimage']['embridge_image_upload'] : []; $plugin_settings += ['directory' => 'embridge-inline-images', 'max_size' => '', 'catalog_id' => '', 'enabled' => FALSE]; $sub_form = []; $sub_form['warning'] = ['#markup' => t("<strong>Warning: This plugin overrides the standard drupal image plugin.</strong>")]; $sub_form['enabled'] = ['#type' => 'checkbox', '#default_value' => $plugin_settings['enabled'], '#title' => t('Enable plugin'), '#description' => t("Tick this to connect the image dialog with EMDB."), '#attributes' => array('data-editor-embridge-upload' => 'enabled')]; $show_if_plugin_uploads_enabled = array('visible' => array(':input[data-editor-embridge-upload="enabled"]' => array('checked' => TRUE))); $sub_form['directory'] = ['#type' => 'textfield', '#default_value' => $plugin_settings['directory'], '#title' => t('Upload directory'), '#description' => t("A temporary directory to upload images into before sending to EMDB."), '#states' => $show_if_plugin_uploads_enabled]; $default_max_size = format_size(file_upload_max_size()); $sub_form['max_size'] = ['#type' => 'textfield', '#default_value' => $plugin_settings['max_size'], '#title' => t('Maximum file size'), '#description' => t('If this is left empty, then the file size will be limited by the PHP maximum upload size of @size.', ['@size' => $default_max_size]), '#maxlength' => 20, '#size' => 10, '#placeholder' => $default_max_size, '#states' => $show_if_plugin_uploads_enabled]; /** @var EmbridgeCatalog[] $entities */ $entities = EmbridgeCatalog::loadMultiple(); $options = []; foreach ($entities as $entity) { $options[$entity->id()] = $entity->label(); } $sub_form['catalog_id'] = ['#type' => 'select', '#title' => t('Catalog'), '#default_value' => $plugin_settings['catalog_id'], '#options' => $options, '#description' => t("Select the Catalog to source media from for this field."), '#required' => TRUE, '#weight' => 6, '#states' => $show_if_plugin_uploads_enabled]; $sub_form['library_id'] = array('#type' => 'textfield', '#title' => t('Library'), '#default_value' => $plugin_settings['library_id'], '#description' => t("Limit uploads via this field to a specific library."), '#required' => FALSE, '#size' => 10, '#weight' => 6); $sub_form['#attached']['library'][] = 'embridge_ckeditor/drupal.embridge_ckeditor.embridgeimage.admin'; $form['embridge_image_upload'] = $sub_form; return $form; }
public function maintenance() { $this->title($this('maintenance'))->icon('fa-power-off')->css('maintenance')->js('maintenance'); $form_opening = $this->load->library('form')->add_rules(array('opening' => array('type' => 'datetime', 'value' => $this->config->nf_maintenance_opening)))->fast_mode()->add_submit($this('save'))->save(); $form_maintenance = $this->form->add_rules(array('title' => array('label' => $this('title'), 'type' => 'text', 'value' => $this->config->nf_maintenance_title), 'content' => array('label' => $this('content'), 'type' => 'editor', 'value' => $this->config->nf_maintenance_content), 'logo' => array('label' => $this('logo'), 'value' => $this->config->nf_maintenance_logo, 'type' => 'file', 'upload' => 'maintenance', 'info' => $this('file_picture', file_upload_max_size() / 1024 / 1024), 'check' => function ($filename, $ext) { if (!in_array($ext, array('gif', 'jpeg', 'jpg', 'png'))) { return i18n('select_image_file'); } }), 'background' => array('label' => $this('background'), 'value' => $this->config->nf_maintenance_background, 'type' => 'file', 'upload' => 'maintenance', 'info' => $this('file_picture', file_upload_max_size() / 1024 / 1024), 'check' => function ($filename, $ext) { if (!in_array($ext, array('gif', 'jpeg', 'jpg', 'png'))) { return i18n('select_image_file'); } }), 'repeat' => array('label' => $this('background_repeat'), 'value' => $this->config->nf_maintenance_background_repeat, 'values' => array('no-repeat' => $this('no'), 'repeat-x' => $this('horizontally'), 'repeat-y' => $this('vertically'), 'repeat' => $this('both')), 'type' => 'radio'), 'positionX' => array('label' => $this('position'), 'value' => $this->config->nf_maintenance_background_position ? explode(' ', $this->config->nf_maintenance_background_position)[0] : '', 'values' => array('left' => $this('left'), 'center' => $this('center'), 'right' => $this('right')), 'type' => 'radio'), 'positionY' => array('value' => $this->config->nf_maintenance_background_position ? explode(' ', $this->config->nf_maintenance_background_position)[1] : '', 'values' => array('top' => $this('top'), 'center' => $this('middle'), 'bottom' => $this('bottom')), 'type' => 'radio'), 'background_color' => array('label' => $this('background_color'), 'value' => $this->config->nf_maintenance_background_color, 'type' => 'colorpicker'), 'text_color' => array('label' => $this('text_color'), 'value' => $this->config->nf_maintenance_text_color, 'type' => 'colorpicker'), 'facebook' => array('label' => 'Facebook', 'icon' => 'fa-facebook', 'value' => $this->config->nf_maintenance_facebook, 'type' => 'url'), 'twitter' => array('label' => 'Twitter', 'icon' => 'fa-twitter', 'value' => $this->config->nf_maintenance_twitter, 'type' => 'url'), 'google' => array('label' => 'Google+', 'icon' => 'fa-google-plus', 'value' => $this->config->{'nf_maintenance_google-plus'}, 'type' => 'url'), 'steam' => array('label' => 'Steam', 'icon' => 'fa-steam', 'value' => $this->config->nf_maintenance_steam, 'type' => 'url'), 'twitch' => array('label' => 'Twitch', 'icon' => 'fa-twitch', 'value' => $this->config->nf_maintenance_twitch, 'type' => 'url')))->add_submit($this('save'))->save(); if ($form_opening->is_valid($post)) { $this->config('nf_maintenance_opening', $post['opening']); refresh(); } else { if ($form_maintenance->is_valid($post)) { $this->config('nf_maintenance_title', $post['title'])->config('nf_maintenance_content', $post['content'])->config('nf_maintenance_logo', $post['logo'], 'int')->config('nf_maintenance_background', $post['background'], 'int')->config('nf_maintenance_background_repeat', $post['repeat'])->config('nf_maintenance_background_position', $post['positionX'] . ' ' . $post['positionY'])->config('nf_maintenance_background_color', $post['background_color'])->config('nf_maintenance_text_color', $post['text_color'])->config('nf_maintenance_facebook', $post['facebook'])->config('nf_maintenance_twitter', $post['twitter'])->config('nf_maintenance_google-plus', $post['google'])->config('nf_maintenance_steam', $post['steam'])->config('nf_maintenance_twitch', $post['twitch']); refresh(); } } return new Row(new Col(new Panel(array('title' => $this('website_status'), 'icon' => 'fa-power-off', 'content' => $this->load->view('maintenance'))), new Panel(array('title' => $this('planned_opening'), 'icon' => 'fa-clock-o', 'content' => $form_opening->display())), 'col-md-3'), new Col(new Panel(array('title' => $this('customizing_maintenance_page'), 'icon' => 'fa-paint-brush', 'content' => $form_maintenance->display())), 'col-md-9')); }
/** * Retrieves the upload validators for a file field. * * @return array * An array suitable for passing to file_save_upload() or the file field * element's '#upload_validators' property. */ public function getUploadValidators() { $validators = array(); $settings = $this->getSettings(); // Cap the upload size according to the PHP limit. $max_filesize = Bytes::toInt(file_upload_max_size()); if (!empty($settings['max_filesize'])) { $max_filesize = min($max_filesize, Bytes::toInt($settings['max_filesize'])); } // There is always a file size limit due to the PHP server limit. $validators['file_validate_size'] = array($max_filesize); // Add the extension check if necessary. if (!empty($settings['file_extensions'])) { $validators['file_validate_extensions'] = array($settings['file_extensions']); } return $validators; }
the Free Software Foundation, either version 3 of the License, or (at your option) any later version. NeoFrag is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with NeoFrag. If not, see <http://www.gnu.org/licenses/>. **************************************************************************/ $rules = array('title' => array('label' => '{lang title}', 'value' => $title, 'type' => 'text', 'rules' => 'required'), 'image' => array('label' => '{lang image}', 'value' => $image, 'upload' => 'news/categories', 'type' => 'file', 'info' => i18n('file_picture', file_upload_max_size() / 1024 / 1024), 'check' => function ($filename, $ext) { if (!in_array($ext, array('gif', 'jpeg', 'jpg', 'png'))) { return i18n('select_image_file'); } }), 'icon' => array('label' => '{lang icon}', 'value' => $icon, 'upload' => 'news/categories', 'type' => 'file', 'info' => i18n('file_icon', 16, file_upload_max_size() / 1024 / 1024), 'check' => function ($filename, $ext) { if (!in_array($ext, array('gif', 'jpeg', 'jpg', 'png'))) { return i18n('select_image_file'); } list($w, $h) = getimagesize($filename); if ($w != $h) { return i18n('icon_must_be_square'); } else { if ($w < 16) { return i18n('icon_size_error', 16); } } }, 'post_upload' => function ($filename) { image_resize($filename, 16, 16); })); /*
protected function getValidators() { $extensions = array(); $types = file_type_get_enabled_types(); foreach ($types as $t => $type) { $extensions = array_merge($extensions, _os_files_extensions_from_type($t)); } $validators = array('file_validate_extensions' => array(implode(' ', $extensions)), 'file_validate_size' => array(parse_size(file_upload_max_size()))); return $validators; }
$imgcreatefrom = "ImageCreateFromPNG"; } if ($imgt) { $old_image = $imgcreatefrom("{$img}"); $new_image = imagecreatetruecolor($thumbnail_width, $thumbnail_height); imagecopyresized($new_image, $old_image, $dest_x, $dest_y, 0, 0, $new_width, $new_height, $original_width, $original_height); $n = pathinfo($img, PATHINFO_BASENAME); $imgt($new_image, "thumbs/" . $n); } } if (isset($_POST['submit'])) { $conn = new mysqli(dbHost, dbUser, dbPass, dbName); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $max_file_size = file_upload_max_size(); $j = 0; //Variable for indexing uploaded image $x = 0; $target_path = "uploads/"; //Declaring Path for uploaded images for ($i = 0; $i < count($_FILES['file']['name']); $i++) { //loop to get individual element from the array $validextensions = array("jpeg", "jpg", "png", "JPG", "JPEG", "PNG"); //Extensions which are allowed $ext = explode('.', basename($_FILES['file']['name'][$i])); //explode file name from dot(.) $file_extension = end($ext); //store extensions in the variable $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1]; //set the target path with a new name of image
/** * Wraps file_upload_max_size(). * * @return string * A translated string representation of the size of the file size limit * based on the PHP upload_max_filesize and post_max_size. */ protected function getFileUploadMaxSize() { return file_upload_max_size(); }
function user_import_add_file_form(&$form, $ftp_files = NULL) { $form['browser'] = array('#type' => 'fieldset', '#title' => t('Browser Upload'), '#collapsible' => TRUE, '#description' => t("Upload a CSV file.")); if (function_exists('file_upload_max_size')) { $file_size = t('Maximum file size: !size MB.', array('!size' => file_upload_max_size())); } $form['browser']['file_upload'] = array('#type' => 'file', '#title' => t('CSV File'), '#size' => 40, '#description' => t('Select the CSV file to be imported. ') . $file_size); if (!empty($ftp_files)) { $form['ftp'] = array('#type' => 'fieldset', '#title' => t('FTP Upload'), '#collapsible' => TRUE, '#collapsed' => TRUE, '#description' => t("Any files uploaded to the 'user_import' directory using FTP can be selected for import here. Useful if the import file is too large for upload via the browser.")); $form['ftp']['file_ftp'] = array('#type' => 'radios', '#title' => t('Files'), '#default_value' => 0, '#options' => $ftp_files); // reload the page to show any files that have been added by FTP $form['ftp']['scan'] = array('#type' => 'submit', '#value' => t('Check for new files'), '#validate' => array(), '#submit' => array()); } return; }
/** * {@inheritdoc} * * @param \Drupal\filter\Entity\FilterFormat $filter_format * The filter format for which this dialog corresponds. */ public function buildForm(array $form, FormStateInterface $form_state, FilterFormat $filter_format = NULL) { // This form is special, in that the default values do not come from the // server side, but from the client side, from a text editor. We must cache // this data in form state, because when the form is rebuilt, we will be // receiving values from the form, instead of the values from the text // editor. If we don't cache it, this data will be lost. if (isset($form_state->getUserInput()['editor_object'])) { // By convention, the data that the text editor sends to any dialog is in // the 'editor_object' key. And the image dialog for text editors expects // that data to be the attributes for an <img> element. $file_element = $form_state->getUserInput()['editor_object']; $form_state->set('file_element', $file_element); $form_state->setCached(TRUE); } else { // Retrieve the image element's attributes from form state. $file_element = $form_state->get('file_element') ?: []; } $form['#tree'] = TRUE; $form['#attached']['library'][] = 'editor/drupal.editor.dialog'; $form['#prefix'] = '<div id="editor-file-dialog-form">'; $form['#suffix'] = '</div>'; // Load dialog settings. $editor = editor_load($filter_format->id()); $file_upload = $editor->getThirdPartySettings('editor_file'); $max_filesize = min(Bytes::toInt($file_upload['max_size']), file_upload_max_size()); $existing_file = isset($file_element['data-entity-uuid']) ? \Drupal::entityManager()->loadEntityByUuid('file', $file_element['data-entity-uuid']) : NULL; $fid = $existing_file ? $existing_file->id() : NULL; $form['fid'] = array( '#title' => $this->t('File'), '#type' => 'managed_file', '#upload_location' => $file_upload['scheme'] . '://' . $file_upload['directory'], '#default_value' => $fid ? array($fid) : NULL, '#upload_validators' => array( 'file_validate_extensions' => !empty($file_upload['extensions']) ? $file_upload['extensions'] : array('txt'), 'file_validate_size' => array($max_filesize), ), '#required' => TRUE, ); $form['attributes']['href'] = array( '#title' => $this->t('URL'), '#type' => 'textfield', '#default_value' => isset($file_element['href']) ? $file_element['href'] : '', '#maxlength' => 2048, '#required' => TRUE, ); if ($file_upload['status']) { $form['attributes']['href']['#access'] = FALSE; $form['attributes']['href']['#required'] = FALSE; } else { $form['fid']['#access'] = FALSE; $form['fid']['#required'] = FALSE; } $form['actions'] = array( '#type' => 'actions', ); $form['actions']['save_modal'] = array( '#type' => 'submit', '#value' => $this->t('Save'), // No regular submit-handler. This form only works via JavaScript. '#submit' => array(), '#ajax' => array( 'callback' => '::submitForm', 'event' => 'click', ), ); return $form; }
<div class="modal-dialog modal-xs"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only"><?php echo i18n('close'); ?> </span></button> <h4 class="modal-title"><?php echo i18n('install_theme'); ?> </h4> </div> <div class="modal-body"> <div class="modal-theme-install-upload"> <p><?php echo icon('fa-download') . ' ' . i18n('upload_zip_file', file_upload_max_size() / 1024 / 1024); ?> </p> <input type="file" accept=".zip" /> </div> <div class="modal-theme-install-progress progress"> <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100"></div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal"><?php echo i18n('cancel'); ?> </button> <button type="button" class="btn btn-info disabled"><?php echo i18n('install');
if (!defined('NEOFRAG_CMS')) { exit; } /************************************************************************** Copyright © 2015 Michaël BILCOT & Jérémy VALENTIN This file is part of NeoFrag. NeoFrag is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. NeoFrag is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with NeoFrag. If not, see <http://www.gnu.org/licenses/>. **************************************************************************/ $rules = array('title' => array('label' => '{lang title}', 'value' => $title, 'type' => 'text', 'rules' => 'required'), 'category' => array('label' => '{lang category}', 'value' => $category_id, 'values' => $categories, 'type' => 'select', 'rules' => 'required'), 'image' => array('label' => '{lang upload}', 'value' => $image, 'type' => 'file', 'upload' => 'gallery/covers', 'info' => i18n('file_picture', file_upload_max_size() / 1024 / 1024), 'check' => function ($filename, $ext) { if (!in_array($ext, array('gif', 'jpeg', 'jpg', 'png'))) { return i18n('select_image_file'); } }), 'description' => array('label' => '{lang description}', 'value' => $description, 'type' => 'editor'), 'published' => array('type' => 'checkbox', 'checked' => array('on' => $published), 'values' => array('on' => '{lang album_visible}'))); /* NeoFrag Alpha 0.1.3 ./modules/gallery/forms/album.php */
/** * Checks of there is an error with the file upload and throws an exception. * * @param string $source * The name of the uploaded file * @param array $files * Array containing information about the files. * * @throws \Drupal\restful\Exception\BadRequestException * @throws \Drupal\restful\Exception\ServiceUnavailableException */ protected function checkUploadErrors($source, array $files) { // Check for file upload errors and return FALSE if a lower level system // error occurred. For a complete list of errors: // See http://php.net/manual/features.file-upload.errors.php. switch ($files['files']['error'][$source]) { case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: $message = format_string('The file %file could not be saved, because it exceeds %maxsize, the maximum allowed size for uploads.', array('%file' => $files['files']['name'][$source], '%maxsize' => format_size(file_upload_max_size()))); throw new BadRequestException($message); case UPLOAD_ERR_PARTIAL: case UPLOAD_ERR_NO_FILE: $message = format_string('The file %file could not be saved, because the upload did not complete.', array('%file' => $files['files']['name'][$source])); throw new BadRequestException($message); case UPLOAD_ERR_OK: // Final check that this is a valid upload, if it isn't, use the // default error handler. if ($this::isUploadedFile($files['files']['tmp_name'][$source])) { break; } default: // Unknown error. $message = format_string('The file %file could not be saved. An unknown error has occurred.', array('%file' => $files['files']['name'][$source])); throw new ServiceUnavailableException($message); } }
/** * {@inheritdoc} */ public function defaultConfiguration() { return ['upload_location' => 'public://', 'dropzone_description' => t('Drop files here to upload them'), 'max_filesize' => file_upload_max_size() / pow(Bytes::KILOBYTE, 2) . 'M', 'extensions' => 'jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp'] + parent::defaultConfiguration(); }
/** * {@inheritdoc} * * @param \Drupal\filter\Entity\FilterFormat $filter_format * The filter format for which this dialog corresponds. */ public function buildForm(array $form, FormStateInterface $form_state, FilterFormat $filter_format = NULL) { // The default values are set directly from \Drupal::request()->request, // provided by the editor plugin opening the dialog. if (!($image_element = $form_state->get('image_element'))) { $user_input = $form_state->getUserInput(); $image_element = isset($user_input['editor_object']) ? $user_input['editor_object'] : []; $form_state->set('image_element', $image_element); } $form['#tree'] = TRUE; $form['#attached']['library'][] = 'editor/drupal.editor.dialog'; $form['#prefix'] = '<div id="editor-image-dialog-form">'; $form['#suffix'] = '</div>'; $editor = editor_load($filter_format->id()); // Construct strings to use in the upload validators. $image_upload = $editor->getImageUploadSettings(); if (!empty($image_upload['dimensions'])) { $max_dimensions = $image_upload['dimensions']['max_width'] . '×' . $image_upload['dimensions']['max_height']; } else { $max_dimensions = 0; } $max_filesize = min(Bytes::toInt($image_upload['max_size']), file_upload_max_size()); $existing_file = isset($image_element['data-entity-uuid']) ? \Drupal::entityManager()->loadEntityByUuid('file', $image_element['data-entity-uuid']) : NULL; $fid = $existing_file ? $existing_file->id() : NULL; $form['fid'] = array('#title' => $this->t('Image'), '#type' => 'managed_file', '#upload_location' => $image_upload['scheme'] . '://' . $image_upload['directory'], '#default_value' => $fid ? array($fid) : NULL, '#upload_validators' => array('file_validate_extensions' => array('gif png jpg jpeg'), 'file_validate_size' => array($max_filesize), 'file_validate_image_resolution' => array($max_dimensions)), '#required' => TRUE); $form['attributes']['src'] = array('#title' => $this->t('URL'), '#type' => 'textfield', '#default_value' => isset($image_element['src']) ? $image_element['src'] : '', '#maxlength' => 2048, '#required' => TRUE); // If the editor has image uploads enabled, show a managed_file form item, // otherwise show a (file URL) text form item. if ($image_upload['status']) { $form['attributes']['src']['#access'] = FALSE; $form['attributes']['src']['#required'] = FALSE; } else { $form['fid']['#access'] = FALSE; $form['fid']['#required'] = FALSE; } // The alt attribute is *required*, but we allow users to opt-in to empty // alt attributes for the very rare edge cases where that is valid by // specifying two double quotes as the alternative text in the dialog. // However, that *is* stored as an empty alt attribute, so if we're editing // an existing image (which means the src attribute is set) and its alt // attribute is empty, then we show that as two double quotes in the dialog. // @see https://www.drupal.org/node/2307647 $alt = isset($image_element['alt']) ? $image_element['alt'] : ''; if ($alt === '' && !empty($image_element['src'])) { $alt = '""'; } $form['attributes']['alt'] = array('#title' => $this->t('Alternative text'), '#placeholder' => $this->t('Short description for the visually impaired'), '#type' => 'textfield', '#required' => TRUE, '#required_error' => $this->t('Alternative text is required.<br />(Only in rare cases should this be left empty. To create empty alternative text, enter <code>""</code> — two double quotes without any content).'), '#default_value' => $alt, '#maxlength' => 2048); $form['dimensions'] = array('#type' => 'fieldset', '#title' => $this->t('Image size'), '#attributes' => array('class' => array('container-inline', 'fieldgroup', 'form-composite'))); $form['dimensions']['width'] = array('#title' => $this->t('Width'), '#title_display' => 'invisible', '#type' => 'number', '#default_value' => isset($image_element['width']) ? $image_element['width'] : '', '#size' => 8, '#maxlength' => 8, '#min' => 1, '#max' => 99999, '#placeholder' => $this->t('width'), '#field_suffix' => ' × ', '#parents' => array('attributes', 'width')); $form['dimensions']['height'] = array('#title' => $this->t('Height'), '#title_display' => 'invisible', '#type' => 'number', '#default_value' => isset($image_element['height']) ? $image_element['height'] : '', '#size' => 8, '#maxlength' => 8, '#min' => 1, '#max' => 99999, '#placeholder' => $this->t('height'), '#field_suffix' => $this->t('pixels'), '#parents' => array('attributes', 'height')); // When Drupal core's filter_align is being used, the text editor may // offer the ability to change the alignment. if (isset($image_element['data-align']) && $filter_format->filters('filter_align')->status) { $form['align'] = array('#title' => $this->t('Align'), '#type' => 'radios', '#options' => array('none' => $this->t('None'), 'left' => $this->t('Left'), 'center' => $this->t('Center'), 'right' => $this->t('Right')), '#default_value' => $image_element['data-align'] === '' ? 'none' : $image_element['data-align'], '#wrapper_attributes' => array('class' => array('container-inline')), '#attributes' => array('class' => array('container-inline')), '#parents' => array('attributes', 'data-align')); } // When Drupal core's filter_caption is being used, the text editor may // offer the ability to in-place edit the image's caption: show a toggle. if (isset($image_element['hasCaption']) && $filter_format->filters('filter_caption')->status) { $form['caption'] = array('#title' => $this->t('Caption'), '#type' => 'checkbox', '#default_value' => $image_element['hasCaption'] === 'true', '#parents' => array('attributes', 'hasCaption')); } $form['actions'] = array('#type' => 'actions'); $form['actions']['save_modal'] = array('#type' => 'submit', '#value' => $this->t('Save'), '#submit' => array(), '#ajax' => array('callback' => '::submitForm', 'event' => 'click')); return $form; }
openProject(); editProjectMeta2("projectMeta", $_GET["metadataKey"], $_GET["metadataValue"]); closeProject(); } else { if (isset($_GET["edit"]) && isset($_GET["to"])) { editProject($_GET["edit"], $_GET["to"]); } } } } } } } } if (isset($_GET["status"])) { //Récupère le lieu de l'édition //$details = json_decode(file_get_contents("http://ipinfo.io/{$_SERVER['REMOTE_ADDR']}")); $retour = array("uploadMax" => file_upload_max_size(), "owner" => array("canEdit" => false, "author" => "", "locationGps" => "", "locationName" => "")); if (isset($details) && property_exists($details, "city")) { $retour["owner"]["locationName"] = $details->city; } if ($_SESSION["canEdit"] === realpath(dirname(__FILE__))) { $retour["owner"]["canEdit"] = true; } $retour["owner"]["author"] = ""; echo json_encode($retour); } else { if (isset($_GET["update"])) { update(); } }
/** * {@inheritdoc} * * @param \Drupal\editor\Entity\Editor $editor * The text editor to which this dialog corresponds. */ public function buildForm(array $form, FormStateInterface $form_state, Editor $editor = NULL) { // This form is special, in that the default values do not come from the // server side, but from the client side, from a text editor. We must cache // this data in form state, because when the form is rebuilt, we will be // receiving values from the form, instead of the values from the text // editor. If we don't cache it, this data will be lost. if (isset($form_state->getUserInput()['editor_object'])) { // By convention, the data that the text editor sends to any dialog is in // the 'editor_object' key. And the image dialog for text editors expects // that data to be the attributes for an <img> element. $image_element = $form_state->getUserInput()['editor_object']; $form_state->set('image_element', $image_element); $form_state->setCached(TRUE); } else { // Retrieve the image element's attributes from form state. $image_element = $form_state->get('image_element') ?: []; } $form['#tree'] = TRUE; $form['#attached']['library'][] = 'editor/drupal.editor.dialog'; $form['#prefix'] = '<div id="editor-image-dialog-form">'; $form['#suffix'] = '</div>'; // Construct strings to use in the upload validators. $image_upload = $editor->getImageUploadSettings(); if (!empty($image_upload['max_dimensions']['width']) || !empty($image_upload['max_dimensions']['height'])) { $max_dimensions = $image_upload['max_dimensions']['width'] . 'x' . $image_upload['max_dimensions']['height']; } else { $max_dimensions = 0; } $max_filesize = min(Bytes::toInt($image_upload['max_size']), file_upload_max_size()); $existing_file = isset($image_element['data-entity-uuid']) ? \Drupal::entityManager()->loadEntityByUuid('file', $image_element['data-entity-uuid']) : NULL; $fid = $existing_file ? $existing_file->id() : NULL; $form['fid'] = array('#title' => $this->t('Image'), '#type' => 'managed_file', '#upload_location' => $image_upload['scheme'] . '://' . $image_upload['directory'], '#default_value' => $fid ? array($fid) : NULL, '#upload_validators' => array('file_validate_extensions' => array('gif png jpg jpeg'), 'file_validate_size' => array($max_filesize), 'file_validate_image_resolution' => array($max_dimensions)), '#required' => TRUE); $form['attributes']['src'] = array('#title' => $this->t('URL'), '#type' => 'textfield', '#default_value' => isset($image_element['src']) ? $image_element['src'] : '', '#maxlength' => 2048, '#required' => TRUE); // If the editor has image uploads enabled, show a managed_file form item, // otherwise show a (file URL) text form item. if ($image_upload['status']) { $form['attributes']['src']['#access'] = FALSE; $form['attributes']['src']['#required'] = FALSE; } else { $form['fid']['#access'] = FALSE; $form['fid']['#required'] = FALSE; } // The alt attribute is *required*, but we allow users to opt-in to empty // alt attributes for the very rare edge cases where that is valid by // specifying two double quotes as the alternative text in the dialog. // However, that *is* stored as an empty alt attribute, so if we're editing // an existing image (which means the src attribute is set) and its alt // attribute is empty, then we show that as two double quotes in the dialog. // @see https://www.drupal.org/node/2307647 $alt = isset($image_element['alt']) ? $image_element['alt'] : ''; if ($alt === '' && !empty($image_element['src'])) { $alt = '""'; } $form['attributes']['alt'] = array('#title' => $this->t('Alternative text'), '#placeholder' => $this->t('Short description for the visually impaired'), '#type' => 'textfield', '#required' => TRUE, '#required_error' => $this->t('Alternative text is required.<br />(Only in rare cases should this be left empty. To create empty alternative text, enter <code>""</code> — two double quotes without any content).'), '#default_value' => $alt, '#maxlength' => 2048); // When Drupal core's filter_align is being used, the text editor may // offer the ability to change the alignment. if (isset($image_element['data-align']) && $editor->getFilterFormat()->filters('filter_align')->status) { $form['align'] = array('#title' => $this->t('Align'), '#type' => 'radios', '#options' => array('none' => $this->t('None'), 'left' => $this->t('Left'), 'center' => $this->t('Center'), 'right' => $this->t('Right')), '#default_value' => $image_element['data-align'] === '' ? 'none' : $image_element['data-align'], '#wrapper_attributes' => array('class' => array('container-inline')), '#attributes' => array('class' => array('container-inline')), '#parents' => array('attributes', 'data-align')); } // When Drupal core's filter_caption is being used, the text editor may // offer the ability to in-place edit the image's caption: show a toggle. if (isset($image_element['hasCaption']) && $editor->getFilterFormat()->filters('filter_caption')->status) { $form['caption'] = array('#title' => $this->t('Caption'), '#type' => 'checkbox', '#default_value' => $image_element['hasCaption'] === 'true', '#parents' => array('attributes', 'hasCaption')); } $form['actions'] = array('#type' => 'actions'); $form['actions']['save_modal'] = array('#type' => 'submit', '#value' => $this->t('Save'), '#submit' => array(), '#ajax' => array('callback' => '::submitForm', 'event' => 'click')); return $form; }
<?php $maxsize = round(file_upload_max_size() / 1000000); if ($_POST) { /** * Since I dont' wanna bother with javascript, I'm setting input to disabled * So I need to check if image is actually set. */ $image = isset($_POST['image']) ? filter_var(trim($_POST['image']), FILTER_VALIDATE_URL) : ''; $description = trim($_POST['description']); $setToActive = isset($_POST['set_as_active']); $upload = false; if (isset($_FILES['upload'])) { $f = $_FILES['upload']; if ($f['error'] === 0 && $f['size'] !== 0) { $image = $f['tmp_name']; $upload = true; } } /** * Check only image since it's the only required field */ if (!empty($image)) { /** * Check image extension, getimagetype and mime-type */ if ($upload) { $imageCheck = validateImageExtension($f['name']) && validateImageMimeType($image) && getimagesize($image); } else { $imageCheck = getimagesize($image) !== false; }
/** * An adaptation of file_save_upload() that includes more verbose errors. * * @param string $source * A string specifying the filepath or URI of the uploaded file to save. * * @return stdClass * The saved file object. * * @throws \RestfulBadRequestException * @throws \RestfulServiceUnavailable * * @see file_save_upload() */ protected function fileSaveUpload($source) { static $upload_cache; $account = $this->getAccount(); $options = $this->getPluginKey('options'); $validators = $options['validators']; $destination = $options['scheme'] . "://"; $replace = $options['replace']; // Return cached objects without processing since the file will have // already been processed and the paths in _FILES will be invalid. if (isset($upload_cache[$source])) { return $upload_cache[$source]; } // Make sure there's an upload to process. if (empty($_FILES['files']['name'][$source])) { return NULL; } // Check for file upload errors and return FALSE if a lower level system // error occurred. For a complete list of errors: // See http://php.net/manual/features.file-upload.errors.php. switch ($_FILES['files']['error'][$source]) { case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: $message = format_string('The file %file could not be saved, because it exceeds %maxsize, the maximum allowed size for uploads.', array('%file' => $_FILES['files']['name'][$source], '%maxsize' => format_size(file_upload_max_size()))); throw new \RestfulBadRequestException($message); case UPLOAD_ERR_PARTIAL: case UPLOAD_ERR_NO_FILE: $message = format_string('The file %file could not be saved, because the upload did not complete.', array('%file' => $_FILES['files']['name'][$source])); throw new \RestfulBadRequestException($message); case UPLOAD_ERR_OK: // Final check that this is a valid upload, if it isn't, use the // default error handler. if (is_uploaded_file($_FILES['files']['tmp_name'][$source])) { break; } // Unknown error default: $message = format_string('The file %file could not be saved. An unknown error has occurred.', array('%file' => $_FILES['files']['name'][$source])); throw new \RestfulServiceUnavailable($message); } // Begin building file object. $file = new stdClass(); $file->uid = $account->uid; $file->status = 0; $file->filename = trim(drupal_basename($_FILES['files']['name'][$source]), '.'); $file->uri = $_FILES['files']['tmp_name'][$source]; $file->filemime = file_get_mimetype($file->filename); $file->filesize = $_FILES['files']['size'][$source]; $extensions = ''; if (isset($validators['file_validate_extensions'])) { if (isset($validators['file_validate_extensions'][0])) { // Build the list of non-munged extensions if the caller provided them. $extensions = $validators['file_validate_extensions'][0]; } else { // If 'file_validate_extensions' is set and the list is empty then the // caller wants to allow any extension. In this case we have to remove the // validator or else it will reject all extensions. unset($validators['file_validate_extensions']); } } else { // No validator was provided, so add one using the default list. // Build a default non-munged safe list for file_munge_filename(). $extensions = 'jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp'; $validators['file_validate_extensions'] = array(); $validators['file_validate_extensions'][0] = $extensions; } if (!empty($extensions)) { // Munge the filename to protect against possible malicious extension hiding // within an unknown file type (ie: filename.html.foo). $file->filename = file_munge_filename($file->filename, $extensions); } // Rename potentially executable files, to help prevent exploits (i.e. will // rename filename.php.foo and filename.php to filename.php.foo.txt and // filename.php.txt, respectively). Don't rename if 'allow_insecure_uploads' // evaluates to TRUE. if (!variable_get('allow_insecure_uploads', 0) && preg_match('/\.(php|pl|py|cgi|asp|js)(\.|$)/i', $file->filename) && (substr($file->filename, -4) != '.txt')) { $file->filemime = 'text/plain'; $file->uri .= '.txt'; $file->filename .= '.txt'; // The .txt extension may not be in the allowed list of extensions. We have // to add it here or else the file upload will fail. if (!empty($extensions)) { $validators['file_validate_extensions'][0] .= ' txt'; // Unlike file_save_upload() we don't need to let the user know that // for security reasons, your upload has been renamed, since RESTful // will return the file name in the response. } } // If the destination is not provided, use the temporary directory. if (empty($destination)) { $destination = 'temporary://'; } // Assert that the destination contains a valid stream. $destination_scheme = file_uri_scheme($destination); if (!$destination_scheme || !file_stream_wrapper_valid_scheme($destination_scheme)) { $message = format_string('The file could not be uploaded, because the destination %destination is invalid.', array('%destination' => $destination)); throw new \RestfulServiceUnavailable($message); } $file->source = $source; // A URI may already have a trailing slash or look like "public://". if (substr($destination, -1) != '/') { $destination .= '/'; } $file->destination = file_destination($destination . $file->filename, $replace); // If file_destination() returns FALSE then $replace == FILE_EXISTS_ERROR and // there's an existing file so we need to bail. if ($file->destination === FALSE) { $message = format_string('The file %source could not be uploaded because a file by that name already exists in the destination %directory.', array('%source' => $source, '%directory' => $destination)); throw new \RestfulServiceUnavailable($message); } // Add in our check of the the file name length. $validators['file_validate_name_length'] = array(); // Call the validation functions specified by this function's caller. $errors = file_validate($file, $validators); // Check for errors. if (!empty($errors)) { $message = format_string('The specified file %name could not be uploaded.', array('%name' => $file->filename)); if (count($errors) > 1) { $message .= theme('item_list', array('items' => $errors)); } else { $message .= ' ' . array_pop($errors); } throw new \RestfulServiceUnavailable($message); } // Move uploaded files from PHP's upload_tmp_dir to Drupal's temporary // directory. This overcomes open_basedir restrictions for future file // operations. $file->uri = $file->destination; if (!drupal_move_uploaded_file($_FILES['files']['tmp_name'][$source], $file->uri)) { watchdog('file', 'Upload error. Could not move uploaded file %file to destination %destination.', array('%file' => $file->filename, '%destination' => $file->uri)); $message = 'File upload error. Could not move uploaded file.'; throw new \RestfulServiceUnavailable($message); } // Set the permissions on the new file. drupal_chmod($file->uri); // If we are replacing an existing file re-use its database record. if ($replace == FILE_EXISTS_REPLACE) { $existing_files = file_load_multiple(array(), array('uri' => $file->uri)); if (count($existing_files)) { $existing = reset($existing_files); $file->fid = $existing->fid; } } // If we made it this far it's safe to record this file in the database. if ($file = file_save($file)) { // Add file to the cache. $upload_cache[$source] = $file; return $file; } // Something went wrong, so throw a general exception. throw new \RestfulServiceUnavailable('Unknown error has occurred.'); }
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with NeoFrag. If not, see <http://www.gnu.org/licenses/>. **************************************************************************/ $rules = array('username' => array('label' => '{lang username}', 'value' => $username, 'rules' => 'required', 'check' => function ($value) use($username) { if ($value != $username && NeoFrag::loader()->db->select('1')->from('nf_users')->where('username', $value)->row()) { return i18n('username_unavailable'); } }), 'email' => array('label' => '{lang email}', 'value' => $email, 'type' => 'email', 'rules' => 'required', 'check' => function ($value) use($email) { if ($value != $email && NeoFrag::loader()->db->select('1')->from('nf_users')->where('email', $value)->row()) { return i18n('email_unavailable'); } }), 'first_name' => array('label' => '{lang first_name}', 'value' => $first_name), 'last_name' => array('label' => '{lang last_name}', 'value' => $last_name), 'avatar' => array('label' => '{lang avatar}', 'value' => $avatar, 'upload' => 'members', 'type' => 'file', 'info' => i18n('file_icon', 250, file_upload_max_size() / 1024 / 1024), 'check' => function ($filename, $ext) { if (!in_array($ext, array('gif', 'jpeg', 'jpg', 'png'))) { return i18n('select_image_file'); } list($w, $h) = getimagesize($filename); if ($w != $h) { return i18n('avatar_must_be_square'); } else { if ($w < 250) { return i18n('avatar_size_error', 250); } } }, 'post_upload' => function ($filename) { image_resize($filename, 250, 250); }), 'date_of_birth' => array('label' => '{lang birth_date}', 'value' => $date_of_birth && $date_of_birth != '0000-00-00' ? timetostr(NeoFrag::loader()->lang('date_short'), strtotime($date_of_birth)) : '', 'type' => 'date', 'check' => function ($value) { if ($value && strtotime($value) > strtotime(date('Y-m-d'))) {
/** * Uploads the file to EMDB. * * @param string $form_field_name * A string that is the associative array key of the upload form element in * the form array. * @param string $catalog_id * The catalog id for the catalog we are uploading to. * @param array $metadata * Additional properties that can be passed into EMDB and stored as metadata * on the file. These values are not stored locally in Drupal. * @param array $validators * An optional, associative array of callback functions used to validate the * file. * @param string|bool $destination_dir * A string containing the URI that the file should be copied to. This must * be a stream wrapper URI. If this value is omitted, Drupal's temporary * files scheme will be used ("temporary://"). * @param int $delta * Delta of the file to save or NULL to save all files. Defaults to NULL. * @param int $replace * Replace behavior when the destination file already exists: * - FILE_EXISTS_REPLACE: Replace the existing file. * - FILE_EXISTS_RENAME: Append _{incrementing number} until the filename is * unique. * - FILE_EXISTS_ERROR: Do nothing and return FALSE. * * @return \Drupal\embridge\EmbridgeAssetEntityInterface[] * Function returns array of files or a single file object if $delta * != NULL. Each file object contains the file information if the * upload succeeded or FALSE in the event of an error. Function * returns NULL if no file was uploaded. * * The docs for the "File interface" group, which you can find under * Related topics, or the header at the top of this file, documents the * components of a file entity. In addition to the standard components, * this function adds: * - source: Path to the file before it is moved. * - destination: Path to the file after it is moved (same as 'uri'). */ public static function saveUpload($form_field_name, $catalog_id, $metadata = array(), $validators = array(), $destination_dir = FALSE, $delta = NULL, $replace = FILE_EXISTS_RENAME) { $user = \Drupal::currentUser(); static $upload_cache; $file_upload = \Drupal::request()->files->get("files[{$form_field_name}]", NULL, TRUE); // Make sure there's an upload to process. if (empty($file_upload)) { return NULL; } // Return cached objects without processing since the file will have // already been processed and the paths in $_FILES will be invalid. if (isset($upload_cache[$form_field_name])) { if (isset($delta)) { return $upload_cache[$form_field_name][$delta]; } return $upload_cache[$form_field_name]; } // Prepare uploaded files info. Representation is slightly different // for multiple uploads and we fix that here. /** @var \Symfony\Component\HttpFoundation\File\UploadedFile[] $uploaded_files */ $uploaded_files = $file_upload; if (!is_array($file_upload)) { $uploaded_files = array($file_upload); } $assets = array(); foreach ($uploaded_files as $i => $file_info) { // Check for file upload errors and return FALSE for this file if a lower // level system error occurred. For a complete list of errors: // See http://php.net/manual/features.file-upload.errors.php. switch ($file_info->getError()) { case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: drupal_set_message(t('The file %file could not be saved because it exceeds %maxsize, the maximum allowed size for uploads.', array('%file' => $file_info->getFilename(), '%maxsize' => format_size(file_upload_max_size()))), 'error'); $assets[$i] = FALSE; continue; case UPLOAD_ERR_PARTIAL: case UPLOAD_ERR_NO_FILE: drupal_set_message(t('The file %file could not be saved because the upload did not complete.', array('%file' => $file_info->getFilename())), 'error'); $assets[$i] = FALSE; continue; case UPLOAD_ERR_OK: // Final check that this is a valid upload, if it isn't, use the // default error handler. if (is_uploaded_file($file_info->getRealPath())) { break; } default: // Unknown error. drupal_set_message(t('The file %file could not be saved. An unknown error has occurred.', array('%file' => $file_info->getFilename())), 'error'); $assets[$i] = FALSE; continue; } // Begin building file entity. $values = array('uid' => $user->id(), 'filename' => $file_info->getClientOriginalName(), 'filesize' => $file_info->getSize(), 'catalog_id' => $catalog_id); $values['filemime'] = \Drupal::service('file.mime_type.guesser')->guess($values['filename']); // Create our Embridge Entity. /** @var \Drupal\embridge\EmbridgeAssetEntityInterface $asset */ $asset = EmbridgeAssetEntity::create($values); $extensions = ''; if (isset($validators['embridge_asset_validate_file_extensions'])) { if (isset($validators['embridge_asset_validate_file_extensions'][0])) { // Build the list of non-munged exts if the caller provided them. $extensions = $validators['embridge_asset_validate_file_extensions'][0]; } else { // If 'file_validate_extensions' is set and the list is empty then the // caller wants to allow any extension. In this case we have to remove // the validator or else it will reject all extensions. unset($validators['embridge_asset_validate_file_extensions']); } } else { // No validator was provided, so add one using the default list. // Build a default non-munged safe list for file_munge_filename(). $extensions = 'jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp'; $validators['embridge_asset_validate_file_extensions'] = array(); $validators['embridge_asset_validate_file_extensions'][0] = $extensions; } if (!empty($extensions)) { // Munge the filename to protect against possible malicious extension // hiding within an unknown file type (ie: filename.html.foo). $asset->setFilename(file_munge_filename($asset->getFilename(), $extensions)); } // Rename potentially executable files, to help prevent exploits. if (!\Drupal::config('system.file')->get('allow_insecure_uploads') && preg_match('/\\.(php|pl|py|cgi|asp|js)(\\.|$)/i', $asset->getFilename()) && substr($asset->getFilename(), -4) != '.txt') { $asset->setMimeType('text/plain'); // The destination filename will also later be used to create the URI. $asset->setFilename($asset->getFilename() . '.txt'); // The .txt extension may not be in the allowed list of extensions. // We have to add it here or else the file upload will fail. if (!empty($extensions)) { $validators['embridge_asset_validate_file_extensions'][0] .= ' txt'; drupal_set_message(t('For security reasons, your upload has been renamed to %filename.', array('%filename' => $asset->getFilename()))); } } // If the destination is not provided, use the temporary directory. if (empty($destination_dir)) { $destination_dir = 'temporary://'; } // Assert that the destination contains a valid stream. $destination_scheme = file_uri_scheme($destination_dir); if (!file_stream_wrapper_valid_scheme($destination_scheme)) { drupal_set_message(t('The file could not be uploaded because the destination %destination is invalid.', array('%destination' => $destination_dir)), 'error'); $assets[$i] = FALSE; continue; } // A file URI may already have a trailing slash or look like "public://". if (substr($destination_dir, -1) != '/') { $destination_dir .= '/'; } $asset_destination = file_destination($destination_dir . $asset->getFilename(), $replace); // If file_destination() returns FALSE then $replace === FILE_EXISTS_ERROR // and there's an existing file so we need to bail. if ($asset_destination === FALSE) { drupal_set_message(t('The file %source could not be uploaded because a file by that name already exists in the destination %directory.', array('%source' => $form_field_name, '%directory' => $destination_dir)), 'error'); $assets[$i] = FALSE; continue; } // Add in our check of the file name length. // TODO: Do we need this? // $validators['file_validate_name_length'] = array(); // Call the validation functions specified by this function's caller. $errors = embridge_asset_validate($asset, $validators); // Check for errors. if (!empty($errors)) { $message = array('error' => array('#markup' => t('The specified file %name could not be uploaded.', array('%name' => $asset->getFilename()))), 'item_list' => array('#theme' => 'item_list', '#items' => $errors)); // @todo Add support for render arrays in drupal_set_message()? See // https://www.drupal.org/node/2505497. drupal_set_message(\Drupal::service('renderer')->renderPlain($message), 'error'); $assets[$i] = FALSE; continue; } // Move uploaded files from PHP's upload_tmp_dir to Drupal's temporary // directory. This overcomes open_basedir restrictions for future file // operations. $asset->setSourcePath($asset_destination); if (!drupal_move_uploaded_file($file_info->getRealPath(), $asset->getSourcePath())) { drupal_set_message(t('File upload error. Could not move uploaded file.'), 'error'); \Drupal::logger('file')->notice('Upload error. Could not move uploaded file %file to destination %destination.', array('%file' => $asset->getFilename(), '%destination' => $asset->getSourcePath())); $assets[$i] = FALSE; continue; } // Set the permissions on the new file. drupal_chmod($asset->getSourcePath()); // If we are replacing an existing file re-use its database record. // @todo Do not create a new entity in order to update it. See // https://www.drupal.org/node/2241865. if ($replace == FILE_EXISTS_REPLACE) { $existing_files = entity_load_multiple_by_properties('embridge_asset_entity', array('uri' => $asset->getSourcePath())); if (count($existing_files)) { $existing = reset($existing_files); $asset->setOriginalId($existing->id()); } } /** @var \Drupal\embridge\EnterMediaDbClientInterface $embridge_client */ $embridge_client = \Drupal::getContainer()->get('embridge.client'); try { $embridge_client->upload($asset, $metadata); } catch (\Exception $e) { $message = $e->getMessage(); drupal_set_message(t('Uploading the file "%file" to EnterMedia failed with the message "%message".', array('%file' => $asset->getFilename(), '%message' => $message)), 'error'); $assets[$i] = FALSE; continue; } // If we made it this far it's safe to record this file in the database. $asset->save(); $assets[$i] = $asset; } // Add files to the cache. $upload_cache[$form_field_name] = $assets; return isset($delta) ? $assets[$delta] : $assets; }