Example #1
0
		/**
		*	Load up an RSS feed, parse its contents and return it.
		*/
		public function _LoadFeed($FeedURL, $NumEntries=0, $CacheTime=0, $FeedId="", $RSSFeedSnippet="", $helpLinks = false)
		{
			$reload = true;
			if($CacheTime > 0) {
				if($FeedId != "") {
					$FeedID = md5($FeedURL);
				}
				$reload = false;
				if(!is_dir(ISC_BASE_PATH."/cache/feeds")) {
					isc_mkdir(ISC_BASE_PATH."/cache/feeds/");
				}
				// Using a cached version that hasn't expired yet
				if(file_exists(ISC_BASE_PATH."/cache/feeds/".$FeedId) && filemtime(ISC_BASE_PATH."/cache/feeds/".$FeedId) > time()-$CacheTime) {
					$contents = file_get_contents(ISC_BASE_PATH."/cache/feeds/".$FeedId);
					// Cache was bad, recreate
					if(!$contents) {
						$reload = true;
					}
				}
				else {
					$reload = true;
				}
			}

			if ($reload === true) {
				$contents = PostToRemoteFileAndGetResponse($FeedURL);
				// Do we need to cache this version?
				if ($CacheTime > 0 && $contents != "") {
					@file_put_contents(ISC_BASE_PATH."/cache/feeds/".$FeedId, $contents);
				}
			}

			$output = "";
			$count = 0;

			// Could not load the feed, return an error
			if(!$contents) {
				return false;
			}


			// Silence errors to not polute out logs with peoples invalid XML feeds
			if($xml = @simplexml_load_string($contents)) {
				require_once(ISC_BASE_PATH . "/lib/xml.php");

				$rss = new ISC_XML();
				$entries = $rss->ParseRSS($xml);

				foreach($entries as $entry) {
					$GLOBALS['RSSTitle'] = $entry['title'];
					$GLOBALS['RSSDescription'] = $entry['description'];
					$GLOBALS['RSSLink'] = $entry['link'];

					if ($RSSFeedSnippet != "") {
						if ($helpLinks) {
							preg_match('#/questions/([0-9]+)/#si', $entry['link'], $matches);
							if (!empty($matches)) {
								$GLOBALS['RSSLink'] = $matches[1];
							}
						}
						if(defined('ISC_ADMIN_CP')) {
							$output .= Interspire_Template::getInstance('admin')->render('Snippets/'.$RSSFeedSnippet.'.html');
						}
						else {
							$output .= $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet($RSSFeedSnippet);
						}
					} else {
						if(defined('ISC_ADMIN_CP')) {
							$output .= Interspire_Template::getInstance('admin')->render('Snippets/PageRSSItem.html');
						}
						else {
							$output .= $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("PageRSSItem");
						}
					}

					if($NumEntries > 0 && ++$count >= $NumEntries) {
						break;
					}
				}

				return $output;
			}
			else {
				return false;
			}
		}
