Пример #1
0
 function addStreamFormSubmit($form_id, $form_values)
 {
     module_load_include('inc', 'Fedora_Repository', 'api/fedora_utils');
     module_load_include('inc', 'Fedora_Repository', 'api/fedora_item');
     module_load_include('php', 'Fedora_Repository', 'ObjectHelper');
     $types = array('application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.wordperfect', 'application/wordperfect', 'application/vnd.oasis.opendocument.text', 'text/rtf', 'application/rtf', 'application/msword', 'application/vnd.ms-powerpoint', 'application/pdf');
     global $user;
     /* TODO Modify the validators array to suit your needs.
        This array is used in the revised file_save_upload */
     $fileObject = file_save_upload('file_uploaded');
     if (!in_array($fileObject->filemime, $types)) {
         drupal_set_message(t('The detected mimetype %s is not supported', array('%s' => $fileObject->filemime)), 'error');
         return false;
     }
     file_move($fileObject->filepath, 0, 'FILE_EXISTS_RENAME');
     $objectHelper = new ObjectHelper();
     $pid = $form_values['pid'];
     $fedora_item = new Fedora_Item($pid);
     $test = NULL;
     $test = $fedora_item->add_datastream_from_file($fileObject->filepath, 'OBJ');
     if ($test) {
         $this->updateMODSStream($form_values['pid'], $form_values['version'], $form_values['usage']);
     }
     file_delete($fileObject->filepath);
     return true;
 }
Пример #2
0
 public function generateValues($object, $instance, $plugin_definition, $form_display_options)
 {
     static $file;
     $settings = $instance->getFieldSettings();
     if (empty($file)) {
         if ($path = $this->generateTextFile()) {
             $source = new stdClass();
             $source->uri = $path;
             $source->uid = 1;
             // TODO: randomize? use case specific.
             $source->filemime = 'text/plain';
             $source->filename = drupal_basename($path);
             $destination_dir = $settings['uri_scheme'] . '://' . $settings['file_directory'];
             file_prepare_directory($destination_dir, FILE_CREATE_DIRECTORY);
             $destination = $destination_dir . '/' . basename($path);
             $file = file_move($source, $destination, FILE_CREATE_DIRECTORY);
         } else {
             return FALSE;
         }
     }
     if (!$file) {
         // In case a previous file operation failed or no file is set, return FALSE
         return FALSE;
     } else {
         $object_field['target_id'] = $file->id();
         $object_field['display'] = $settings['display_default'];
         $object_field['description'] = DevelGenerateBase::createGreeking(10);
         return $object_field;
     }
 }
Пример #3
0
/**
 * Moves a private managed file to the public directory.
 */
function _os_files_deprivatize_file($fid)
{
    $file = file_load($fid);
    // Builds new public path.
    $dest_uri = str_replace('private://', 'public://', $file->uri);
    $dest_path = _os_files_deprivatize_get_dest_path($dest_uri);
    // Creates the destination folder if it doesn't exist.
    if (!is_dir($dest_path)) {
        // Creates the folder.
        drupal_mkdir($dest_path, NULL, TRUE);
    }
    $moved_file = @file_move($file, $dest_uri);
    if ($moved_file) {
        drush_log(dt('File @name moved successfully.', array('@name' => $file->filename)), 'success');
    } else {
        drush_log(dt('Error moving file @name.', array('@name' => $file->filename)), 'error');
        return FALSE;
    }
    $file->uri = $moved_file->uri;
    $file_moved = file_save($file);
    if (isset($file_moved->fid)) {
        drush_log(dt('[O] File @name updated successfully.', array('@name' => $file->filename)), 'success');
        return TRUE;
    } else {
        drush_log(dt('[!] Error updating file @name.', array('@name' => $file->filename)), 'error');
        return FALSE;
    }
}
Пример #4
0
 public function generateImage($object, $field, $instance, $bundle)
 {
     static $images = array();
     $min_resolution = empty($instance['settings']['min_resolution']) ? '100x100' : $instance['settings']['min_resolution'];
     $max_resolution = empty($instance['settings']['max_resolution']) ? '600x600' : $instance['settings']['max_resolution'];
     $extension = 'jpg';
     if (!isset($images[$extension][$min_resolution][$max_resolution]) || count($images[$extension][$min_resolution][$max_resolution]) <= DEVEL_GENERATE_IMAGE_MAX) {
         if ($tmp_file = drupal_tempnam('temporary://', 'imagefield_')) {
             $destination = $tmp_file . '.' . $extension;
             file_unmanaged_move($tmp_file, $destination, FILE_EXISTS_REPLACE);
             $min = explode('x', $min_resolution);
             $max = explode('x', $max_resolution);
             $max[0] = $max[0] < $min[0] ? $min[0] : $max[0];
             $max[1] = $max[1] < $min[1] ? $min[1] : $max[1];
             $width = rand((int) $min[0], (int) $max[0]);
             $height = rand((int) $min[1], (int) $max[1]);
             $gray = isset($this->settings['devel_image_provider_gray']) ? $this->settings['devel_image_provider_gray'] : NULL;
             $tags = isset($this->settings['devel_image_provider_tags']) ? $this->settings['devel_image_provider_tags'] : NULL;
             $url = "{$this->provider_base_url}/{$width}/{$height}";
             if (!empty($tags)) {
                 $url .= '/' . $tags;
             }
             $url = $gray ? $url . '/bw' : $url;
             // Generate seed value.
             $seed = isset($this->settings['devel_image_provider_seed']) ? $this->settings['devel_image_provider_seed'] : NULL;
             $rand_value = rand(0, $seed);
             $url .= '/' . $rand_value;
             $method = isset($this->settings['devel_image_provider_get_method']) ? $this->settings['devel_image_provider_get_method'] : 'file_get_contents';
             $path = devel_image_provider_get_file($url, $destination, $method);
             $source = new stdClass();
             $source->uri = $path;
             $source->uid = 1;
             // TODO: randomize? Use case specific.
             $source->filemime = 'image/jpg';
             if (!empty($instance['settings']['file_directory'])) {
                 $instance['settings']['file_directory'] = $instance['settings']['file_directory'] . '/';
             }
             $destination_dir = $field['settings']['uri_scheme'] . '://' . $instance['settings']['file_directory'];
             file_prepare_directory($destination_dir, FILE_CREATE_DIRECTORY);
             $destination = $destination_dir . basename($path);
             $file = file_move($source, $destination, FILE_CREATE_DIRECTORY);
         } else {
             return FALSE;
         }
     } else {
         // Select one of the images we've already generated for this field.
         $file = new stdClass();
         $file->fid = array_rand($images[$extension][$min_resolution][$max_resolution]);
     }
     $object_field['fid'] = $file->fid;
     $object_field['alt'] = devel_create_greeking(4);
     $object_field['title'] = devel_create_greeking(4);
     return $object_field;
 }
  /**
   * Test token values with a moved text file.
   */
  public function testTokensMoved() {
    // Prepare a test text file.
    /** @var \Drupal\file\Entity\File $text_file */
    $text_file = $this->getTestFile('text');
    $text_file->save();

    // Move the text file.
    $moved_file = file_move($text_file, 'public://moved.diff');

    // Ensure tokens are processed correctly.
    $data = ['file' => $moved_file];
    $this->assertToken('[file:ffp-name-only]', 'moved', $data);
    $this->assertToken('[file:ffp-name-only-original]', 'text-0', $data);
    $this->assertToken('[file:ffp-extension-original]', 'txt', $data);
  }
