Example #1
0
File: Init.php Project: impakho/DHT
function format_size($sizeb)
{
    if (strpos($sizeb, "|") !== false) {
        $size = "";
        $sizeb_split = split("\\|", $sizeb);
        for ($i = 0; $i < count($sizeb_split); $i++) {
            if ($i != 0) {
                $size .= '|';
            }
            $size .= format_size($sizeb_split[$i]);
        }
        return $size;
    } else {
        $sizekb = $sizeb / 1024;
        $sizemb = $sizekb / 1024;
        $sizegb = $sizemb / 1024;
        $sizetb = $sizegb / 1024;
        if ($sizeb > 1) {
            $size = round($sizeb, 2) . " B";
        }
        if ($sizekb > 1) {
            $size = round($sizekb, 2) . " KB";
        }
        if ($sizemb > 1) {
            $size = round($sizemb, 2) . " MB";
        }
        if ($sizegb > 1) {
            $size = round($sizegb, 2) . " GB";
        }
        if ($sizetb > 1) {
            $size = round($sizetb, 2) . " TB";
        }
        return $size;
    }
}
Example #2
0
/**
 * Overrides theme_file_widget().
 */
function bootstrap_file_widget($variables)
{
    $output = '';
    $element = $variables['element'];
    $element['upload_button']['#attributes']['class'][] = 'btn-primary';
    $element['upload_button']['#prefix'] = '<span class="input-group-btn">';
    $element['upload_button']['#suffix'] = '</span>';
    // The "form-managed-file" class is required for proper Ajax functionality.
    if (!empty($element['filename'])) {
        $output .= '<div class="file-widget form-managed-file clearfix">';
        // Add the file size after the file name.
        $element['filename']['#markup'] .= ' <span class="file-size badge">' . format_size($element['#file']->filesize) . '</span>';
    } else {
        $output .= '<div class="file-widget form-managed-file clearfix input-group">';
    }
    // Immediately render hidden elements before the rest of the output.
    // The uploadprogress extension requires that the hidden identifier input
    // element appears before the file input element. They must also be siblings
    // inside the same parent element.
    // @see https://www.drupal.org/node/2155419
    foreach (element_children($element) as $child) {
        if (isset($element[$child]['#type']) && $element[$child]['#type'] === 'hidden') {
            $output .= drupal_render($element[$child]);
        }
    }
    // Render the rest of the element.
    $output .= drupal_render_children($element);
    $output .= '</div>';
    return $output;
}
Example #3
0
function showContent($path)
{
    if ($handle = opendir($path)) {
        while (false !== ($file = readdir($handle))) {
            if ($file == '.' || $file == '..' || valid_extension($file)) {
                // echo "hidden<br>";
            } else {
                $fName = htmlspecialchars($file, ENT_QUOTES);
                $file = $path . "/" . $file;
                $file = htmlspecialchars($file, ENT_QUOTES);
                $fileurl = str_replace(" ", "%20", $file);
                if (is_file($file)) {
                    echo "<li class='music' data-icon='false'><a class='musicfile' href='#' data-src='" . $_ENV['domain'] . $fileurl . "'><h3>" . $fName . "</h3>" . "<p class='size ui-li-aside'> " . format_size(filesize($file)) . "</p></a></li>";
                } elseif (is_dir($file)) {
                    echo "<li class='folder'><a href='" . $_SERVER['SCRIPT_NAME'] . "?path=" . $file . "'>";
                    if (file_exists($file . "/" . $_ENV['coverart'])) {
                        $folderart = $_ENV['domain'] . $fileurl . "/" . $_ENV['coverart'];
                        echo "<img src='{$folderart}'>";
                    } else {
                        echo "<img src='images/jewelcase_empty.png'>";
                    }
                    echo "<h3>{$fName}</h3></a></li>";
                }
            }
        }
        closedir($handle);
    }
}
Example #4
0
function listFileJson($dir, $start = 0, $limit = 500, $orderby = array())
{
    $arr = array();
    $arr['totalCount'] = 0;
    $arr['que_results'] = array();
    $arr['success'] = true;
    try {
        //$dir=ProdsDir::fromURI("rods://rods.tempZone:RODS@rt.sdsc.edu:1247/tempZone/home/rods", false);
        $arr['totalCount'] = 0;
        $childdirs = $dir->getChildDirs($orderby);
        $arr['totalCount'] = $arr['totalCount'] + count($childdirs);
        foreach ($childdirs as $childdir) {
            $childstats = array();
            $childstats['id'] = $childdir->stats->id;
            $childstats['name'] = $childdir->stats->name;
            $childstats['size'] = -1;
            $childstats['fmtsize'] = "";
            $childstats['mtime'] = $childdir->stats->mtime;
            $childstats['ctime'] = $childdir->stats->ctime;
            $childstats['owner'] = $childdir->stats->owner;
            $childstats['type'] = 0;
            $childstats['ruri'] = $childdir->toURI();
            $arr['que_results'][] = $childstats;
        }
        $totalcount = 0;
        //$childfiles=$dir->getChildFiles($orderby,0, -1, $totalcount, true);
        $childfiles = $dir->getChildFiles($orderby);
        $arr['totalCount'] = $arr['totalCount'] + count($childfiles);
        foreach ($childfiles as $childfile) {
            $childstats = array();
            $childstats['id'] = $childfile->stats->id . '_' . $childfile->stats->rescname;
            $childstats['name'] = $childfile->stats->name;
            $childstats['size'] = $childfile->stats->size;
            $childstats['fmtsize'] = format_size($childfile->stats->size);
            $childstats['mtime'] = $childfile->stats->mtime;
            $childstats['ctime'] = $childfile->stats->ctime;
            $childstats['owner'] = $childfile->stats->owner;
            $childstats['rescname'] = $childfile->stats->rescname;
            $childstats['num_replica'] = $childfile->stats->num_replica;
            $childstats['typename'] = $childfile->stats->typename;
            $childstats['type'] = 1;
            $childstats['ruri'] = $childfile->toURI();
            $arr['que_results'][] = $childstats;
        }
        $_SESSION['acct_manager']->updateAcct($dir->account);
        $arr['que_results'] = array_slice($arr['que_results'], $start, $limit);
        $str = json_encode($arr);
        echo "({$str})";
    } catch (RODSException $e) {
        //echo ($e);
        //echo $e->showStackTrace();
        $arr = array();
        $arr['success'] = false;
        $arr['errmsg'] = $e->getCodeAbbr() . ":" . $e->getMessage();
        $arr['errcode'] = $e->getCode();
        $str = json_encode($arr);
        echo "({$str})";
        exit(0);
    }
}
/**
 * Overrides theme_file_widget().
 */
