<?php


  $fieldname        = @$_REQUEST['fieldName'];
  $maxUploads       = (int) @$schema[$fieldname]['maxUploads'];
  $isUploadLimit    = @$schema[$fieldname]['checkMaxUploads'];
  $fieldUploadCount = getUploadCount($tableName, $fieldname, @$_REQUEST['num'], @$_REQUEST['preSaveTempId']);

  // get uploadsRemaining
  if (!$isUploadLimit)   { $uploadsRemaining = 9999; }
  else                   { $uploadsRemaining = (int) $schema[$fieldname]['maxUploads']; }
  if ($fieldUploadCount) { $uploadsRemaining = max($uploadsRemaining-$fieldUploadCount, 0); }

  // error checking
  if (!array_key_exists('fieldName', $_REQUEST)) { die("no 'fieldName' value specified!"); }
  if (!array_key_exists($fieldname, $schema))    { die("Can't find field '" .htmlspecialchars($fieldname). "' in table '" .htmlspecialchars($tableName). "'!"); }
  if ($schema[$fieldname]['type'] != 'upload' && $schema[$fieldname]['type'] != 'wysiwyg') { die("Field '" .htmlspecialchars($fieldname). "' isn't an upload field!"); }
  if ($schema[$fieldname]['type'] == 'wysiwyg' && !@$schema[$fieldname]['allowUploads'])   { die("Wysiwyg field '" .htmlspecialchars($fieldname). "' doesn't allow uploads!"); }
  if (!@$_REQUEST['num'] && !@$_REQUEST['preSaveTempId'])   { die("No record 'num' or 'preSaveTempId' was specified!"); }

  $uploadDir = @$schema[$fieldname]['useCustomUploadDir'] ? $schema[$fieldname]['customUploadDir'] : $SETTINGS['uploadDir'];
  $uploadUrl = @$schema[$fieldname]['useCustomUploadDir'] ? $schema[$fieldname]['customUploadUrl'] : $SETTINGS['uploadUrl'];
  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 '" .htmlspecialchars($uploadDir). "' doesn't exist!"); }
  elseif (!is_writable($uploadDir)) { die("Upload directory '" .htmlspecialchars($uploadDir). "' isn't writable!"); }

  // submit uploads
  if (@$_REQUEST['submitUploads']) { submitUploadForm(); }


