Source

yii-img / components / ImgManager.php

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
<?php
/**
 * Image manager class file.
 * @author Christoffer Niska <ChristofferNiska@gmail.com>
 * @copyright Copyright &copy; Christoffer Niska 2011-
 * @license http://www.opensource.org/licenses/bsd-license New BSD License
 * @since 0.5
 */

/**
 * Provides easy image manipulation with the help of the excellent PHP Thumbnailer library.
 * @see http://phpthumb.gxdlabs.com/
 */

require_once(dirname(__FILE__) . '/../vendors/phpthumb/ThumbLib.inc.php'); // Yii::import() will not work in this case.

class ImgManager extends CApplicationComponent
{
	/**
	 * PhpThumb options that are passed to the ThumbFactory.
	 * Default values are the following:
	 *
	 * <code>
	 * array(
	 *     'resizeUp' => false,
	 *     'jpegQuality' => 100,
	 *     'correctPermissions' => false,
	 *     'preserveAlpha' => true,
	 *     'alphaMaskColor'	=> array(255, 255, 255),
	 *     'preserveTransparency' => true,
	 *     'transparencyMaskColor' => array(0, 0, 0),
	 * );
	 * </code>
	 *
	 * @var array
	 */
	public $thumbOptions=array();
	/**
	 * @var string the base url.
	 */
	public $baseUrl;
	/**
	 * @var string the relative path where to store images.
	 */
	public $imagePath='files/images/';
	/**
	 * @var string the name of the original directory.
	 */
	public $originalDir='original';
	/**
	 * @var string the name of the version directory.
	 */
	public $versionDir='versions';
	/**
	 * @var array the image versions.
	 */
	public $versions=array();
	/**
	 * @var string the base path.
	 */
	protected $_basePath;
	/**
	 * @var string the path to the original images.
	 */
	protected $_originalBasePath;
	/**
	 * @var string the path to the versioned images.
	 */
	protected $_versionBasePath;

	private static $_thumbOptions=array(); // needed for the static factory-method
	private static $_imagePath;

	/**
	 * Initializes the component.
	 */
	public function init()
	{
		self::$_thumbOptions=$this->thumbOptions;
		self::$_imagePath=$this->getImagePath(true);

		if ($this->baseUrl === null)
			$this->baseUrl = Yii::app()->request->baseUrl;

		parent::init();
	}

	/**
	 * Returns the URL for a specific image.
	 * @param string $id the image id.
	 * @param string $version the name of the image version.
	 * @param boolean $absolute whether or not to get an absolute URL.
	 * @return string the URL.
	 * @throws ImgException if the version is not defined.
	 */
	public function getURL($id,$version,$absolute=false)
	{
		if(isset($this->versions[$version]))
		{
			$image=$this->loadModel($id);
			$path=$this->getVersionPath($version,$absolute).$image->getPath().$this->resolveFileName($image);
			return $this->baseUrl.'/'.$path;
		}
		else
			throw new ImgException(Img::t('error','Failed to get image URL! Version is unknown.'));
	}

	/**
	 * Saves a new image.
	 * @param CUploadedFile $file the uploaded image.
	 * @param string $name the image name. Available since 1.2.0
	 * @param string $path the path to save the file to. Available since 1.2.1.
	 * @return Image the image record.
	 * @throws ImgException if saving the file or creating the directory fails.
	 * @throws CException if a query fails.
	 */
	public function save($file,$name=null,$path=null)
	{
		$trx=Yii::app()->db->beginTransaction();

		try
		{
			$image=new Image();
			$image->extension=strtolower($file->getExtensionName());
			$image->filename=$file->getName();
			$image->byteSize=$file->getSize();
			$image->mimeType=$file->getType();
			$image->created=new CDbExpression('NOW()');

			if($name!==null)
				$image->name=$this->normalizeString($name);

			if($path!==null)
				$image->path=trim($path,'/');

			if($image->save()===false)
				throw new ImgException(Img::t('error','Failed to save image! Record could not be saved.'));

			$path=$this->resolveImagePath($image);

			if(!file_exists($path) && !$this->createDirectory($path))
				throw new ImgException(Img::t('error','Failed to save image! Directory could not be created.'));

			$path.=$this->resolveFileName($image);

			if($file->saveAs($path)===false)
				throw new ImgException(Img::t('error','Failed to save image! File could not be saved.'));

			$trx->commit();
			return $image;
		}
		catch(CException $e)
		{
			$trx->rollback();
			throw $e;
		}
	}