function bootstrap_file_widget($variables)
{
    $element = $variables['element'];
    $output = '';
    $hidden_elements = array();
    foreach (element_children($element) as $child) {
        if (isset($element[$child]['#type']) && $element[$child]['#type'] === 'hidden') {
            $hidden_elements[$child] = $element[$child];
            unset($element[$child]);
        }
    }
    $element['upload_button']['#prefix'] = '<span class="input-group-btn">';
    $element['upload_button']['#suffix'] = '</span>';
    // The "form-managed-file" class is required for proper Ajax functionality.
    if (!empty($element['filename'])) {
        $output .= '<div class="file-widget form-managed-file clearfix">';
        // Add the file size after the file name.
        $element['filename']['#markup'] .= ' <span class="file-size badge">' . format_size($element['#file']->filesize) . '</span>';
    } else {
        $output .= '<div class="file-widget form-managed-file clearfix input-group">';
    }
    $output .= drupal_render_children($element);
    $output .= '</div>';
    $output .= render($hidden_elements);
    return $output;
}
Example #6
0
 /**
  * {@inheritdoc}
  */
 public function viewElements(FieldItemListInterface $items)
 {
     $elements = [];
     foreach ($items as $delta => $item) {
         $elements[$delta] = ['#markup' => format_size($item->value)];
     }
     return $elements;
 }
 /**
  * {@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;
 }
Example #8
0
function GetDirectorySize($path)
{
    $bytestotal = 0;
    $path = realpath($path);
    if ($path !== false) {
        foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS)) as $object) {
            $bytestotal += $object->getSize();
        }
    }
    return format_size($bytestotal);
}
 /**
  * List the backups in the given destination.
  *
  * @param \BackupMigrate\Core\Destination\ListableDestinationInterface $destination
  * @return mixed
  */
 public function listDestinationBackups(ListableDestinationInterface $destination, $backup_migrate_destination_id)
 {
     $backups = $destination->listFiles();
     $rows = [];
     $header = array(array('data' => $this->t('Name'), 'class' => array(RESPONSIVE_PRIORITY_MEDIUM)), array('data' => $this->t('Date'), 'class' => array(RESPONSIVE_PRIORITY_MEDIUM)), array('data' => $this->t('Size'), 'class' => array(RESPONSIVE_PRIORITY_MEDIUM)), array('data' => $this->t('Operations'), 'class' => array(RESPONSIVE_PRIORITY_LOW)));
     foreach ($backups as $backup_id => $backup) {
         $rows[] = ['data' => [$backup->getFullName(), \Drupal::service('date.formatter')->format($backup->getMeta('datestamp')), format_size($backup->getMeta('filesize')), ['data' => ['#type' => 'operations', '#links' => ['restore' => ['title' => $this->t('Restore'), 'url' => Url::fromRoute('entity.backup_migrate_destination.backup_restore', ['backup_migrate_destination' => $backup_migrate_destination_id, 'backup_id' => $backup_id])], 'download' => ['title' => $this->t('Download'), 'url' => Url::fromRoute('entity.backup_migrate_destination.backup_download', ['backup_migrate_destination' => $backup_migrate_destination_id, 'backup_id' => $backup_id])], 'delete' => ['title' => $this->t('Delete'), 'url' => Url::fromRoute('entity.backup_migrate_destination.backup_delete', ['backup_migrate_destination' => $backup_migrate_destination_id, 'backup_id' => $backup_id])]]]]]];
     }
     $build['backups_table'] = array('#type' => 'table', '#header' => $header, '#rows' => $rows, '#empty' => $this->t('There are no backups in this destination.'));
     return $build;
 }
Example #10
0
 /**
  * {@inheritdoc}
  */
 public function instanceSettingsForm(array $form, FormStateInterface $form_state)
 {
     $element = array();
     $settings = $this->getSettings();
     $element['file_directory'] = array('#type' => 'textfield', '#title' => t('File directory'), '#default_value' => $settings['file_directory'], '#description' => t('Optional subdirectory within the upload destination where files will be stored. Do not include preceding or trailing slashes.'), '#element_validate' => array(array(get_class($this), 'validateDirectory')), '#weight' => 3);
     // Make the extension list a little more human-friendly by comma-separation.
     $extensions = str_replace(' ', ', ', $settings['file_extensions']);
     $element['file_extensions'] = array('#type' => 'textfield', '#title' => t('Allowed file extensions'), '#default_value' => $extensions, '#description' => t('Separate extensions with a space or comma and do not include the leading dot.'), '#element_validate' => array(array(get_class($this), 'validateExtensions')), '#weight' => 1, '#maxlength' => 256, '#required' => TRUE);
     $element['max_filesize'] = array('#type' => 'textfield', '#title' => t('Maximum upload size'), '#default_value' => $settings['max_filesize'], '#description' => t('Enter a value like "512" (bytes), "80 KB" (kilobytes) or "50 MB" (megabytes) in order to restrict the allowed file size. If left empty the file sizes will be limited only by PHP\'s maximum post and file upload sizes (current limit <strong>%limit</strong>).', array('%limit' => format_size(file_upload_max_size()))), '#size' => 10, '#element_validate' => array(array(get_class($this), 'validateMaxFilesize')), '#weight' => 5);
     $element['description_field'] = array('#type' => 'checkbox', '#title' => t('Enable <em>Description</em> field'), '#default_value' => isset($settings['description_field']) ? $settings['description_field'] : '', '#description' => t('The description field allows users to enter a description about the uploaded file.'), '#parents' => array('instance', 'settings', 'description_field'), '#weight' => 11);
     return $element;
 }
 /**
  * {@inheritdoc}
  */
 public function preprocessElement(Variables $variables, $hook, array $info)
 {
     $variables->addClass(['image-widget', 'js-form-managed-file', 'form-managed-file', 'clearfix']);
     /** @var \Drupal\file\Entity\File $file */
     foreach ($variables->element->getProperty('files') as $file) {
         $variables->element->{'file_' . $file->id()}->filename->setProperty('suffix', ' <span class="file-size badge">' . format_size($file->getSize()) . '</span>');
     }
     $data =& $variables->offsetGet('data', []);
     foreach ($variables->element->children() as $key => $child) {
         $data[$key] = $child->getArray();
     }
 }