//
function submitUploadForm() {
  global $TABLE_PREFIX, $schema, $errors, $SETTINGS, $fieldUploadCount, $uploadDir, $uploadUrl, $menu;
  $isWysiwyg      = @$_REQUEST['wysiwygForm'];

  //
  if ($isWysiwyg) { disableInDemoMode('', 'default/wysiwygUploads.php', false); }
  else            { disableInDemoMode('', 'default/uploadForm.php', false); }

  // Error checking
  $uploadTmpDir = ini_get('upload_tmp_dir');
  if ($uploadTmpDir && !is_dir($uploadTmpDir)) { die("Temp Upload dir '$uploadTmpDir' does't exist!  Ask server admin to check 'upload_tmp_dir' setting in php.ini.<br/>\n"); }

  // remove uploads without record numbers that are older than 1 day
  _removeExpiredUploads();

  // get highest upload order
  $newOrder = 0;
  $uploadResults = getUploads2($GLOBALS['tableName'], $_REQUEST['fieldName'], @$_REQUEST['num'], @$_REQUEST['preSaveTempId'], '');
  while ($row = mysql_fetch_assoc($uploadResults)) {
     if ($row['order'] > $newOrder) { $newOrder = $row['order']; }
  }
  if (is_resource($uploadResults)) { mysql_free_result($uploadResults); }

  ### process uploads
  $errors           = '';
  $acceptedUploads  = 0;
  $newUploadNums    = array();
  foreach (array_values($_FILES) as $uploadInfo) {
    if (!$uploadInfo['name']) { continue; } // skip blank upload fields


    // Error checking
    $fileErrors = _getUploadErrors($uploadInfo, $_REQUEST['fieldName'], $fieldUploadCount);
    $errors    .= $fileErrors;
    if ($fileErrors) { continue; }

    // get save filename
    $uploadFilename = pathinfo($uploadInfo['name'], PATHINFO_BASENAME);
    $uploadFilename = preg_replace("/\.[^\.]+$/", '', $uploadFilename); // remove ext
    $uploadFilename  = preg_replace("/[^A-Za-z0-9\&\*\(\)\_\-]+/", '_', $uploadFilename);   # replace invalid chars with _
    $uploadFilename  = preg_replace("/_+/", '_', $uploadFilename);                          # condense duplicate underscores
    $uploadFilename  = preg_replace("/(^_+|_+$)/", '', $uploadFilename);                    # remove leading and trailing underscores
    if ($uploadFilename == '') { $uploadFilename = "upload"; }                              # default name if no valid chars
    $uploadFilename .= "." . pathinfo($uploadInfo['name'], PATHINFO_EXTENSION);

    // save upload (resizing uploaded images if needed)
    $uploadSavePath   = _getUnusedUploadFilepath($uploadDir, $uploadFilename);
    $fieldSchema      = $schema[$_REQUEST['fieldName']];
    $_imageInfo       = getimagesize($uploadInfo['tmp_name']);
    $isImage          = ($_imageInfo[2] == IMAGETYPE_GIF || $_imageInfo[2] == IMAGETYPE_JPEG || $_imageInfo[2] == IMAGETYPE_PNG);
    $resizeIfNeeded   = $isImage && $fieldSchema['resizeOversizedImages'] && $fieldSchema['maxImageHeight'] && $fieldSchema['maxImageWidth'];
    if ($resizeIfNeeded) { saveResampledImageAs($uploadSavePath, $uploadInfo['tmp_name'], $fieldSchema['maxImageWidth'], $fieldSchema['maxImageHeight']); }
    else                 {
      move_uploaded_file($uploadInfo['tmp_name'], $uploadSavePath) || die("Error moving uploaded file! $php_errormsg");

      // make upload readable and writable
      // NOTE: Sometimes when upload are create in /tmp/ by PHP they don't the correct read and write permissions
      $permissions = fileperms($uploadSavePath);
      $isReadable  = (($permissions | 0444) == $permissions); // has read bits for User, Group, and World
      $isWritable  = (($permissions | 0222) == $permissions); // has write bits for User, Group, and World
      if (!$isReadable) {
        chmod($uploadSavePath, 0666) || die("Error changing permissions on '" .htmlspecialchars($uploadSavePath). "'! $php_errormsg");
      }

    }

    // create thumbnails
    $createThumbnail  = $isImage && $fieldSchema['createThumbnails']   && $fieldSchema['maxThumbnailHeight']   && $fieldSchema['maxThumbnailWidth'];
    $createThumbnail2 = $isImage && @$fieldSchema['createThumbnails2'] && @$fieldSchema['maxThumbnailHeight2'] && @$fieldSchema['maxThumbnailWidth2'];
    $createThumbnail3 = $isImage && @$fieldSchema['createThumbnails3'] && @$fieldSchema['maxThumbnailHeight3'] && @$fieldSchema['maxThumbnailWidth3'];
    $createThumbnail4 = $isImage && @$fieldSchema['createThumbnails4'] && @$fieldSchema['maxThumbnailHeight4'] && @$fieldSchema['maxThumbnailWidth4'];
    $thumbSavePath    = $createThumbnail  ? preg_replace("|([^/]+)$|", "thumb/$1",  $uploadSavePath) : '';
    $thumbSavePath2   = $createThumbnail2 ? preg_replace("|([^/]+)$|", "thumb2/$1", $uploadSavePath) : '';
    $thumbSavePath3   = $createThumbnail3 ? preg_replace("|([^/]+)$|", "thumb3/$1", $uploadSavePath) : '';
    $thumbSavePath4   = $createThumbnail4 ? preg_replace("|([^/]+)$|", "thumb4/$1", $uploadSavePath) : '';
    if ($createThumbnail)  { saveResampledImageAs($thumbSavePath,  $uploadSavePath, $fieldSchema['maxThumbnailWidth'],  $fieldSchema['maxThumbnailHeight']); }
    if ($createThumbnail2) { saveResampledImageAs($thumbSavePath2, $uploadSavePath, $fieldSchema['maxThumbnailWidth2'], $fieldSchema['maxThumbnailHeight2']); }
    if ($createThumbnail3) { saveResampledImageAs($thumbSavePath3, $uploadSavePath, $fieldSchema['maxThumbnailWidth3'], $fieldSchema['maxThumbnailHeight3']); }
    if ($createThumbnail4) { saveResampledImageAs($thumbSavePath4, $uploadSavePath, $fieldSchema['maxThumbnailWidth4'], $fieldSchema['maxThumbnailHeight4']); }


    // add to database
    list($imageWidth,  $imageHeight,  $imageType)  = getimagesize($uploadSavePath);
    list($thumbWidth,  $thumbHeight,  $thumbType)  = @getimagesize($thumbSavePath);
    list($thumbWidth2, $thumbHeight2, $thumbType2) = @getimagesize($thumbSavePath2);
    list($thumbWidth3, $thumbHeight3, $thumbType3) = @getimagesize($thumbSavePath3);
    list($thumbWidth4, $thumbHeight4, $thumbType4) = @getimagesize($thumbSavePath4);
    $fileUploadUrl = preg_replace('/^.+\//', $uploadUrl, $uploadSavePath);
    $thumbUrl      = $createThumbnail  ? preg_replace("|([^/]+)$|", "thumb/$1",  $fileUploadUrl) : '';
    $thumbUrl2     = $createThumbnail2 ? preg_replace("|([^/]+)$|", "thumb2/$1", $fileUploadUrl) : '';
    $thumbUrl3     = $createThumbnail3 ? preg_replace("|([^/]+)$|", "thumb3/$1", $fileUploadUrl) : '';
    $thumbUrl4     = $createThumbnail4 ? preg_replace("|([^/]+)$|", "thumb4/$1", $fileUploadUrl) : '';
    $query =  "INSERT INTO `{$TABLE_PREFIX}uploads` SET \n";
    #$query .= "num = NULL,\n";
    $query .= "`order`        = '" . ++$newOrder. "',\n";
    $query .= "createdTime    = NOW(),\n";
    $query .= "tableName      = '".mysql_escape( $GLOBALS['tableName'] )."',\n";
    $query .= "fieldName      = '".mysql_escape( $_REQUEST['fieldName'] )."',\n";
    $query .= "recordNum      = '".mysql_escape( (int) @$_REQUEST['num'] )."',\n";
    $query .= "preSaveTempId  = '".mysql_escape( @$_REQUEST['preSaveTempId'] )."',\n";
    $query .= "filePath       = '".mysql_escape( $uploadSavePath )."',\n";
    $query .= "urlPath        = '".mysql_escape( $fileUploadUrl )."',\n";
    $query .= "width          = '".mysql_escape( (int) $imageWidth )."',\n";
    $query .= "height         = '".mysql_escape( (int) $imageHeight )."',\n";
    $query .= "thumbFilePath  = '".mysql_escape( $thumbSavePath )."',\n";
    $query .= "thumbUrlPath   = '".mysql_escape( $thumbUrl )."',\n";
    $query .= "thumbWidth     = '".mysql_escape( (int) $thumbWidth )."',\n";
    $query .= "thumbHeight    = '".mysql_escape( (int) $thumbHeight )."',\n";
    $query .= "thumbFilePath2 = '".mysql_escape( $thumbSavePath2 )."',\n";
    $query .= "thumbUrlPath2  = '".mysql_escape( $thumbUrl2 )."',\n";
    $query .= "thumbWidth2    = '".mysql_escape( (int) $thumbWidth2 )."',\n";
    $query .= "thumbHeight2   = '".mysql_escape( (int) $thumbHeight2 )."',\n";
    $query .= "thumbFilePath3 = '".mysql_escape( $thumbSavePath3 )."',\n";
    $query .= "thumbUrlPath3  = '".mysql_escape( $thumbUrl3 )."',\n";
    $query .= "thumbWidth3    = '".mysql_escape( (int) $thumbWidth3 )."',\n";
    $query .= "thumbHeight3   = '".mysql_escape( (int) $thumbHeight3 )."',\n";
    $query .= "thumbFilePath4 = '".mysql_escape( $thumbSavePath4 )."',\n";
    $query .= "thumbUrlPath4  = '".mysql_escape( $thumbUrl4 )."',\n";
    $query .= "thumbWidth4    = '".mysql_escape( (int) $thumbWidth4 )."',\n";
    $query .= "thumbHeight4   = '".mysql_escape( (int) $thumbHeight4 )."',\n";
    $query .= "info1          = '',\n";
    $query .= "info2          = '',\n";
    $query .= "info3          = '',\n";
    $query .= "info4          = '',\n";
    $query .= "info5          = ''\n";
    mysql_query($query) or die("MySQL Error: ". htmlspecialchars(mysql_error()) . "\n");

    // get new upload num
    array_push($newUploadNums, mysql_insert_id());

    //
    $fieldUploadCount++;
    $acceptedUploads++;
  }

  ### Error checking
  if (!$acceptedUploads && !$errors) {
    $errors = __("Please select a file to upload.") . "\n";
  }


  ### display errors - errors will automatically be displayed when page is refreshed
  if ($errors) { return; }

  ### On Successful Save
  $isDetailFields = getUploadInfoFields($_REQUEST['fieldName']);
  if ($isWysiwyg) { //
    $errors = "File Uploaded";
  }

  elseif ($isDetailFields) { // redirect to modify upload details page
    $newUploadNumsAsCSV = join(',', $newUploadNums);
    $modifyUrl          = "?menu=$menu"
                        . "&action=uploadModify"
                        . "&fieldName={$_REQUEST['fieldName']}"
                        . "&num={$_REQUEST['num']}"
                        . "&preSaveTempId={$_REQUEST['preSaveTempId']}"
                        . "&uploadNums=$newUploadNumsAsCSV";
    print "<script>self.parent.reloadIframe('{$_REQUEST['fieldName']}_iframe')</script>";  // reload uploadlist
    print "<script>window.location='$modifyUrl'</script>";  // go to modify page
    exit;
  }

  else { // reload parent iframe (with upload list)
    print "<script>self.parent.reloadIframe('{$_REQUEST['fieldName']}_iframe')</script>";  // reload uploadlist
    print "<script>self.parent.tb_remove();</script>\n";  // close thickbox
    exit;
  }

}