Пример #6
0
function bulkSavePictures(&$form_state)
{
    $num_files = count($_FILES['files']['name']);
    for ($i = 0; $i < $num_files; $i++) {
        $file = file_save_upload($i, array('file_validate_is_image' => array(), 'file_validate_extensions' => array('png gif jpg jpeg')));
        if ($file) {
            if ($file = file_move($file, 'public://')) {
                $form_state['values']['file'][$i] = $file;
            } else {
                form_set_error('file', t('Failed to write the uploaded file the site\'s file folder.'));
            }
        } else {
            form_set_error('file', t('No file was uploaded.'));
        }
    }
}
Пример #7
0
 public function test_file()
 {
     $file1 = self::getDir() . '/dir1/foo.txt';
     $file2 = self::getDir() . '/dir2/bar.txt';
     $file3 = self::getDir() . '/dir2/baz.txt';
     $file3_name = 'baz.txt';
     $file4 = self::getDir() . '/dir4/yolo.txt';
     $this->assertFalse(file_exists($file1));
     file_create($file1);
     file_write($file1, '');
     $this->assertTrue(file_exists($file1));
     $this->assertEquals('', file_read($file1));
     file_write($file1, 'foo');
     $this->assertEquals('foo', file_read($file1));
     file_append($file1, '_bar');
     $this->assertEquals('foo_bar', file_read($file1));
     file_prepend($file1, '#');
     $this->assertEquals('#foo_bar', file_read($file1));
     file_append($file1, '_bar');
     file_prepend($file1, '#');
     $this->assertEquals('##foo_bar_bar', file_read($file1));
     file_append($file1 . '_append', '_bar');
     $this->assertEquals(file_read($file1 . '_append'), '_bar');
     file_prepend($file1 . '_prepend', '#');
     $this->assertEquals(file_read($file1 . '_prepend'), '#');
     $this->assertFalse(file_exists($file2));
     file_copy($file1, $file2);
     $this->assertTrue(file_exists($file2));
     $this->assertEquals(file_read($file1), file_read($file2));
     $this->assertFalse(file_exists($file3));
     file_rename($file2, $file3_name);
     $this->assertFalse(file_exists($file2));
     $this->assertTrue(file_exists($file3));
     $this->assertEquals(file_read($file1), file_read($file3));
     $this->assertFalse(file_exists($file4));
     file_move($file3, $file4);
     $this->assertFalse(file_exists($file3));
     $this->assertTrue(file_exists($file4));
     $this->assertEquals(file_read($file1), file_read($file4));
     file_delete($file4);
     file_delete($file4);
     $this->assertFalse(file_exists($file4));
     $this->assertEquals(self::getDir() . '/dir1', file_get_directory($file1));
     $this->assertEquals('txt', file_get_extension($file1));
     $this->assertEquals('foo.txt', file_get_name($file1));
 }
Пример #8
0
 /**
  * Tests moving a randomly generated image.
  */
 function testNormal()
 {
     // Pick a file for testing.
     $file = File::create((array) current($this->drupalGetTestFiles('image')));
     // Create derivative image.
     $styles = ImageStyle::loadMultiple();
     $style = reset($styles);
     $original_uri = $file->getFileUri();
     $derivative_uri = $style->buildUri($original_uri);
     $style->createDerivative($original_uri, $derivative_uri);
     // Check if derivative image exists.
     $this->assertTrue(file_exists($derivative_uri), 'Make sure derivative image is generated successfully.');
     // Clone the object so we don't have to worry about the function changing
     // our reference copy.
     $desired_filepath = 'public://' . $this->randomMachineName();
     $result = file_move(clone $file, $desired_filepath, FILE_EXISTS_ERROR);
     // Check if image has been moved.
     $this->assertTrue(file_exists($result->getFileUri()), 'Make sure image is moved successfully.');
     // Check if derivative image has been flushed.
     $this->assertFalse(file_exists($derivative_uri), 'Make sure derivative image has been flushed.');
 }
Пример #9
0
function imglist_main()
{
    global $print, $x7s, $x7c, $x7p;
    $base_image_dir = "/images/";
    $image_dir = "/images/";
    if (isset($_GET['subdir']) && $_GET['subdir'] != "") {
        $image_dir .= $_GET['subdir'] . "/";
    }
    if ($x7c->permissions['admin_panic'] || authorized($image_dir, $x7p->profile['usergroup'])) {
        $basedir = dirname($_SERVER['DOCUMENT_ROOT'] . $_SERVER['PHP_SELF']);
        $file_path = $basedir . $image_dir;
        $image_root_dir = $basedir . $base_image_dir;
        $error = "<p style=\"color: red; font-weight: bold;\">";
        if (isset($_GET['file'])) {
            $error .= file_upload($file_path);
        } elseif (isset($_GET['delete'])) {
            $error .= file_delete($file_path . $_GET['delete']);
        } elseif (isset($_POST['multidel'])) {
            if ($_POST['action'] == 'delete') {
                foreach ($_POST['multidel'] as $file) {
                    $error .= file_delete($file_path . $file);
                }
            } elseif ($_POST['action'] == 'move') {
                foreach ($_POST['multidel'] as $file) {
                    $error .= file_move($file_path . $file, $image_root_dir . $_POST['dest'] . $file);
                }
            }
        }
        $error .= "</p>";
        $site_path = dirname($_SERVER['PHP_SELF']) . $image_dir;
        $output = file_list($file_path, $site_path);
        $body = $error . $output['body'];
        $head = $output['head'];
        $print->normal_window($head, $body);
    } else {
        return "Non sei autorizzato a vedere questa pagina <br>";
    }
}
Пример #10
0
 /**
  * Save uploaded file. Call this from the form submit handler
  * @return
  * 		true if success, false if not
  * @param object $file_field[optional]
  * 		field name of the form
  * @param object $file_type[optional]
  * 		acceptable MIME type substring, e.g. 'image/'
  */
 function saveFile($file_field = 'attachment', $file_type = '')
 {
     if (isset($_FILES[$file_field]) && !empty($_FILES[$file_field]['name'])) {
         // we only care about single file uploads here
         $uploadkey = '';
         //the original name of the file is $_FILES[$file_field]['name'][$upload_key]
         if (is_array($_FILES[$file_field]['name'])) {
             foreach ($_FILES[$file_field]['name'] as $key => $val) {
                 $uploadkey = $key;
                 break;
             }
         }
         // valid attachment ?
         if ($file_type != '') {
             if (!eregi($file_type, $uploadkey == '' ? $_FILES[$file_field]['type'] : $_FILES[$file_field]['type'][$uploadkey])) {
                 // invalid data mime type found
                 return false;
             }
         }
         //01. we store the file into the file_managed table temporarily, and get the file object
         $file = file_save_upload($uploadkey, array(), NULL);
         //02. we get the file id in the file_managed table, and by using the file id together with the original filename, we create the new filename
         //also, we store the file id into the last_upload_id
         $filename = $file->fid . $_FILES[$file_field]['name'][$uploadkey];
         $this->last_uploaded_id = $file->fid;
         //03. we save the file to be uploaded into the public file directory.
         $file = file_move($file, 'public://' . $filename, FILE_EXISTS_REPLACE);
         //04. set file the status to be permanently and save the file.
         $file->status = FILE_STATUS_PERMANENT;
         variable_set('file_id', $file->fid);
         file_save($file);
         //upload success;
         return true;
     } else {
         // invalid attachment data found
         return false;
     }
 }
