smarty_internal_write_file.php 2.6 KB

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