/** * Implements hook_setings_submit(). */ function nuboot_radix_settings_submit($form, &$form_state) { $settings = array(); // If the user entered a path relative to the system files directory for // for the hero unit, store a public:// URI so the theme system can handle it. if (!empty($values['hero_path'])) { $values['hero_path'] = _system_theme_settings_validate_path($values['hero_path']); } // Get the previous value. $previous = $form['hero']['hero_path']['#default_value']; if ($previous !== 'profiles/dkan/themes/contrib/nuboot_radix/assets/images/hero.jpg') { $previous = 'public://' . $previous; } else { $previous = FALSE; } if ($file = file_save_upload('hero_upload')) { $parts = pathinfo($file->filename); $destination = 'public://' . $parts['basename']; $file->status = FILE_STATUS_PERMANENT; if (file_copy($file, $destination, FILE_EXISTS_REPLACE)) { $_POST['hero_path'] = $form_state['values']['hero_path'] = $destination; // If new file has a different name than the old one, delete the old. if ($previous && $destination != $previous) { drupal_unlink($previous); } } } else { // Avoid error when the form is submitted without specifying a new image. $_POST['hero_path'] = $form_state['values']['hero_path'] = $previous; } }
/** * Submit handler */ function flux_theme_settings_submit($form, &$form_state) { $previous = theme_get_setting('cover_photo_path'); // If the user uploaded a new cover_photo or favicon, save it to a permanent location // and use it in place of the default theme-provided file. if (!empty($form_state['values']['cover_photo_upload'])) { $file = $form_state['values']['cover_photo_upload']; unset($form_state['values']['cover_photo_upload']); $filename = file_unmanaged_copy($file->uri, NULL, FILE_EXISTS_REPLACE); $form_state['values']['default_cover_photo'] = 0; $form_state['values']['cover_photo_path'] = $filename; $form_state['values']['toggle_cover_photo'] = 1; // Remove previous file uploaded $current = $form_state['values']['cover_photo_path']; if ($previous != $current && is_file($previous)) { // Delete previous file drupal_unlink($previous); } } // If the user entered a path relative to the system files directory for // a cover_photo or favicon, store a public:// URI so the theme system can handle it. if (!empty($form_state['values']['cover_photo_path'])) { $form_state['values']['cover_photo_path'] = flux_system_theme_settings_validate_path($form_state['values']['cover_photo_path']); } }
/** * Test directory handling functions. */ function testFileCheckDirectoryHandling() { // A directory to operate on. $directory = file_default_scheme() . '://' . $this->randomMachineName() . '/' . $this->randomMachineName(); $this->assertFalse(is_dir($directory), 'Directory does not exist prior to testing.'); // Non-existent directory. $this->assertFalse(file_prepare_directory($directory, 0), 'Error reported for non-existing directory.', 'File'); // Make a directory. $this->assertTrue(file_prepare_directory($directory, FILE_CREATE_DIRECTORY), 'No error reported when creating a new directory.', 'File'); // Make sure directory actually exists. $this->assertTrue(is_dir($directory), 'Directory actually exists.', 'File'); if (substr(PHP_OS, 0, 3) != 'WIN') { // PHP on Windows doesn't support any kind of useful read-only mode for // directories. When executing a chmod() on a directory, PHP only sets the // read-only flag, which doesn't prevent files to actually be written // in the directory on any recent version of Windows. // Make directory read only. @drupal_chmod($directory, 0444); $this->assertFalse(file_prepare_directory($directory, 0), 'Error reported for a non-writeable directory.', 'File'); // Test directory permission modification. $this->setSetting('file_chmod_directory', 0777); $this->assertTrue(file_prepare_directory($directory, FILE_MODIFY_PERMISSIONS), 'No error reported when making directory writeable.', 'File'); } // Test that the directory has the correct permissions. $this->assertDirectoryPermissions($directory, 0777, 'file_chmod_directory setting is respected.'); // Remove .htaccess file to then test that it gets re-created. @drupal_unlink(file_default_scheme() . '://.htaccess'); $this->assertFalse(is_file(file_default_scheme() . '://.htaccess'), 'Successfully removed the .htaccess file in the files directory.', 'File'); file_ensure_htaccess(); $this->assertTrue(is_file(file_default_scheme() . '://.htaccess'), 'Successfully re-created the .htaccess file in the files directory.', 'File'); // Verify contents of .htaccess file. $file = file_get_contents(file_default_scheme() . '://.htaccess'); $this->assertEqual($file, FileStorage::htaccessLines(FALSE), 'The .htaccess file contains the proper content.', 'File'); }
/** * {@inheritdoc} */ public function wipe() { parent::wipe(); $this->raw = ''; if (file_exists($this->uri)) { drupal_unlink($this->uri); } }
/** * Test read-only specific behavior. */ function testReadOnlyBehavior() { // Generate a test file $filename = $this->randomMachineName(); $site_path = $this->container->get('site.path'); $filepath = $site_path . '/files/' . $filename; file_put_contents($filepath, $filename); // Generate a read-only stream wrapper instance $uri = $this->scheme . '://' . $filename; file_stream_wrapper_get_instance_by_scheme($this->scheme); // Attempt to open a file in read/write mode $handle = @fopen($uri, 'r+'); $this->assertFalse($handle, 'Unable to open a file for reading and writing with the read-only stream wrapper.'); // Attempt to open a file in binary read mode $handle = fopen($uri, 'rb'); $this->assertTrue($handle, 'Able to open a file for reading in binary mode with the read-only stream wrapper.'); $this->assertTrue(fclose($handle), 'Able to close file opened in binary mode using the read_only stream wrapper.'); // Attempt to open a file in text read mode $handle = fopen($uri, 'rt'); $this->assertTrue($handle, 'Able to open a file for reading in text mode with the read-only stream wrapper.'); $this->assertTrue(fclose($handle), 'Able to close file opened in text mode using the read_only stream wrapper.'); // Attempt to open a file in read mode $handle = fopen($uri, 'r'); $this->assertTrue($handle, 'Able to open a file for reading with the read-only stream wrapper.'); // Attempt to change file permissions $this->assertFalse(@chmod($uri, 0777), 'Unable to change file permissions when using read-only stream wrapper.'); // Attempt to acquire an exclusive lock for writing $this->assertFalse(@flock($handle, LOCK_EX | LOCK_NB), 'Unable to acquire an exclusive lock using the read-only stream wrapper.'); // Attempt to obtain a shared lock $this->assertTrue(flock($handle, LOCK_SH | LOCK_NB), 'Able to acquire a shared lock using the read-only stream wrapper.'); // Attempt to release a shared lock $this->assertTrue(flock($handle, LOCK_UN | LOCK_NB), 'Able to release a shared lock using the read-only stream wrapper.'); // Attempt to truncate the file $this->assertFalse(@ftruncate($handle, 0), 'Unable to truncate using the read-only stream wrapper.'); // Attempt to write to the file $this->assertFalse(@fwrite($handle, $this->randomMachineName()), 'Unable to write to file using the read-only stream wrapper.'); // Attempt to flush output to the file $this->assertFalse(@fflush($handle), 'Unable to flush output to file using the read-only stream wrapper.'); // Attempt to close the stream. (Suppress errors, as fclose triggers fflush.) $this->assertTrue(fclose($handle), 'Able to close file using the read_only stream wrapper.'); // Test the rename() function $this->assertFalse(@rename($uri, $this->scheme . '://newname.txt'), 'Unable to rename files using the read-only stream wrapper.'); // Test the unlink() function $this->assertTrue(@drupal_unlink($uri), 'Able to unlink file using read-only stream wrapper.'); $this->assertTrue(file_exists($filepath), 'Unlink File was not actually deleted.'); // Test the mkdir() function by attempting to create a directory. $dirname = $this->randomMachineName(); $dir = $site_path . '/files/' . $dirname; $readonlydir = $this->scheme . '://' . $dirname; $this->assertFalse(@drupal_mkdir($readonlydir, 0775, 0), 'Unable to create directory with read-only stream wrapper.'); // Create a temporary directory for testing purposes $this->assertTrue(drupal_mkdir($dir), 'Test directory created.'); // Test the rmdir() function by attempting to remove the directory. $this->assertFalse(@drupal_rmdir($readonlydir), 'Unable to delete directory with read-only stream wrapper.'); // Remove the temporary directory. drupal_rmdir($dir); }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { if ($path = $form_state->getValue('import_tarball')) { $this->configStorage->deleteAll(); try { $archiver = new ArchiveTar($path, 'gz'); $files = array(); foreach ($archiver->listContent() as $file) { $files[] = $file['filename']; } $archiver->extractList($files, config_get_config_directory(CONFIG_SYNC_DIRECTORY)); drupal_set_message($this->t('Your configuration files were successfully uploaded and are ready for import.')); $form_state->setRedirect('config.sync'); } catch (\Exception $e) { drupal_set_message($this->t('Could not extract the contents of the tar file. The error message is <em>@message</em>', array('@message' => $e->getMessage())), 'error'); } drupal_unlink($path); } }
function academy_settings_submit($form, &$form_state) { $settings = array(); // Get the previous value $previous = 'public://' . $form['bg_image']['bg_path']['#default_value']; $file = file_save_upload('bg_upload'); if ($file) { $parts = pathinfo($file->filename); $destination = 'public://' . $parts['basename']; $file->status = FILE_STATUS_PERMANENT; if (file_copy($file, $destination, FILE_EXISTS_REPLACE)) { $_POST['bg_path'] = $form_state['values']['bg_path'] = $destination; // If new file has a different name than the old one, delete the old if ($destination != $previous) { drupal_unlink($previous); } } } else { // Avoid error when the form is submitted without specifying a new image $_POST['bg_path'] = $form_state['values']['bg_path'] = $previous; } }
/** * Test exportation of translations. */ public function testExportTranslation() { // First import some known translations. // This will also automatically add the 'fr' language. $name = tempnam('temporary://', "po_") . '.po'; file_put_contents($name, $this->getPoFile()); $this->drupalPostForm('admin/config/regional/translate/import', array('langcode' => 'fr', 'files[file]' => $name), t('Import')); drupal_unlink($name); // Get the French translations. $this->drupalPostForm('admin/config/regional/translate/export', array('langcode' => 'fr'), t('Export')); // Ensure we have a translation file. $this->assertRaw('# French translation of Drupal', 'Exported French translation file.'); // Ensure our imported translations exist in the file. $this->assertRaw('msgstr "lundi"', 'French translations present in exported file.'); // Import some more French translations which will be marked as customized. $name = tempnam('temporary://', "po2_") . '.po'; file_put_contents($name, $this->getCustomPoFile()); $this->drupalPostForm('admin/config/regional/translate/import', array('langcode' => 'fr', 'files[file]' => $name, 'customized' => 1), t('Import')); drupal_unlink($name); // Create string without translation in the locales_source table. $this->container->get('locale.storage')->createString()->setString('February')->save(); // Export only customized French translations. $this->drupalPostForm('admin/config/regional/translate/export', array('langcode' => 'fr', 'content_options[not_customized]' => FALSE, 'content_options[customized]' => TRUE, 'content_options[not_translated]' => FALSE), t('Export')); // Ensure we have a translation file. $this->assertRaw('# French translation of Drupal', 'Exported French translation file with only customized strings.'); // Ensure the customized translations exist in the file. $this->assertRaw('msgstr "janvier"', 'French custom translation present in exported file.'); // Ensure no untranslated strings exist in the file. $this->assertNoRaw('msgid "February"', 'Untranslated string not present in exported file.'); // Export only untranslated French translations. $this->drupalPostForm('admin/config/regional/translate/export', array('langcode' => 'fr', 'content_options[not_customized]' => FALSE, 'content_options[customized]' => FALSE, 'content_options[not_translated]' => TRUE), t('Export')); // Ensure we have a translation file. $this->assertRaw('# French translation of Drupal', 'Exported French translation file with only untranslated strings.'); // Ensure no customized translations exist in the file. $this->assertNoRaw('msgstr "janvier"', 'French custom translation not present in exported file.'); // Ensure the untranslated strings exist in the file, and with right quotes. $this->assertRaw($this->getUntranslatedString(), 'Empty string present in exported file.'); }
/** * This ensures the resolution of a specific file is within bounds. * The image will be resized if it's too large. */ function testFileValidateImageResolution() { // Non-images. $errors = file_validate_image_resolution($this->non_image); $this->assertEqual(count($errors), 0, 'Should not get any errors for a non-image file.', 'File'); $errors = file_validate_image_resolution($this->non_image, '50x50', '100x100'); $this->assertEqual(count($errors), 0, 'Do not check the resolution on non files.', 'File'); // Minimum size. $errors = file_validate_image_resolution($this->image); $this->assertEqual(count($errors), 0, 'No errors for an image when there is no minimum or maximum resolution.', 'File'); $errors = file_validate_image_resolution($this->image, 0, '200x1'); $this->assertEqual(count($errors), 1, 'Got an error for an image that was not wide enough.', 'File'); $errors = file_validate_image_resolution($this->image, 0, '1x200'); $this->assertEqual(count($errors), 1, 'Got an error for an image that was not tall enough.', 'File'); $errors = file_validate_image_resolution($this->image, 0, '200x200'); $this->assertEqual(count($errors), 1, 'Small images report an error.', 'File'); // Maximum size. if ($this->container->get('image.factory')->getToolkitId()) { // Copy the image so that the original doesn't get resized. copy('core/misc/druplicon.png', 'temporary://druplicon.png'); $this->image->setFileUri('temporary://druplicon.png'); $errors = file_validate_image_resolution($this->image, '10x5'); $this->assertEqual(count($errors), 0, 'No errors should be reported when an oversized image can be scaled down.', 'File'); $image = $this->container->get('image.factory')->get($this->image->getFileUri()); $this->assertTrue($image->getWidth() <= 10, 'Image scaled to correct width.', 'File'); $this->assertTrue($image->getHeight() <= 5, 'Image scaled to correct height.', 'File'); // Once again, now with negative width and height to force an error. copy('core/misc/druplicon.png', 'temporary://druplicon.png'); $this->image->setFileUri('temporary://druplicon.png'); $errors = file_validate_image_resolution($this->image, '-10x-5'); $this->assertEqual(count($errors), 1, 'An error reported for an oversized image that can not be scaled down.', 'File'); drupal_unlink('temporary://druplicon.png'); } else { // TODO: should check that the error is returned if no toolkit is available. $errors = file_validate_image_resolution($this->image, '5x10'); $this->assertEqual(count($errors), 1, 'Oversize images that cannot be scaled get an error.', 'File'); } }
/** * {@inheritdoc} */ public function delete($name) { if (!$this->exists($name)) { $dir = $this->getCollectionDirectory(); if (!file_exists($dir)) { throw new StorageException($dir . '/ not found.'); } return FALSE; } return drupal_unlink($this->getFilePath($name)); }
/** * Handles multipart uploads. * * @throws \Drupal\plupload\UploadException */ protected function handleUpload() { /* @var $multipart_file \Symfony\Component\HttpFoundation\File\UploadedFile */ $is_multipart = strpos($this->request->headers->get('Content-Type'), 'multipart') !== FALSE; // If this is a multipart upload there needs to be a file on the server. if ($is_multipart) { $multipart_file = $this->request->files->get('file', array()); // TODO: Not sure if this is the best check now. // Originally it was: // if (empty($multipart_file['tmp_name']) || !is_uploaded_file($multipart_file['tmp_name'])) { if (!$multipart_file->getPathname() || !is_uploaded_file($multipart_file->getPathname())) { throw new UploadException(UploadException::MOVE_ERROR); } } // Open temp file. if (!($out = fopen($this->temporaryUploadLocation . $this->getFilename(), $this->request->request->get('chunk', 0) ? 'ab' : 'wb'))) { throw new UploadException(UploadException::OUTPUT_ERROR); } // Read binary input stream. $input_uri = $is_multipart ? $multipart_file->getRealPath() : 'php://input'; if (!($in = fopen($input_uri, 'rb'))) { throw new UploadException(UploadException::INPUT_ERROR); } // Append input stream to temp file. while ($buff = fread($in, 4096)) { fwrite($out, $buff); } // Be nice and keep everything nice and clean. fclose($in); fclose($out); if ($is_multipart) { drupal_unlink($multipart_file->getRealPath()); } }
/** * Helper function: install languages. */ protected function installLanguages() { foreach ($this->languages as $langcode => $name) { // Generate custom .po contents for the language. $contents = $this->poFileContents($langcode); if ($contents) { // Add test language for translation testing. $edit = array('predefined_langcode' => 'custom', 'langcode' => $langcode, 'label' => $name, 'direction' => LanguageInterface::DIRECTION_LTR); // Install the language in Drupal. $this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add custom language')); $this->assertRaw('"edit-languages-' . $langcode . '-weight"', 'Language code found.'); // Import the custom .po contents for the language. $filename = tempnam('temporary://', "po_") . '.po'; file_put_contents($filename, $contents); $options = array('files[file]' => $filename, 'langcode' => $langcode, 'customized' => TRUE); $this->drupalPostForm('admin/config/regional/translate/import', $options, t('Import')); drupal_unlink($filename); } } $this->container->get('language_manager')->reset(); }
/** * Helper function: import a standalone .po file in a given language. * * @param string $contents * Contents of the .po file to import. * @param array $options * (optional) Additional options to pass to the translation import form. */ public function importPoFile($contents, array $options = array()) { $name = tempnam('temporary://', "po_") . '.po'; file_put_contents($name, $contents); $options['files[file]'] = $name; $this->drupalPostForm('admin/config/regional/translate/import', $options, t('Import')); drupal_unlink($name); }
/** * Implements Drupal\Core\FileTransfer\FileTransfer::removeFileJailed(). */ protected function removeFileJailed($file) { if (@(!drupal_unlink($file))) { throw new FileTransferException('Cannot remove file %file.', NULL, array('%file' => $file)); } }
function hoteldiamond_sublayer_delete($form, &$form_state) { $SlideId = $form_state['triggering_element']['#parents'][2]; $LayerId = $form_state['triggering_element']['#parents'][4]; @drupal_unlink($form_state['values']['slider']['layers'][$SlideId]['sublayers'][$LayerId]['image']['path']); unset($form_state['values']['slider']['layers'][$SlideId]['sublayers'][$LayerId]); variable_set($form_state['values']['var'], $form_state['values']); drupal_set_message(t('Layer deleted.')); }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { global $config_directories, $install_state; $sync_directory = $form_state->getValue('sync_directory'); if ($sync_directory != config_get_config_directory(CONFIG_SYNC_DIRECTORY)) { $settings['config_directories'][CONFIG_SYNC_DIRECTORY] = (object) array('value' => $sync_directory, 'required' => TRUE); drupal_rewrite_settings($settings); $config_directories[CONFIG_SYNC_DIRECTORY] = $sync_directory; } if ($path = $form_state->getValue('import_tarball')) { // Ensure that we have an empty directory if we're going. $sync = new FileStorage($sync_directory); $sync->deleteAll(); try { $archiver = new ArchiveTar($path, 'gz'); $files = array(); foreach ($archiver->listContent() as $file) { $files[] = $file['filename']; } $archiver->extractList($files, config_get_config_directory(CONFIG_SYNC_DIRECTORY)); drupal_set_message($this->t('Your configuration files were successfully uploaded, ready for import.')); } catch (\Exception $e) { drupal_set_message($this->t('Could not extract the contents of the tar file. The error message is <em>@message</em>', array('@message' => $e->getMessage())), 'error'); } drupal_unlink($path); } // Change the langcode to the site default langcode provided by the // configuration. $config_storage = new FileStorage(config_get_config_directory(CONFIG_SYNC_DIRECTORY)); $install_state['parameters']['langcode'] = $config_storage->read('system.site')['langcode']; }
/** * Support for unlink(). * * @param string $uri * A string containing the URI to the resource to delete. * * @return bool * TRUE if resource was successfully deleted. * * @see http://php.net/manual/streamwrapper.unlink.php */ public function unlink($uri) { $this->uri = $uri; return drupal_unlink($this->getLocalPath()); }