Пример #11
0
 public function new_file_upload($file, $type = 'image')
 {
     if (empty($file)) {
         return error(-1, '没有上传内容');
     }
     $limit = 5000;
     $extention = pathinfo($file['name'], PATHINFO_EXTENSION);
     if (empty($type) || $type == 'image') {
         $extentions = array('gif', 'jpg', 'jpeg', 'png');
     }
     if ($type == 'music') {
         $extentions = array('mp3', 'mp4');
     }
     if ($type == 'other') {
         $extentions = array('gif', 'jpg', 'jpeg', 'png', 'mp3', 'mp4', 'doc');
     }
     if (!in_array(strtolower($extention), $extentions)) {
         return error(-1, '不允许上传此类文件');
     }
     if ($limit * 1024 < filesize($file['tmp_name'])) {
         return error(-1, "上传的文件超过大小限制,请上传小于 " . $limit . "k 的文件");
     }
     $result = array();
     $path = '/attachment/';
     $result['path'] = "{$type}/" . date('Y/m/');
     mkdirs(WEB_ROOT . $path . $result['path']);
     do {
         $filename = random(15) . ".{$extention}";
     } while (file_exists(SYSTEM_WEBROOT . $path . $filename));
     $result['path'] .= $filename;
     $filename = WEB_ROOT . $path . $result['path'];
     if (!file_move($file['tmp_name'], $filename)) {
         return error(-1, '保存上传文件失败');
     }
     $result['success'] = true;
     return $result;
 }
Пример #12
0
 function generateValues($object, $instance, $plugin_definition, $form_display_options)
 {
     $object_field = array();
     static $images = array();
     $settings = $instance->getSettings();
     $min_resolution = empty($settings['min_resolution']) ? '100x100' : $settings['min_resolution'];
     $max_resolution = empty($settings['max_resolution']) ? '600x600' : $settings['max_resolution'];
     $extensions = array_intersect(explode(' ', $settings['file_extensions']), array('png', 'gif', 'jpg', 'jpeg'));
     $extension = array_rand(array_combine($extensions, $extensions));
     // Generate a max of 5 different images.
     if (!isset($images[$extension][$min_resolution][$max_resolution]) || count($images[$extension][$min_resolution][$max_resolution]) <= DEVEL_GENERATE_IMAGE_MAX) {
         if ($path = $this->generateImage($extension, $min_resolution, $max_resolution)) {
             $account = user_load(1);
             $image = entity_create('file', array());
             $image->setFileUri($path);
             $image->setOwner($account);
             $image->setMimeType('image/' . pathinfo($path, PATHINFO_EXTENSION));
             $image->setFileName(drupal_basename($path));
             $destination_dir = $settings['uri_scheme'] . '://' . $settings['file_directory'];
             file_prepare_directory($destination_dir, FILE_CREATE_DIRECTORY);
             $destination = $destination_dir . '/' . basename($path);
             $file = file_move($image, $destination, FILE_CREATE_DIRECTORY);
             $images[$extension][$min_resolution][$max_resolution][$file->id()] = $file;
         } else {
             return FALSE;
         }
     } else {
         // Select one of the images we've already generated for this field.
         $image_index = array_rand($images[$extension][$min_resolution][$max_resolution]);
         $file = $images[$extension][$min_resolution][$max_resolution][$image_index];
     }
     $object_field['target_id'] = $file->id();
     $object_field['alt'] = DevelGenerateBase::createGreeking(4);
     $object_field['title'] = DevelGenerateBase::createGreeking(4);
     return $object_field;
 }
Пример #13
0
 /**
  * Test file munge handling.
  */
 function testHandleFileMunge()
 {
     // Ensure insecure uploads are disabled for this test.
     $this->config('system.file')->set('allow_insecure_uploads', 0)->save();
     $this->image = file_move($this->image, $this->image->getFileUri() . '.foo.' . $this->imageExtension);
     // Reset the hook counters to get rid of the 'move' we just called.
     file_test_reset();
     $extensions = $this->imageExtension;
     $edit = array('files[file_test_upload]' => drupal_realpath($this->image->getFileUri()), 'extensions' => $extensions);
     $munged_filename = $this->image->getFilename();
     $munged_filename = substr($munged_filename, 0, strrpos($munged_filename, '.'));
     $munged_filename .= '_.' . $this->imageExtension;
     $this->drupalPostForm('file-test/upload', $edit, t('Submit'));
     $this->assertResponse(200, 'Received a 200 response for posted test file.');
     $this->assertRaw(t('For security reasons, your upload has been renamed'), 'Found security message.');
     $this->assertRaw(t('File name is @filename', array('@filename' => $munged_filename)), 'File was successfully munged.');
     $this->assertRaw(t('You WIN!'), 'Found the success message.');
     // Check that the correct hooks were called.
     $this->assertFileHooksCalled(array('validate', 'insert'));
     // Ensure we don't munge files if we're allowing any extension.
     // Reset the hook counters.
     file_test_reset();
     $edit = array('files[file_test_upload]' => drupal_realpath($this->image->getFileUri()), 'allow_all_extensions' => TRUE);
     $this->drupalPostForm('file-test/upload', $edit, t('Submit'));
     $this->assertResponse(200, 'Received a 200 response for posted test file.');
     $this->assertNoRaw(t('For security reasons, your upload has been renamed'), 'Found no security message.');
     $this->assertRaw(t('File name is @filename', array('@filename' => $this->image->getFilename())), 'File was not munged when allowing any extension.');
     $this->assertRaw(t('You WIN!'), 'Found the success message.');
     // Check that the correct hooks were called.
     $this->assertFileHooksCalled(array('validate', 'insert'));
 }