Example #12
0
function fileInfo($sFile)
{
    $aRtr = array();
    $aRtr["type"] = filetype($sFile);
    $nx_tmp = split("\\/", $sFile);
    $sFileName = array_pop($nx_tmp);
    if ($aRtr["type"] == "file") {
        $aRtr["time"] = filemtime($sFile);
        $aRtr["date"] = date(FILETIME, $aRtr["time"]);
        $aRtr["size"] = filesize($sFile);
        $nx_tmp2 = split("\\.", $sFile);
        $aRtr["mime"] = array_pop($nx_tmp2);
        //mime_content_type($sFile);
        //
        $aRtr["width"] = 0;
        $aRtr["height"] = 0;
        $aImgNfo = $aRtr["mime"] == "jpeg" || $aRtr["mime"] == "jpg" || $aRtr["mime"] == "gif" ? getimagesize($sFile) : "";
        if (is_array($aImgNfo)) {
            list($width, $height, $type, $attr) = $aImgNfo;
            $aRtr["width"] = $width;
            $aRtr["height"] = $height;
        }
        $sNfo = '"file":"' . $sFileName . '",';
        $sNfo .= '"mime":"' . $aRtr["mime"] . '",';
        $sNfo .= '"rsize":' . $aRtr["size"] . ',';
        $sNfo .= '"size":"' . format_size($aRtr["size"]) . '",';
        $sNfo .= '"time":' . $aRtr["time"] . ',';
        $sNfo .= '"date":"' . $aRtr["date"] . '",';
        $sNfo .= '"width":' . $aRtr["width"] . ',';
        $sNfo .= '"height":' . $aRtr["height"];
        $aRtr["stringdata"] = $sNfo;
    } else {
        if ($aRtr["type"] == "dir" && $sFileName != "." && $sFileName != ".." && !preg_match("/^\\./", $sFileName)) {
            $aRtr["mime"] = "folder";
            $aRtr["time"] = filemtime($sFile);
            $aRtr["date"] = date(FILETIME, $aRtr["time"]);
            $aRtr["size"] = filesize($sFile);
            $sNfo = '"file":"' . $sFileName . '",';
            $sNfo .= '"mime":"' . 'folder",';
            $sNfo .= '"rsize":' . '0,';
            $sNfo .= '"size":"' . '-",';
            $sNfo .= '"time":' . $aRtr["time"] . ',';
            $sNfo .= '"date":"' . $aRtr["date"] . '"';
            $aRtr["stringdata"] = $sNfo;
        }
    }
    $aDeny = explode(",", SFB_DENY);
    if (!isset($aRtr["mime"]) || in_array($aRtr["mime"], $aDeny)) {
        return null;
    }
    return $aRtr;
}
 /**
  * {@inheritdoc}
  */
 public function settingsForm(array $form, FormStateInterface $form_state)
 {
     $element = parent::settingsForm($form, $form_state);
     $settings = $this->getSettings();
     $element['file_directory'] = array('#type' => 'textfield', '#title' => t('File directory'), '#default_value' => $settings['file_directory'], '#description' => t('Optional subdirectory within the upload destination where files will be stored. Do not include preceding or trailing slashes.'), '#element_validate' => array(array(get_class($this), 'validateDirectory')), '#weight' => 3);
     // Make the extension list a little more human-friendly by comma-separation.
     $extensions = str_replace(' ', ', ', $settings['file_extensions']);
     $element['file_extensions'] = array('#type' => 'textfield', '#title' => t('Allowed file extensions'), '#default_value' => $extensions, '#description' => t('Separate extensions with a space or comma and do not include the leading dot.'), '#element_validate' => array(array(get_class($this), 'validateExtensions')), '#weight' => 1, '#maxlength' => 256, '#required' => TRUE);
     $element['max_filesize'] = array('#type' => 'textfield', '#title' => t('Maximum upload size'), '#default_value' => $settings['max_filesize'], '#description' => t('Enter a value like "512" (bytes), "80 KB" (kilobytes) or "50 MB" (megabytes) in order to restrict the allowed file size. If left empty the file sizes will be limited only by PHP\'s maximum post and file upload sizes (current limit <strong>%limit</strong>).', array('%limit' => format_size(file_upload_max_size()))), '#size' => 10, '#element_validate' => array(array(get_class($this), 'validateMaxFilesize')), '#weight' => 5);
     $scheme_options = \Drupal::service('stream_wrapper_manager')->getNames(StreamWrapperInterface::WRITE_VISIBLE);
     $element['uri_scheme'] = array('#type' => 'radios', '#title' => t('Upload destination'), '#options' => $scheme_options, '#default_value' => $this->getSetting('uri_scheme'), '#description' => t('Select where the final files should be stored. Private file storage has significantly more overhead than public files, but allows restricted access to files within this field.'), '#weight' => 6);
     return $element;
 }