	/**
	 * Creates a new version of a specific image.
	 * @param integer $id the image id.
	 * @param string $version the image version.
	 * @return ThumbBase
	 * @throws ImgException if creating the image version fails.
	 */
	public function createVersion($id,$version)
	{
		if(isset($this->versions[$version]))
		{
			$image=$this->loadModel($id);

			if($image!=null)
			{
				$fileName=$this->resolveFileName($image);
				$thumb=self::thumbFactory($this->resolveImagePath($image).$fileName);
				$options=ImgOptions::create($this->versions[$version]);
				$thumb->applyOptions($options);
				$path=$this->resolveImageVersionPath($image,$version);

				if(!file_exists($path) && !$this->createDirectory($path))
					throw new ImgException(Img::t('error','Failed to create version! Directory could not be created.'));

				$path.=$fileName;

				return $thumb->save($path);
			}
			else
				throw new ImgException(Img::t('error','Failed to create version! Image could not be found.'));
		}
		else
			throw new ImgException(Img::t('error','Failed to create version! Version is unknown.'));
	}

	/**
	 * Deletes a specific image.
	 * @param integer $id the image id.
	 * @return boolean whether the image was deleted.
	 * @throws ImgException if the image cannot be deleted.
	 */
	public function delete($id)
	{
		/** @var Image $image */
		$image = Image::model()->findByPk($id);

		if($image instanceof Image)
		{
			$deleted = true;

			$path=$this->resolveImagePath($image).$this->resolveFileName($image);

			if($image->delete()===false)
				throw new ImgException(Img::t('error', 'Failed to delete image! Record could not be deleted.'));

			if(file_exists($path)!==false && unlink($path)===false)
				throw new ImgException(Img::t('error', 'Failed to delete image! File could not be deleted.'));

			foreach($this->versions as $version=>$config)
				$deleted = $this->deleteVersion($image,$version);

			return $deleted;
		}
		else
			throw new ImgException(Img::t('error', 'Failed to delete image! Record could not be found.'));
	}

	/**
	 * Deletes a specific image version.
	 * @param Image $image the image model.
	 * @param string $version the image version.
	 * @return boolean whether the image was deleted.
	 * @throws ImgException if the image cannot be deleted.
	 */
	protected function deleteVersion($image,$version)
	{
		if(isset($this->versions[$version]))
		{
			$path=$this->resolveImageVersionPath($image,$version).$this->resolveFileName($image);
			
			if(file_exists($path)!==false && unlink($path)===false)
				throw new ImgException(Img::t('error', 'Failed to delete the image version! File could not be deleted.'));

			return true;
		}
		else
			throw new ImgException(Img::t('error', 'Failed to delete image version! Version is unknown.'));
	}

	/**
	 * Loads a thumb of a specific image.
	 * @param integer $id the image id.
	 * @return ThumbBase
	 */
	public function loadThumb($id)
	{
		$image=$this->loadModel($id);

		if($image!==null)
		{
			$fileName=$this->resolveFileName($image);
			$thumb=self::thumbFactory($this->resolveImagePath($image).$fileName);
			return $thumb;
		}
		else
			return null;
	}

	/**
	 * Loads a specific image model.
	 * @param integer $id the image id.
	 * @return Image
	 */
	public function loadModel($id)
	{
		return Image::model()->findByPk($id);
	}