Пример #14
0
function file_upload($file, $type = 'image', $name = '', $is_wechat = false)
{
    $harmtype = array('asp', 'php', 'jsp', 'js', 'css', 'php3', 'php4', 'php5', 'ashx', 'aspx', 'exe', 'cgi');
    if (empty($file)) {
        return error(-1, '没有上传内容');
    }
    if (!in_array($type, array('image', 'thumb', 'voice', 'video', 'audio'))) {
        return error(-2, '未知的上传类型');
    }
    global $_W;
    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $ext = strtolower($ext);
    if (!$is_wechat) {
        $setting = $_W['setting']['upload'][$type];
        if (!in_array(strtolower($ext), $setting['extentions']) || in_array(strtolower($ext), $harmtype)) {
            return error(-3, '不允许上传此类文件');
        }
        if (!empty($setting['limit']) && $setting['limit'] * 1024 < filesize($file['tmp_name'])) {
            return error(-4, "上传的文件超过大小限制,请上传小于 {$setting['limit']}k 的文件");
        }
    }
    $result = array();
    if (empty($name) || $name == 'auto') {
        $uniacid = intval($_W['uniacid']);
        $path = "{$type}s/{$uniacid}/" . date('Y/m/');
        mkdirs(ATTACHMENT_ROOT . '/' . $path);
        $filename = file_random_name(ATTACHMENT_ROOT . '/' . $path, $ext);
        $result['path'] = $path . $filename;
    } else {
        mkdirs(dirname(ATTACHMENT_ROOT . '/' . $name));
        if (!strexists($name, $ext)) {
            $name .= '.' . $ext;
        }
        $result['path'] = $name;
    }
    if (!file_move($file['tmp_name'], ATTACHMENT_ROOT . '/' . $result['path'])) {
        return error(-1, '保存上传文件失败');
    }
    $result['success'] = true;
    return $result;
}
Пример #15
0
 public function generateImage($object, $field, $instance, $bundle)
 {
     static $images = array();
     $min_resolution = empty($instance['settings']['min_resolution']) ? '100x100' : $instance['settings']['min_resolution'];
     $max_resolution = empty($instance['settings']['max_resolution']) ? '600x600' : $instance['settings']['max_resolution'];
     $extension = 'jpg';
     if (!isset($images[$extension][$min_resolution][$max_resolution]) || count($images[$extension][$min_resolution][$max_resolution]) <= DEVEL_GENERATE_IMAGE_MAX) {
         if ($tmp_file = drupal_tempnam('temporary://', 'imagefield_')) {
             $destination = $tmp_file . '.' . $extension;
             file_unmanaged_move($tmp_file, $destination, FILE_CREATE_DIRECTORY);
             $min = explode('x', $min_resolution);
             $max = explode('x', $max_resolution);
             $max[0] = $max[0] < $min[0] ? $min[0] : $max[0];
             $max[1] = $max[1] < $min[1] ? $min[1] : $max[1];
             $width = rand((int) $min[0], (int) $max[0]);
             $height = rand((int) $min[1], (int) $max[1]);
             $background_color = isset($this->settings['devel_image_provider_background_color']) ? $this->settings['devel_image_provider_background_color'] : FALSE;
             if ($background_color) {
                 if (preg_match('/^#[a-f0-9]{6}$/i', $background_color)) {
                     // Check for valid hex number
                     $background_color = "/" . str_replace('#', '', check_plain($background_color));
                     // Strip out #
                 } else {
                     $background_color = '';
                 }
             } else {
                 $background_color = '';
             }
             $text_color = isset($this->settings['devel_image_provider_text_color']) ? $this->settings['devel_image_provider_text_color'] : FALSE;
             if ($text_color) {
                 // Check for valid hex number.
                 if (preg_match('/^#[a-f0-9]{6}$/i', $text_color)) {
                     // Strip out # character.
                     $text_color = "/" . str_replace('#', '', check_plain($text_color));
                 } else {
                     $text_color = '';
                 }
             } else {
                 $text_color = '';
             }
             $include_text = isset($this->settings['devel_image_provider_include_text']) ? $this->settings['devel_image_provider_include_text'] : FALSE;
             switch ($include_text) {
                 case 'custom':
                     $custom_text = isset($this->settings['devel_image_provider_custom_text']) ? $this->settings['devel_image_provider_custom_text'] : '';
                     break;
                 case 'random':
                     // Small random text as text size is depending on the image size.
                     $custom_text = trim(substr(devel_create_greeking(mt_rand(1, 3)), 0, 8));
                     break;
                 case 'default':
                 default:
                     $custom_text = '';
                     break;
             }
             if (!empty($custom_text)) {
                 //Replace the spaces with + as per provider specifications
                 $custom_text = "&text=" . str_replace(' ', '+', check_plain($custom_text));
             }
             $url = "{$this->provider_base_url}/" . $width . "x" . $height . '/' . $background_color . '/' . $text_color . '&text=' . $custom_text;
             $method = isset($this->settings['devel_image_provider_get_method']) ? $this->settings['devel_image_provider_get_method'] : 'file_get_contents';
             $path = devel_image_provider_get_file($url, $destination, $method);
             $source = new stdClass();
             $source->uri = $path;
             $source->uid = 1;
             // TODO: randomize? Use case specific.
             $source->filemime = 'image/jpg';
             if (!empty($instance['settings']['file_directory'])) {
                 $instance['settings']['file_directory'] = $instance['settings']['file_directory'] . '/';
             }
             $destination_dir = $field['settings']['uri_scheme'] . '://' . $instance['settings']['file_directory'];
             file_prepare_directory($destination_dir, FILE_CREATE_DIRECTORY);
             $destination = $destination_dir . basename($path);
             $file = file_move($source, $destination, FILE_CREATE_DIRECTORY);
         } else {
             return FALSE;
         }
     } else {
         // Select one of the images we've already generated for this field.
         $file = new stdClass();
         $file->fid = array_rand($images[$extension][$min_resolution][$max_resolution]);
     }
     $object_field['fid'] = $file->fid;
     $object_field['alt'] = devel_create_greeking(4);
     $object_field['title'] = devel_create_greeking(4);
     return $object_field;
 }
