function HookFormat_chooserCollection_downloadReplacedownloadfile($resource, $size, $ext) { if (!supportsInputFormat($resource['file_extension'])) { # Do not replace files we do not support return false; } $baseDirectory = get_temp_dir() . '/format_chooser'; @mkdir($baseDirectory); $target = $baseDirectory . '/' . getTargetFilename($resource['ref'], $ext, $size); $format = getImageFormat($size); $width = (int) $format['width']; $height = (int) $format['height']; set_time_limit(0); convertImage($resource, 1, -1, $target, $width, $height); return $target; }
function test($filename) { $filename = convertImage($filename, uniqid() . '.jpg'); list($width, $height) = getimagesize($filename); $img = imagecreatefromjpeg($filename); $new_img = imagecreatetruecolor(8, 8); imagecopyresampled($new_img, $img, 0, 0, 0, 0, 8, 8, $width, $height); imagefilter($new_img, IMG_FILTER_GRAYSCALE); $colors = array(); $sum = 0; for ($i = 0; $i < 8; $i++) { for ($j = 0; $j < 8; $j++) { $color = imagecolorat($new_img, $i, $j) & 0xff; $sum += $color; $colors[] = $color; } } $avg = $sum / 64; $hash = ''; $curr = ''; $count = 0; foreach ($colors as $color) { if ($color > $avg) { $curr .= '1'; } else { $curr .= '0'; } $count++; if (!($count % 4)) { $hash .= dechex(bindec($curr)); $curr = ''; } } unlink($filename); return $hash; }
/** * Takes some work orders from the process queue and performs them */ function processQueue() { global $db, $config; //Only allows a few work orders being executed at once, so we can do this very often if (TaskQueue::getTaskQueueStatusCnt(ORDER_EXECUTING) >= $config['process']['process_limit']) { echo "TOO MUCH ACTIVE WORK, ABORTING\n"; return; } $job = TaskQueue::getOldestEntry(); if (!$job) { return; } //mark current job as "IN PROGRESS" so another process won't start on it aswell TaskQueue::markTask($job['entryId'], ORDER_EXECUTING); echo "\n\n-------------\n"; switch ($job['orderType']) { case TASK_IMAGE_RECODE: echo 'IMAGE RECODE<br/>'; if (!in_array($job['orderParams'], $h->files->image_mime_types)) { echo 'error: invalid mime type<br/>'; $h->session->log('Process queue error - image conversion destination mimetype not supported: ' . $job['orderParams'], LOGLEVEL_ERROR); break; } $newId = $h->files->cloneFile($job['referId'], FILETYPE_CLONE_CONVERTED); $exec_start = microtime(true); $check = convertImage($h->files->findUploadPath($job['referId']), $h->files->findUploadPath($newId), $job['orderParams']); $exec_time = microtime(true) - $exec_start; echo 'Execution time: ' . shortTimePeriod($exec_time) . '<br/>'; if (!$check) { $h->session->log('#' . $job['entryId'] . ': IMAGE CONVERT failed! format=' . $job['orderParams'], LOGLEVEL_ERROR); echo 'Error: Image convert failed!<br/>'; break; } $h->files->updateFile($newId, $job['orderParams']); markQueueCompleted($job['entryId'], $exec_time); break; case TASK_AUDIO_RECODE: //Recodes source audio file into orderParams destination format $dst_audio_ok = array('ogg', 'wma', 'mp3'); //FIXME: config item or $h->files->var if (!in_array($job['orderParams'], $dst_audio_ok)) { echo 'error: invalid mime type<br/>'; $h->session->log('Process queue error - audio conversion destination mimetype not supported: ' . $job['orderParams'], LOGLEVEL_ERROR); break; } $file = $h->files->getFileInfo($job['referId']); if (!$file) { echo 'Error: no fileentry existed for fileId ' . $job['referId']; break; } $newId = $h->files->cloneFile($job['referId'], FILETYPE_CLONE_CONVERTED); echo 'Recoding source audio of "' . $file['fileName'] . '" (' . $file['fileMime'] . ') to format ' . $job['orderParams'] . " ...\n"; switch ($job['orderParams']) { case 'application/x-ogg': //FIXME hur anger ja dst-format utan filändelse? tvingas göra det i 2 steg nu $dst_file = 'tmpfile.ogg'; $c = '/usr/local/bin/ffmpeg -i "' . $h->files->findUploadPath($job['referId']) . '" ' . $dst_file; break; case 'audio/x-ms-wma': $dst_file = 'tmpfile.wma'; $c = '/usr/local/bin/ffmpeg -i "' . $h->files->findUploadPath($job['referId']) . '" ' . $dst_file; break; case 'audio/mpeg': case 'audio/x-mpeg': //fixme: source & destination should not be able to be the same! $dst_file = 'tmpfile.mp3'; $c = '/usr/local/bin/ffmpeg -i "' . $h->files->findUploadPath($job['referId']) . '" ' . $dst_file; break; default: die('unknown destination audio format: ' . $job['orderParams']); } echo 'Executing: ' . $c . "\n"; $exec_time = exectime($c); echo 'Execution time: ' . shortTimePeriod($exec_time) . "\n"; if (!file_exists($dst_file)) { echo '<b>FAILED - dst file ' . $dst_file . " dont exist!\n"; break; } //FIXME: behöver inget rename-steg. kan skriva till rätt output fil i första steget rename($dst_file, $h->files->upload_dir . $newId); $h->files->updateFile($newId); markQueueCompleted($job['entryId'], $exec_time); break; case TASK_VIDEO_RECODE: echo "VIDEO RECODE:\n"; $exec_start = microtime(true); if (convertVideo($job['referId'], $job['orderParams']) === false) { markQueue($job['entryId'], ORDER_FAILED); } else { markQueueCompleted($job['entryId'], microtime(true) - $exec_start); } break; case TASK_FETCH: echo "FETCH CONTENT\n"; $fileName = basename($job['orderParams']); //extract filename part of url, used as "filename" in database $http = new HttpClient($job['orderParams']); $http->getHead(); if ($http->getStatus() != 200) { // retry in 20 seconds if file is not yet ready retryQueueEntry($job['entryId'], 20); break; } $newFileId = FileList::createEntry(FILETYPE_PROCESS, 0, 0, $fileName); $c = 'wget ' . escapeshellarg($job['orderParams']) . ' -O ' . FileInfo::getUploadPath($newFileId); echo "\$ " . $c . "\n"; $retval = 0; $exec_time = exectime($c, $retval); if (!$retval) { //TODO: process html document for media links if it is a html document TaskQueue::markTaskCompleted($job['entryId'], $exec_time, $newFileId); FileInfo::updateData($newFileId); } else { //wget failed somehow, delay work for 1 minute retryQueueEntry($job['entryId'], 60); $files->deleteFile($newFileId, 0, true); //remove failed local file entry } break; case TASK_CONVERT_TO_DEFAULT: echo "CONVERT TO DEFAULT\n"; //referId is entryId of previous proccess queue order $params = unserialize($job['orderParams']); $prev_job = TaskQueue::getEntry($job['referId']); if ($prev_job['orderStatus'] != ORDER_COMPLETED) { retryQueueEntry($job['entryId'], 60); break; } $file = $files->getFileInfo($prev_job['referId']); $exec_start = microtime(true); $newId = false; switch ($file['mediaType']) { case MEDIATYPE_VIDEO: $newId = convertVideo($prev_job['referId'], $h->files->default_video, !empty($params['callback']) ? false : true, !empty($params['watermark']) ? $params['watermark'] : ''); break; case MEDIATYPE_AUDIO: $newId = convertAudio($prev_job['referId'], $h->files->default_audio); break; default: echo "UNKNOWN MEDIA TYPE " . $file['mediaType'] . ", MIME TYPE " . $file['fileMime'] . ", CANNOT CONVERT MEDIA!!!\n"; break; } if (!$newId) { markQueue($job['entryId'], ORDER_FAILED); return false; } markQueueCompleted($job['entryId'], microtime(true) - $exec_start); if (empty($params['callback'])) { break; } //'uri' isnt known before the new file is created so it is added at this point $uri = $config['core']['full_url'] . 'api/file.php?id=' . $newId; $params['callback'] .= (strpos($params['callback'], '?') !== false ? '&' : '?') . 'uri=' . urlencode($uri); $data = file_get_contents($params['callback']); echo "Performing callback: " . $params['callback'] . "\n\n"; echo "Callback script returned:\n" . $data; storeCallbackData($job['entryId'], $data, $params); break; default: echo "Unknown ordertype: " . $job['orderType'] . "\n"; d($job); die; } }
function HookFormat_chooserCollection_downloadReplacedownloadfile($resource, $size, $ext, $fileExists) { if (!supportsInputFormat($resource['file_extension'])) { # Do not replace files we do not support return false; } $profile = getProfileFileName(getvalescaped('profile', null)); if ($profile === null && $fileExists) { # Just serve the original file return false; } $baseDirectory = get_temp_dir() . '/format_chooser'; @mkdir($baseDirectory); $target = $baseDirectory . '/' . getTargetFilename($resource['ref'], $ext, $size); $format = getImageFormat($size); $width = (int) $format['width']; $height = (int) $format['height']; set_time_limit(0); convertImage($resource, 1, -1, $target, $width, $height, $profile); return $target; }
include '../../../include/db.php'; include '../../../include/authenticate.php'; include '../../../include/general.php'; include '../../../include/resource_functions.php'; include_once dirname(__FILE__) . "/../include/utility.php"; $ref = getvalescaped('ref', 0, true); $size = getvalescaped('size', ''); $page = getvalescaped('page', 1, true); $alternative = getvalescaped('alt', -1, true); $resource = get_resource_data($ref); if (!resource_download_allowed($ref, $size, $resource["resource_type"])) { # This download is not allowed. exit("Permission denied"); } $width = getvalescaped('width', 0, true); $height = getvalescaped('height', 0, true); if ($width == 0 && $height == 0) { $format = getImageFormat($size); $width = (int) $format['width']; $height = (int) $format['height']; } $ext = getvalescaped('ext', getDefaultOutputFormat()); $profile = getProfileFileName(getvalescaped('profile', null)); $baseDirectory = get_temp_dir() . '/format_chooser'; @mkdir($baseDirectory); $target = $baseDirectory . '/' . getTargetFilename($ref, $ext, $size); set_time_limit(0); convertImage($resource, $page, $alternative, $target, $width, $height, $profile); sendFile($target); unlink($target);
function buildCache($barcode, $filename) { global $basedir; global $resolutions; $filename_base = $barcode; // Zwischenspeicher prüfen und bei Bedarf anlegen $ret = checkDir($basedir . '/cache/', true, true, 0777); if (!$ret) { $errorstring = "Fehler beim Anlegen des Zwischenspeicher-Verzeichnisses! \n<br>\n"; die($errorstring); } else { $ret = checkDir($basedir . '/cache/1600x1200/', true, true, 0777); if (!$ret) { $errorstring = "Fehler beim Anlegen des Zwischenspeicher-Verzeichnisses (1600x1200)! \n<br>\n"; die($errorstring); } // zunächst in 1600x1200 umwandeln (als Basis für weitere Konvertierungen) $baseimage_filename = $basedir . '/cache/1600x1200/' . $filename_base . '.jpg'; $res = '1600x1200'; $ret = convertImage($filename, $baseimage_filename, $res, false); if (!$ret) { $errorstring = "Fehler beim Umrechnen des Bildes in die Auflösung 1600x1200! \n<br>\n"; die($errorstring); } foreach ($resolutions as $res) { // Unterverzeichnisse für einzelne Auflösungen prüfen $ret = checkDir($basedir . '/cache/' . $res, true, true, 0777); if (!$ret) { $errorstring = "Fehler beim Anlegen des Zwischenspeicher-Verzeichnisses (" . $res . ")\n<br>\n"; die($errorstring); } if ($res == '120x90') { $is_thumbnail = true; } else { $is_thumbnail = false; } $output_filename = $basedir . '/cache/' . $res . '/' . $filename_base . '.jpg'; $ret = convertImage($baseimage_filename, $output_filename, $res, $is_thumbnail); if (!$ret) { $errorstring = "Fehler beim Umrechnen des Bildes in die Auflösung (" . $res . ")! \n<br>\n"; die($errorstring); } } } }
} $conn->close(); return $uid; } if (isset($_FILES['file'])) { $file_name = $_FILES['file']['name']; $file_size = $_FILES['file']['size']; $file_tmp = $_FILES['file']['tmp_name']; $file_type = $_FILES['file']['type']; $move = move_uploaded_file($file_tmp, $albumURL . $_FILES['file']['name']); if ($move) { $ext = get_extension($_FILES['file']['name']); $newName = $newImageNameAndId; rename('' . $albumURL . '' . $_FILES['file']['name'], '' . $albumURL . '' . $newName . '.' . $ext); if ($ext !== $convetimageTo) { convertImage($albumURL . $newName . '.' . $ext, $albumURL . $newName . '.' . $convetimageTo, 100); unlink($albumURL . $newName . '.' . $ext); $ext = $convetimageTo; } $width = $cropImagesWidth; $Thumb = $albumURL . $newName . '.' . $ext; $imageFileType = pathinfo($Thumb, PATHINFO_EXTENSION); $imageFile = $Thumb; $info = getimagesize($imageFile); if ($info[0] >= $cropImagesWidth) { include 'tinyImage.php'; $aspectRatio = $info[1] / $info[0]; $newHeight = (int) ($aspectRatio * $width); $image = new SimpleImage(); $image->load($Thumb); $image->resize($width, $newHeight);
/** * Embeds all dependencies (js, css, images) into a slide deck file and serves it as a download * * @param string $html the content of the slides html file */ function compactDeck($html) { $doc = new DOMDocument(); @$doc->loadHTML($html); $xpath = new DOMXPath($doc); $jsFiles = $xpath->evaluate('//script[@type="text/javascript"][@src!=""]'); foreach ($jsFiles as $js) { $node = $doc->createElement('script', ''); $node->appendChild($doc->createCDATASection(file_get_contents($js->getAttribute('src')))); $node->setAttribute('type', 'text/javascript'); $js->parentNode->replaceChild($node, $js); } $cssFiles = $xpath->evaluate('//link[@type="text/css"][@rel="stylesheet"][@href!=""]'); foreach ($cssFiles as $css) { $node = $doc->createElement('style', ''); $node->appendChild($doc->createCDATASection(file_get_contents($css->getAttribute('href')))); $node->setAttribute('type', 'text/css'); $css->parentNode->replaceChild($node, $css); } $imgFiles = $xpath->evaluate('//img[@src!=""]'); $imgAttributes = $xpath->evaluate('//*[@data-background!=""]'); foreach ($imgFiles as $img) { $source = $img->getAttribute('src'); if ($data = convertImage($source)) { $img->setAttribute('src', $data); } } foreach ($imgAttributes as $img) { $source = $img->getAttribute('data-background'); if ($data = convertImage($source)) { $img->setAttribute('data-background', $data); } } return $doc->saveHTML(); }
function runBatch(&$db, &$batch) { $db->setLimit($batch->getStart(), $batch->getLimit()); $result = $db->select(); $db->disconnect(); if (empty($result)) { return NULL; } else { foreach ($result as $oldItem) { if ($_SESSION['wiki_convert_step'] == 1) { if (!convertPage($oldItem)) { $errors[] = $oldItem['label']; } } else { if ($_SESSION['wiki_convert_step'] == 2) { if (!convertInterwiki($oldItem)) { $errors[] = $oldItem['label']; } } else { if (!convertImage($oldItem)) { $errors[] = $oldItem['filename']; } } } } } if (isset($errors)) { return $errors; } else { return TRUE; } }
$file_name = preg_replace("/[^a-zA-Z0-9.]/", "", $file_name); if (file_exists("upload/" . $file_name)) { echo $_FILES["file"]["name"] . " <span id='invalid'><b>Plik już istnieje.</b></span> "; } else { $file_name = $_FILES['file']['name']; $file_name = preg_replace("/[^a-zA-Z0-9.]/", "", $file_name); if (!is_dir("upload/" . $_SESSION['folder'])) { mkdir("upload/" . $_SESSION['folder']); } $sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable $targetPath = "upload/" . $_SESSION['folder'] . "/" . $file_name; // Target path where file is to be stored move_uploaded_file($sourcePath, $targetPath); // Moving Uploaded file convertImage($targetPath, $targetPath . ".jpg", 70); unlink($targetPath); echo '<span id="success" style="color: green; padding: 5px;">Dodano zdjęcie!!!</span><br/>'; // echo "<br/><b>Nazwa:</b> " . $_FILES["file"]["name"] . "<br>"; //echo "<b>Type:</b> " . $_FILES["file"]["type"] . "<br>"; //echo "<b>Size:</b> " . ($_FILES["file"]["size"] / 1024) . " kB<br>"; //echo "<b>Temp file:</b> " . $_FILES["file"]["tmp_name"] . "<br>"; if (empty($_SESSION['folder'])) { $_SESSION['folder'] = "tmp"; } $i = 1; foreach (glob("upload/" . $_SESSION['folder'] . "/*") as $file) { if ($i > 5) { if (file_exists($file)) { unlink($file); }
<?php header('content-type: image/png'); function convertImage($originalImage, $outputImage, $quality) { $exploded = explode('.', $originalImage); $ext = $exploded[count($exploded) - 1]; if (preg_match('/jpg|jpeg/i', $ext)) { $imageTmp = imagecreatefromjpeg($originalImage); } else { if (preg_match('/png/i', $ext)) { $imageTmp = imagecreatefrompng($originalImage); } else { if (preg_match('/gif/i', $ext)) { $imageTmp = imagecreatefromgif($originalImage); } else { if (preg_match('/bmp/i', $ext)) { $imageTmp = imagecreatefrombmp($originalImage); } else { return 0; } } } } imagejpeg($imageTmp, $outputImage, $quality); imagedestroy($imageTmp); print $outputImage; } convertImage("/home/content/53/10471353/html/sites/pccbay_test" . $_GET['img'], null, 100);
function imageUpload() { if ($_FILES['fileToUpload']['size'] == 0 || $_FILES['fileToUpload']['error'] != 0) { echo "Error!"; } else { // Qua diamo il nome all'immagine $_FILES['fileToUpload']['name'] = "profile." . pathinfo($_FILES['fileToUpload']['name'], PATHINFO_EXTENSION); $target_file = requestPath() . "/profile.jpg"; $uploadOk = 1; $imageFileType = pathinfo($target_file, PATHINFO_EXTENSION); // Check if image file is a actual image or fake image $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if ($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } // Check file size if ($_FILES["fileToUpload"]["size"] > 5000000) { echo "Sorry, your file is too large."; $uploadOk = 0; } // Allow certain file formats if ($imageFileType != "jpg" && $imageFileType != "jpeg") { echo "Sorry, only JPG & JPEG files are allowed."; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (convertImage($_FILES["fileToUpload"]["tmp_name"], $target_file, 100)) { echo "The file " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; } } } }