	/**
	 * Returns the original image file name.
	 * @param Image $image the image model.
	 * @return string the file name.
	 */
	protected function resolveFileName($image)
	{
		if(!empty($image->name))
			return $image->name.'-'.$image->id.'.'.$image->extension; // 1.2.0 ->
		else
			return $image->id.'.'.$image->extension; // backwards compatibility
	}

	/**
	 * Returns the path to a specific image.
	 * @param Image $image the image model.
	 * @return string the path.
	 */
	protected function resolveImagePath($image)
	{
		return $this->getOriginalPath(true).$image->getPath();
	}

	/**
	 * Returns the path to a specific image version.
	 * @param Image $image the image model.
	 * @param string $version the image version.
	 * @return string the path.
	 */
	protected function resolveImageVersionPath($image,$version)
	{
		return $this->getVersionPath($version,true).$image->getPath();
	}

	/**
	 * Returns the images path.
	 * @param boolean $absolute whether or not the path should be absolute.
	 * @return string the path.
	 */
	protected function getImagePath($absolute=false)
	{
		$path='';

		if($absolute===true)
			$path.=$this->getBasePath();

		return $path.$this->imagePath;
	}

	/**
	 * Returns the version specific path.
	 * @param string $version the name of the image version.
	 * @param boolean $absolute whether or not the path should be absolute.
	 * @return string the path.
	 */
	protected function getVersionPath($version,$absolute=false)
	{
		$path=$this->getVersionBasePath($absolute).$version.'/';

		// Might be a new version so we need to create the path if it doesn't exist.
		if($absolute && !file_exists($path))
			$this->createDirectory($path);

		return $path;
	}

	/**
	 * Returns the path to the original images.
	 * @param boolean $absolute whether or not the path should be absolute.
	 * @return string the path.
	 */
	protected function getOriginalPath($absolute=false)
	{
		$path='';

		if($absolute===true)
			$path.=$this->getBasePath();

		if($this->_originalBasePath!==null)
			$path.=$this->_originalBasePath;
		else
			$path.=$this->_originalBasePath = $this->getImagePath().$this->originalDir.'/';

		return $path;
	}

	/**
	 * Returns the path to the versioned images.
	 * @param boolean $absolute whether or not the path should be absolute.
	 * @return string the path.
	 */
	protected function getVersionBasePath($absolute=false)
	{
		$path='';

		if($absolute===true)
			$path.=$this->getBasePath();

		if($this->_versionBasePath!==null)
			$path.=$this->_versionBasePath;
		else
			$path.=$this->_versionBasePath = $this->getImagePath().$this->versionDir.'/';

		return $path;
	}

	/**
	 * Returns the base path.
	 * @return string the path.
	 */
	protected function getBasePath()
	{
		if($this->_basePath!==null)
			return $this->_basePath;
		else
			return $this->_basePath=realpath(Yii::app()->basePath.'/../').'/';
	}

	/**
	 * Creates the specified directory.
	 * @param string $path the directory path.
	 * @param integer $mode the file mode.
	 * @param boolean $recursive allows the creation of nested directories.
	 * @return boolean whether or not the directory was created.
	 * @since 1.2.1
	 */
	protected function createDirectory($path,$mode=0777,$recursive=true)
	{
		return mkdir($path,$mode,$recursive);
	}

	/**
	 * Normalizes the given string by replacing special characters. �=>a, �=>e, �=>o, etc.
	 * @param string $string the text to normalize.
	 * @return string the normalized string.
	 * @since 1.2.0
	 */
	protected function normalizeString($string)
	{
		$string=str_replace(str_split('-/\?%*:|"<>. '),'',$string);
		$string=preg_replace('/&([a-z]{1,2})(acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);/i','$1',htmlentities($string,ENT_QUOTES,'UTF-8'));
		$string=preg_replace('/&.+;/','',$string);
		return $string;
	}

	/**
	 * Creates a new image.
	 * @param string $filePath the image file path.
	 * @return ImgThumb
	 */
	protected static function thumbFactory($filePath)
	{
		$phpThumb=PhpThumbFactory::create($filePath,self::$_thumbOptions);
		return new ImgThumb($phpThumb);
	}
}