Пример #16
0
 /**
  * {@inheritdoc}
  */
 public static function generateSampleValue(FieldDefinitionInterface $field_definition)
 {
     $random = new Random();
     $settings = $field_definition->getSettings();
     static $images = array();
     $min_resolution = empty($settings['min_resolution']) ? '100x100' : $settings['min_resolution'];
     $max_resolution = empty($settings['max_resolution']) ? '600x600' : $settings['max_resolution'];
     $extensions = array_intersect(explode(' ', $settings['file_extensions']), array('png', 'gif', 'jpg', 'jpeg'));
     $extension = array_rand(array_combine($extensions, $extensions));
     // Generate a max of 5 different images.
     if (!isset($images[$extension][$min_resolution][$max_resolution]) || count($images[$extension][$min_resolution][$max_resolution]) <= 5) {
         $tmp_file = drupal_tempnam('temporary://', 'generateImage_');
         $destination = $tmp_file . '.' . $extension;
         file_unmanaged_move($tmp_file, $destination, FILE_CREATE_DIRECTORY);
         if ($path = $random->image(drupal_realpath($destination), $min_resolution, $max_resolution)) {
             $image = File::create();
             $image->setFileUri($path);
             $image->setOwnerId(\Drupal::currentUser()->id());
             $image->setMimeType(\Drupal::service('file.mime_type.guesser')->guess($path));
             $image->setFileName(drupal_basename($path));
             $destination_dir = static::doGetUploadLocation($settings);
             file_prepare_directory($destination_dir, FILE_CREATE_DIRECTORY);
             $destination = $destination_dir . '/' . basename($path);
             $file = file_move($image, $destination, FILE_CREATE_DIRECTORY);
             $images[$extension][$min_resolution][$max_resolution][$file->id()] = $file;
         } else {
             return array();
         }
     } else {
         // Select one of the images we've already generated for this field.
         $image_index = array_rand($images[$extension][$min_resolution][$max_resolution]);
         $file = $images[$extension][$min_resolution][$max_resolution][$image_index];
     }
     list($width, $height) = getimagesize($file->getFileUri());
     $values = array('target_id' => $file->id(), 'alt' => $random->sentences(4), 'title' => $random->sentences(4), 'width' => $width, 'height' => $height);
     return $values;
 }
Пример #17
0
/**
 * 上传文件保存,缩略图暂未实现
 * @param string $fname 上传的$_FILE字段
 * @param string $type 上传类型(将按分类保存不同子目录,image -> images)
 * @param string $sname 保存的文件名,如果为 auto 则自动生成文件名,否者请指定从附件目录开始的完整相对路径(包括文件名,不包括文件扩展名)
 * @return array 返回结果数组,字段包括:success => bool 是否上传成功,path => 保存路径(从附件目录开始的完整相对路径),message => 提示信息
 */
function file_upload($file, $type = 'image', $sname = 'auto') {
	if(empty($file)) {
		return error(-1, '没有上传内容');
	}
	global $_W;
	if (empty($_W['uploadsetting'])) {
		$_W['uploadsetting'] = array();
		$_W['uploadsetting']['image']['folder'] = 'images';
		$_W['uploadsetting']['image']['extentions'] = $_W['config']['upload']['image']['extentions'];
		$_W['uploadsetting']['image']['limit'] = $_W['config']['upload']['image']['limit'];
	}
	$settings = $_W['uploadsetting'];
	if(!array_key_exists($type, $settings)) {
		return error(-1, '未知的上传类型');
	}
	$extention = pathinfo($file['name'], PATHINFO_EXTENSION);
	if(!in_array($extention, $settings[$type]['extentions'])) {
		return error(-1, '不允许上传此类文件');
	}
	if(!empty($settings[$type]['limit']) && $settings[$type]['limit'] * 1024 < filesize($file['tmp_name'])) {
		return error(-1, "上传的文件超过大小限制,请上传小于 {$settings[$type]['limit']}k 的文件");
	}
   	//兼容其它平台上传
	if ($func = platform('file_upload')) {
		return call_user_func($func, $file, $type);
	}
	
	$result = array();
	$path = '/'.$_W['config']['upload']['attachdir'];

	if($sname == 'auto') {
		$result['path'] = "{$settings[$type]['folder']}/" . date('Y/m/');
		mkdirs(IA_ROOT . $path . $result['path']);
		do {
			$filename = random(30) . ".{$extention}";
		} while(file_exists(IA_ROOT . $path . $filename));
		$result['path'] .= $filename;
	} else {
		$result['path'] = "{$settings[$type]['folder']}/" . $sname . '.' . $extention;  
		mkdirs(IA_ROOT . dirname($path));
	}
	$filename = IA_ROOT . $path . $result['path'];
	if(!file_move($file['tmp_name'], $filename)) {
		return error(-1, '保存上传文件失败');
	}
	$result['success'] = true;
	return $result; 
}
Пример #18
0
starttable('100%', $lang_plugin_FileMove['display_name'] . ' - ' . $lang_plugin_FileMove['version'] . '    ' . '<a href="pluginmgr.php" class="admin_menu">Plugin Manager</a>', 2);
echo "<tr><td>";
$title = $lang_plugin_FileMove['transfer_file'] . $lang_plugin_FileMove['folder2'] . "<b>" . $DRep . "</b>" . $lang_plugin_FileMove['to'] . $lang_plugin_FileMove['folder2'] . "<b>" . $ARep . "</b>";
starttable('100%', $title);
//Traitement de la base de donnée
$c = 0;
//Sélection des images du répertoire de départ
$result = cpg_db_query("SELECT * FROM {$CONFIG['TABLE_PICTURES']} WHERE `filepath`='{$DRep}'");
echo "<tr><td>";
//echo "name:".$name."<br>";
while ($row = mysql_fetch_array($result)) {
    $base_name = $row['filename'];
    foreach ($file_name as $n => $name) {
        if ($base_name == $name) {
            echo "{$base_name}<br>";
            //déplacement du fichier d'un répertoire à l'autre
            file_move($base_name, $DRep, $ARep);
            ++$c;
            $result2 = cpg_db_query("UPDATE {$CONFIG['TABLE_PICTURES']} SET `filepath`='{$ARep}' WHERE `filepath`='{$DRep}' AND `filename`='{$base_name}'");
        }
    }
}
echo "</td></tr>";
echo "<tr><td align='center'><b>{$c} {$lang_plugin_FileMove['traitement']}</b><a href='index.php'<input type='button' name='ok'value='{$lang_plugin_FileMove['continue']}'></a></td></tr>";
endtable();
echo "</td></tr>";
endtable();
pagefooter();
ob_end_flush();
mysql_free_result($result);
mysql_free_result($result2);
Пример #19
0
 protected function updateFileLocation($wrapper)
 {
     if ($this->request['filename']) {
         $file = file_load($wrapper->getIdentifier());
         $label = $wrapper->name->value();
         $destination = dirname($file->uri) . '/' . $this->request['filename'];
         if ($file = file_move($file, $destination)) {
             $wrapper->set($file);
             $wrapper->name->set($label);
             return true;
         }
     }
     return false;
 }
