<?php

$fieldname = @$_REQUEST['fieldName'];
list($isUploadLimit, $maxUploads, $uploadsRemaining) = getUploadLimits($tableName, $fieldname, @$_REQUEST['num'], @$_REQUEST['preSaveTempId']);
// error checking
if (!array_key_exists('fieldName', $_REQUEST)) {
    die("no 'fieldName' value specified!");
}
if (!array_key_exists($fieldname, $schema)) {
    die("Can't find field '" . htmlencode($fieldname) . "' in table '" . htmlencode($tableName) . "'!");
}
if ($schema[$fieldname]['type'] != 'upload' && $schema[$fieldname]['type'] != 'wysiwyg') {
    die("Field '" . htmlencode($fieldname) . "' isn't an upload field!");
}
if ($schema[$fieldname]['type'] == 'wysiwyg' && !@$schema[$fieldname]['allowUploads']) {
    die("Wysiwyg field '" . htmlencode($fieldname) . "' doesn't allow uploads!");
}
if (!@$_REQUEST['num'] && !@$_REQUEST['preSaveTempId']) {
    die("No record 'num' or 'preSaveTempId' was specified!");
}
list($uploadDir, $uploadUrl) = getUploadDirAndUrl($schema[$fieldname]);
if (!file_exists($uploadDir)) {
    mkdir_recursive($uploadDir, 0755);
}
// create upload dir (if not possible, dir not exists error will show below)
if (!file_exists($uploadDir)) {
    die("Upload directory '" . htmlencode($uploadDir) . "' doesn't exist!");
} elseif (!is_writable($uploadDir)) {
    die("Upload directory '" . htmlencode($uploadDir) . "' isn't writable!");
}
// submit uploads
function _saveUpload_getErrors($tableName, $fieldname, $uploadInfo, $recordNum, $preSaveTempId, $skipUploadSecurityCheck = false)
{
    // error checking
    if (!$tableName) {
        die(__FUNCTION__ . ": No 'tablename' specified!");
    }
    if (!$fieldname) {
        die(__FUNCTION__ . ": No 'fieldname' specified!");
    }
    if (!$uploadInfo) {
        die(__FUNCTION__ . ": No 'uploadInfo' specified!");
    }
    //
    $errors = '';
    $schema = loadSchema($tableName);
    // server issues
    $uploadTmpDir = ini_get('upload_tmp_dir');
    list($uploadDir, $uploadUrl) = getUploadDirAndUrl($schema[$fieldname]);
    if ($uploadTmpDir && !is_dir($uploadTmpDir)) {
        $errors .= "Temp Upload dir '{$uploadTmpDir}' does't exist!  Ask server admin to check 'upload_tmp_dir' setting in php.ini.<br/>\n";
    }
    if (!file_exists($uploadDir)) {
        $errors .= "Upload directory '" . htmlencode($uploadDir) . "' doesn't exist!";
    } elseif (!is_writable($uploadDir)) {
        $errors .= "Upload directory '" . htmlencode($uploadDir) . "' isn't writable!";
    }
    if ($errors) {
        return $errors;
    }
    // return early errors here since nothing else will work otherwise
    // php upload errors
    $encodedFilename = htmlencode($uploadInfo['name']);
    if ($uploadInfo['error'] == UPLOAD_ERR_INI_SIZE) {
        $errors .= "Error saving '{$encodedFilename}', file is larger than '" . ini_get('upload_max_filesize') . "' max size allowed by PHP (check 'upload_max_filesize' in php.ini).<br/>\n";
    } else {
        if ($uploadInfo['error'] == UPLOAD_ERR_PARTIAL) {
            $errors .= "Error saving '{$encodedFilename}', file was only partially uploaded.<br/>\n";
        } else {
            if ($uploadInfo['error'] == UPLOAD_ERR_NO_TMP_DIR) {
                $errors .= "Error saving '{$encodedFilename}', PHP temporary upload folder doesn't exist or isn't defined.  Ask your hosting provider to fix this (check 'upload_tmp_dir' in php.ini).<br/>\n";
            } else {
                if ($uploadInfo['error'] == UPLOAD_ERR_CANT_WRITE) {
                    $errors .= "Error saving '{$encodedFilename}', can't write to disk (could be disk full or permissions).<br/>\n";
                } else {
                    if ($uploadInfo['error']) {
                        $errors .= "Error saving '{$encodedFilename}', unknown error code ({$uploadInfo['error']}).<br/>\n";
                    } else {
                        if (!$skipUploadSecurityCheck && !is_uploaded_file($uploadInfo['tmp_name'])) {
                            $errors .= "Error saving '{$encodedFilename}', file wasn't uploaded properly.<br/>\n";
                        }
                    }
                }
            }
        }
    }
    // field type errors
    $fieldSchema = $schema[$fieldname];
    $encodedLabelOrName = $fieldSchema['label'] ? htmlencode($fieldSchema['label']) : htmlencode($fieldname);
    if ($schema[$fieldname]['type'] != 'upload' && $schema[$fieldname]['type'] != 'wysiwyg') {
        $errors .= "Field '{$encodedLabelOrName}' doesn't accept uploads (field type is '{$fieldSchema['type']}').<br/>\n";
    }
    if ($schema[$fieldname]['type'] == 'wysiwyg' && !@$schema[$fieldname]['allowUploads']) {
        $errors .= "Wysiwyg field '" . htmlencode($fieldname) . "' doesn't allow uploads!";
    }
    // filesize errors
    $filesizeKbytes = $uploadInfo['size'] ? (int) ceil($uploadInfo['size'] / 1024) : 0;
    if ($uploadInfo['size'] == 0 && !$errors) {
        $errors .= "Error saving '{$encodedFilename}', file is 0 bytes.<br/>\n";
    }
    if ($fieldSchema['checkMaxUploadSize'] && $fieldSchema['maxUploadSizeKB'] < $filesizeKbytes) {
        $errors .= "File '{$encodedFilename}' exceeds max upload size (file: {$filesizeKbytes}K, max: {$fieldSchema['maxUploadSizeKB']}K).<br/>\n";
    }
    // check allowed extensions
    if (!_saveUpload_hasValidExt($uploadInfo['name'], $fieldSchema)) {
        $errors .= sprintf(t("File '%s' isn't allowed (valid file extensions: %s)."), $encodedFilename, htmlencode($fieldSchema['allowedExtensions']));
        $errors .= "<br/>\n";
    }
    // check max upload limit
    list($isUploadLimit, $maxUploads, $remainingUploads) = getUploadLimits($tableName, $fieldname, $recordNum, $preSaveTempId);
    if ($isUploadLimit && $remainingUploads <= 0) {
        $errors .= sprintf(t("Skipped '%1\$s', max uploads of %2\$s already reached."), $encodedFilename, $maxUploads);
        $errors .= "<br/>\n";
    }
    //
    return $errors;
}