core.write_file.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. /**
  3. * Smarty plugin
  4. * @package Smarty
  5. * @subpackage plugins
  6. */
  7. /**
  8. * write out a file to disk
  9. *
  10. * @param string $filename
  11. * @param string $contents
  12. * @param boolean $create_dirs
  13. * @return boolean
  14. */
  15. function smarty_core_write_file($params, &$smarty)
  16. {
  17. $_dirname = dirname($params['filename']);
  18. if ($params['create_dirs']) {
  19. $_params = array('dir' => $_dirname);
  20. require_once(SMARTY_CORE_DIR . 'core.create_dir_structure.php');
  21. smarty_core_create_dir_structure($_params, $smarty);
  22. }
  23. // write to tmp file, then rename it to avoid file locking race condition
  24. $_tmp_file = tempnam($_dirname, 'wrt');
  25. if (!($fd = @fopen($_tmp_file, 'wb'))) {
  26. $_tmp_file = $_dirname . DIRECTORY_SEPARATOR . uniqid('wrt');
  27. if (!($fd = @fopen($_tmp_file, 'wb'))) {
  28. $smarty->trigger_error("problem writing temporary file '$_tmp_file'");
  29. return false;
  30. }
  31. }
  32. fwrite($fd, $params['contents']);
  33. fclose($fd);
  34. if (DIRECTORY_SEPARATOR == '\\' || !@rename($_tmp_file, $params['filename'])) {
  35. // On platforms and filesystems that cannot overwrite with rename()
  36. // delete the file before renaming it -- because windows always suffers
  37. // this, it is short-circuited to avoid the initial rename() attempt
  38. @unlink($params['filename']);
  39. @rename($_tmp_file, $params['filename']);
  40. }
  41. @chmod($params['filename'], $smarty->_file_perms);
  42. return true;
  43. }
  44. /* vim: set expandtab: */
  45. ?>