<?php
require "cmsb3/cmsb/lib/init.php";
header("Content-Type: text/plain");

$_REQUEST['tablename'] = 'news';
$_REQUEST['fieldname'] = 'uploads';            // Name of the field within the table
$_REQUEST['maxWidth']  = '300';
$_REQUEST['maxHeight'] = '150';
$_REQUEST['thumbNum']  = '';                   // Thumb: '', '2', '3', '4'
$_REQUEST['offset']    = '0';                  // Offset of processing uploads
$_REQUEST['crop']      = '0';                  // Crop flag: '1' for true, '0' for false

// resize thumbnails
echo "Resizing {$_REQUEST['tablename']}.{$_REQUEST['fieldname']}";
echo " thumb #" . ($_REQUEST['thumbNum'] ?: 1);
echo " to max {$_REQUEST['maxWidth']}w x {$_REQUEST['maxHeight']}h\n";

$output = "start";
while ($output !== "done") {
    $output = recreateThumbnailsNoExit();
    echo "$output\n";

    $_REQUEST['offset']++;
}

exit;


// Copied from cmsb/lib/upload_functions.php that returns output and doesn't exit
function recreateThumbnailsNoExit(): string {
    $tableNameWithoutPrefix = getTablenameWithoutPrefix($_REQUEST['tablename']);

    // error checking
    $stopPrefix = "STOPJS:"; // this tells javascript to stop creating thumbnails
    $requiredFields = array('tablename','fieldname','maxHeight','maxWidth');
    foreach ($requiredFields as $fieldname) {
        if (!request($fieldname)) { die($stopPrefix . "Required fieldname '$fieldname' not specified!"); }
    }
    if (preg_match('/[^0-9_]/', $_REQUEST['maxHeight'])) { die($stopPrefix . "Invalid value for max height!\n"); }
    if (preg_match('/[^0-9_]/', $_REQUEST['maxWidth']))  { die($stopPrefix . "Invalid value for max width!\n"); }

    // get upload count
    static $count;
    if ((string) $count === '') {
        $where = mysql_escapef("tableName = ? AND fieldName = ?", $tableNameWithoutPrefix, $_REQUEST['fieldname']);
        $totalUploads = mysql_count('uploads', $where);
    }

    // load upload
    $whereEtc  = mysql_escapef("tableName = ? AND fieldname = ?", $tableNameWithoutPrefix, $_REQUEST['fieldname'] );
    $whereEtc .= " LIMIT 1 OFFSET ".(int)$_REQUEST['offset'];
    @list($upload) = mysql_select('uploads', $whereEtc);

    //
    if ($upload) {
        $fieldSchemas = getSchemaFields($tableNameWithoutPrefix);
        $fieldSchema  = $fieldSchemas[$upload['fieldName']];
        [$uploadDir, $uploadUrl] = getUploadDirAndUrl($fieldSchema);

        //
        $thumbNum          = $_REQUEST['thumbNum'];
        $mainFullFilePath  = addUploadPathPrefix($upload['filePath'], $uploadDir);
        $thumbFullFilePath = addUploadPathPrefix($upload["thumbFilePath$thumbNum"], $uploadDir);
        if (isImage_SVG($mainFullFilePath)) {
            // note: SVG image doesn't need to be resized/resampled, just copy the main file as a new thumbnail file (if thumb doesn't exist yet)
            // ... then set the width and height

            // if SVG thumbnail doesn't exist yet, create a new one
            if (!file_exists($thumbFullFilePath)) {

                // copy main file to a temp file
                $thumbWorkingPath = tempnam(CMS::$dataDir . '/temp', 'thumb_');
                _saveUpload_fixFilePermission($thumbWorkingPath);
                unlink_on_shutdown($thumbWorkingPath);
                copy($mainFullFilePath, $thumbWorkingPath) || die(__FUNCTION__ . ": error copying image '$mainFullFilePath' - " . errorlog_lastError());

                // move thumb to long-term storage
                upload_storage_strategy()?->storeThumbFile($thumbWorkingPath, $fieldSchema, $thumbNum, $upload);
            }

            $thumbFilePath = $upload['thumbFilePath'.$thumbNum];
            $thumbUrlPath  = $upload['thumbUrlPath'.$thumbNum];
            $thumbWidth    = $_REQUEST['maxWidth'];
            $thumbHeight   = $_REQUEST['maxHeight'];
        }
        else {
            // resize/resample other image file type
            [$thumbFilePath, $thumbUrlPath, $thumbWidth, $thumbHeight] = upload_storage_strategy()?->resizeThumb($upload, $thumbNum, $_REQUEST['maxWidth'], $_REQUEST['maxHeight'], request('crop'));
        }

        // if this is stored in the filesystem, remove upload path prefix
        if ((string)$upload['storage'] === '') {
            $thumbFilePath = removeUploadPathPrefix($thumbFilePath, $uploadDir);
            $thumbUrlPath  = removeUploadPathPrefix($thumbUrlPath, $uploadDir);
        }

        if ($thumbWidth) {
            // update upload database
            $query  =  "UPDATE `" .DB::$tablePrefix. "uploads`\n";
            $query .= "   SET `thumbFilepath$thumbNum` = '".mysql_escape( $thumbFilePath )."',\n";
            $query .= "       `thumbUrlPath$thumbNum`  = '".mysql_escape( $thumbUrlPath )."',\n";
            $query .= "       `thumbWidth$thumbNum`    = '".mysql_escape( $thumbWidth )."',\n";
            $query .= "       `thumbHeight$thumbNum`   = '".mysql_escape( $thumbHeight )."'\n";
            $query .= " WHERE num = '".mysql_escape( $upload['num'] )."'";
            mysqli()?->query($query) or throw new DBException();
        }

        // add plugin hook
        $thumbnailInfo = array($tableNameWithoutPrefix, $upload['fieldName'], $thumbNum, $thumbFullFilePath, $upload);
        doAction('upload_thumbnail_save', $thumbnailInfo);
    }

    // print status message
    $offset = $_REQUEST['offset'] + 1;
    if ($offset <= $totalUploads) { return "$offset/$totalUploads"; }
    else                          { return "done"; }
}