Example #14
0
 /**
  * 创建运行时文件
  *
  * @author          mrmsl <*****@*****.**>
  * @date            2013-01-22 15:45:33
  * @lastmodify      2013-02-18 17:03:00 by mrmsl
  *
  * @return void 无返回值
  */
 private function _buildRuntimeFile()
 {
     $filesize = 0;
     //加载文件大小
     $compile = "<?php\n!defined('YAB_PATH') && exit('Access Denied');";
     //编译内容
     //加载核心文件
     foreach ($this->_require_files as $file) {
         require $file;
         if (defined('APP_DEBUG') && !APP_DEBUG) {
             $filesize += filesize($file);
             $compile .= compile_file($file);
         }
     }
     $require_files = array(CORE_PATH . 'Bootstrap.' . APP_EXT, CORE_PATH . 'Template.' . APP_EXT, CORE_PATH . 'Model.' . APP_EXT, CORE_PATH . 'Logger.' . APP_EXT, CORE_PATH . 'Filter.' . APP_EXT, CORE_PATH . 'Db.' . APP_EXT, CORE_PATH . 'drivers/db/Db' . ucfirst(DB_TYPE) . '.' . APP_EXT);
     if (is_file($filename = LIB_PATH . 'BaseController.' . APP_EXT)) {
         //底层控制器类
         $require_files[] = $filename;
     }
     if (is_file($filename = APP_PATH . 'controllers/Common.' . APP_EXT)) {
         //项目底层通用控制器类
         $require_files[] = $filename;
     }
     if (is_file($filename = LIB_PATH . 'BaseModel.' . APP_EXT)) {
         //底层模型类
         $require_files[] = $filename;
     }
     if (is_file($filename = APP_PATH . 'models/Common.' . APP_EXT)) {
         //项目底层通用模型类
         $require_files[] = $filename;
     }
     //加载核心文件,用空间换时间
     if (APP_DEBUG) {
         //调试
         foreach ($require_files as $file) {
             require $file;
         }
     } else {
         foreach ($require_files as $file) {
             require $file;
             $filesize += filesize($file);
             $compile .= compile_file($file);
         }
         file_put_contents(RUNTIME_FILE, $compile);
         $size = filesize(RUNTIME_FILE);
         //编译后大小
         file_put_contents(LOG_PATH . 'compile_runtime_file.log', new_date() . '(' . format_size($filesize) . ' => ' . format_size($size) . ')' . EOL_LF, FILE_APPEND);
     }
 }
 /**
  * Creates a file, then tests the tokens generated from it.
  */
 function testFileTokenReplacement()
 {
     $node_storage = $this->container->get('entity.manager')->getStorage('node');
     $token_service = \Drupal::token();
     $language_interface = \Drupal::languageManager()->getCurrentLanguage();
     // Create file field.
     $type_name = 'article';
     $field_name = 'field_' . strtolower($this->randomMachineName());
     $this->createFileField($field_name, 'node', $type_name);
     $test_file = $this->getTestFile('text');
     // Coping a file to test uploads with non-latin filenames.
     $filename = drupal_dirname($test_file->getFileUri()) . '/текстовый файл.txt';
     $test_file = file_copy($test_file, $filename);
     // Create a new node with the uploaded file.
     $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
     // Load the node and the file.
     $node_storage->resetCache(array($nid));
     $node = $node_storage->load($nid);
     $file = file_load($node->{$field_name}->target_id);
     // Generate and test sanitized tokens.
     $tests = array();
     $tests['[file:fid]'] = $file->id();
     $tests['[file:name]'] = String::checkPlain($file->getFilename());
     $tests['[file:path]'] = String::checkPlain($file->getFileUri());
     $tests['[file:mime]'] = String::checkPlain($file->getMimeType());
     $tests['[file:size]'] = format_size($file->getSize());
     $tests['[file:url]'] = String::checkPlain(file_create_url($file->getFileUri()));
     $tests['[file:created]'] = format_date($file->getCreatedTime(), 'medium', '', NULL, $language_interface->getId());
     $tests['[file:created:short]'] = format_date($file->getCreatedTime(), 'short', '', NULL, $language_interface->getId());
     $tests['[file:changed]'] = format_date($file->getChangedTime(), 'medium', '', NULL, $language_interface->getId());
     $tests['[file:changed:short]'] = format_date($file->getChangedTime(), 'short', '', NULL, $language_interface->getId());
     $tests['[file:owner]'] = String::checkPlain(user_format_name($this->adminUser));
     $tests['[file:owner:uid]'] = $file->getOwnerId();
     // Test to make sure that we generated something for each token.
     $this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
     foreach ($tests as $input => $expected) {
         $output = $token_service->replace($input, array('file' => $file), array('langcode' => $language_interface->getId()));
         $this->assertEqual($output, $expected, format_string('Sanitized file token %token replaced.', array('%token' => $input)));
     }
     // Generate and test unsanitized tokens.
     $tests['[file:name]'] = $file->getFilename();
     $tests['[file:path]'] = $file->getFileUri();
     $tests['[file:mime]'] = $file->getMimeType();
     $tests['[file:size]'] = format_size($file->getSize());
     foreach ($tests as $input => $expected) {
         $output = $token_service->replace($input, array('file' => $file), array('langcode' => $language_interface->getId(), 'sanitize' => FALSE));
         $this->assertEqual($output, $expected, format_string('Unsanitized file token %token replaced.', array('%token' => $input)));
     }
 }