Пример #20
0
 public function generateImage($object, $field, $instance, $bundle)
 {
     $object_field = array();
     static $available_images = array();
     if (empty($available_images)) {
         $available_images = $this->getImages();
     }
     if (empty($available_images)) {
         $args = func_get_args();
         return call_user_func_array('_image_devel_generate', $args);
     }
     $extension = array_rand(array('jpg' => 'jpg', 'png' => 'png'));
     $min_resolution = empty($instance['settings']['min_resolution']) ? '100x100' : $instance['settings']['min_resolution'];
     $max_resolution = empty($instance['settings']['max_resolution']) ? '600x600' : $instance['settings']['max_resolution'];
     if (FALSE === ($tmp_file = drupal_tempnam('temporary://', 'imagefield_'))) {
         return FALSE;
     }
     $destination = $tmp_file . '.' . $extension;
     file_unmanaged_move($tmp_file, $destination, FILE_EXISTS_REPLACE);
     $rand_file = array_rand($available_images);
     if (!empty($instance['settings']['file_directory'])) {
         $instance['settings']['file_directory'] = $instance['settings']['file_directory'] . '/';
     }
     $destination_dir = $field['settings']['uri_scheme'] . '://' . $instance['settings']['file_directory'];
     file_prepare_directory($destination_dir, FILE_CREATE_DIRECTORY);
     if ($this->settings['devel_image_no_alter']) {
         $file = $available_images[$rand_file];
         $file = file_copy($file, $destination_dir);
     } else {
         $image = image_load($rand_file);
         $min = explode('x', $min_resolution);
         $max = explode('x', $max_resolution);
         $max[0] = $max[0] < $min[0] ? $min[0] : $max[0];
         $max[1] = $max[1] < $min[1] ? $min[1] : $max[1];
         $width = rand((int) $min[0], (int) $max[0]);
         $height = rand((int) $min[1], (int) $max[1]);
         if (!image_scale_and_crop($image, $width, $height)) {
             return FALSE;
         }
         // Use destination image type.
         $image->info['extension'] = $extension;
         if (!image_save($image, $destination)) {
             return FALSE;
         }
         $source = new stdClass();
         $source->uri = $destination;
         $source->uid = 1;
         // TODO: randomize? Use case specific.
         $source->filemime = $image->info['mime_type'];
         $source->filename = drupal_basename($image->source);
         $destination = $destination_dir . basename($destination);
         $file = file_move($source, $destination, FILE_CREATE_DIRECTORY);
     }
     $object_field['fid'] = $file->fid;
     $object_field['alt'] = devel_create_greeking(4);
     $object_field['title'] = devel_create_greeking(4);
     return $object_field;
 }
Пример #21
0
 public function approveFileSubmission($id)
 {
     $nexcloud = filedepot_nexcloud();
     $query = db_query("SELECT * FROM {filedepot_filesubmissions} WHERE id=:fid", array('fid' => $id));
     $rec = $query->fetchObject();
     $newfid = 0;
     // @TODO: Check if there have been multiple submission requests for the same file and thus have same new version #
     if ($rec->version == 1) {
         $private_destination = "private://filedepot/{$rec->cid}/";
         // Best to call file_prepare_directory() - even if you believe directory exists
         file_prepare_directory($private_destination, FILE_CREATE_DIRECTORY);
         $file = file_load($rec->drupal_fid);
         $private_uri = $private_destination . $rec->fname;
         $file = file_move($file, $private_uri, FILE_EXISTS_RENAME);
         // Get name of new file in case it was renamed after the file_move()
         list($scheme, $target) = explode('://', $file->uri, 2);
         $filename = str_replace("filedepot/{$rec->cid}/", '', $target);
         if (isset($rec->title) and !empty($rec->title)) {
             $filetitle = $rec->title;
         } else {
             $filetitle = $rec->fname;
         }
         // Load the node for the folder and then update the file usage table
         $nid = db_query("SELECT nid FROM {filedepot_categories} WHERE cid=:cid", array(':cid' => $rec->cid))->fetchField();
         $node = node_load($nid);
         file_usage_add($file, 'filedepot', 'node', $node->nid);
         // Remove the record for the core file module from the file usage table
         file_usage_delete($file, 'file');
         $query = db_insert('filedepot_files');
         $query->fields(array('cid', 'fname', 'title', 'description', 'version', 'drupal_fid', 'size', 'mimetype', 'submitter', 'status', 'date', 'version_ctl', 'extension'));
         $query->values(array('cid' => $rec->cid, 'fname' => $filename, 'title' => $filetitle, 'description' => $rec->description, 'version' => $rec->version, 'drupal_fid' => $file->fid, 'size' => $file->filesize, 'mimetype' => $file->filemime, 'submitter' => $rec->submitter, 'status' => 1, 'date' => $rec->date, 'version_ctl' => $rec->version_ctl, 'extension' => $rec->extension));
         $query->execute();
         // Get fileid for the new file record
         $newfid = db_query_range("SELECT fid FROM {filedepot_files} WHERE cid=:cid AND submitter=:uid ORDER BY fid DESC", 0, 1, array(':cid' => $rec->cid, ':uid' => $rec->submitter))->fetchField();
         $query = db_insert('filedepot_fileversions');
         $query->fields(array('fid', 'fname', 'drupal_fid', 'version', 'notes', 'size', 'date', 'uid', 'status'));
         $query->values(array('fid' => $newfid, 'fname' => $filename, 'drupal_fid' => $file->fid, 'version' => 1, 'notes' => $rec->version_note, 'size' => $file->filesize, 'date' => time(), 'uid' => $rec->submitter, 'status' => 1));
         $query->execute();
         if (!empty($rec->tags) and $this->checkPermission($rec->cid, 'view', 0, FALSE)) {
             $nexcloud->update_tags($newfid, $rec->tags);
         }
     }
     if ($newfid > 0) {
         if ($rec->notify == 1) {
             filedepot_sendNotification($newfid, FILEDEPOT_NOTIFY_APPROVED);
         }
         db_delete('filedepot_filesubmissions')->condition('id', $id)->execute();
         // Send out notifications of update to all subscribed users
         filedepot_sendNotification($newfid, FILEDEPOT_NOTIFY_NEWFILE);
         // Update related folders last_modified_date
         $workspaceParentFolder = filedepot_getTopLevelParent($rec->cid);
         filedepot_updateFolderLastModified($workspaceParentFolder);
         return TRUE;
     } else {
         return FALSE;
     }
 }
