smarty_internal_write_file.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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');
  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. // remove original file
  44. @unlink($_filepath);
  45. // rename tmp file
  46. $success = rename($_tmp_file, $_filepath);
  47. if (!$success) {
  48. error_reporting($_error_reporting);
  49. throw new SmartyException("unable to write file {$_filepath}");
  50. return false;
  51. }
  52. if ($smarty->_file_perms !== null) {
  53. // set file permissions
  54. chmod($_filepath, $smarty->_file_perms);
  55. umask($old_umask);
  56. }
  57. error_reporting($_error_reporting);
  58. return true;
  59. }
  60. }
  61. ?>