Example #2
0
// 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");
	}

	header("Last-Modified: " . gmdate("r", filemtime($CacheTemplateImageFile)));
	echo file_get_contents($CacheTemplateImageFile);
	die();
}elseif(file_exists($TemplateImageFile)) {
	if(!is_dir(ISC_BASE_PATH . '/cache/tplthumbs/')) {
		isc_mkdir(ISC_BASE_PATH . '/cache/tplthumbs/');
	}
	if((strtolower(substr($TemplateImageFile,-4)) == ".jpg" || strtolower(substr($TemplateImageFile,-5)) == ".jpeg") && function_exists('imagejpeg')) {
		// jpeg image
		header("Content-type: image/jpeg");
		$writeOptions = new ISC_IMAGE_WRITEOPTIONS_JPEG();
	}elseif(strtolower(substr($TemplateImageFile,-4)) == ".gif" && function_exists('imagegif') ) {
		// gif image
		header("Content-type: image/gif");
		$writeOptions = new ISC_IMAGE_WRITEOPTIONS_GIF();
	}
	header("Last-Modified: " . gmdate("r"));

	$image = ISC_IMAGE_LIBRARY_FACTORY::getImageLibraryInstance($TemplateImageFile);
	$image->loadImageFileToScratch();
	$image->resampleScratchToMaximumDimensions(200, 200);
Example #3
0
	public function CreateDirectory($directory)
	{
		return isc_mkdir($this->pwd . "/" . $directory, ISC_WRITEABLE_DIR_PERM, true);
	}
Example #4
0
		private function SaveCategoryImage()
		{
			if (!array_key_exists('catimagefile', $_FILES) || $_FILES['catimagefile']['error'] !== 0 || strtolower(substr($_FILES['catimagefile']['type'], 0, 6)) !== 'image/') {
				return false;
			}

			// Attempt to set the memory limit so we can resize this image
			ISC_IMAGE_LIBRARY_FACTORY::setImageFileMemLimit($_FILES['catimagefile']['tmp_name']);

			// Determine the destination directory
			$randomDir = strtolower(chr(rand(65, 90)));
			$destPath = realpath(ISC_BASE_PATH.'/' . GetConfig('ImageDirectory'));

			if (!is_dir($destPath . '/' . $randomDir)) {
				if (!isc_mkdir($destPath . '/' . $randomDir)) {
					$randomDir = '';
				}
			}

			$destFile = GenRandFileName($_FILES['catimagefile']['name'], 'category');
			$destPath = $destPath . '/' . $randomDir . '/' . $destFile;
			$returnPath = $randomDir . '/' . $destFile;

			$tmp = explode('.', $_FILES['catimagefile']['name']);
			$ext = strtolower($tmp[count($tmp)-1]);

			if ($ext == 'jpg') {
				$srcImg = imagecreatefromjpeg($_FILES['catimagefile']['tmp_name']);
			} else if($ext == 'gif') {
				$srcImg = imagecreatefromgif($_FILES['catimagefile']['tmp_name']);
				if(!function_exists('imagegif')) {
					$gifHack = 1;
				}
			} else {
				$srcImg = imagecreatefrompng($_FILES['catimagefile']['tmp_name']);
			}

			$srcWidth = imagesx($srcImg);
			$srcHeight = imagesy($srcImg);
			$widthLimit = GetConfig('CategoryImageWidth');
			$heightLimit = GetConfig('CategoryImageHeight');

			// If the image is small enough, simply move it
			if($srcWidth <= $widthLimit && $srcHeight <= $heightLimit) {
				imagedestroy($srcImg);
				move_uploaded_file($_FILES['catimagefile']['tmp_name'], $destPath);
				// set image to be writable
				isc_chmod($destPath, ISC_WRITEABLE_FILE_PERM);
				return $returnPath;
			}

			// Otherwise, resize it
			$attribs = getimagesize($_FILES['catimagefile']['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['catimagefile']['tmp_name']);

			// Change the permissions on the thumbnail file
			isc_chmod($destPath, ISC_WRITEABLE_FILE_PERM);

			return $returnPath;
		}
Example #5
0
	/**
	 * Runs the import actions
	 */

	public function __construct($customFields=array())
	{
		parent::__construct();
		$GLOBALS['ISC_CLASS_ADMIN_ENGINE']->LoadLangFile('batch.importer');

		define("ISC_TMP_IMPORT_DIRECTORY", ISC_CACHE_DIRECTORY."/import");

		// Set the import session

		if(!isset($_REQUEST['ImportSession'])) {
			$_REQUEST['ImportSession'] = md5(uniqid(rand(), true).time());
		} else {
			require_once ISC_TMP_IMPORT_DIRECTORY . "/session-" . $_REQUEST['ImportSession'];
			if (isset($ImportSession)) {
				$this->ImportSession = $ImportSession;
			}
		}

		$this->ServerImportDirectory = dirname(__FILE__)."/../../import";

		/**
		 * Set the custom fields
		 */
		if (!is_array($customFields)) {
			$customFields = array();
		}

		$this->customFields = $customFields;

		if (!is_dir(ISC_TMP_IMPORT_DIRECTORY)) {
			isc_mkdir(ISC_TMP_IMPORT_DIRECTORY);
		}

		$GLOBALS['ToDo'] = $_REQUEST['ToDo'];

		if(!isset($_REQUEST['Step'])) {
			$_REQUEST['Step'] = 1;
		}
		switch($_REQUEST['Step'])
		{
			case 2:
				$this->_ImportStep2();
				break;
			case 3:
				$this->_ImportStep3();
				break;
			case 4:
				$this->_Import();
				break;
			case 5:
				$this->_GenerateImportSummary();
				break;
			case 'ImportFrame':
				$this->_ImportStatusFrame();
				break;
			case "ViewReport":
				$this->_GenerateReport($_REQUEST['ReportType']);
			default:
				$this->_ImportStep1();
		}
	}
Example #6
0
		/**
		* copy a product image to another random directory
		*
		* @param string $imagePath, the path to the origin image
		*
		* return string path to the new image
		*/
		public function _CopyImages($imagePath, $dir = '')
		{
			//check if the original file exist
			if (!is_file($imagePath)) {
				return '';
			}

			if($dir == '') {
				$dir = GetConfig('ImageDirectory');
			}

			$dest = realpath(ISC_BASE_PATH."/" . $dir);
			$randomDir = strtolower(chr(rand(65, 90)));
			if(!is_dir("../".$dir."/".$randomDir)) {
				if(!isc_mkdir("../".$dir."/".$randomDir)) {
					$randomDir = '';
				}
			}

			$fileName = preg_replace('/^.*\//', '', $imagePath);

			//check is filename exsits in the dest directory, rename file name if exsits
			if (file_exists($dest.$randomDir.'/'.$fileName)) {
				$fileName = basename($randomFileName);
				$fileName = substr_replace($randomFileName, "-".rand(0, 10000000000), strrpos($randomFileName, "."), 0);
			}
			$newPath = $dest.'/'.$randomDir.'/'.$fileName;

			//cppy file to new directory
			if (copy($imagePath, $newPath)) {
				return $randomDir.'/'.$fileName;
			} else {
				return '';
			}
		}
Example #7
0
	private function _ImportFile($record, $index = '')
	{
		$productFileName = $record['prodfile' . $index];

		$fileDescription = '';
		if (!empty($record['prodfiledescription' . $index])) {
			$fileDescription = $record['prodfiledescription' . $index];
		}

		$fileMaxDownloads = 0;
		if (!empty($record['prodfilemaxdownloads' . $index])) {
			$fileMaxDownloads = (int)$record['prodfilemaxdownloads' . $index];
		}

		$fileExpiresAfter = 0;
		if (!empty($record['prodfileexpiresafter' . $index])) {
			if (preg_match('/([0-9]+) (days|weeks|months|years)/i', $record['prodfileexpiresafter' . $index], $matches)) {
				$quantity = $matches[1];
				$unit = strtolower($matches[2]);

				switch ($unit) {
					case 'days':
						$fileExpiresAfter = 86400 * $quantity;
						break;
					case 'weeks':
						$fileExpiresAfter = 604800 * $quantity;
						break;
					case 'months':
						$fileExpiresAfter = 2592000 * $quantity; //assumed to be 30 days, as per class.product.php
						break;
					case 'years':
						$fileExpiresAfter = 31536000 * $quantity;
						break;
				}
			}
		}

		$productFile = false;

		// Is this a remote file?
		$downloadDirectory = ISC_BASE_PATH."/".GetConfig('DownloadDirectory');
		if(isc_substr(isc_strtolower($productFileName), 0, 7) == "http://") {
			// Need to fetch the remote file
			$file = PostToRemoteFileAndGetResponse($productFileName);
			if($file) {
				// Place it in our downloads directory
				$randomDir = strtolower(chr(rand(65, 90)));
				if(!is_dir($downloadDirectory.$randomDir)) {
					if(!isc_mkdir($downloadDirectory."/".$randomDir)) {
						$randomDir = '';
					}
				}

				// Generate a random filename
				$fileName = $randomDir . "/" . GenRandFileName(basename($productFileName));
				if(!@file_put_contents($downloadDirectory."/".$fileName, $file)) {
					$this->ImportSession['Results']['Warnings'][] = $record['prodname'].GetLang('ImportProductFileUnableToMove');
				}
				else {
					$productFile = array(
						"prodhash" => "",
						"downfile" => $fileName,
						"downdateadded" => time(),
						"downmaxdownloads" => $fileMaxDownloads,
						"downexpiresafter" => $fileExpiresAfter,
						"downfilesize" => filesize($downloadDirectory."/".$fileName),
						"downname" => basename($productFileName),
						"downdescription" => $fileDescription
					);
				}
			}
			else {
				$this->ImportSession['Results']['Warnings'][] = $record['prodname'].GetLang('ImportProductFileDoesntExist');
			}
		}
		// Treating the file as a local file, in the product_fules/import directory
		else {
			// This file exists, can be imported
			if(file_exists($downloadDirectory."/import/".$productFileName)) {

				// Move it to our images directory
				$randomDir = strtolower(chr(rand(65, 90)));
				if(!is_dir("../".$downloadDirectory."/".$randomDir)) {
					if(!isc_mkdir($downloadDirectory."/".$randomDir)) {
						$randomDir = '';
					}
				}

				// Generate a random filename
				$fileName = $randomDir . "/" . GenRandFileName($productFileName);
				if(!@copy($downloadDirectory."/import/".$productFileName, $downloadDirectory."/".$fileName)) {
					$this->ImportSession['Results']['Warnings'][] = $record['prodname'].GetLang('ImportProductFileUnableToMove');
				}
				else {
					$productFile = array(
						"prodhash" => "",
						"downfile" => $fileName,
						"downdateadded" => time(),
						"downmaxdownloads" => $fileMaxDownloads,
						"downexpiresafter" => $fileExpiresAfter,
						"downfilesize" => filesize($downloadDirectory."/".$fileName),
						"downname" => basename($productFileName),
						"downdescription" => $fileDescription
					);
				}
			}
			else {
				$this->ImportSession['Results']['Warnings'][] = $record['prodname'].GetLang('ImportProductFileDoesntExist');
			}
		}

		return $productFile;
	}
Example #8
0
	/**
	 * 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);
	}
Example #9
0
  /**
   * 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;
		}
	}
Example #10
0
		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
			)));
		}
Example #11
0
	/**
	* _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)) {
			isc_mkdir($this->imagedir);
		}

		$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;
	}
Example #12
0
	/**
	* 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;
	}