Example #16
0
 /**
  * {@inheritdoc}
  */
 public function render(ResultRow $values)
 {
     $value = $this->getValue($values);
     if ($value) {
         switch ($this->options['file_size_display']) {
             case 'bytes':
                 return $value;
             case 'formatted':
             default:
                 return format_size($value);
         }
     } else {
         return '';
     }
 }
Example #17
0
 /**
  * {@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);
 }
Example #18
0
 /**
  * {@inheritdoc}
  */
 public function viewElements(FieldItemListInterface $items)
 {
     $elements = array();
     if ($files = $this->getEntitiesToView($items)) {
         $header = array(t('Attachment'), t('Size'));
         $rows = array();
         foreach ($files as $delta => $file) {
             $rows[] = array(array('data' => array('#theme' => 'file_link', '#file' => $file, '#cache' => array('tags' => $file->getCacheTags()))), array('data' => format_size($file->getSize())));
         }
         $elements[0] = array();
         if (!empty($rows)) {
             $elements[0] = array('#theme' => 'table__file_formatter_table', '#header' => $header, '#rows' => $rows);
         }
     }
     return $elements;
 }
Example #19
0
/**
 * Overrides theme_file_widget().
 */
function bootstrap_preprocess_file_widget(&$variables)
{
    $element = $variables['element'];
    if (!empty($element['fids']['#value'])) {
        // Add the file size after the file name.
        $file = reset($element['#files']);
        $element['file_' . $file->id()]['filename']['#suffix'] = ' <span class="file-size badge">' . format_size($file->getSize()) . '</span> ';
    }
    // The "form-managed-file" class is required for proper Ajax functionality.
    $variables['attributes'] = array('class' => array('file-widget', 'form-managed-file', 'clearfix'));
    $element['upload']['#prefix'] = '<div class="input-group">';
    $element['upload_button']['#prefix'] = '<span class="input-group-btn">';
    $element['upload_button']['#suffix'] = '</span></div>';
    $element['upload_button']['#attributes']['class'] = array('btn', 'btn-primary');
    $variables['element'] = $element;
}
Example #20
0
 function display()
 {
     current_page('files');
     page_title(lang('fl_mylist'), URL . '/files/');
     if (!user('logged')) {
         return login_req();
     }
     $data = ldb_select('upload', '*', '`uid`=' . user('id') . ' ORDER BY `tms_upload` DESC');
     $u_list = '';
     for ($x = 0; $x < count($data); $x++) {
         $f_title = '';
         if ($data[$x]['comment']) {
             $f_title = htmlspecialchars($data[$x]['comment']);
         } else {
             # Get files
             $f_list = ldb_select('file', array('file_name'), '`upid`=' . $data[$x]['id'] . ' ORDER BY `id`');
             $f_list_len = 0;
             $f_list_d = array();
             for ($a = 0; $a < count($f_list); $a++) {
                 $f_list_d[] = '<i>' . htmlspecialchars($f_list[$a]['file_name']) . '</i>';
                 $f_list_len += mb_strlen($f_list[$a]['file_name'], 'UTF-8');
                 if ($f_list_len > 50) {
                     break;
                 }
             }
             if (count($f_list_d) < count($f_list)) {
                 $f_list_d[] = '<b>...</b>';
             }
             $f_title = implode(', ', $f_list_d);
         }
         $f_title = trim($f_title);
         if (!$f_title) {
             $f_title = sprintf(lang('fld_title_n'), $data[$x]['id']);
         }
         $u_list .= '<tr>';
         $u_list .= '<td align="center">' . $data[$x]['id'] . '</td>';
         $u_list .= '<td align="left" class="mf-table-flink"><a href="' . URL . '/f/' . $data[$x]['code'] . '/">' . $f_title . '</a></td>';
         $u_list .= '<td align="center">' . date('d.m.Y H:i', $data[$x]['tms_upload']) . '</td>';
         $u_list .= '<td align="center">' . time_delete($data[$x]['tms_upload'], $data[$x]['tms_delete']) . '</td>';
         $u_list .= '<td align="center">' . format_size($data[$x]['file_size']) . '</td>';
         $u_list .= '</tr>';
     }
     $tpl = new ltpl('myfiles');
     $tpl->v('u_list', $u_list);
     return $tpl->get();
 }
