<?php

/* setup includes */
require_once('../../../core/includes/master.inc.php');

// require login
$Auth->requireUser(WEB_ROOT . '/login.' . SITE_CONFIG_PAGE_EXTENSION);

// prepare result
$rs          = array();
$rs['error'] = true;
$rs['msg']   = 'Failed loading selected files, please try again later.';

// get variables
$fileIds = $_REQUEST['fileIds'];

// loop file ids and get paths
$filePaths = array();
if (COUNT($fileIds))
{
    foreach ($fileIds AS $fileId)
    {
        // load file
        $file = file::loadById($fileId);

        // duplicate
        $newFile = $file->duplicateFile();

        // set folder id
        $db->query('UPDATE file SET folderId = ' . ((int) $file->folderId ? $file->folderId : 'NULL') . ' WHERE id = ' . (int) $newFile->id . ' LIMIT 1');

        // if any previews exist, copy them
        $mediaConverterScreenPath = CACHE_DIRECTORY_ROOT . '/plugins/mediaconverter/' . $file->id . '/original_thumb.jpg';
        if (file_exists($mediaConverterScreenPath))
        {
            $newPath     = CACHE_DIRECTORY_ROOT . '/plugins/mediaconverter/' . $newFile->id . '/';
            mkdir($newPath, 0777, true);
            $newFilePath = $newPath . 'original_thumb.jpg';
            copy($mediaConverterScreenPath, $newFilePath);
        }
    }

    $rs['error'] = false;
    $rs['msg']   = t('file_manager_files_duplicated_success_message', 'Files duplicated in current folder.');
}

echo json_encode($rs);