PageRenderTime 30ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/php5-3/core/tools/smarty/sysplugins/SmartyInternalWriteFile.class.php

https://bitbucket.org/ronaldobrandini/framework
PHP | 89 lines | 44 code | 9 blank | 36 comment | 9 complexity | 18cc4d41019e823acea0da0529936202 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception
  1. <?php
  2. namespace core\tools\smarty\sysplugins;
  3. /**
  4. * Smarty write file plugin
  5. *
  6. * @package Smarty
  7. * @subpackage PluginsInternal
  8. * @author Monte Ohrt
  9. */
  10. /**
  11. * Smarty Internal Write File Class
  12. *
  13. * @package Smarty
  14. * @subpackage PluginsInternal
  15. */
  16. class SmartyInternalWriteFile {
  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. * @return boolean true
  24. */
  25. public static function writeFile($_filepath, $_contents, \core\tools\smarty\Smarty $smarty)
  26. {
  27. $_error_reporting = error_reporting();
  28. error_reporting($_error_reporting & ~E_NOTICE & ~E_WARNING);
  29. if ($smarty->_file_perms !== null) {
  30. $old_umask = umask(0);
  31. }
  32. $_dirpath = dirname($_filepath);
  33. // if subdirs, create dir structure
  34. if ($_dirpath !== '.' && !file_exists($_dirpath)) {
  35. mkdir($_dirpath, $smarty->_dir_perms === null ? 0777 : $smarty->_dir_perms, true);
  36. }
  37. // write to tmp file, then move to overt file lock race condition
  38. $_tmp_file = $_dirpath . _DS . uniqid('wrt', true);
  39. if (!file_put_contents($_tmp_file, $_contents)) {
  40. error_reporting($_error_reporting);
  41. throw new SmartyException("unable to write file {$_tmp_file}");
  42. return false;
  43. }
  44. /*
  45. * Windows' rename() fails if the destination exists,
  46. * Linux' rename() properly handles the overwrite.
  47. * Simply unlink()ing a file might cause other processes
  48. * currently reading that file to fail, but linux' rename()
  49. * seems to be smart enough to handle that for us.
  50. */
  51. if (\core\tools\smarty\Smarty::$_IS_WINDOWS) {
  52. // remove original file
  53. @unlink($_filepath);
  54. // rename tmp file
  55. $success = @rename($_tmp_file, $_filepath);
  56. } else {
  57. // rename tmp file
  58. $success = @rename($_tmp_file, $_filepath);
  59. if (!$success) {
  60. // remove original file
  61. @unlink($_filepath);
  62. // rename tmp file
  63. $success = @rename($_tmp_file, $_filepath);
  64. }
  65. }
  66. if (!$success) {
  67. error_reporting($_error_reporting);
  68. throw new SmartyException("unable to write file {$_filepath}");
  69. return false;
  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. }
  80. ?>