Example #21
0
 /**
  * {@inheritdoc}
  */
 public function preprocessVariables(Variables $variables, $hook, array $info)
 {
     if (!empty($variables['description'])) {
         $variables['description'] = FieldFilteredMarkup::create($variables['description']);
     }
     $descriptions = [];
     $cardinality = $variables['cardinality'];
     if (isset($cardinality)) {
         if ($cardinality == -1) {
             $descriptions[] = t('Unlimited number of files can be uploaded to this field.');
         } else {
             $descriptions[] = \Drupal::translation()->formatPlural($cardinality, 'One file only.', 'Maximum @count files.');
         }
     }
     $upload_validators = $variables['upload_validators'];
     if (isset($upload_validators['file_validate_size'])) {
         $descriptions[] = t('@size limit.', ['@size' => format_size($upload_validators['file_validate_size'][0])]);
     }
     if (isset($upload_validators['file_validate_extensions'])) {
         $extensions = new FormattableMarkup('<code>@extensions</code>', ['@extensions' => implode(', ', explode(' ', $upload_validators['file_validate_extensions'][0]))]);
         $descriptions[] = t('Allowed types: @extensions.', ['@extensions' => $extensions]);
     }
     if (isset($upload_validators['file_validate_image_resolution'])) {
         $max = $upload_validators['file_validate_image_resolution'][0];
         $min = $upload_validators['file_validate_image_resolution'][1];
         if ($min && $max && $min == $max) {
             $descriptions[] = t('Images must be exactly <strong>@size</strong> pixels.', ['@size' => $max]);
         } elseif ($min && $max) {
             $descriptions[] = t('Images must be larger than <strong>@min</strong> pixels. Images larger than <strong>@max</strong> pixels will be resized.', ['@min' => $min, '@max' => $max]);
         } elseif ($min) {
             $descriptions[] = t('Images must be larger than <strong>@min</strong> pixels.', ['@min' => $min]);
         } elseif ($max) {
             $descriptions[] = t('Images larger than <strong>@max</strong> pixels will be resized.', ['@max' => $max]);
         }
     }
     $variables['descriptions'] = $descriptions;
     if ($descriptions) {
         $build = array();
         $id = Html::getUniqueId('upload-instructions');
         $build['toggle'] = ['#type' => 'link', '#title' => t('Upload requirements'), '#url' => Url::fromUserInput("#{$id}"), '#icon' => Bootstrap::glyphicon('question-sign'), '#attributes' => ['class' => ['icon-before'], 'data-toggle' => 'popover', 'data-html' => 'true', 'data-placement' => 'bottom', 'data-title' => t('Upload requirements')]];
         $build['requirements'] = ['#type' => 'container', '#theme_wrappers' => ['container__file_upload_help'], '#attributes' => ['id' => $id, 'class' => ['hidden', 'help-block'], 'aria-hidden' => 'true']];
         $build['requirements']['descriptions'] = ['#theme' => 'item_list__file_upload_help', '#items' => $descriptions];
         $variables['popover'] = $build;
     }
 }
 /**
  * {@inheritdoc}
  */
 public function preprocessVariables(Variables $variables, $hook, array $info)
 {
     $options = [];
     $file = $variables['file'] instanceof File ? $variables['file'] : File::load($variables['file']->fid);
     $url = file_create_url($file->getFileUri());
     $file_size = $file->getSize();
     $mime_type = $file->getMimeType();
     // Set options as per anchor format described at
     // http://microformats.org/wiki/file-format-examples
     $options['attributes']['type'] = "{$mime_type}; length={$file_size}";
     // Use the description as the link text if available.
     if (empty($variables['description'])) {
         $link_text = $file->getFilename();
     } else {
         $link_text = $variables['description'];
         $options['attributes']['title'] = $file->getFilename();
     }
     // Retrieve the generic mime type from core (mislabeled as "icon_class").
     $generic_mime_type = file_icon_class($mime_type);
     // Map the generic mime types to an icon and state.
     $mime_map = ['application-x-executable' => ['label' => t('binary file'), 'icon' => 'console'], 'audio' => ['label' => t('audio file'), 'icon' => 'headphones'], 'image' => ['label' => t('image'), 'icon' => 'picture'], 'package-x-generic' => ['label' => t('archive'), 'icon' => 'compressed'], 'text' => ['label' => t('document'), 'icon' => 'file'], 'video' => ['label' => t('video'), 'icon' => 'film']];
     // Retrieve the mime map array.
     $mime = isset($mime_map[$generic_mime_type]) ? $mime_map[$generic_mime_type] : ['label' => t('file'), 'icon' => 'file', 'state' => 'primary'];
     // Classes to add to the file field for icons.
     //    $variables->addClass([
     //      'file',
     //      // Add a specific class for each and every mime type.
     //      'file--mime-' . strtr($mime_type, ['/' => '-', '.' => '-']),
     //      // Add a more general class for groups of well known mime types.
     //      'file--' . $generic_mime_type,
     //    ]);
     // Set the icon for the mime type.
     $icon = Materialize::material_icons_font($mime['icon']);
     $variables->icon = Element::create($icon)->addClass('text-primary')->getArray();
     $options['attributes']['title'] = t('Open @mime in new window', ['@mime' => $mime['label']]);
     if ($this->theme->getSetting('tooltip_enabled')) {
         $options['attributes']['data-toggle'] = 'tooltip';
         $options['attributes']['data-placement'] = 'bottom';
     }
     $variables['link'] = Link::fromTextAndUrl($link_text, Url::fromUri($url, $options));
     // Add the file size as a variable.
     $variables->file_size = format_size($file_size);
     // Preprocess attributes.
     $this->preprocessAttributes($variables, $hook, $info);
 }
 /**
  * {@inheritdoc}
  */
 public function viewElements(FieldItemListInterface $items)
 {
     $elements = array();
     if (!$items->isEmpty()) {
         $header = array(t('Attachment'), t('Size'));
         $rows = array();
         foreach ($items as $delta => $item) {
             if ($item->isDisplayed() && $item->entity) {
                 $rows[] = array(array('data' => array('#theme' => 'file_link', '#file' => $item->entity)), array('data' => format_size($item->entity->getSize())));
             }
         }
         $elements[0] = array();
         if (!empty($rows)) {
             $elements[0] = array('#theme' => 'table__file_formatter_table', '#header' => $header, '#rows' => $rows);
         }
     }
     return $elements;
 }