// remove temporary uploads from unsaved records and uploads who's field has been erased
function _removeExpiredUploads() {
  global $TABLE_PREFIX;

  // List old uploads in database (limit to 25 at a time to avoid timeouts)
  $query  = "SELECT * FROM `{$TABLE_PREFIX}uploads`";
  $query .= " WHERE (recordNum = 0 AND preSaveTempId != '' AND createdTime < (NOW() - INTERVAL 1 DAY)) OR"; // temporary upload for unsaved record more than 1 day old
  $query .= "       fieldName = ''";  // upload from field that was removed
  $query .= " LIMIT 0, 25";
  $result = mysql_query($query) or die("MySQL Error: ". htmlspecialchars(mysql_error()) . "\n");
  while ($row = mysql_fetch_assoc($result)) {

    // remove uploads and thumbnails
    @unlink($row['filePath']);
    @unlink($row['thumbFilePath']);
    @unlink($row['thumbFilePath2']);
    @unlink($row['thumbFilePath3']);
    @unlink($row['thumbFilePath4']);

    // remove record
    mysql_query("DELETE FROM `{$TABLE_PREFIX}uploads` WHERE num = {$row['num']}") or die("MySQL Error: ". htmlspecialchars(mysql_error()) . "\n");
  }
}



//
function _getUploadErrors($uploadInfo, $fieldname, $fieldUploadCount) {
  global $schema, $tableName;

  // error checking
  if (!$uploadInfo) { die("No 'uploadInfo' attribute specified!"); }
  if (!$fieldname)  { die("No 'fieldname' attribute specified!"); }

  // php upload errors
  $fileErrors      = '';
  $encodedFilename = htmlspecialchars($uploadInfo['name']);
  if      ($uploadInfo['error'] == UPLOAD_ERR_INI_SIZE)   { $fileErrors .= "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)    { $fileErrors .= "Error saving '$encodedFilename', file was only partially uploaded.<br/>\n"; }
  else if ($uploadInfo['error'] == UPLOAD_ERR_NO_TMP_DIR) { $fileErrors .= "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) { $fileErrors .= "Error saving '$encodedFilename', can't write to disk (could be disk full or permissions).<br/>\n"; }
  else if ($uploadInfo['error'])                          { $fileErrors .= "Error saving '$encodedFilename', unknown error code ({$uploadInfo['error']}).<br/>\n"; }
  else if (!is_uploaded_file($uploadInfo['tmp_name']))    { $fileErrors .= "Error saving '$encodedFilename', file wasn't uploaded properly.<br/>\n"; }

  // field type errors
  $fieldSchema        = $schema[$fieldname];
  $encodedLabelOrName = $fieldSchema['label'] ? htmlspecialchars($fieldSchema['label']) : htmlspecialchars($fieldname);
  if ($schema[$fieldname]['type'] != 'upload' && $schema[$fieldname]['type'] != 'wysiwyg') { $fileErrors .= "Field '$encodedLabelOrName' doesn't accept uploads (field type is '{$fieldSchema['type']}').<br/>\n"; }
  if ($schema[$fieldname]['type'] == 'wysiwyg' && !@$schema[$fieldname]['allowUploads'])   { $fileErrors .= "Wysiwyg field '" .htmlspecialchars($fieldname). "' doesn't allow uploads!"; }

  // filesize errors
  $filesizeKbytes     = $uploadInfo['size'] ? (int) ceil( $uploadInfo['size']/1024 ) : 0;
  if ($uploadInfo['size'] == 0 && !$fileErrors) { $fileErrors .= "Error saving '$encodedFilename', file is 0 bytes.<br/>\n"; }
  if ($fieldSchema['checkMaxUploadSize'] &&
      $fieldSchema['maxUploadSizeKB'] < $filesizeKbytes) { $fileErrors .= "File '$encodedFilename' exceeds max upload size (file: {$filesizeKbytes}K, max: {$fieldSchema['maxUploadSizeKB']}K).<br/>\n"; }

  // check allowed extensions
  $validExt        = preg_split("/\s*\,\s*/", strtolower($fieldSchema['allowedExtensions']));
  $fileExt         = pathinfo(strtolower($uploadInfo['name']), PATHINFO_EXTENSION);
  $encodedValidExt = htmlspecialchars( $fieldSchema['allowedExtensions'] );
  if (!in_array('*', $validExt) && !in_array($fileExt, $validExt)) {
    $fileErrors .= sprintf(__("File '%s' isn't allowed (valid file extensions: %s)."), $encodedFilename, $encodedValidExt);
    $fileErrors .= "<br/>\n";
  }

  // check max upload limit
  if ($fieldSchema['checkMaxUploads'] && $fieldUploadCount >= $fieldSchema['maxUploads']) {
    $fileErrors .= "Skipped '$encodedFilename'.  Max uploads of {$fieldSchema['maxUploads']} already reached.<br/>\n";
  }

  //
  return $fileErrors;
}






//
function _getUnusedUploadFilepath($uploadDir, $filename) {

  $basename = pathinfo($filename, PATHINFO_BASENAME);
  $basename = preg_replace("/\.[^\.]+$/", '', $basename); // remove ext


  $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
  $counter   = "000";
  $filepath  = "$uploadDir/$basename.$extension";

  // find unused filepath
  while (file_exists($filepath)) {

    // increment counter
    $counter = str_pad(++$counter, 3, '0', STR_PAD_LEFT);

    // update filepath
    $filepath = "$uploadDir/{$basename}_$counter.$extension";
  }

  //
  $filepath = preg_replace('/[\\\\\/]+/', '/', $filepath); // replace and collapse slashes
  return $filepath;
}


//
function _showWysiwygUploadPreview($row, $maxWidth = 150, $maxHeight = 125) {
  $filename     = pathinfo($row['filePath'], PATHINFO_BASENAME);
  $isImage      = preg_match("/\.(gif|jpg|jpeg|png)$/i", $row['urlPath']);
  $hasThumbnail = $isImage && $row['thumbUrlPath'];

  // get preview size
  if ($isImage) {
    $widthScale   = $maxWidth / $row['width'];
    $heightScale  = $maxHeight / $row['height'];
    $scaleFactor  = min($widthScale, $heightScale, 1);  # don't scale above 1:1
    $previewHeight = ceil($row['height'] * $scaleFactor); # round up
    $previewWidth  = ceil($row['width'] * $scaleFactor);  # round up
  }

  // show preview
  if ($hasThumbnail) {
    print "<a href='{$row['urlPath']}' target='_BLANK'><img src='{$row['thumbUrlPath']}' border='0' width='$previewWidth' height='$previewHeight' alt='' title='Click to view $filename' /></a>\n";
  }
  elseif ($isImage) {
    print "<a href='{$row['urlPath']}' target='_BLANK'><img src='{$row['urlPath']}' border='0' width='$previewWidth' height='$previewHeight' alt='' title='Click to view $filename'  /></a>\n";
  }
  else {
    print "(No Preview)<br/><a href='{$row['urlPath']}' target='_BLANK'>" .__('Download'). "</a>\n";
  }



}

//
function _showLinks($row) {
  $filename     = pathinfo($row['filePath'], PATHINFO_BASENAME);
  $isImage      = preg_match("/\.(gif|jpg|jpeg|png)$/i", $row['urlPath']);
  $hasThumbnail = $isImage && $row['thumbUrlPath'];

  if ($hasThumbnail) {
    print "<a href='#' onclick=\"insertUpload('" .addcslashes(htmlspecialchars($row['thumbUrlPath']), '\\\''). "', $isImage)\">" .__('Small'). "</a> | ";
    print "<a href='#' onclick=\"insertUpload('" .addcslashes(htmlspecialchars($row['urlPath']), '\\\''). "', $isImage)\">" .__('Large'). "</a> | ";
  }
  else {
    print "<a href='#' onclick=\"insertUpload('" .addcslashes(htmlspecialchars($row['urlPath']), '\\\''). "', $isImage)\">" .__('Insert'). "</a> | ";
  }

  $removeUrl = "removeUpload('{$row['num']}', '" .addcslashes(htmlspecialchars($filename), '\\\''). "', this);";
  print "<a href='#' onclick=\"$removeUrl\">" .__('Delete'). "</a><br/>";

  print "<div style='color: #666; padding-top: 1px'>$filename</div>";


}

?>
