smarty_internal_write_file.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. /**
  3. * Smarty write file plugin
  4. *
  5. * @package Smarty
  6. * @subpackage PluginsInternal
  7. * @author Monte Ohrt
  8. */
  9. /**
  10. * Smarty Internal Write File Class
  11. *
  12. * @package Smarty
  13. * @subpackage PluginsInternal
  14. */
  15. class Smarty_Internal_Write_File {
  16. /**
  17. * Writes file in a safe way to disk
  18. *
  19. * @param string $_filepath complete filepath
  20. * @param string $_contents file content
  21. * @param Smarty $smarty smarty instance
  22. * @return boolean true
  23. */
  24. public static function writeFile($_filepath, $_contents, Smarty $smarty)
  25. {
  26. $_error_reporting = error_reporting();
  27. error_reporting($_error_reporting & ~E_NOTICE & ~E_WARNING);
  28. if ($smarty->_file_perms !== null) {
  29. $old_umask = umask(0);
  30. }
  31. $_dirpath = dirname($_filepath);
  32. // if subdirs, create dir structure
  33. if ($_dirpath !== '.' && !file_exists($_dirpath)) {
  34. mkdir($_dirpath, $smarty->_dir_perms === null ? 0777 : $smarty->_dir_perms, true);
  35. }
  36. // write to tmp file, then move to overt file lock race condition
  37. $_tmp_file = $_dirpath . DS . uniqid('wrt', true);
  38. if (!file_put_contents($_tmp_file, $_contents)) {
  39. error_reporting($_error_reporting);
  40. throw new SmartyException("unable to write file {$_tmp_file}");
  41. return false;
  42. }
  43. /*
  44. * Windows' rename() fails if the destination exists,
  45. * Linux' rename() properly handles the overwrite.
  46. * Simply unlink()ing a file might cause other processes
  47. * currently reading that file to fail, but linux' rename()
  48. * seems to be smart enough to handle that for us.
  49. */
  50. if (Smarty::$_IS_WINDOWS) {
  51. // remove original file
  52. @unlink($_filepath);
  53. // rename tmp file
  54. $success = @rename($_tmp_file, $_filepath);
  55. } else {
  56. // rename tmp file
  57. $success = @rename($_tmp_file, $_filepath);
  58. if (!$success) {
  59. // remove original file
  60. @unlink($_filepath);
  61. // rename tmp file
  62. $success = @rename($_tmp_file, $_filepath);
  63. }
  64. }
  65. if (!$success) {
  66. error_reporting($_error_reporting);
  67. throw new SmartyException("unable to write file {$_filepath}");
  68. return false;
  69. }
  70. if ($smarty->_file_perms !== null) {
  71. // set file permissions
  72. chmod($_filepath, $smarty->_file_perms);
  73. umask($old_umask);
  74. }
  75. error_reporting($_error_reporting);
  76. return true;
  77. }
  78. }
  79. ?>