Example #24
0
    protected function render_inner_html()
    {
        $path = $this['value'];
        $rc = new Text(['value' => $this['value'], 'readonly' => true, 'name' => $this['name'], 'class' => 'reminder']) . ' <div class="alert alert-error undismissable"></div>' . ' <label class="btn trigger"><i class="icon-file"></i> ' . $this->t($this[self::BUTTON_LABEL], [], ['scope' => 'button']) . '<input type="file" /></label>';
        #
        # uploading element
        #
        $rc .= '<div class="uploading">';
        $rc .= '<span class="progress like-input"><span class="position"><span class="text">&nbsp;</span></span></span> ';
        $rc .= '<button type="button" class="btn btn-danger cancel">' . $this->t('cancel', [], ['scope' => 'button']) . '</button>';
        $rc .= '</div>';
        #
        # the FILE_WITH_LIMIT tag can be used to add a little text after the element
        # reminding the maximum file size allowed for the upload
        #
        $limit = $this[self::FILE_WITH_LIMIT];
        if ($limit) {
            if ($limit === true) {
                $limit = ini_get('upload_max_filesize') * 1024;
            }
            $limit = format_size($limit * 1024);
            $rc .= PHP_EOL . '<div class="file-size-limit small" style="margin-top: .5em">';
            $rc .= $this->t('The maximum file size must be less than :size.', [':size' => $limit]);
            $rc .= '</div>';
        }
        #
        # infos
        #
        $infos = null;
        if ($path) {
            if (!is_file(DOCUMENT_ROOT . $path)) {
                $this->app->logger->debug("path: {$path}");
                $infos = '<span class="warn">' . $this->t('The file %file is missing !', ['%file' => basename($path)]) . '</span>';
            } else {
                $infos = $this->infos();
            }
            if ($infos) {
                $this->add_class('has-info');
            }
        }
        return $rc . <<<EOT
<div class="infos">{$infos}</div>
EOT;
    }
 /**
  * Returns the progress status for a file upload process.
  *
  * @param string $key
  *   The unique key for this upload process.
  *
  * @return \Symfony\Component\HttpFoundation\JsonResponse
  *   A JsonResponse object.
  */
 public function progress($key)
 {
     $progress = array('message' => t('Starting upload...'), 'percentage' => -1);
     $implementation = file_progress_implementation();
     if ($implementation == 'uploadprogress') {
         $status = uploadprogress_get_info($key);
         if (isset($status['bytes_uploaded']) && !empty($status['bytes_total'])) {
             $progress['message'] = t('Uploading... (@current of @total)', array('@current' => format_size($status['bytes_uploaded']), '@total' => format_size($status['bytes_total'])));
             $progress['percentage'] = round(100 * $status['bytes_uploaded'] / $status['bytes_total']);
         }
     } elseif ($implementation == 'apc') {
         $status = apc_fetch('upload_' . $key);
         if (isset($status['current']) && !empty($status['total'])) {
             $progress['message'] = t('Uploading... (@current of @total)', array('@current' => format_size($status['current']), '@total' => format_size($status['total'])));
             $progress['percentage'] = round(100 * $status['current'] / $status['total']);
         }
     }
     return new JsonResponse($progress);
 }
/**
 * Prepares variables for file upload help text templates.
 *
 * Default template: file-upload-help.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - description: The normal description for this field, specified by the
 *     user.
 *   - upload_validators: An array of upload validators as used in
 *     $element['#upload_validators'].
 */
function bootstrap_preprocess_file_upload_help(&$variables)
{
    $config = \Drupal::config('bootstrap.settings');
    $upload_validators = $variables['upload_validators'];
    $cardinality = $variables['cardinality'];
    $descriptions = array();
    if (isset($cardinality)) {
        if ($cardinality == -1) {
            $descriptions[] = t('Unlimited number of files can be uploaded to this field.');
        } else {
            $descriptions[] = \Drupal::translation()->formatPlural($cardinality, 'One file only.', 'Maximum @count files.');
        }
    }
    if (isset($upload_validators['file_validate_size'])) {
        $descriptions[] = t('@size limit.', array('@size' => format_size($upload_validators['file_validate_size'][0])));
    }
    if (isset($upload_validators['file_validate_extensions'])) {
        $descriptions[] = t('Allowed types: @extensions.', array('@extensions' => $upload_validators['file_validate_extensions'][0]));
    }
    if (isset($upload_validators['file_validate_image_resolution'])) {
        $max = $upload_validators['file_validate_image_resolution'][0];
        $min = $upload_validators['file_validate_image_resolution'][1];
        if ($min && $max && $min == $max) {
            $descriptions[] = t('Images must be exactly <strong>@size</strong> pixels.', array('@size' => $max));
        } elseif ($min && $max) {
            $descriptions[] = t('Images must be larger than <strong>@min</strong> pixels. Images larger than <strong>@max</strong> pixels will be resized.', array('@min' => $min, '@max' => $max));
        } elseif ($min) {
            $descriptions[] = t('Images must be larger than <strong>@min</strong> pixels.', array('@min' => $min));
        } elseif ($max) {
            $descriptions[] = t('Images larger than <strong>@max</strong> pixels will be resized.', array('@max' => $max));
        }
    }
    // If popovers are enabled.
    if ($config->get('bootstrap_popover_enabled')) {
        $id = html::getUniqueId('upload-instructions');
        $icon = _bootstrap_icon('question-sign');
        $link_title = SafeMarkup::format($icon . ' ' . '@text', array('@text' => 'More information'));
        $variables['popover_link'] = _bootstrap_popover_link($link_title, $id, t('File requirements'), 'bottom');
        $description_content = array('#theme' => 'item_list', '#items' => $descriptions);
        $variables['popover_content'] = _bootstrap_popover_content($id, array($description_content));
    }
    $variables['descriptions'] = $descriptions;
}
Example #27
0
function content()
{
    if (!user_logged_in()) {
        return must_log_in();
    }
    $files = fetch_wol('*', 'files', sprintf("user_id=%d", user_logged_in()));
    if (count($files) == 0) {
        ?>
    <p>You have not <a href="upload">uploaded</a> any files.</p>
    <?php 
        return;
    }
    ?>
  <table class="data">
    <?php 
    foreach ($files as $f) {
        ?>
      <tr><td class="file-id"><a href="<?php 
        esc($f->id . '.' . $f->extension);
        ?>
"><?php 
        esc(sprintf("%06d", $f->id));
        ?>
</a></td>
        <td><?php 
        esc(date_format('Y-m-d H:i:s', $f->date_uploaded));
        ?>
</td>
        <td><?php 
        esc(format_size($f->length));
        ?>
</td>
      </tr>
    <?php 
    }
    ?>
  </table>

<?php 
}
Example #28
0
/**
插件函数
**/
function Get_Filelist($current_path)
{
    $current_path = get_input_filename($current_path);
    $file_list = array();
    //遍历目录取得文件信息
    if ($handle = opendir($current_path)) {
        while (false !== ($filename = readdir($handle))) {
            if ($filename[0] == '.') {
                continue;
            }
            $file = $current_path . $filename;
            if (is_dir($file)) {
                $file_list['dir'][] = array('has_file' => count(scandir($file)) > 2, 'filesize' => 0, 'filename' => get_output_filename($filename), 'fileperms' => substr(sprintf('%o', fileperms($current_path . $filename)), -4), 'datetime' => date('Y-m-d H:i:s', filemtime($file)));
            } else {
                $file_ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
                $file_list['file'][] = array('filesize' => format_size(filesize($file)), 'filetype' => strtolower($file_ext), 'filename' => get_output_filename($filename), 'fileperms' => substr(sprintf('%o', fileperms($current_path . $filename)), -4), 'datetime' => date('Y-m-d H:i:s', filemtime($file)));
            }
        }
        closedir($handle);
    }
    return $file_list;
}
/**
 * Returns HTML for help text based on file upload validators.
 *
 * @param array $variables
 *   An associative array containing:
 *   - description: The normal description for this field, specified by the
 *     user.
 *   - upload_validators: An array of upload validators as used in
 *     $element['#upload_validators'].
 *
 * @return string
 *   The constructed HTML.
 *
 * @see theme_file_upload_help()
 *
 * @ingroup theme_functions
 */
