3 * Smarty write file plugin
6 * @subpackage PluginsInternal
11 * Smarty Internal Write File Class
14 * @subpackage PluginsInternal
16 class Smarty_Internal_Runtime_WriteFile
19 * Writes file in a safe way to disk
21 * @param string $_filepath complete filepath
22 * @param string $_contents file content
23 * @param Smarty $smarty smarty instance
25 * @throws SmartyException
26 * @return boolean true
28 public function writeFile($_filepath, $_contents, Smarty $smarty)
30 $_error_reporting = error_reporting();
31 error_reporting($_error_reporting & ~E_NOTICE & ~E_WARNING);
32 $_file_perms = property_exists($smarty, '_file_perms') ? $smarty->_file_perms : 0644;
34 property_exists($smarty, '_dir_perms') ? (isset($smarty->_dir_perms) ? $smarty->_dir_perms : 0777) : 0771;
35 if ($_file_perms !== null) {
36 $old_umask = umask(0);
39 $_dirpath = dirname($_filepath);
40 // if subdirs, create dir structure
41 if ($_dirpath !== '.' && !file_exists($_dirpath)) {
42 mkdir($_dirpath, $_dir_perms, true);
45 // write to tmp file, then move to overt file lock race condition
46 $_tmp_file = $_dirpath . $smarty->ds . str_replace(array('.', ','), '_', uniqid('wrt', true));
47 if (!file_put_contents($_tmp_file, $_contents)) {
48 error_reporting($_error_reporting);
49 throw new SmartyException("unable to write file {$_tmp_file}");
53 * Windows' rename() fails if the destination exists,
54 * Linux' rename() properly handles the overwrite.
55 * Simply unlink()ing a file might cause other processes
56 * currently reading that file to fail, but linux' rename()
57 * seems to be smart enough to handle that for us.
59 if (Smarty::$_IS_WINDOWS) {
60 // remove original file
61 if (is_file($_filepath)) {
65 $success = @rename($_tmp_file, $_filepath);
68 $success = @rename($_tmp_file, $_filepath);
70 // remove original file
71 if (is_file($_filepath)) {
75 $success = @rename($_tmp_file, $_filepath);
79 error_reporting($_error_reporting);
80 throw new SmartyException("unable to write file {$_filepath}");
82 if ($_file_perms !== null) {
83 // set file permissions
84 chmod($_filepath, $_file_perms);
87 error_reporting($_error_reporting);