/**
* Copy a file from source to destination. If unique == true, then if
* the destination exists, it will be renamed by appending an increamenting
* counting number.
* @param string $source where the file is from, full path to the files required
* @param string $destination_file name of the new file, just the filename
* @param string $destination_dir where the files, just the destination dir,
* e.g., /www/html/gallery/
* @param boolean $unique create unique destination file if true.
* @return string the new copied filename, else error if anything goes bad.
*/
function copyFile($source, $destination_dir, $destination_file, $unique = true)
{
if (!(file_exists($source) && is_file($source))) {
return FILE_ERROR_NO_SOURCE;
}
$destination_dir = Files::fixPath($destination_dir);
if (!is_dir($destination_dir)) {
return FILE_ERROR_DST_DIR_FAILED;
}
$filename = Files::escape($destination_file);
if ($unique) {
$dotIndex = strrpos($destination_file, '.');
$ext = '';
if (is_int($dotIndex)) {
$ext = substr($destination_file, $dotIndex);
$base = substr($destination_file, 0, $dotIndex);
}
$counter = 0;
while (is_file($destination_dir . $filename)) {
$counter++;
$filename = $base . '_' . $counter . $ext;
}
}
if (!copy($source, $destination_dir . $filename)) {
return FILE_ERROR_COPY_FAILED;
}
//verify that it copied, new file must exists
if (is_file($destination_dir . $filename)) {
return $filename;
} else {
return FILE_ERROR_COPY_FAILED;
}
}