function bootstrap_file_upload_help($variables)
{
    // If popover's are disabled, just theme this normally.
    if (!bootstrap_setting('popover_enabled')) {
        return theme_file_upload_help($variables);
    }
    $build = array();
    if (!empty($variables['description'])) {
        $build['description'] = array('#markup' => $variables['description'] . '<br>');
    }
    $descriptions = array();
    $upload_validators = $variables['upload_validators'];
    if (isset($upload_validators['file_validate_size'])) {
        $descriptions[] = t('Files must be less than !size.', array('!size' => '<strong>' . format_size($upload_validators['file_validate_size'][0]) . '</strong>'));
    }
    if (isset($upload_validators['file_validate_extensions'])) {
        $descriptions[] = t('Allowed file types: !extensions.', array('!extensions' => '<strong>' . check_plain($upload_validators['file_validate_extensions'][0]) . '</strong>'));
    }
    if (isset($upload_validators['file_validate_image_resolution'])) {
        $max = $upload_validators['file_validate_image_resolution'][0];
        $min = $upload_validators['file_validate_image_resolution'][1];
        if ($min && $max && $min == $max) {
            $descriptions[] = t('Images must be exactly !size pixels.', array('!size' => '<strong>' . $max . '</strong>'));
        } elseif ($min && $max) {
            $descriptions[] = t('Images must be between !min and !max pixels.', array('!min' => '<strong>' . $min . '</strong>', '!max' => '<strong>' . $max . '</strong>'));
        } elseif ($min) {
            $descriptions[] = t('Images must be larger than !min pixels.', array('!min' => '<strong>' . $min . '</strong>'));
        } elseif ($max) {
            $descriptions[] = t('Images must be smaller than !max pixels.', array('!max' => '<strong>' . $max . '</strong>'));
        }
    }
    if ($descriptions) {
        $id = drupal_html_id('upload-instructions');
        $build['instructions'] = array('#theme' => 'link__file_upload_requirements', '#text' => _bootstrap_icon('question-sign') . ' ' . t('More information'), '#path' => '#', '#options' => array('attributes' => array('data-toggle' => 'popover', 'data-target' => "#{$id}", 'data-html' => TRUE, 'data-placement' => 'bottom', 'data-title' => t('File requirements')), 'html' => TRUE, 'external' => TRUE));
        $build['requirements'] = array('#theme_wrappers' => array('container__file_upload_requirements'), '#attributes' => array('id' => $id, 'class' => array('element-invisible', 'help-block')));
        $build['requirements']['validators'] = array('#theme' => 'item_list__file_upload_requirements', '#items' => $descriptions);
    }
    return drupal_render($build);
}
Example #30
0
function sp2015_file_link($variables)
{
    $file = $variables['file'];
    $icon_directory = $variables['icon_directory'];
    $url = file_create_url($file->uri);
    // Human-readable names, for use as text-alternatives to icons.
    $mime_name = array('application/msword' => t('Microsoft Office document icon'), 'application/vnd.ms-excel' => t('Office spreadsheet icon'), 'application/vnd.ms-powerpoint' => t('Office presentation icon'), 'application/pdf' => t('PDF icon'), 'video/quicktime' => t('Movie icon'), 'audio/mpeg' => t('Audio icon'), 'audio/wav' => t('Audio icon'), 'image/jpeg' => t('Image icon'), 'image/png' => t('Image icon'), 'image/gif' => t('Image icon'), 'application/zip' => t('Package icon'), 'text/html' => t('HTML icon'), 'text/plain' => t('Plain text icon'), 'application/octet-stream' => t('Binary Data'));
    $fileclass = substr($file->filename, -3);
    $mimetype = file_get_mimetype($file->uri);
    $icon = theme('file_icon', array('file' => $file, 'icon_directory' => $icon_directory, 'alt' => !empty($mime_name[$mimetype]) ? $mime_name[$mimetype] : t('File')));
    // Set options as per anchor format described at
    // http://microformats.org/wiki/file-format-examples
    $options = array('attributes' => array('type' => $file->filemime . '; length=' . $file->filesize));
    // Use the description as the link text if available.
    if (empty($file->description)) {
        $link_text = $file->filename . ' (' . format_size($file->filesize) . ')';
    } else {
        $link_text = $file->description . format_size($file->filesize);
        $options['attributes']['title'] = check_plain($file->filename);
    }
    return '<span class="file ' . $fileclass . '">' . l($link_text, $url, $options) . '</span>';
}