public function CommitSettings(&$messages=array()) { // If the shop path has changed normalize it and set the app path too if (isset($GLOBALS['ISC_NEW_CFG']['ShopPath']) && $GLOBALS['ISC_NEW_CFG']['ShopPath'] != GetConfig('ShopPath')) { $parsedPath = ParseShopPath($GLOBALS['ISC_NEW_CFG']['ShopPath']); $GLOBALS['ISC_NEW_CFG']['ShopPath'] = $parsedPath['shopPath']; // add an event to resubscribe to ebay notifications since the notification url will now be different if (ISC_ADMIN_EBAY::checkEbayConfig()) { Interspire_Event::bind('settings_updated', array('ISC_ADMIN_EBAY', 'resubscribeNotifications')); } } // normalize our shared ssl path if (isset($GLOBALS['ISC_NEW_CFG']['SharedSSLPath']) && trim($GLOBALS['ISC_NEW_CFG']['SharedSSLPath'])) { $ssl_path_parts = parse_url($GLOBALS['ISC_NEW_CFG']['SharedSSLPath']); if (!isset($ssl_path_parts['path'])) { $ssl_path_parts['path'] = ''; } $ssl_path_parts['path'] = rtrim($ssl_path_parts['path'], '/'); // Workout the Shop Path $GLOBALS['ISC_NEW_CFG']['SharedSSLPath'] = 'https://' . $ssl_path_parts['host']; if (isset($ssl_path_parts['port']) && $ssl_path_parts['port'] != '443') { $GLOBALS['ISC_NEW_CFG']['SharedSSLPath'] .= ':'.$ssl_path_parts['port']; } $GLOBALS['ISC_NEW_CFG']['SharedSSLPath'] .= $ssl_path_parts['path']; } // normalize our subdomain ssl path if (isset($GLOBALS['ISC_NEW_CFG']['SubdomainSSLPath']) && trim($GLOBALS['ISC_NEW_CFG']['SubdomainSSLPath'])) { $ssl_path_parts = parse_url($GLOBALS['ISC_NEW_CFG']['SubdomainSSLPath']); if (!isset($ssl_path_parts['path'])) { $ssl_path_parts['path'] = ''; } $ssl_path_parts['path'] = rtrim($ssl_path_parts['path'], '/'); // Workout the Shop Path $GLOBALS['ISC_NEW_CFG']['SubdomainSSLPath'] = 'https://' . $ssl_path_parts['host']; if (isset($ssl_path_parts['port']) && $ssl_path_parts['port'] != '443') { $GLOBALS['ISC_NEW_CFG']['SubdomainSSLPath'] .= ':'.$ssl_path_parts['port']; } $GLOBALS['ISC_NEW_CFG']['SubdomainSSLPath'] .= $ssl_path_parts['path']; } if (!isset($GLOBALS['ISC_NEW_CFG'])) { $GLOBALS['ISC_NEW_CFG'] = array(); } $directories = array( 'ImageDirectory' => 'product_images', 'DownloadDirectory' => 'product_downloads' ); foreach($directories as $directory => $default) { if(isset($GLOBALS['ISC_NEW_CFG'][$directory])) { $newDirectory = ISC_BASE_PATH.'/'.$GLOBALS['ISC_NEW_CFG'][$directory]; if(!$GLOBALS['ISC_NEW_CFG'][$directory] || !is_dir($newDirectory)) { $GLOBALS['ISC_NEW_CFG'][$directory] = $default; } } } // Wht we're doing here is we copy the current configuration in to another variable and // then load the store configuration file again. We do this to prevent any settings // that may have temporarily been modified in memory from propagating to the configuration // file. We then revert back to the in memory settings $memoryConfig = $GLOBALS['ISC_CFG']; unset($GLOBALS['ISC_CFG']); require ISC_CONFIG_FILE; $originalConfig = $GLOBALS['ISC_CFG']; $GLOBALS['ISC_CFG'] = $memoryConfig; $GLOBALS['ISC_SAVE_CFG'] = array_merge($originalConfig, $GLOBALS['ISC_NEW_CFG']); // Save the var_exported vars in the globals array temporarily for saving foreach ($this->all_vars as $var) { if (!array_key_exists($var, $GLOBALS['ISC_SAVE_CFG'])) { if(array_key_exists($var, $memoryConfig)) { $GLOBALS[$var] = var_export($memoryConfig[$var], true); } else { $GLOBALS[$var] = "null"; } } else { $GLOBALS[$var] = var_export($GLOBALS['ISC_SAVE_CFG'][$var], true); } } $config_data = $this->template->render('config.file.tpl'); $setting_string = "<" . "?php\n\n"; $setting_string .= "\t// Last Updated: ".isc_date("jS M Y @ g:i A") . "\n"; $setting_string .= $config_data; if (!defined("ISC_CONFIG_FILE") || !defined("ISC_CONFIG_BACKUP_FILE")) { die("Config sanity check failed"); } // Try to copy the current config file to a backup file if (!@copy(ISC_CONFIG_FILE, ISC_CONFIG_BACKUP_FILE)) { isc_chmod(ISC_CONFIG_BACKUP_FILE, ISC_WRITEABLE_FILE_PERM); $messages = array(GetLang('CouldntBackupConfig') => MSG_INFO); } // Try to write to the config file if (!is_writable(ISC_CONFIG_FILE)) { $this->error = GetLang('CouldntSaveConfig'); return false; } if (!($fp = @fopen(ISC_CONFIG_FILE, "wb+"))) { $this->error = GetLang('CouldntSaveConfig'); return false; } if (@fwrite($fp, $setting_string)) { fclose($fp); $prevCatListDepth = GetConfig('CategoryListDepth'); // Include the config file again to initialize the new values include(ISC_CONFIG_FILE); if (isset($GLOBALS['ISC_NEW_CFG']['CategoryListDepth']) && $GLOBALS['ISC_NEW_CFG']['CategoryListDepth'] != $prevCatListDepth) { $GLOBALS['ISC_CLASS_DATA_STORE']->UpdateRootCategories(); } // trigger any events that should run after the settings have been saved Interspire_Event::trigger('settings_updated'); return true; } fclose($fp); $this->error = GetLang('CouldntSaveConfig'); return false; }
/** * _SaveImages * This goes through the images in _EmbeddedImages and saves them for us to access easily when we need to add them to the content. * If it needs to, it will create the image directory to store the files in. * * @see _EmbeddedImages * @see imagedir * @see GetImage * @see _JoinImages * * @return Void Doesn't return anything. If it doesn't need to save anything, it will quickly return. */ public function _SaveImages() { if (empty($this->_EmbeddedImages)) { return; } if (!is_dir($this->imagedir)) { mkdir($this->imagedir, 0777); } $new_list = array(); foreach ($this->_EmbeddedImages as $md5 => $imageurl) { list($img_contents, $status) = $this->GetImage($imageurl); $imagefile = basename($imageurl); $img_parts = parse_url($imagefile); /* * for stupid "urls" in stylesheets like: * BEHAVIOR: url(#default#VML) * there is no 'path' to the url. so skip that one. */ if (!isset($img_parts['path'])) { unset($this->_EmbeddedImages[$md5]); $this->body['h'] = str_replace('cid:' . $md5, $imageurl, $this->body['h']); continue; } $imagefile = $img_parts['path']; $ext = substr($imagefile, strrpos($imagefile, '.') + 1); $imgfile = $this->imagedir . '/' . $imagefile; $imghandle = fopen($imgfile, 'wb'); fputs($imghandle, $img_contents); fclose($imghandle); // we set "666" here in case we start a send through the popup, enable cron jobs and finish it in scheduled mode. Otherwise the job won't be able to read the file to embed it. @isc_chmod($imgfile, ISC_WRITEABLE_FILE_PERM); $new_list[$md5] = $imgfile; } $this->_EmbeddedImages = $new_list; }
private function UploadFavicon() { if($_FILES['FaviconFile']['error'] == 0 && $_FILES['FaviconFile']['size'] > 0) { $_FILES['FaviconFile']['name'] = basename($_FILES['FaviconFile']['name']); if(!$this->IsValidFavicoFile($_FILES['FaviconFile'])) { $this->ManageLayouts(GetLang('UploadedFaviconNoValidImage2'), MSG_ERROR); } else { $destination = ISC_BASE_PATH.'/'.GetConfig('ImageDirectory').'/'.$_FILES['FaviconFile']['name']; if (file_exists($destination)) { @unlink($destination); } // Upload and store the actual logo if(move_uploaded_file($_FILES['FaviconFile']['tmp_name'], $destination)) { // Save the updated logo in the configuration file $GLOBALS['ISC_NEW_CFG']['Favicon'] = $_FILES['FaviconFile']['name']; $settings = GetClass('ISC_ADMIN_SETTINGS'); if($settings->CommitSettings()) { isc_chmod(ISC_BASE_PATH.'/'.GetConfig('ImageDirectory').'/'.$GLOBALS['ISC_NEW_CFG']['Favicon'], ISC_WRITEABLE_FILE_PERM); FlashMessage(GetLang('FaviconUploadSuccess'), MSG_SUCCESS, 'index.php?ToDo=viewTemplates'); } else { FlashMessage(GetLang('FaviconUploadWorkedConfigError'), MSG_ERROR, 'index.php?ToDo=viewTemplates'); } } else { FlashMessage(GetLang('FaviconUploadErrorPath'), MSG_ERROR, 'index.php?ToDo=viewTemplates'); } } } else { FlashMessage(GetLang('FaviconUploadNoValidImage'), MSG_ERROR, 'index.php?ToDo=viewTemplates'); exit; } }
private function SaveQValueAssociationImage() { if (!array_key_exists('associationimage', $_FILES) || $_FILES['associationimage']['error'] !== 0 || strtolower(substr($_FILES['associationimage']['type'], 0, 6)) !== 'image/') { return false; } // Attempt to set the memory limit setImageFileMemLimit($_FILES['associationimage']['tmp_name']); // Generate the destination path $randomDir = strtolower(chr(rand(65, 90))); $destPath = realpath(ISC_BASE_PATH . '/' . GetConfig('ImageDirectory')); if (!is_dir($destPath . '/' . $randomDir)) { if (!@mkdir($destPath . '/' . $randomDir, 0777)) { $randomDir = ''; } } $destFile = GenRandFileName($_FILES['associationimage']['name'], 'category'); $destPath = $destPath . '/' . $randomDir . '/' . $destFile; $returnPath = $randomDir . '/' . $destFile; $tmp = explode('.', $_FILES['associationimage']['name']); $ext = strtolower($tmp[count($tmp) - 1]); if ($ext == 'jpg') { $srcImg = imagecreatefromjpeg($_FILES['associationimage']['tmp_name']); } else { if ($ext == 'gif') { $srcImg = imagecreatefromgif($_FILES['associationimage']['tmp_name']); if (!function_exists('imagegif')) { $gifHack = 1; } } else { $srcImg = imagecreatefrompng($_FILES['associationimage']['tmp_name']); } } $srcWidth = imagesx($srcImg); $srcHeight = imagesy($srcImg); $widthLimit = GetConfig('BrandImageWidth'); $heightLimit = GetConfig('BrandImageHeight'); // If the image is small enough, simply move it and leave it as is if ($srcWidth <= $widthLimit && $srcHeight <= $heightLimit) { imagedestroy($srcImg); move_uploaded_file($_FILES['associationimage']['tmp_name'], $destPath); return $returnPath; } // Otherwise, the image needs to be resized $attribs = getimagesize($_FILES['associationimage']['tmp_name']); $width = $attribs[0]; $height = $attribs[1]; if ($width > $widthLimit) { $height = ceil($widthLimit / $width * $height); $width = $widthLimit; } if ($height > $heightLimit) { $width = ceil($heightLimit / $height * $width); $height = $heightLimit; } $dstImg = imagecreatetruecolor($width, $height); if ($ext == "gif" && !isset($gifHack)) { $colorTransparent = imagecolortransparent($srcImg); imagepalettecopy($srcImg, $dstImg); imagecolortransparent($dstImg, $colorTransparent); imagetruecolortopalette($dstImg, true, 256); } else { if ($ext == "png") { ImageColorTransparent($dstImg, ImageColorAllocate($dstImg, 0, 0, 0)); ImageAlphaBlending($dstImg, false); } } imagecopyresampled($dstImg, $srcImg, 0, 0, 0, 0, $width, $height, $srcWidth, $srcHeight); if ($ext == "jpg") { imagejpeg($dstImg, $destPath, 100); } else { if ($ext == "gif") { if (isset($gifHack) && $gifHack == true) { $thumbFile = isc_substr($destPath, 0, -3) . "jpg"; imagejpeg($dstImg, $destPath, 100); } else { imagegif($dstImg, $destPath); } } else { imagepng($dstImg, $destPath); } } @imagedestroy($dstImg); @imagedestroy($srcImg); @unlink($_FILES['associationimage']['tmp_name']); // Change the permissions on the thumbnail file isc_chmod($returnPath, ISC_WRITEABLE_FILE_PERM); return $returnPath; }
$maxheight = '200'; // check cache first if (file_exists($CacheTemplateImageFile)) { if (strtolower(substr($TemplateImageFile, -4)) == ".jpg" || strtolower(substr($TemplateImageFile, -5)) == ".jpeg") { // jpeg image header("Content-type: image/jpeg"); } elseif (strtolower(substr($TemplateImageFile, -4)) == ".gif") { // gif image header("Content-type: image/gif"); } echo file_get_contents($CacheTemplateImageFile); die; } elseif (file_exists($TemplateImageFile)) { if (!is_dir(ISC_BASE_PATH . '/cache/tplthumbs/')) { mkdir(ISC_BASE_PATH . '/cache/tplthumbs/'); isc_chmod(ISC_BASE_PATH . '/cache/tplthumbs/', ISC_WRITEABLE_DIR_PERM); } if ((strtolower(substr($TemplateImageFile, -4)) == ".jpg" || strtolower(substr($TemplateImageFile, -5)) == ".jpeg") && function_exists('imagejpeg')) { // jpeg image header("Content-type: image/jpeg"); } elseif (strtolower(substr($TemplateImageFile, -4)) == ".gif" && function_exists('imagegif')) { // gif image header("Content-type: image/gif"); } GenerateThumbnail($TemplateImageFile, $CacheTemplateImageFile, 200); if (file_exists($CacheTemplateImageFile)) { echo file_get_contents($CacheTemplateImageFile); } else { OutputNoImage(); } die;
/** * Validate the passed input for a gift wrapping type for errors. * * @param array An array of data about the gift wrapping type. * @param string An error message (if any) from validation errors (on return false - by reference) * @return boolean True if successful, false if not. */ private function ValidateWrap($data, &$error) { $requiredFields = array( 'wrapname' => GetLang('EnterGiftWrapName'), 'wrapprice' => GetLang('EnterGiftWrapPrice') ); foreach($requiredFields as $field => $message) { if(!isset($data[$field]) || trim($data[$field]) == '') { $error = $message; return false; } } // Does a wrapping type exist with the same name? $wrapIdQuery = ''; if(isset($data['wrapId']) && $data['wrapId'] > 0) { $wrapIdQuery = " AND wrapid!='".(int)$data['wrapId']."'"; } // Check that a duplicate wrapping type doesn't exist with this name $query = " SELECT wrapid FROM [|PREFIX|]gift_wrapping WHERE wrapname='".$GLOBALS['ISC_CLASS_DB']->Quote($data['wrapname'])."'".$wrapIdQuery; // if an image was uploaded, validate that try { $files = ISC_UPLOADHANDLER::getUploadedFiles(); foreach ($files as /** @var UploadHandlerFile */$file) { if ($file->fieldName == 'wrapimage') { $dest = ISC_BASE_PATH . '/' . GetConfig('ImageDirectory') . '/wrap_images/' . GenRandFileName($file->name); $file->moveAs($dest); $image = @getimagesize($dest); if ($image === false) { unlink($dest); $error = GetLang("WrapImageInvalid"); return false; } isc_chmod($dest, ISC_WRITEABLE_FILE_PERM); break; } } } catch (UploadHandlerException $exception) { $error = $exception->getMessage(); return false; } if($GLOBALS['ISC_CLASS_DB']->FetchOne($query)) { $error = GetLang('DuplicateGiftWrapName'); return false; } // Otherwise it's valid return true; }
public function CommitSettings(&$messages = array()) { // If the shop path has changed normalize it and set the app path too if (isset($GLOBALS['ISC_NEW_CFG']['ShopPath'])) { $shop_path_parts = parse_url($GLOBALS['ISC_NEW_CFG']['ShopPath']); if (!isset($shop_path_parts['scheme'])) { $shop_path_parts['scheme'] = 'http'; } if (!isset($shop_path_parts['path'])) { $shop_path_parts['path'] = ''; } $shop_path_parts['path'] = rtrim($shop_path_parts['path'], '/'); // Workout the Shop Path $GLOBALS['ISC_NEW_CFG']['ShopPath'] = $shop_path_parts['scheme'] . '://' . $shop_path_parts['host']; if (isset($shop_path_parts['port']) && $shop_path_parts['port'] != '80') { $GLOBALS['ISC_NEW_CFG']['ShopPath'] .= ':' . $shop_path_parts['port']; } $GLOBALS['ISC_NEW_CFG']['ShopPath'] .= $shop_path_parts['path']; // Work out the AppPath automatically $GLOBALS['ISC_NEW_CFG']['AppPath'] = $shop_path_parts['path']; } if (!isset($GLOBALS['ISC_NEW_CFG'])) { $GLOBALS['ISC_NEW_CFG'] = array(); } $directories = array('ImageDirectory' => 'product_images', 'InstallImageDirectory' => 'install_images', 'VideoDirectory' => 'product_videos', 'InstallVideoDirectory' => 'install_videos', 'DownloadDirectory' => 'product_downloads'); //New directories of index 1,2,3 added by Simha foreach ($directories as $directory => $default) { if (isset($GLOBALS['ISC_NEW_CFG'][$directory])) { $newDirectory = ISC_BASE_PATH . '/' . $GLOBALS['ISC_NEW_CFG'][$directory]; if (!$GLOBALS['ISC_NEW_CFG'][$directory] || !is_dir($newDirectory)) { $GLOBALS['ISC_NEW_CFG'][$directory] = $default; } } } if (!isset($GLOBALS['ISC_NEW_CFG']['ShopPath'])) { $GLOBALS['ISC_CFG']['ShopPath'] = GetConfig('ShopPathNormal'); } $GLOBALS['ISC_SAVE_CFG'] = array_merge($GLOBALS['ISC_CFG'], $GLOBALS['ISC_NEW_CFG']); // Save the var_exported vars in the globals array temporarily for saving foreach ($this->all_vars as $var) { if (!array_key_exists($var, $GLOBALS['ISC_SAVE_CFG'])) { $GLOBALS[$var] = "null"; } else { $GLOBALS[$var] = var_export($GLOBALS['ISC_SAVE_CFG'][$var], true); } } $GLOBALS['ISC_CLASS_TEMPLATE']->SetTemplate("config.file"); $config_data = $GLOBALS['ISC_CLASS_TEMPLATE']->ParseTemplate(true); $setting_string = "<" . "?php\n\n"; $setting_string .= "\t// Last Updated: " . isc_date("jS M Y @ g:i A") . "\n"; $setting_string .= $config_data; $setting_string .= "?" . ">"; if (!defined("ISC_CONFIG_FILE") || !defined("ISC_CONFIG_BACKUP_FILE")) { die("Config sanity check failed"); } // Try to copy the current config file to a backup file if (!@copy(ISC_CONFIG_FILE, ISC_CONFIG_BACKUP_FILE)) { isc_chmod(ISC_CONFIG_BACKUP_FILE, ISC_WRITEABLE_FILE_PERM); $messages = array(GetLang('CouldntBackupConfig') => MSG_INFO); } // Try to write to the config file if (is_writable(ISC_CONFIG_FILE)) { if ($fp = @fopen(ISC_CONFIG_FILE, "wb+")) { if (@fwrite($fp, $setting_string)) { $prevCatListDepth = GetConfig('CategoryListDepth'); // Include the config file again to initialize the new values include ISC_CONFIG_FILE; if (isset($GLOBALS['ISC_NEW_CFG']['CategoryListDepth']) && $GLOBALS['ISC_NEW_CFG']['CategoryListDepth'] != $prevCatListDepth) { $GLOBALS['ISC_CLASS_DATA_STORE']->UpdateRootCategories(); } return true; } else { $this->error = GetLang('CouldntSaveConfig'); return false; } } else { $this->error = GetLang('CouldntSaveConfig'); return false; } } else { $this->error = GetLang('CouldntSaveConfig'); return false; } }
/** * Upload a new image from the Image Manager or TinyMCE itself. Images are thrown in the uploaded_images * directory. Invalid images (no dimensions available, mismatched type) are not accepted. Will output * a JSON encoded array of details about the image just uploaded. */ private function UploadImage() { if(empty($_FILES['Filedata'])) { exit; } $_FILES['Filedata']['filesize'] = Store_Number::niceSize($_FILES['Filedata']['size']); $_FILES['Filedata']['id'] = substr(md5($_FILES['Filedata']['name']), 0, 10); $_FILES['Filedata']['errorfile'] = false; $_FILES['Filedata']['imagepath'] = GetConfig('AppPath').'/'.GetConfig('ImageDirectory').'/uploaded_images/'; $_FILES['Filedata']['duplicate'] = false; if($_FILES['Filedata']['error'] != UPLOAD_ERR_OK) { $_FILES['Filedata']['erorrfile'] = 'badupload'; die(isc_json_encode($_FILES)); } // Sanitise uploaded image file name. $tmpName = $_FILES['Filedata']['tmp_name']; $name = slugify(basename($_FILES['Filedata']['name'])); $info = pathinfo($name); if ($info['filename'] == '') { $name = uniqid().$name; } $destination = ISC_BASE_PATH.'/'.GetConfig('ImageDirectory').'/uploaded_images/'.$name; if(!$this->IsImageFile(isc_strtolower($name))) { $_FILES['Filedata']['errorfile'] = 'badname'; } else if(file_exists($destination)) { $_FILES['Filedata']['duplicate'] = true; } else if(!@move_uploaded_file($tmpName, $destination)) { $_FILES['Filedata']['errorfile'] = 'badupload'; } else if(!$this->IsValidImageFile($destination)) { $_FILES['Filedata']['errorfile'] = 'badtype'; @unlink($destination); } if (!($_FILES['Filedata']['errorfile'] || $_FILES['Filedata']['duplicate'])) { isc_chmod($destination, ISC_WRITEABLE_FILE_PERM); // Get the image dimensions so we can show a thumbnail list($imgWidth, $imgHeight) = @getimagesize($destination); if(!$imgWidth || !$imgHeight) { $imgWidth = 200; $imgHeight = 150; } $_FILES['Filedata']['origwidth'] = $imgWidth; $_FILES['Filedata']['origheight'] = $imgHeight; if($imgWidth > 200) { $imgHeight = (200/$imgWidth) * $imgHeight; $imgWidth = 200; } if($imgHeight > 150) { $imgWidth = (150/$imgHeight) * $imgWidth; $imgHeight = 150; } $_FILES['Filedata']['width'] = $imgWidth; $_FILES['Filedata']['height'] = $imgHeight; $_FILES['Filedata']['name'] = $name; unset($_FILES['Filedata']['tmp_name']); } echo isc_json_encode($_FILES); exit; }
/** * Downloads image from picnik (or can be used for any url, really) and stores it at a file named $destination -- primarily a wrapper for PostToRemoteFileAndGetResponse with built-in file writing and error handling * * @param string $url * @param string $destination (optional) * @return string|bool Returns the filename the image was saved to, or false if anything went wrong */ public function downloadToFile($url, $destination = false, &$errorType = null) { $result = PostToRemoteFileAndGetResponse($url); if (!$destination) { // generate a random name for our downloaded file and store it in cache dir while (true) { // we can name it .tmp because the extension will be corrected after the image type is detected $destination = ISC_CACHE_DIRECTORY . 'picnikimage_' . Interspire_String::generateRandomString(16) . '.tmp'; if (!file_exists($destination)) { break; } } } $fh = fopen($destination, 'wb'); if ($fh) { if (!fwrite($fh, $result)) { fclose($fh); $this->log->LogSystemError('general', 'Failed to write downloaded Picnik image to local file'); $errorType = 1; return false; } fclose($fh); isc_chmod($destination, ISC_WRITEABLE_FILE_PERM); // set the chmod just incase this was a new file } else { $this->log->LogSystemError('general', 'Failed to open local file for saving downloaded Picnik image'); $errorType = 2; return false; } return $destination; }
/** * DesignMode::UpdateLayoutPanels() * * @return */ protected function UpdateLayoutPanels() { $FileContent = ""; $LayoutFile = $this->FileName; $PanelString = $this->PanelString; // we need to put the columns into an associative array $cols = explode("|", $PanelString); foreach ($cols as $key => $val) { if($val == '') { unset($cols[$key]); } } foreach($cols as $key => $val) { $PanelSplit = explode(":", $val); $Columns[$PanelSplit[0]] = explode(",",$PanelSplit[1]); } $LayoutFilePath = str_replace('//', '/', $this->templateDirectories[count($this->templateDirectories)-1].'/'.$LayoutFile); $MasterLayoutFilePath = ''; $sortedDirectories = array_reverse($this->templateDirectories); foreach($sortedDirectories as $directory) { if(file_exists($directory.'/'.$LayoutFile)) { $MasterLayoutFilePath = $directory.'/'.$LayoutFile; break; } } // File doesn't exist in the local template and in the master template. Exit if((!$MasterLayoutFilePath || !file_exists($MasterLayoutFilePath)) && !file_exists($LayoutFilePath)) { return false; } // File doesn't exist in the local template, we need to create it if(!file_exists($LayoutFilePath)) { $parentDir = dirname($LayoutFilePath); if(!is_dir($parentDir) && !isc_mkdir($parentDir, ISC_WRITEABLE_DIR_PERM, true)) { $this->SetError($LayoutFilePath); return false; } if(!@touch($LayoutFilePath)) { $this->SetError($LayoutFilePath); return false; } $FileContent = file_get_contents($MasterLayoutFilePath); } else { $FileContent = file_get_contents($LayoutFilePath); } foreach($Columns as $PanelName => $PanelList) { // we need to get the content between a div, but there might be sub-divs that we still want included... // we do this loop to get the whole bit of the correct div $inDivCount = 0; $position = 0; $count = 0; $LastReplace = ''; $LastPosition = ''; $found_gt = false; // gt = greater than $divPos = isc_strpos($FileContent, $PanelName); $size = isc_strlen($FileContent); // start the loop through the html to get it all for($i = $divPos; $i < $size; ++$i) { if($found_gt == false) { if($FileContent[$i] == ">") { // we found the end of the starting div tag, now we can search for the correct </div> $found_gt = true; $start_pos = $i+1; } } else { // looping through the content if($FileContent[$i] == "<") { if($FileContent[$i+1].$FileContent[$i+2].$FileContent[$i+3].$FileContent[$i+4] == "/div") { // we've found a closing div! if($inDivCount == 0) { // we found the end! hooray! $end_pos = $i; break; } else { // we're in a sub-div, but it closed! =D --$inDivCount; } } elseif($FileContent[$i+1].$FileContent[$i+2].$FileContent[$i+3] == "div") { // found a sub-div, up the count =( ++$inDivCount; } } } } // now we get the content! $origcontent = $content = isc_substr($FileContent, $start_pos, ($end_pos - $start_pos)); // find the panel placeholders $regex_one = '%%GLOBAL_[a-zA-Z0-9]+_Position[0-9]+%%'; $regex_two = '%%Panel[\._]([a-zA-Z0-9]{1,})%%'; preg_match_all("/(?siU)(" . $regex_one . ")|(" . $regex_two . ")/", $content , $panel_matches); // loop through the matches and replace them with temporary position placeholders foreach ($panel_matches[0] as $key => $k) { $content = str_replace($panel_matches[0][$key], "%%GLOBAL_".$PanelName."_Position".$position.'%%', $content); ++$position; } // loop through and replace the temporary position placeholders with the new panels foreach($PanelList as $key => $NewPanel) { if($count == ($position-1)) { // reached the last one! $LastPosition = "%%GLOBAL_".$PanelName."_Position".$count.'%%'; $LastReplace .= '%%Panel.'.$NewPanel."%%\r\n"; } else { $content = str_replace("%%GLOBAL_".$PanelName."_Position".$count.'%%','%%Panel.'.$NewPanel.'%%', $content); ++$count; } } if($LastPosition != '') { $content = str_replace($LastPosition,$LastReplace, $content); } $FileContent = str_replace($origcontent,$content, $FileContent); } // Fix up any stray tags we may still have $FileContent= preg_replace("#%%GLOBAL_[a-zA-Z0-9]+_Position[0-9]+%%#isu",'', $FileContent); // All done, now write the file back isc_chmod($LayoutFilePath, ISC_WRITEABLE_FILE_PERM); if (@file_put_contents($LayoutFilePath, $FileContent)) { return true; } else { $this->SetError($LayoutFilePath); return false; } }
/** * Write the result of the request cache that return from eBay * * @param int $site The Id of the site to write the cache for * @return boolean Return true if we saved the content successfully. Otherwise, return false */ public function WriteCache($siteId, $content) { $name = $this->cacheBaseDir . '/ebaydetails_' . $siteId . '.xml'; if (!is_dir($this->cacheBaseDir)) { if (!isc_mkdir($this->cacheBaseDir)) { return false; } } if (!$this->fileHandler->CheckDirWritable($this->cacheBaseDir)) { isc_chmod($this->cacheBaseDir, ISC_WRITEABLE_DIR_PERM); } // Create a file if it's not exist if (!is_file($name)) { touch($name); } return $this->fileHandler->WriteToFile($content, $name); }
private function uploadHeaderImage() { $GLOBALS['ISC_CLASS_ADMIN_ENGINE']->LoadLangFile('layout'); if ($_FILES['HeaderImageFile']['error'] != 0 || $_FILES['HeaderImageFile']['size'] == 0) { die(isc_json_encode(array( 'success' => false, 'message' => GetLang('LayoutHeaderImageUploadNoValidImage').ini_get('upload_max_filesize') ))); } if (!$this->IsImageFileJpgPng($_FILES["HeaderImageFile"]["name"])) { die(isc_json_encode(array( 'success' => false, 'message' => GetLang('LayoutHeaderImageUploadNoValidImage2') ))); } $templateName = GetConfig('template'); $fileParts = pathinfo($_FILES['HeaderImageFile']['name']); $ext = $fileParts['extension']; $imagesPath = ISC_BASE_PATH . '/' . GetConfig('ImageDirectory') . '/header_images'; $imagesUri = GetConfig('ShopPath') . '/' . GetConfig('ImageDirectory') . '/header_images'; if(!is_dir($imagesPath)) { isc_mkdir($imagesPath); } $headerImagePath = $imagesPath . '/' . $templateName . '_headerImage.' . $ext; if (!move_uploaded_file($_FILES['HeaderImageFile']['tmp_name'], $headerImagePath)) { $message = str_replace('%%PATH%%', '/'. GetConfig('ImageDirectory') . '/header_images/', GetLang('LayoutHeaderImageUploadErrorPath')); die(isc_json_encode(array( 'success' => false, 'message' => $message ))); } isc_chmod($headerImagePath, ISC_WRITEABLE_FILE_PERM); $dirObject = new DirectoryIterator($imagesPath ); foreach($dirObject as $fileName=>$objFile){ if($objFile->getFilename() != $templateName . '_headerImage.' . $ext){ @unlink($objFile->getPath()."/". $objFile->getFilename()); } } die(isc_json_encode(array( 'success' => true, 'message' => GetLang('LayoutHeaderImageUploadSuccess'), 'currentImage' => $imagesUri . '/' . $templateName . '_headerImage.' . $ext ))); }
function ChangeMode($file, $dirmode, $filemode, $recursive = false) { if (in_array($file, array(".", ".."))) { return false; } if (is_dir($this->GetDir() . $file)) { $mode = $dirmode; } elseif (is_file($this->GetDir() . $file)) { $mode = $filemode; } else { return false; } if (isc_chmod($this->GetDir() . $file, $mode)) { if ($recursive === true && is_dir($this->GetDir() . $file)) { $tmp = new FileClass(); $tmp->SetLoadDir($this->GetDir() . $file); while (($f = $tmp->NextDirElement()) !== false) { $tmp->ChangeMode($f, $dirmode, $filemode, $recursive); } $tmp->CloseHandle(); unset($tmp); } else { return true; } } else { return false; } }
/** * Generate resized version of this product image according to ISC settings, returning the absolute file path of the newly created image. If the resized image already exists and is up to date, a new one will not be generated but the file path will still be returned. * * @param int $size One of ISC_PRODUCT_IMAGE_SIZE_XXX * @param bool $save If necessary, update image in database with the correct path * @param bool $force Set to true to bypass existing file and mtime checks to force the resized image to be generated * @return string Absolute file path pointing to resized image * @throws ISC_PRODUCT_IMAGE_SOURCEFILEDOESNTEXIST_EXCEPTION If the source file does not exist */ public function generateResizedFile($size, $save = true, $force = false) { $resizedFilePath = $this->getAbsoluteResizedFilePath($size, false, $save); $absoluteSourceFilePath = $this->getAbsoluteSourceFilePath(); if (!file_exists($absoluteSourceFilePath)) { throw new ISC_PRODUCT_IMAGE_SOURCEFILEDOESNTEXIST_EXCEPTION($absoluteSourceFilePath); } $sourceImageModifiedTime = filemtime($absoluteSourceFilePath); $resizedImageModifiedTime = 0; $resizedImageFileExists = file_exists($resizedFilePath); if ($resizedImageFileExists) { $resizedImageModifiedTime = filemtime($resizedFilePath); } $configDimensionSettingTime = $this->getSizeChangedTime($size); if (!$force && $resizedImageFileExists && $sourceImageModifiedTime < $resizedImageModifiedTime && $configDimensionSettingTime < $resizedImageModifiedTime) { // resized file exists // ... and source file is hasn't changed since it was resized // ... and config settings haven't changed since it was resized // use the existing file. return $resizedFilePath; } $width = self::getSizeWidth($size); $height = self::getSizeHeight($size); // clamp the width and height to maximum internal sizes if ($width > ISC_PRODUCT_IMAGE_MAXLONGEDGE) { $width = ISC_PRODUCT_IMAGE_MAXLONGEDGE; } if ($height > ISC_PRODUCT_IMAGE_MAXLONGEDGE) { $height = ISC_PRODUCT_IMAGE_MAXLONGEDGE; } // it's possible that the destination directory may not exist yet if safe mode is off -- attempt to create it $resizedDirectoryPath = dirname($resizedFilePath); if (!file_exists($resizedDirectoryPath)) { if (!isc_mkdir($resizedDirectoryPath)) { throw new ISC_PRODUCT_IMAGE_CREATEDIRECTORY_EXCEPTION(null); } } // since the image library is cached we need to clear it just incase a resized image is already in memory $this->clearImageLibrary(); $image = $this->getImageLibrary(); $writeOptions = self::getWriteOptionsForImageType($image->getImageType()); if ($image->getWidth() > $width || $image->getHeight() > $height) { // the source image is larger than the specified resize, so scale it down $image->loadImageFileToScratch(); $image->resampleScratchToMaximumDimensions($width, $height); $image->saveScratchToFile($resizedFilePath, $writeOptions); } else { // the source image is smaller or equal to the specified resize, make a copy only copy($image->getFilePath(), $resizedFilePath); isc_chmod($image->getFilePath(), ISC_WRITEABLE_FILE_PERM); } $relativePath = $this->getResizedFilePath($size); $this->_resizedFilePaths[$size] = $relativePath; $this->_resizedFileDimensions[$size] = array($image->getWidth(), $image->getHeight()); if ($save) { $this->saveToDatabase(false); } // remove resizing resources $this->clearImageLibrary(); return $resizedFilePath; }
/** * Creates the preupgradeconfig.php cache file based on the current config values but only if the file does not already exist * * @return bool false if creation of the file failed, otherwise true on success or if the file already existed */ protected function _createPreUpgradeConfigFile ($force = false) { $file = ISC_CACHE_DIRECTORY . 'preupgradeconfig.php'; if (file_exists($file) && !$force) { return true; } $contents = '<' . '?php' . "\n" . '$preUpgradeConfig = ' . var_export($GLOBALS['ISC_CFG'], true) . ';' . "\n"; if (!file_put_contents($file, $contents)) { $this->errors[] = sprintf(GetLang('UpgradePreUpgradeConfigFileWriteFailed'), $folder); return false; } if (!isc_chmod($file, ISC_WRITEABLE_FILE_PERM)) { $this->errors[] = sprintf(GetLang('UpgradePreUpgradeConfigFileWriteFailed'), $folder); return false; } return true; }
public function _StoreFileAndReturnId($FileName) { // This function takes a file name as its arguement and stores // this file in the /downloads or /images directory depending // on the $FileType enumeration value $dir = "series_images"; if (is_array($_FILES[$FileName]) && $_FILES[$FileName]['name'] != "") { // If it's an image, make sure it's a valid image type if (isc_strtolower(isc_substr($_FILES[$FileName]['type'], 0, 5)) != "image") { return ""; } if (is_dir(sprintf("../%s", $dir))) { // Clean up the incoming file name a bit $_FILES[$FileName]['name'] = preg_replace("#[^\\w.]#i", "_", $_FILES[$FileName]['name']); $_FILES[$FileName]['name'] = preg_replace("#_{1,}#i", "_", $_FILES[$FileName]['name']); $randomFileName = GenRandFileName($_FILES[$FileName]['name']); $fileName = $randomFileName; $dest = realpath(ISC_BASE_PATH . "/" . $dir); while (file_exists($dest . "/" . $fileName)) { $fileName = basename($randomFileName); $fileName = substr_replace($randomFileName, "-" . rand(0, 10000000000.0), strrpos($randomFileName, "."), 0); $fileName = $randomDir . "/" . $fileName; } $dest .= "/" . $fileName; if (move_uploaded_file($_FILES[$FileName]["tmp_name"], $dest)) { isc_chmod($dest, ISC_WRITEABLE_FILE_PERM); // The file was moved successfully return $fileName; } else { // Couldn't move the file, maybe the directory isn't writable? return ""; } } else { // The directory doesn't exist return ""; } } else { // The file doesn't exist in the $_FILES array return ""; } }
/** * Writes a string to a file. * * @param string $content String to write to the file. * @param string $filename Full path and name of the file to be written to. * @return boolean */ public function writeToFile($content, $filename) { $res = $this->write($content, $filename, 'w+'); // Set the chmod just in case this was a new file. isc_chmod($filename, ISC_WRITEABLE_FILE_PERM); return $res; }
public function _AutoGenerateThumbForLargeImage($ImageName) { // Takes the filename of an image already uploaded into the // image directory, generates a thumbnal from it, stores it // in the image directory and returns its name $imgFile = realpath(ISC_BASE_PATH . "/" . "series_images"); $imgFile .= "/" . $ImageName; if ($ImageName == '' || !file_exists($imgFile)) { return false; } // A list of thumbnails too $tmp = explode(".", $imgFile); $ext = isc_strtolower($tmp[count($tmp) - 1]); // If overriding the existing image, set the output filename to the input filename //Large and medium size images by Simha $thumbFileName = $ImageName; $attribs = @getimagesize($imgFile); $width = $attribs[0]; $height = $attribs[1]; if (!is_array($attribs)) { return false; } // Check if we have enough available memory to create this image - if we don't, attempt to bump it up setImageFileMemLimit($imgFile); $thumbFile = realpath(ISC_BASE_PATH . "/" . "series_images"); $thumbFile .= "/" . $thumbFileName; if ($ext == "jpg") { $srcImg = @imagecreatefromjpeg($imgFile); } else { if ($ext == "gif") { $srcImg = @imagecreatefromgif($imgFile); if (!function_exists("imagegif")) { $gifHack = 1; } } else { $srcImg = @imagecreatefrompng($imgFile); } } if (!$srcImg) { return false; } $srcWidth = @imagesx($srcImg); $srcHeight = @imagesy($srcImg); //Large and medium size images by Simha $AutoThumbSize = 240; // This thumbnail is smaller than the Interspire Shopping Cart dimensions, simply copy the image and return if ($srcWidth <= $AutoThumbSize && $srcHeight <= $AutoThumbSize) { @imagedestroy($srcImg); if ($OverrideExisting == false) { @copy($imgFile, $thumbFile); } return $thumbFileName; } // Make sure the thumb has a constant height $thumbWidth = $width; $thumbHeight = $height; if ($width > $AutoThumbSize) { $thumbWidth = $AutoThumbSize; $thumbHeight = ceil($height * ($AutoThumbSize * 100 / $width) / 100); $height = $thumbHeight; $width = $thumbWidth; } if ($height > $AutoThumbSize) { $thumbHeight = $AutoThumbSize; $thumbWidth = ceil($width * ($AutoThumbSize * 100 / $height) / 100); } $thumbImage = @imagecreatetruecolor($thumbWidth, $thumbHeight); if ($ext == "gif" && !isset($gifHack)) { $colorTransparent = @imagecolortransparent($srcImg); @imagepalettecopy($srcImg, $thumbImage); @imagecolortransparent($thumbImage, $colorTransparent); @imagetruecolortopalette($thumbImage, true, 256); } else { if ($ext == "png") { @ImageColorTransparent($thumbImage, @ImageColorAllocate($thumbImage, 0, 0, 0)); @ImageAlphaBlending($thumbImage, false); } } @imagecopyresampled($thumbImage, $srcImg, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $srcWidth, $srcHeight); if ($ext == "jpg") { @imagejpeg($thumbImage, $thumbFile, 100); } else { if ($ext == "gif") { if (isset($gifHack) && $gifHack == true) { $thumbFile = isc_substr($thumbFile, 0, -3) . "jpg"; @imagejpeg($thumbImage, $thumbFile, 100); } else { @imagegif($thumbImage, $thumbFile); } } else { @imagepng($thumbImage, $thumbFile); } } @imagedestroy($thumbImage); @imagedestroy($srcImg); // Change the permissions on the thumbnail file isc_chmod($thumbFile, ISC_WRITEABLE_FILE_PERM); return $thumbFileName; }
/** * Commit a gift wrapping type to the database (either create a new one or update an existing one) * * @param array An array of data about the gift wrapping type. * @param int If updating an existing wrap, the ID. * @return boolean True if successful, false if not. */ private function CommitWrap($data, $wrapId = 0) { if (!isset($data['wrapvisible'])) { $data['wrapvisible'] = 0; } if (!isset($data['wrapallowcomments'])) { $data['wrapallowcomments'] = ''; } if (isset($_FILES['wrapimage']) && is_array($_FILES['wrapimage']) && $_FILES['wrapimage']['name'] != '') { // Clean up the incoming file name a bit $_FILES['wrapimage']['name'] = preg_replace("#[^\\w.]#i", "_", $_FILES['wrapimage']['name']); $_FILES['wrapimage']['name'] = preg_replace("#_{1,}#i", "_", $_FILES['wrapimage']['name']); $randomFileName = GenRandFileName($_FILES['wrapimage']['name']); $imageLocation = 'wrap_images/' . $randomFileName; $dest = ISC_BASE_PATH . '/' . GetConfig('ImageDirectory') . '/' . $imageLocation; if (move_uploaded_file($_FILES['wrapimage']['tmp_name'], $dest)) { isc_chmod($dest, ISC_WRITEABLE_FILE_PERM); $data['wrappreview'] = $imageLocation; } } $wrapData = array('wrapname' => $data['wrapname'], 'wrapprice' => DefaultPriceFormat($data['wrapprice']), 'wrapvisible' => (int) $data['wrapvisible'], 'wrapallowcomments' => (int) $data['wrapallowcomments']); if (isset($data['wrappreview'])) { $wrapData['wrappreview'] = $data['wrappreview']; } if ($wrapId == 0) { $wrapId = $GLOBALS['ISC_CLASS_DB']->InsertQuery('gift_wrapping', $wrapData); } else { $GLOBALS['ISC_CLASS_DB']->UpdateQuery('gift_wrapping', $wrapData, "wrapid='" . (int) $wrapId . "'"); } $GLOBALS['ISC_CLASS_DATA_STORE']->UpdateGiftWrapping(); // Couldn't save? return an error message if ($GLOBALS['ISC_CLASS_DB']->GetErrorMsg()) { return false; } return true; }
private function UploadLogo() { if ($_FILES['LogoFile']['error'] == 0 && $_FILES['LogoFile']['size'] > 0) { if (!$this->IsValidUploadedLogo($_FILES['LogoFile'])) { $this->ManageLayouts(GetLang('UploadedLogoNoValidImage2'), MSG_ERROR); } else { $_FILES['LogoFile']['name'] = basename($_FILES['LogoFile']['name']); // Upload and store the actual logo if (move_uploaded_file($_FILES['LogoFile']['tmp_name'], ISC_BASE_PATH . '/' . GetConfig('ImageDirectory') . '/' . basename($_FILES['LogoFile']['name']))) { // Save the updated logo in the configuration file $GLOBALS['ISC_NEW_CFG']['StoreLogo'] = $_FILES['LogoFile']['name']; $GLOBALS['ISC_NEW_CFG']['UsingTemplateLogo'] = 0; $GLOBALS['ISC_NEW_CFG']['LogoType'] = 'image'; $GLOBALS['ISC_NEW_CFG']['UsingLogoEditor'] = 0; $settings = GetClass('ISC_ADMIN_SETTINGS'); if ($settings->CommitSettings()) { isc_chmod(ISC_BASE_PATH . '/' . GetConfig('ImageDirectory') . '/' . $GLOBALS['ISC_NEW_CFG']['StoreLogo'], ISC_WRITEABLE_FILE_PERM); FlashMessage(GetLang('LogoUploadSuccess'), MSG_SUCCESS, 'index.php?ToDo=viewTemplates'); } else { FlashMessage(GetLang('UploadWorkedConfigError'), MSG_ERROR, 'index.php?ToDo=viewTemplates'); } } else { FlashMessage(GetLang('UploadErrorPath'), MSG_ERROR, 'index.php?ToDo=viewTemplates'); } } } else { FlashMessage(GetLang('LogoUploadNoValidImage'), MSG_ERROR, 'index.php?ToDo=viewTemplates'); exit; } }
/** * _StoreOptionImageAndReturnId * Works the same way as the _StoreFileAndReturnId function except there's a few changes because of the way images for options are retrieved from the $_FILES array * * @param Int $OptionFileId The ID of the option whose image should be saved * @return String Empty on failure, the new filename on success */ public function _StoreOptionImageAndReturnId($OptionFileId) { // This function takes a file name as its arguement and stores // this file in the /downloads or /images directory depending // on the $FileType enumeration value $dir = GetConfig('ImageDirectory'); if (is_dir(sprintf("../%s", $dir))) { // Images are stored within a directory randomly chosen from a-z. $randomDir = strtolower(chr(rand(65, 90))); if (!is_dir("../" . $dir . "/" . $randomDir)) { if (!@mkdir("../" . $dir . "/" . $randomDir, 0777)) { $randomDir = ''; } } // Clean up the incoming file name a bit $_FILES['options']['name'][$OptionFileId]['image'] = preg_replace("#[^\\w.]#i", "_", $_FILES['options']['name'][$OptionFileId]['image']); $_FILES['options']['name'][$OptionFileId]['image'] = preg_replace("#_{1,}#i", "_", $_FILES['options']['name'][$OptionFileId]['image']); $randomFileName = GenRandFileName($_FILES['options']['name'][$OptionFileId]['image']); $fileName = $randomDir . "/" . $randomFileName; $dest = realpath(ISC_BASE_PATH . '/' . $dir); while (file_exists($dest . "/" . $fileName)) { $fileName = basename($randomFileName); $fileName = substr_replace($randomFileName, "-" . rand(0, 10000000000.0), strrpos($randomFileName, "."), 0); $fileName = $randomDir . "/" . $fileName; } $dest .= "/" . $fileName; if (move_uploaded_file($_FILES['options']['tmp_name'][$OptionFileId]['image'], $dest)) { isc_chmod($dest, ISC_WRITEABLE_FILE_PERM); // The file was moved successfully return $fileName; } else { // Couldn't move the file, maybe the directory isn't writable? return ""; } } else { // The directory doesn't exist return ""; } }
public function _StoreCSVfile($FileName) { $dir = "ymmfiles"; $MsgStatus = ""; if (is_array($_FILES[$FileName]) && $_FILES[$FileName]['name'] != "") { if (isc_strtolower(isc_substr($_FILES[$FileName]['name'], -3)) != "csv") { echo $GLOBALS['Message'] = MessageBox("Please upload a csv file as YMM data", $MsgStatus); return ""; } if (!is_dir(sprintf("../%s", $dir))) { @mkdir("../" . $dir, 0777); } // Clean up the incoming file name a bit $_FILES[$FileName]['name'] = preg_replace("#[^\\w.]#i", "_", $_FILES[$FileName]['name']); $_FILES[$FileName]['name'] = preg_replace("#_{1,}#i", "_", $_FILES[$FileName]['name']); $randomFileName = GenRandFileName($_FILES[$FileName]['name']); $dest = realpath(ISC_BASE_PATH . "/" . $dir); $dest .= "/" . $randomFileName; if (move_uploaded_file($_FILES[$FileName]["tmp_name"], $dest)) { isc_chmod($dest, ISC_WRITEABLE_FILE_PERM); // The file was moved successfully return $randomFileName; } else { // Couldn't move the file, maybe the directory isn't writable? return ""; } } else { // The file doesn't exist in the $_FILES array return ""; } }
/** * Generate a thumbnail version of a particular image. * * @param string The file system path of the image to create a thumbnail of. * @param string The file system path of the name/location to save the thumbnail. * @param int The maximum width of the image. * @param boolean If the image is small enough, copy it to destLocation, otherwise just return. */ function GenerateThumbnail($sourceLocation, $destLocation, $maxWidth, $maxHeight = null) { if (is_null($maxHeight)) { $maxHeight = $maxWidth; } if ($sourceLocation == '' || !file_exists($sourceLocation)) { return false; } else { if (!is_dir(dirname($destLocation)) || !is_writable(dirname($destLocation))) { return false; } } // A list of thumbnails too $tmp = explode(".", $sourceLocation); $ext = isc_strtolower($tmp[count($tmp) - 1]); $attribs = @getimagesize($sourceLocation); $srcWidth = $attribs[0]; $srcHeight = $attribs[1]; if (!is_array($attribs)) { return false; } // Check if we have enough available memory to create this image - if we don't, attempt to bump it up SetImageFileMemLimit($sourceLocation); if ($ext == "jpg") { $srcImg = @imagecreatefromjpeg($sourceLocation); } else { if ($ext == "gif") { $srcImg = @imagecreatefromgif($sourceLocation); if (!function_exists("imagegif")) { $gifHack = 1; } } else { $srcImg = @imagecreatefrompng($sourceLocation); } } if (!$srcImg) { return false; } // This image dimensions. Simply copy and return if ($srcWidth <= $maxWidth && $srcHeight <= $maxHeight) { @imagedestroy($srcImg); if ($sourceLocation != $destLocation && copy($sourceLocation, $destLocation)) { return true; } } // Make sure the thumb has a constant height $width = $srcWidth; $thumbWidth = $srcWidth; $height = $srcHeight; $thumbHeight = $srcHeight; if ($width > $maxWidth) { $thumbWidth = $maxWidth; $thumbHeight = $maxWidth / $srcWidth * $srcHeight; } else { $thumbHeight = $maxHeight; $thumbWidth = $maxHeight / $srcHeight * $srcWidth; } $thumbImage = @imagecreatetruecolor($thumbWidth, $thumbHeight); if ($ext == "gif" && !isset($gifHack)) { $colorTransparent = @imagecolortransparent($srcImg); @imagepalettecopy($srcImg, $thumbImage); @imagecolortransparent($thumbImage, $colorTransparent); @imagetruecolortopalette($thumbImage, true, 256); } else { if ($ext == "png") { @ImageColorTransparent($thumbImage, @ImageColorAllocate($thumbImage, 0, 0, 0)); @ImageAlphaBlending($thumbImage, false); } } @imagecopyresampled($thumbImage, $srcImg, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $srcWidth, $srcHeight); if ($ext == "jpg") { @imagejpeg($thumbImage, $destLocation, 100); } else { if ($ext == "gif") { if (isset($gifHack) && $gifHack == true) { $thumbFile = isc_substr($thumbFile, 0, -3) . "jpg"; @imagejpeg($thumbImage, $destLocation, 100); } else { @imagegif($thumbImage, $destLocation); } } else { @imagepng($thumbImage, $destLocation); } } @imagedestroy($thumbImage); @imagedestroy($srcImg); // Change the permissions on the thumbnail file isc_chmod($destLocation, ISC_WRITEABLE_FILE_PERM); return true; }
/** * Write the current scratch to a file using the file format specs set in $imageWriteOptions * * @param string $destinationFilePath * @param ISC_IMAGE_WRITEOPTIONS $imageWriteOptions */ public function saveScratchToFile($destinationFilePath, ISC_IMAGE_WRITEOPTIONS $imageWriteOptions) { $imageType = $imageWriteOptions->getImageType(); switch ($imageType) { case IMAGETYPE_JPEG: imagejpeg($this->getScratchResource(), $destinationFilePath, (int)$imageWriteOptions->getQuality()); break; case IMAGETYPE_PNG: if (version_compare(PHP_VERSION, '5.1.3', '>=')) { // filters parameter was added in 5.1.3 imagepng($this->getScratchResource(), $destinationFilePath, (int)$imageWriteOptions->getCompression(), (int)$imageWriteOptions->getFilters()); } else if (version_compare(PHP_VERSION, '5.1.2', '>=')) { // quality parameter was added in 5.1.2 imagepng($this->getScratchResource(), $destinationFilePath, (int)$imageWriteOptions->getCompression()); } else { imagepng($this->getScratchResource(), $destinationFilePath); } break; case IMAGETYPE_GIF: imagegif($this->getScratchResource(), $destinationFilePath); break; default: throw new ISC_IMAGE_LIBRARY_GD_UNSUPPORTEDIMAGETYPE_EXCEPTION($imageType); break; } isc_chmod($destinationFilePath, ISC_WRITEABLE_FILE_PERM); }