function file_upload($fileUrl, $file_path = "files") { //echo $file_path; // echo 's3://'.$fileUrl; $file_temp = file_get_contents('http://www.voteapps.com/' . $fileUrl); //print_r(); //Saves a file to the specified destination and creates a database entry. if (!file_exists($public_path . '/apkfiles')) { drupal_mkdir($public_path . '/apkfiles'); } $file_arry = file_save_data($file_temp, 's3://' . $fileUrl, FILE_EXISTS_REPLACE); //print_r($file_arry); //转存视频和图片 if ($file_arry) { // echo "</br>上传成功..."; return $file_arry; } else { //echo "</br>再次尝试上传..."; $file_arry = file_save_data($file_temp, 's3://' . $fileUrl, FILE_EXISTS_REPLACE); if ($file_arry) { //清空视频 //unlink($$fileUrl); // echo "</br>上传成功..."; return $file_arry; } else { //清空视频 // unlink($$fileUrl); // echo "</br>上传失败..."; return $file_arry; //header('HTTP/1.1 500 Internal Server Error'); //exit; } } }
/** * 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; } }
/** * Test local directory handling functions. */ function testFileCheckLocalDirectoryHandling() { $site_path = $this->container->get('site.path'); $directory = $site_path . '/files'; // Check a new recursively created local directory for correct file system // permissions. $parent = $this->randomMachineName(); $child = $this->randomMachineName(); // Files directory already exists. $this->assertTrue(is_dir($directory), t('Files directory already exists.'), 'File'); // Make files directory writable only. $old_mode = fileperms($directory); // Create the directories. $parent_path = $directory . DIRECTORY_SEPARATOR . $parent; $child_path = $parent_path . DIRECTORY_SEPARATOR . $child; $this->assertTrue(drupal_mkdir($child_path, 0775, TRUE), t('No error reported when creating new local directories.'), 'File'); // Ensure new directories also exist. $this->assertTrue(is_dir($parent_path), t('New parent directory actually exists.'), 'File'); $this->assertTrue(is_dir($child_path), t('New child directory actually exists.'), 'File'); // Check that new directory permissions were set properly. $this->assertDirectoryPermissions($parent_path, 0775); $this->assertDirectoryPermissions($child_path, 0775); // Check that existing directory permissions were not modified. $this->assertDirectoryPermissions($directory, $old_mode); // Check creating a directory using an absolute path. $absolute_path = drupal_realpath($directory) . DIRECTORY_SEPARATOR . $this->randomMachineName() . DIRECTORY_SEPARATOR . $this->randomMachineName(); $this->assertTrue(drupal_mkdir($absolute_path, 0775, TRUE), 'No error reported when creating new absolute directories.', 'File'); $this->assertDirectoryPermissions($absolute_path, 0775); }
/** * Preprocess Page */ function superhero_preprocess_page(&$vars) { $theme = superhero_get_theme(); $theme->page =& $vars; $vars['attributes_array']['class'] = array('body'); // Primary nav $vars['primary_nav'] = FALSE; if ($vars['main_menu']) { // Build links $vars['primary_nav'] = menu_tree(variable_get('menu_main_links_source', 'main-menu')); // Provide default theme wrapper function $vars['primary_nav']['#theme_wrappers'] = array('menu_tree__primary'); } $default_preset = $theme->settings['default_preset']; $force = false; $superhero_base_url = variable_get('superhero_base_url', ''); global $base_url; if ($superhero_base_url != $base_url) { $force = true; } variable_set('superhero_base_url', $base_url); require_once dirname(__FILE__) . '/includes/superhero_scss.php'; $scss = new Superhero_scss($theme); if (!file_exists('public://css')) { drupal_mkdir('public://css'); } $file = $scss->outputFile('public://css/' . $theme->theme . '-theme-preset' . ($default_preset + 1) . '.css', $force); drupal_add_css($file, array('type' => 'file', 'group' => CSS_THEME)); }
/** * Invokes system_retrieve_file() in several scenarios. */ function testFileRetrieving() { // Test 404 handling by trying to fetch a randomly named file. drupal_mkdir($sourcedir = 'public://' . $this->randomMachineName()); $filename = 'Файл для тестирования ' . $this->randomMachineName(); $url = file_create_url($sourcedir . '/' . $filename); $retrieved_file = system_retrieve_file($url); $this->assertFalse($retrieved_file, 'Non-existent file not fetched.'); // Actually create that file, download it via HTTP and test the returned path. file_put_contents($sourcedir . '/' . $filename, 'testing'); $retrieved_file = system_retrieve_file($url); // URLs could not contains characters outside the ASCII set so $filename // has to be encoded. $encoded_filename = rawurlencode($filename); $this->assertEqual($retrieved_file, 'public://' . $encoded_filename, 'Sane path for downloaded file returned (public:// scheme).'); $this->assertTrue(is_file($retrieved_file), 'Downloaded file does exist (public:// scheme).'); $this->assertEqual(filesize($retrieved_file), 7, 'File size of downloaded file is correct (public:// scheme).'); file_unmanaged_delete($retrieved_file); // Test downloading file to a different location. drupal_mkdir($targetdir = 'temporary://' . $this->randomMachineName()); $retrieved_file = system_retrieve_file($url, $targetdir); $this->assertEqual($retrieved_file, "{$targetdir}/{$encoded_filename}", 'Sane path for downloaded file returned (temporary:// scheme).'); $this->assertTrue(is_file($retrieved_file), 'Downloaded file does exist (temporary:// scheme).'); $this->assertEqual(filesize($retrieved_file), 7, 'File size of downloaded file is correct (temporary:// scheme).'); file_unmanaged_delete($retrieved_file); file_unmanaged_delete_recursive($sourcedir); file_unmanaged_delete_recursive($targetdir); }
function mylog($data, $file_name) { if (file_destination('public://log', FILE_EXISTS_ERROR)) { // The file doesn't exist. do something drupal_mkdir('public://log'); } file_save_data(print_r($data, true), "public://log/{$file_name}", FILE_EXISTS_REPLACE); }
public static function directory_cache($subdir = '') { $dir = UPAL_TMP . '/' . $subdir; if (!file_exists($dir)) { drupal_mkdir($dir, NULL, TRUE); } return $dir; }
/** * 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); }
/** * Test the import subscriber. */ public function testSubscribers() { // Without this the config exporter breaks. \Drupal::service('config.installer')->installDefaultConfig('module', 'config_devel'); $filename = vfsStream::url('public://' . static::CONFIGNAME . '.yml'); drupal_mkdir(vfsStream::url('public://exported')); $exported_filename = vfsStream::url('public://exported/' . static::CONFIGNAME . '.yml'); \Drupal::configFactory()->getEditable('config_devel.settings')->set('auto_import', array(array('filename' => $filename, 'hash' => '')))->set('auto_export', array($exported_filename))->save(); $this->storage = \Drupal::service('config.storage'); $this->assertFalse($this->storage->exists(static::CONFIGNAME)); $subscriber = \Drupal::service('config_devel.auto_import_subscriber'); for ($i = 2; $i; $i--) { $data['label'] = $this->randomString(); file_put_contents($filename, Yaml::encode($data)); // The import fires an export too. $subscriber->autoImportConfig(); $this->doAssert($data, Yaml::decode(file_get_contents($exported_filename))); } }
/** * {@inheritdoc} */ protected function setUpSyncForm() { // Create a new sync directory. drupal_mkdir($this->sync_dir); // Extract the tarball into the sync directory. $archiver = new ArchiveTar($this->tarball, 'gz'); $files = array(); foreach ($archiver->listContent() as $file) { $files[] = $file['filename']; } $archiver->extractList($files, $this->sync_dir); // Change the user.settings::register so that we can test that // standard_install() does not override it. $sync = new FileStorage($this->sync_dir); $user_settings = $sync->read('user.settings'); $user_settings['register'] = USER_REGISTER_ADMINISTRATORS_ONLY; $sync->write('user.settings', $user_settings); $this->drupalPostForm(NULL, array('sync_directory' => drupal_realpath($this->sync_dir)), 'Save and continue'); }
/** * Returns TRUE if the path is a directory or we can create one in that path. */ public static function checkDirectory($dir_path) { if (!is_dir($dir_path)) { if (drupal_mkdir($dir_path, NULL, TRUE)) { return TRUE; } else { // If the directory does not exists and cannot be created. drupal_set_message(st('The directory %directory does not exist and could not be created.', array('%directory' => $dir_path)), 'error'); watchdog('file system', 'The directory %directory does not exist and could not be created.', array('%directory' => $dir_path), WATCHDOG_ERROR); return FALSE; } } else { if (is_writable($dir_path) || drupal_chmod($dir_path)) { return TRUE; } watchdog('configuration', 'The current user does not have write permissions in the directory %dir.', array('%dir' => $dir_path), WATCHDOG_ERROR); drupal_set_message(t('The current user does not have write permissions in the directory %dir.', array('%dir' => $dir_path)), 'error', FALSE); } return FALSE; }
function unl_reset_site_submit($form, &$form_state) { $nids = db_select('node', 'n')->fields('n', array('nid'))->execute()->fetchCol(); node_delete_multiple($nids); variable_set('site_frontpage', 'node'); $mlids = db_select('menu_links', 'm')->fields('m', array('mlid'))->condition('m.menu_name', 'main-menu')->execute()->fetchCol(); foreach ($mlids as $mlid) { menu_link_delete($mlid); } $home_link = array('link_path' => '<front>', 'link_title' => 'Home', 'menu_name' => 'main-menu', 'module' => 'menu'); menu_link_save($home_link); $fids = db_select('file_managed', 'f')->fields('f', array('fid'))->execute()->fetchCol(); $files = file_load_multiple($fids); foreach ($files as $file) { file_delete($file); } $files_dir = DRUPAL_ROOT . '/' . conf_path() . '/files/'; $cmd = 'rm -rf ' . $files_dir . '*'; echo shell_exec($cmd); drupal_mkdir('public://styles/'); variable_set('site_name', 'Site Name'); }
/** * Overrides \Drupal\Core\Database\Connection::createDatabase(). * * @param string $database * The name of the database to create. * * @throws \Drupal\Core\Database\DatabaseNotFoundException */ public function createDatabase($database) { // Verify the database is writable. $db_directory = new \SplFileInfo(dirname($database)); if (!$db_directory->isDir() && !drupal_mkdir($db_directory->getPathName(), 0755, TRUE)) { throw new DatabaseNotFoundException('Unable to create database directory ' . $db_directory->getPathName()); } }
/** * Create a directory and assert it exists. * * @param $path * Optional string with a directory path. If none is provided, a random * name in the site's files directory will be used. * @return * The path to the directory. */ function createDirectory($path = NULL) { // A directory to operate on. if (!isset($path)) { $path = file_default_scheme() . '://' . $this->randomMachineName(); } $this->assertTrue(drupal_mkdir($path) && is_dir($path), 'Directory was created successfully.'); return $path; }
/** * Writes a file to the file system, creating its directory as needed. * * @param string $directory * The extension's directory. * @param array $file * Array with the following keys: * - 'filename': the name of the file. * - 'subdirectory': any subdirectory of the file within the extension * directory. * - 'string': the contents of the file. * * @throws Exception */ protected function generateFile($directory, array $file) { if (!empty($file['subdirectory'])) { $directory .= '/' . $file['subdirectory']; } if (!is_dir($directory)) { if (drupal_mkdir($directory, NULL, TRUE) === FALSE) { throw new \Exception($this->t('Failed to create directory @directory.', ['@directory' => $directory])); } } if (file_put_contents($directory . '/' . $file['filename'], $file['string']) === FALSE) { throw new \Exception($this->t('Failed to write file @filename.', ['@filename' => $file['filename']])); } }
/** * Backup Theme Settings */ function md_boom_multi_backup_theme_settings() { $theme_settings = variable_get('theme_md_boom_multi_settings'); $current_time = time(); $cv_datetime = date("Y-m-d", $current_time); $backup_file = serialize(base64_encode(drupal_json_encode($theme_settings))); $bu_folder = 'public://md_boom_multi_backup'; if (file_prepare_directory($bu_folder) === false) { drupal_mkdir($bu_folder); } if (file_unmanaged_save_data($backup_file, $bu_folder . '/backup-' . $cv_datetime . '-' . $current_time . '.txt', FILE_EXISTS_REPLACE) === FALSE) { drupal_set_message(t("Could not create backup file.")); return; } else { drupal_set_message(t("Backup Theme Settings Successful!")); } }
/** * Support for mkdir(). * * @param string $uri * A string containing the URI to the directory to create. * @param int $mode * Permission flags - see mkdir(). * @param int $options * A bit mask of STREAM_REPORT_ERRORS and STREAM_MKDIR_RECURSIVE. * * @return bool * TRUE if directory was successfully created. * * @see http://php.net/manual/streamwrapper.mkdir.php */ public function mkdir($uri, $mode, $options) { $this->uri = $uri; $recursive = (bool) ($options & STREAM_MKDIR_RECURSIVE); if ($recursive) { // $this->getLocalPath() fails if $uri has multiple levels of directories // that do not yet exist. $localpath = $this->getDirectoryPath() . '/' . $this->getTarget($uri); } else { $localpath = $this->getLocalPath($uri); } if ($options & STREAM_REPORT_ERRORS) { return drupal_mkdir($localpath, $mode, $recursive); } else { return @drupal_mkdir($localpath, $mode, $recursive); } }
/** * Backup Theme Settings */ function md_leaders_backup_theme_settings() { global $theme_key; $theme_settings = variable_get('theme_md_leaders_settings'); $current_time = time(); $cv_datetime = date("Y-m-d", $current_time); $backup_file = serialize(base64_encode(drupal_json_encode($theme_settings))); $bu_folder = 'public://md_leaders_backup'; if (file_prepare_directory($bu_folder) === false) { drupal_mkdir($bu_folder); } if (file_unmanaged_save_data($backup_file, $bu_folder . '/' . str_replace('_', '-', 'md_leaders') . '-backup-' . $cv_datetime . '-' . $current_time . '.txt', FILE_EXISTS_REPLACE) === FALSE) { drupal_set_message(t("Could not create backup file.")); return; } else { drupal_set_message(t("Backup Theme Settings Successful!")); drupal_set_message(t("Your backup settings is stored in " . file_create_url('' . $bu_folder . '/' . str_replace('_', '-', 'md_leaders') . '-backup-' . $cv_datetime . '-' . $current_time . '.txt') . "")); } }
// Handling with the person photo. if (empty($node->field_person_photo[LANGUAGE_NONE][0])) { continue; } $personal_photo = $node->field_person_photo[LANGUAGE_NONE][0]; if (strpos($personal_photo['uri'], 'private://') !== 0) { drush_log(dt('The person photo(@name) is already public - skipping.', array('@name' => $value['filename'])), 'warning'); continue; } $file = file_load($personal_photo['fid']); // Building the new path of the file. $destination = str_replace('private://', 'public://', $file->uri); // Create the destined folder if it's not exists. if (!is_dir(get_destination_dir($destination))) { // Creating the folder. drupal_mkdir($destination_folder, NULL, TRUE); } $moved_file = @file_move($file, $destination); if ($moved_file) { drush_log(dt('File @name moved successfully.', array('@name' => $file->filename)), 'success'); } $file->uri = $moved_file->uri; file_save($file); drush_log(dt('File @name updated successfully.', array('@name' => $file->filename)), 'success'); $flush_cache = TRUE; } // Flushing caches for rebuild filed data. if ($flush_cache) { drush_log(dt('Flushing the cache for update the files field data.'), 'warning'); drupal_flush_all_caches(); }
/** * Tests for log entry on failing destination. */ function testDrupalMovingUploadedFileError() { // Create a directory and make it not writable. $test_directory = 'test_drupal_move_uploaded_file_fail'; drupal_mkdir('temporary://' . $test_directory, 00); $this->assertTrue(is_dir('temporary://' . $test_directory)); $edit = array('file_subdir' => $test_directory, 'files[file_test_upload]' => drupal_realpath($this->image->getFileUri())); \Drupal::state()->set('file_test.disable_error_collection', TRUE); $this->drupalPostForm('file-test/upload', $edit, t('Submit')); $this->assertResponse(200, 'Received a 200 response for posted test file.'); $this->assertRaw(t('File upload error. Could not move uploaded file.'), 'Found the failure message.'); $this->assertRaw(t('Epic upload FAIL!'), 'Found the failure message.'); // Uploading failed. Now check the log. $this->drupalGet('admin/reports/dblog'); $this->assertResponse(200); $this->assertRaw(t('Upload error. Could not move uploaded file @file to destination @destination.', array('@file' => $this->image->getFilename(), '@destination' => 'temporary://' . $test_directory . '/' . $this->image->getFilename())), 'Found upload error log entry.'); }
/** * Returns the git clone file system directory path. * * @param bool $create * Toggle determining whether or not to create the directory if it does not * exist. * @param bool $absolute * Toggle determining whether or not to return the entire system path. If * FALSE, it will be prefixed with the gitclone:// stream wrapper. * * @return string|FALSE * The git clone path or FALSE on error. */ public function getPath($create = TRUE, $absolute = TRUE) { if (empty($this->refType) || empty($this->ref) || empty($this->name)) { return FALSE; } $path = "gitclone://{$this->refType}/{$this->name}"; if ($create) { if (!is_dir($path) && !drupal_mkdir($path, NULL, TRUE)) { drupal_set_message(t('The directory %directory does not exist and could not be created.', array('%directory' => $path)), 'error'); return FALSE; } if (is_dir($path) && !is_writable($path) && !drupal_chmod($path)) { drupal_set_message(t('The directory %directory exists but is not writable and could not be made writable.', array('%directory' => $path)), 'error'); return FALSE; } } else { if (!is_dir($path)) { return FALSE; } if (!drupal_is_cli() && is_dir($path) && !is_writable($path) && !drupal_chmod($path)) { drupal_set_message(t('The directory %directory exists but is not writable and could not be made writable.', array('%directory' => $path)), 'error'); } } if ($absolute) { return drupal_realpath($path); } return $path; }
function get_store_of_collection($nid) { if (!is_integer($nid)) { $nid = intval($nid); } // try to convert $nid to integer $store_dir = strval3(floor($nid / 1000)); // archive $archive_store_path = 'public://digicoll' . DIRECTORY_SEPARATOR . 'archive'; $archive_path = $archive_store_path . DIRECTORY_SEPARATOR . $store_dir; if (!file_exists($archive_path)) { drupal_mkdir($archive_path); } // archive0 $archive0_store_path = 'public://digicoll' . DIRECTORY_SEPARATOR . 'archive0'; $archive0_path = $archive0_store_path . DIRECTORY_SEPARATOR . $store_dir; if (!file_exists($archive0_path)) { drupal_mkdir($archive0_path); } // archive_mosbk $archive_mosbk_store_path = 'public://digicoll' . DIRECTORY_SEPARATOR . 'archive_mosbk'; $archive_mosbk_path = $archive_mosbk_store_path . DIRECTORY_SEPARATOR . $store_dir; if (!file_exists($archive_mosbk_path)) { drupal_mkdir($archive_mosbk_path); } // public $public_store_path = 'public://digicoll' . DIRECTORY_SEPARATOR . 'public'; $public_path = $public_store_path . DIRECTORY_SEPARATOR . $store_dir; if (!file_exists($public_path)) { drupal_mkdir($public_path); } // public0 $public0_store_path = 'public://digicoll' . DIRECTORY_SEPARATOR . 'public0'; $public0_path = $public0_store_path . DIRECTORY_SEPARATOR . $store_dir; if (!file_exists($public0_path)) { drupal_mkdir($public0_path); } // meta $meta_store_path = 'public://digicoll' . DIRECTORY_SEPARATOR . 'meta'; $meta_path = $meta_store_path . DIRECTORY_SEPARATOR . $store_dir; if (!file_exists($meta_path)) { drupal_mkdir($meta_path); } return array($archive_path, $archive0_path, $archive_mosbk_path, $public_path, $public0_path, $meta_path); }
/** * create folder for images download * @return boolean return always boolean */ function createFolder() { if (file_exists(PATH) === FALSE || is_dir(PATH) === FALSE) { return drupal_mkdir(PATH, 0755); } return TRUE; }
public function saveLayoutSuggestionsMarkup() { $template_suggestions = array(); if (!empty($this->form_values['settings_suggestions'])) { $template_suggestions = $this->form_values['settings_suggestions']; } if (!empty($this->form_values['ts_name'])) { $template_suggestions['page__' . $this->form_values['ts_name']] = 'page__' . $this->form_values['ts_name']; } // Don't regenerate templates to be deleted. foreach ($this->form_values as $values_key => $values_value) { if (substr($values_key, 0, 18) === 'delete_suggestion_') { if ($values_value === 1) { $delete_suggestion_keys[] = Unicode::substr($values_key, 18); } } } if (!empty($delete_suggestion_keys)) { foreach ($delete_suggestion_keys as $template_to_remove) { unset($template_suggestions[$template_to_remove]); } } // Template path $template_file = $this->layout_path . '/' . $this->layout_name . '.html.twig'; // Path to target theme where the template will be saved. $path = drupal_get_path('theme', $this->theme_name); $template_directory = $path . '/templates/page'; if (!file_exists($path . '/templates')) { drupal_mkdir($path . '/templates'); } if (!file_exists($template_directory)) { drupal_mkdir($template_directory); } // We have to save every template every time, in case a row has been added to the layout, all template MUST update. // This could be changed later to only do this IF a row has been added, we're not that flash right now :) foreach ($template_suggestions as $suggestion_key => $suggestions_name) { $output = array(); $suggestion_key = Html::escape($suggestion_key); // Doc block $doc = array(); $doc[$suggestion_key][] = '{#'; $doc[$suggestion_key][] = '/**'; $doc[$suggestion_key][] = ' * ' . $this->layout_name . ' ' . $suggestion_key . ' template.'; $doc[$suggestion_key][] = ' * Generated on: ' . date(DATE_RFC822); $doc[$suggestion_key][] = ' */'; $doc[$suggestion_key][] = '#}' . "\n"; $docblock[$suggestion_key] = implode("\n", $doc[$suggestion_key]); // Attach layout $generated_files_path = $this->form_values['settings_generated_files_path']; $layout_file = $this->theme_name . '.layout.' . str_replace('_', '-', $suggestion_key) . '.css'; if (file_exists($generated_files_path .'/'. $layout_file)) { $library = $this->theme_name .'/'. $this->theme_name . '.layout.' . $suggestion_key; } else { $library = $this->theme_name .'/'. $this->theme_name . '.layout.page'; } $attach_layout = "{{ attach_library('$library') }}"; // Get the template file, if not found attempt to generate template code programmatically. if (file_exists($template_file)) { $template = file_get_contents($template_file); } else { foreach ($this->layout_config['rows'] as $row => $row_values) { // Row attributes. $attributes[$row]['class'][] = 'l-pr page__row'; $attributes[$row]['class'][] = 'pr-' . $row; foreach ($row_values['attributes'] as $attribute_type => $attribute_values) { if (is_array($attribute_values)) { $attributes[$row][$attribute_type][] = implode(' ', $attribute_values); } else { $attributes[$row][$attribute_type][] = $attribute_values; } } ksort($attributes[$row], SORT_STRING); foreach ($attributes[$row] as $attr_type => $attr_array_vales) { $attr_array_vales = array_unique($attr_array_vales); $this_row_attr[$row][$attr_type] = $attr_type . '="' . implode(' ', $attr_array_vales) . '"'; } $wrapper_element[$suggestion_key] = 'div'; if ($row == 'header' || $row == 'footer') { $wrapper_element[$suggestion_key] = $row; } $output[$suggestion_key][$row]['prefix'] = ' {% if '. $row . '__regions.active == true %}'; $output[$suggestion_key][$row]['wrapper_open'] = ' <'. $wrapper_element[$suggestion_key] . '{{ ' . $row . '__wrapper_attributes }}>'; $output[$suggestion_key][$row]['container_open'] = ' <div{{ ' . $row . '__container_attributes }}>'; foreach ($row_values['regions'] as $region_name => $region_value) { $row_regions[$suggestion_key][$row][] = ' {{ page.' . $region_name . ' }}'; } $output[$suggestion_key][$row]['regions'] = implode("\n", $row_regions[$suggestion_key][$row]); $output[$suggestion_key][$row]['container_close'] = ' </div>'; $output[$suggestion_key][$row]['wrapper_close'] = ' </' . $wrapper_element[$suggestion_key] . '>'; $output[$suggestion_key][$row]['suffix'] = ' {% endif %}' . "\n"; } //$generated[$suggestion_key][] = "{# No template file found - template code programmatically generated. #}" . "\n"; $generated[$suggestion_key][] = '<div{{ attributes }}>'. "\n"; foreach ($output[$suggestion_key] as $row_output) { $generated[$suggestion_key][] = implode("\n", $row_output); } $generated[$suggestion_key][] = " {{ attribution }}" . "\n"; $generated[$suggestion_key][] = '</div>'; $template[$suggestion_key] = implode($generated[$suggestion_key]); } // Prepend the docblock to the template markup. $template_markup[$suggestion_key] = $docblock[$suggestion_key] . $attach_layout . "\n" . $template[$suggestion_key]; // Set the template file, either it's page or a page suggestion. if ($suggestion_key !== 'page') { $template_file = str_replace('_', '-', $suggestion_key) . '.html.twig'; } else { $template_file = 'page.html.twig'; } // Set the template path. $template_path = $template_directory . '/' . $template_file; // Build array of files to be saved. $templates[$suggestion_key]['markup'] = $template_markup[$suggestion_key]; $templates[$suggestion_key]['template_path'] = $template_path; // Create a backup. if ($this->form_values['settings_enable_backups'] == 1) { $fileOperations = new FileOperations(); $directoryOperations = new DirectoryOperations(); $backup_path = $directoryOperations->directoryPrepare($backup_file_path = array($path, 'backup', 'templates')); //Add a date time string to make unique and for easy identification, save as .txt to avoid conflicts. $backup_file = $template_file . '.' . date(DATE_ISO8601) . '.txt'; $file_paths = array( 'copy_source' => $template_path, 'copy_dest' => $backup_path . '/' . $template_file, 'rename_oldname' => $backup_path . '/' . $template_file, 'rename_newname' => $backup_path . '/' . $backup_file, ); $backupTemplate = $fileOperations->fileCopyRename($file_paths); } } $saved_templates = array(); foreach ($templates as $suggestion => $template_values) { file_unmanaged_save_data($templates[$suggestion]['markup'], $templates[$suggestion]['template_path'], FILE_EXISTS_REPLACE); if (file_exists($templates[$suggestion]['template_path'])) { $saved_templates[] = $templates[$suggestion]['template_path']; } } if (!empty($saved_templates)) { $saved_templates_message_list = array( '#theme' => 'item_list', '#items' => $saved_templates, ); $saved_templates_message = drupal_render($saved_templates_message_list); drupal_set_message(t('The following <b>templates</b> were generated: !saved_templates', array('!saved_templates' => $saved_templates_message)), 'status'); } }