Пример #22
0
 public function generateImage($object, $field, $instance, $bundle)
 {
     static $images = array();
     $min_resolution = empty($instance['settings']['min_resolution']) ? '100x100' : $instance['settings']['min_resolution'];
     $max_resolution = empty($instance['settings']['max_resolution']) ? '600x600' : $instance['settings']['max_resolution'];
     $extension = 'jpg';
     if (!isset($images[$extension][$min_resolution][$max_resolution]) || count($images[$extension][$min_resolution][$max_resolution]) <= DEVEL_GENERATE_IMAGE_MAX) {
         if ($tmp_file = drupal_tempnam('temporary://', 'imagefield_')) {
             $destination = $tmp_file . '.' . $extension;
             file_unmanaged_move($tmp_file, $destination, FILE_CREATE_DIRECTORY);
             $min = explode('x', $min_resolution);
             $max = explode('x', $max_resolution);
             $max[0] = $max[0] < $min[0] ? $min[0] : $max[0];
             $max[1] = $max[1] < $min[1] ? $min[1] : $max[1];
             $width = rand((int) $min[0], (int) $max[0]);
             $height = rand((int) $min[1], (int) $max[1]);
             $gray = isset($this->settings['devel_image_provider_gray']) ? $this->settings['devel_image_provider_gray'] : NULL;
             $gray_part = $gray ? '/g' : '';
             $url = "{$this->provider_base_url}" . $gray_part . "/{$width}/{$height}";
             $categories = isset($this->settings['devel_image_provider_categories']) ? $this->settings['devel_image_provider_categories'] : array();
             $category = array_rand($categories);
             if (!empty($category) && $category != 'any') {
                 $url .= '/' . $category;
             }
             $include_text = isset($this->settings['devel_image_provider_include_text']) ? $this->settings['devel_image_provider_include_text'] : FALSE;
             switch ($include_text) {
                 case 'custom':
                     $custom_text = isset($this->settings['devel_image_provider_custom_text']) ? $this->settings['devel_image_provider_custom_text'] : '';
                     break;
                 case 'random':
                     $custom_text = trim(substr(devel_create_greeking(mt_rand(1, 4)), 0, 16));
                     break;
                 case 'default':
                 default:
                     $custom_text = '';
                     break;
             }
             if (!empty($custom_text)) {
                 // Replace the spaces with - as per lorempixum specifications.
                 $custom_text = str_replace(' ', '-', check_plain($custom_text));
                 $url .= '/' . $custom_text;
             }
             $method = isset($this->settings['devel_image_provider_get_method']) ? $this->settings['devel_image_provider_get_method'] : 'file_get_contents';
             $path = devel_image_provider_get_file($url, $destination, $method);
             $source = new stdClass();
             $source->uri = $path;
             $source->uid = 1;
             // TODO: randomize? Use case specific.
             $source->filemime = 'image/jpg';
             if (!empty($instance['settings']['file_directory'])) {
                 $instance['settings']['file_directory'] = $instance['settings']['file_directory'] . '/';
             }
             $destination_dir = $field['settings']['uri_scheme'] . '://' . $instance['settings']['file_directory'];
             file_prepare_directory($destination_dir, FILE_CREATE_DIRECTORY);
             $destination = $destination_dir . basename($path);
             $file = file_move($source, $destination, FILE_CREATE_DIRECTORY);
         } else {
             return FALSE;
         }
     } else {
         // Select one of the images we've already generated for this field.
         $file = new stdClass();
         $file->fid = array_rand($images[$extension][$min_resolution][$max_resolution]);
     }
     $object_field['fid'] = $file->fid;
     $object_field['alt'] = devel_create_greeking(4);
     $object_field['title'] = devel_create_greeking(4);
     return $object_field;
 }
Пример #23
0
        }
        if (!empty($_FILES['headimg']['tmp_name'])) {
            $_W['uploadsetting'] = array();
            $_W['uploadsetting']['image']['folder'] = '';
            $_W['uploadsetting']['image']['extentions'] = array('jpg');
            $_W['uploadsetting']['image']['limit'] = $_W['config']['upload']['image']['limit'];
            $upload = file_upload($_FILES['headimg'], 'image', "headimg_{$acid}");
            if (is_array($upload)) {
                $result = file_remote_upload($upload['path']);
                if (!is_error($result) && $result !== false) {
                    file_delete($upload['path']);
                }
            }
        } else {
            if (file_exists(IA_ROOT . '/attachment/headimg_' . $update['account'] . '.jpg')) {
                file_move(IA_ROOT . '/attachment/headimg_' . $update['account'] . '.jpg', IA_ROOT . '/attachment/headimg_' . $acid . '.jpg');
                $result = file_remote_upload('headimg_' . $acid . '.jpg');
                if (!is_error($result) && $result !== false) {
                    file_delete('headimg_' . $acid . '.jpg');
                }
            }
        }
        cache_delete("unisetting:{$uniacid}");
        if (!empty($_GPC['uniacid']) || empty($_W['isfounder'])) {
            header("Location: " . url('account/post-step/', array('uniacid' => $uniacid, 'acid' => $acid, 'step' => 4)));
        } else {
            header("Location: " . url('account/post-step/', array('uniacid' => $uniacid, 'acid' => $acid, 'step' => 3)));
        }
        exit;
    }
} elseif ($step == 3) {
Пример #24
0
 /**
  * Test that moving onto an existing file fails when FILE_EXISTS_ERROR is
  * specified.
  */
 function testExistingError()
 {
     $contents = $this->randomMachineName(10);
     $source = $this->createFile();
     $target = $this->createFile(NULL, $contents);
     $this->assertDifferentFile($source, $target);
     // Clone the object so we don't have to worry about the function changing
     // our reference copy.
     $result = file_move(clone $source, $target->getFileUri(), FILE_EXISTS_ERROR);
     // Check the return status and that the contents did not change.
     $this->assertFalse($result, 'File move failed.');
     $this->assertTrue(file_exists($source->getFileUri()));
     $this->assertEqual($contents, file_get_contents($target->getFileUri()), 'Contents of file were not altered.');
     // Check that no hooks were called while failing.
     $this->assertFileHooksCalled(array());
     // Load the file from the database and make sure it is identical to what
     // was returned.
     $this->assertFileUnchanged($source, file_load($source->id(), TRUE));
     $this->assertFileUnchanged($target, file_load($target->id(), TRUE));
 }
Пример #25
0
$DRep = $superCage->get->getRaw('Drep') . "/";
$ARep = $superCage->get->getRaw('Arep') . "/";
//affichagede l'entête
pageheader($lang_plugin_FileMove['display_name']);
starttable('100%', $lang_plugin_FileMove['display_name'] . ' - ' . $lang_plugin_FileMove['version'] . '    ' . '<a href="pluginmgr.php" class="admin_menu">Plugin Manager</a>', 2);
echo "<tr><td>";
$title = $lang_plugin_FileMove['transfer'] . $lang_plugin_FileMove['folder2'] . "<b>" . $DRep . "</b>" . $lang_plugin_FileMove['to'] . $lang_plugin_FileMove['folder2'] . "<b>" . $ARep . "</b>";
starttable('100%', $title);
//Traitement de la base de donnée
$c = 0;
//Sélection des images du répertoire de départ
$result = cpg_db_query("SELECT * FROM {$CONFIG['TABLE_PICTURES']} WHERE `filepath`='{$DRep}'");
echo "<tr><td>";
while ($row = mysql_fetch_array($result)) {
    $file_name = $row['filename'];
    echo "{$file_name}<br>";
    //déplacement du fichier d'un répertoire à l'autre
    file_move($file_name, $DRep, $ARep);
    $c++;
}
// while
$result2 = cpg_db_query("UPDATE {$CONFIG['TABLE_PICTURES']} SET `filepath`='{$ARep}' WHERE `filepath`='{$DRep}'");
echo "</td></tr>";
echo "<tr><td align='center'><b>{$c} {$lang_plugin_FileMove['traitement']}</b><a href='index.php'<input type='button' name='ok'value='{$lang_plugin_FileMove['continue']}'></a></td></tr>";
endtable();
echo "</td></tr>";
endtable();
pagefooter();
ob_end_flush();
mysql_free_result($result);
mysql_free_result($result2);
Пример #26
0
     }
     if ($rDefine) {
         f_write("{$mRoot}/receiver.php", $rDefine);
     }
     if ($sDefine) {
         f_write("{$mRoot}/site.php", $sDefine);
     }
     mkdirs("{$mRoot}/template");
     if ($m['application']['setting']) {
         f_write("{$mRoot}/template/setting.html", "{template 'common/header'}\r\n这里定义页面内容\r\n{template 'common/footer'}");
     }
     if ($m['icon']) {
         file_move($m['icon'], "{$mRoot}/icon.jpg");
     }
     if ($m['preview']) {
         file_move($m['preview'], "{$mRoot}/preview.jpg");
     }
     message("生成成功. 请访问 {$mRoot} 继续实现你的模块.", 'refresh');
 }
 if ($_GPC['method'] == 'download') {
     $fname = IA_ROOT . "/data/tmp.zip";
     $zip = new ZipArchive();
     $zip->open($fname, ZipArchive::CREATE);
     $zip->addFromString('manifest.xml', $manifest);
     if ($mDefine) {
         $zip->addFromString('module.php', $mDefine);
     }
     if ($pDefine) {
         $zip->addFromString('processor.php', $pDefine);
     }
     if ($rDefine) {
Пример #27
0
function file_upload($file, $type = 'image', $name = '')
{
    if (empty($file)) {
        return error(-1, '没有上传内容');
    }
    if (!in_array($type, array('image', 'audio'))) {
        return error(-1, '未知的上传类型');
    }
    global $_W;
    if (empty($_W['uploadsetting'][$type])) {
        $_W['uploadsetting'] = array();
        $_W['uploadsetting'][$type]['folder'] = "{$type}s/{$_W['uniacid']}";
        $_W['uploadsetting'][$type]['extentions'] = $_W['config']['upload'][$type]['extentions'];
        $_W['uploadsetting'][$type]['limit'] = $_W['config']['upload'][$type]['limit'];
    }
    $settings = $_W['uploadsetting'];
    $extention = pathinfo($file['name'], PATHINFO_EXTENSION);
    if (!in_array(strtolower($extention), $settings[$type]['extentions'])) {
        return error(-1, '不允许上传此类文件');
    }
    if (!empty($settings[$type]['limit']) && $settings[$type]['limit'] * 1024 < filesize($file['tmp_name'])) {
        return error(-1, "上传的文件超过大小限制,请上传小于 {$settings[$type]['limit']}k 的文件");
    }
    $result = array();
    if (empty($name) || $name == 'auto') {
        $result['path'] = "{$settings[$type]['folder']}/" . date('Y/m/');
        mkdirs(ATTACHMENT_ROOT . '/' . $result['path']);
        do {
            $filename = random(30) . ".{$extention}";
        } while (file_exists(ATTACHMENT_ROOT . '/' . $result['path'] . $filename));
        $result['path'] .= $filename;
    } else {
        $result['path'] = $name . '.' . $extention;
    }
    if (!file_move($file['tmp_name'], ATTACHMENT_ROOT . '/' . $result['path'])) {
        return error(-1, '保存上传文件失败');
    }
    $result['success'] = true;
    return $result;
}
Пример #28
0
 public function fileUpload2($file, $type = 'image', $name = '')
 {
     if (empty($file)) {
         return '-1';
     }
     global $_W;
     if (empty($cfg['size'])) {
         $defsize = 2;
     }
     $deftype = array('jpg', 'png', 'jpeg');
     if (empty($_W['uploadsetting'])) {
         $_W['uploadsetting'] = array();
         $_W['uploadsetting'][$type]['folder'] = 'images';
         $_W['uploadsetting'][$type]['extentions'] = $deftype;
         $_W['uploadsetting'][$type]['limit'] = 1024 * $defsize;
     }
     $settings = $_W['uploadsetting'];
     if (!array_key_exists($type, $settings)) {
         return '-1';
     }
     $extention = pathinfo($file['name'], PATHINFO_EXTENSION);
     if (!in_array(strtolower($extention), $settings[$type]['extentions'])) {
         return '-1';
     }
     if (!empty($settings[$type]['limit']) && $settings[$type]['limit'] * 1024 < $file['size']) {
         return '-2';
     }
     $result = array();
     load()->func('file');
     if (empty($name) || $name == 'auto') {
         $result['path'] = "{$settings[$type]['folder']}/" . date('Y/m/');
         mkdirs(ATTACHMENT_ROOT . '/' . $result['path']);
         do {
             $filename = random(30) . ".{$extention}";
         } while (file_exists(ATTACHMENT_ROOT . '/' . $result['path'] . $filename));
         $result['path'] .= $filename;
     } else {
         $result['path'] = $name . '.' . $extention;
     }
     if (!file_move($file['tmp_name'], ATTACHMENT_ROOT . '/' . $result['path'])) {
         return '-3';
     }
     return $result;
 }
Пример #29
0
     }
 }
 if ($_FILES['preview'] && $_FILES['preview']['error'] == '0' && !empty($_FILES['preview']['tmp_name'])) {
     $t['preview'] = $_FILES['preview']['tmp_name'];
 }
 $manifest = manifest($t);
 load()->func('file');
 if ($_GPC['method'] == 'create') {
     $tpldir = IA_ROOT . '/app/themes/' . strtolower($t['template']['identifie']);
     if (is_dir($tpldir)) {
         message('模板目录' . $tpldir . '已存在,请更换模板标识还删除已存在模板');
     }
     mkdirs($tpldir);
     file_put_contents("{$tpldir}/manifest.xml", $manifest);
     if (!empty($t['preview'])) {
         file_move($t['preview'], "{$tpldir}/preview.jpg");
     }
     message('模板生成成功,请访问' . $tpldir . '目录进行查看', referer(), 'success');
     exit;
 }
 if ($_GPC['method'] == 'download') {
     $zipfile = IA_ROOT . '/data/temp.zip';
     $zip = new ZipArchive();
     $zip->open($zipfile, ZipArchive::CREATE);
     $zip->addFromString('manifest.xml', $manifest);
     if (!empty($t['preview'])) {
         $zip->addFile($t['preview'], "preview.jpg");
     }
     $zip->close();
     header('content-type: application/zip');
     header('content-disposition: attachment; filename="' . $t['template']['identifie'] . '.zip"');
Пример #30
0
 /**
  * Move directory to the specified path.
  *
  * @param $oldPath
  * @param $newPath
  *
  * @return bool
  */
 function directory_move($oldPath, $newPath)
 {
     return file_move($oldPath, $newPath);
 }