Location: PHPKode > projects > Kwalbum > kwalbum/include/ItemAdder.php
<?php
/**
 * @package kwalbum
 * @version 2.1.2
 * @since 2.0
 */

require_once 'include/pjmt/EXIF.php';
require_once 'include/pjmt/Photoshop_File_Info.php';
require_once 'include/itemTypes.php';
require_once 'include/funcChangeTags.php';
/**
 * Work with the filesystem and database to add a new item.
 * @since 2.0
 */
class ItemAdder
{
	/**
	 * Remove characters that may cause errors when resizing.
	 * @param string $oldName original filename submitted by the
	 * user
	 * @return string modified filename with characters replaced
	 * @since 2.0
	 */
	public function ReplaceBadFilenameChars($oldName)
	{
		if (get_magic_quotes_gpc())
			$oldName = stripslashes($oldName);
		return strtr($oldName, array (
			' ' => '_',
			'&' => 'and',
			'+' => 'plus',
			'\'' => '_',
			'"' => '_',
			'<' => '_',
			'>' => '_',
			'$' => '_',
			'!' => '_',
			'*' => '_',
			'(' => '-',
			')' => '-'
		));
	}

	/**
	 * Replace a date with the current time if it is not real.
	 * @param string $date original 'yyyy-mm-dd hh:mm:ss' datetime
	 * submitted by the user
	 * @return string valid datetime that can be inserted into the
	 * database
	 * @since 2.0
	 */
	public function ReplaceBadDate($date)
	{

		if (empty ($date) or ($time = @ strtotime($date)) < 1)
			$date = '0000-00-00 00:00:00';
		else
			$date = date('Y-m-d H:i:s', $time);
		return $date;
	}

	/**
	 * Create a path if one does not already exist and create
	 * any directories in the path that do not already exist.
	 *
	 * Echo errors labled with css class "error"
	 *
	 * @param string $existingPath optional predetermined directory
	 * @return string path if successful, empty string if not
	 * @since 2.0
	 */
	public function MakePath($existingPath = '')
	{
		if (!$existingPath)
		{
			$dirs = explode('-', date('y-m'));
			$pathYear = $dirs[0];
			$pathMonth = $dirs[1];

			$path = PICS_PATH . $pathYear;
			if (!file_exists($path))
			{
				if (!mkdir($path))
				{
					echo "<p class='error'>error creating $path</p>";
					return '';
				}
			}
			$path .= '/' . $pathMonth;
			if (!file_exists($path))
			{
				if (!mkdir($path))
				{
					echo "<p class='error'>error creating $path</p>";
					return '';
				}
			}
			$path .= '/';
		} else
			$path = $existingPath;

		if (!file_exists($path . 't'))
		{
			if (!@ mkdir($path . 't'))
			{
				echo "<p class='error'>error creating $path" . "t</p>";
				return '';
			}
		}
		if (!file_exists($path . 'r'))
		{
			if (!@ mkdir($path . 'r'))
			{
				echo "<p class='error'>error creating $path" . "r</p>";
				return '';
			}
		}

		return $path;
	}

	/**
	 * Add an item to the collection.
	 *
	 * First check if the file is already an item in the database.
	 * If not then proceed to adding it.
	 *
	 * Check if it has an acceptable file extension, determine
	 * the filetype based on the extension, move the file into the
	 * necessary directory, create thumbnail and resized versions
	 * if necessary, then insert into the database if there have
	 * not been any errors.
	 *
	 * @param string $path where to move the file to
	 * @param string $filename name of the file
	 * @param string $location physical location of where the
	 * picture was taken or item was created
	 * @param string $tags words that come to mind when looking at
	 * the picture or thinking about the item
	 * @param string $datetime date and time of when the item was
	 * created
	 * @param int $isHidden the hide level to set the new item to
	 * defaults to not hidden (public)
	 * @param string $description an explaination of what the item
	 * is
	 * @return int new ItemId from the database if successful,
	 * 0 if not
	 * @version 2.1.1
	 * @since 2.0
	 */
	public function AddItem($path, $filename, $location, $tags, $datetime, $isHidden = 0, $description = '')
	{
		global $DB;

		// determine file types
		$shortpath = str_replace(PICS_PATH, '', $path);
		if ($filename)
		{
			// check if already added
			$query = 'SELECT ItemId FROM ' . ITEM_TABLE .
			" WHERE ItemPath='$shortpath' AND ItemFilename='$filename'" .
			" LIMIT 1";
			$result = $DB->Query($query);
			if (1 == $result->num_rows)
			{
				$row = $result->fetch_array();
				echo "$filename is already added.  <a href='" . PAGE_URL . "i=$row[0]'>View it here.</a><br/>";
				return $row[0];
			}

			$type = $this->FilterFileType($filename);
			if (!$type)
				return 0;

		} else
			$type = DESCRIPTION_ONLY;

		// get exif data from jpeg files
		if (JPEG_FILE == $type)
		{
			if (!$data = get_EXIF_JPEG($path . $filename))
				$data = get_Meta_JPEG($path . $filename);
			if ($data)
			{

                        $jpeg_header_data = get_jpeg_header_data( $path . $filename );
                        if ($irb = get_Photoshop_IRB( $jpeg_header_data ))
                        {
                       		$xmp = Read_XMP_array_from_text( get_XMP_text( $jpeg_header_data ) );
                   			$pinfo = get_photoshop_file_info($data, $xmp, $irb);
                   			foreach($pinfo['keywords'] as $keyword)
                   			{
                   				if (!empty($tags))
                   					$tags .= ',';
                   				$tags .= $keyword;
                   			}
							//echo '<pre>';print_r( $pinfo );exit;
                        }
				$itemDatetime = $data[0][34665]['Data'][0][36867]['Text Value'];

				if (!$description)
					$description = @$data[0][270]['Text Value'];

			if (!$data = get_EXIF_JPEG($path . $filename))
				if ($latitude = @$data[0][34853]['Data'][0][2]['Data'])
				{
					$lat = @(($latitude[0]['Numerator'])+($latitude[1]['Numerator']/60)+($latitude[2]['Numerator']/$latitude[2]['Denominator']/3600));
					if ('S' == $data[0][34853]['Data'][0][1]['Text Value'])
						$lat = -($lat);
				}
				if ($longitude = @$data[0][34853]['Data'][0][4]['Data'])
				{
					$lon = @(($longitude[0]['Numerator'])+($longitude[1]['Numerator']/60)+(($longitude[2]['Numerator']/$longitude[2]['Denominator'])/3600));
					if ('W' == $data[0][34853]['Data'][0][3]['Text Value'])
						$lon = -($lon);
				}
			}
		}

		// set date and time
		if (empty ($itemDatetime) or @ strtotime($itemDatetime) < 1)
			$itemDatetime = $datetime;
		else
			$itemDatetime = date('Y-m-d H:i:s', strtotime($itemDatetime));

		$dt = explode(' ', $itemDatetime);
		$date = $dt[0];
		$time = $dt[1];

		// resize image types
		if(JPEG_FILE == $type or PNG_FILE == $type or GIF_FILE == $type)
			if (!$this->ResizeImage($path, $filename))
				return 0;

		if (!$locationId = $this->SaveLocation($location))
			return 0;

		// save item
		$insertData = array (
			'ItemTypeId' => $type,
			'ItemUserIdFk' => USER_ID,
			'ItemLocationIdFk' => $locationId,
			'ItemDate' => $date,
			'ItemTime' => $time,
			'ItemOrderBy' => "$date $time",
			'ItemPath' => $shortpath,
			'ItemFilename' => $filename,
			'ItemIsHidden' => $isHidden,
			'ItemDescription' => $description
		);
		if (!empty ($lat))
		{
			$insertData['ItemLatitude'] = $lat;
			$insertData['ItemLongitude'] = $lon;
		}
		$itemId = $DB->Insert(ITEM_TABLE, $insertData);
		if (false === $itemId)
		{
			echo '<p class="error">Error inserting into item table.</p>';
			return false;
		}

		// save year/month index
		$dt = explode('-', $date);
		$year = $dt[0];
		$month = $dt[1];
		$result = $DB->Query('SELECT DateYear FROM ' . DATE_TABLE . " WHERE DateYear='$year' AND DateMonth='$month'");
		if ($row = $result->fetch_array())
			$DB->UpdateSingle(DATE_TABLE, 'DateCount', 'DateCount+1', "DateYear='$year' AND DateMonth='$month'");
		else
		{
			$insertData = array (
				'DateYear' => $year,
				'DateMonth' => $month,
				'DateCount' => 1
			);
			$DB->Insert(DATE_TABLE, $insertData);
		}

		// save tags
		ChangeTags($itemId, $tags, false);

		return $itemId;
	}

	/**
	 * Check if the new file has a valid extension and return the file type
	 * if it is good.
	 *
	 * @param string $filename name of new file
	 * @return int file type from include/itemTypes.php
	 * @since 2.1.1
	 */
	public function FilterFileType($filename)
	{
		$ext = strtolower(strrchr($filename, '.'));
		if ('.jpg' == $ext)
			$type = JPEG_FILE;
		elseif ('.gif' == $ext)
			$type = GIF_FILE;
		elseif ('.png' == $ext)
			$type = PNG_FILE;
		elseif ('.wmv' ==  $ext)
			$type = WMV_FILE;
		elseif ('.divx' == $ext)
			$type = DIVX_FILE;
		elseif ('.ogg' == $ext)
			$type = OGG_FILE;
		elseif ('.zip' ==  $ext)
			$type = ZIP_FILE;
		elseif ('.ods' == $ext)
			$type = ODS_FILE;
		elseif ('.odt' == $ext)
			$type = ODT_FILE;
		elseif ('.wav' == $ext)
			$type = WAV_FILE;
		elseif ('.gpx' ==  $ext)
			$type = GPX_FILE;
		elseif ('.xml' == $ext)
			$type = XML_FILE;
		elseif ('.mp3' == $ext)
			$type = MP3_FILE;
		elseif ('.txt' == $ext)
			$type = TEXT_FILE;
		elseif ('.html' == $ext)
			$type = HTML_FILE;
		elseif ('.flv' == $ext)
			$type = FLV_FILE;
		elseif ('.doc' == $ext)
			$type = DOC_FILE;
		elseif('.mpeg' == $ext)
			$type = MPEG_FILE;
		elseif('.mp4' == $ext)
			$type = MP4_FILE;
		else
			$type = 0;

		return $type;
	}

	/**
	 * Check if thumbnail and resized versions of an image file
	 * exist and create them if not.
	 *
	 * @param string $path
	 * @param string $filename
	 * @return bool if both the thumbnail and resized versions now
	 * exist
	 * @since 2.1.1
	 */
	private function ResizeImage($path, $filename)
	{
	if (!file_exists($path . 't/' . $filename) or 0 == filesize($path . 't/' . $filename))
		{
			$script = IMAGEMAGICK_PATH . 'convert' .
			" $path$filename -resize '" . THUMB_X . "x" . THUMB_Y . ">' -quality 80 " .
			$path . 't/' . $filename;
			exec($script);
			if (!@ chmod($path . 't/' . $filename, 0664))
			{
				echo '<p class="error">Error creating thumbnail version.</p>';
				return false;
			}
		}
		if (!file_exists($path . 'r/' . $filename) or 0 == filesize($path . 'r/' . $filename))
		{
			exec(IMAGEMAGICK_PATH . 'convert' .
			" $path$filename -resize '" . RESIZE_X . "x" . RESIZE_Y . ">' -quality 80 " .
			$path . 'r/' . $filename);
			if (!@ chmod($path . 'r/' . $filename, 0664))
			{
				echo '<p class="error">Error creating resized version.</p>';
				return false;
			}
		}
		return true;
	}

	/**
	 * Save the new location to the database.
	 *
	 * If the location already exists, increase the count by 1.
	 *
	 * @param string $location
	 * @return int LocationId from the database
	 * @since 2.1.1
	 */
	private function SaveLocation($location)
	{
		global $DB;
		$query = 'SELECT LocationId FROM ' . LOCATION_TABLE .
		" WHERE Location='$location'" .
		" LIMIT 1";
		$result = $DB->Query($query);
		if (0 == $result->num_rows)
		{
			$insertData = array (
				'Location' => $location,
				'LocationCount' => 1
			);
			$locationId = $DB->Insert(LOCATION_TABLE, $insertData);
			if (false === $locationId)
			{
				echo '<p class="error">Error inserting into location table.</p>';
				return 0;
			}
		} else
		{
			$row = $result->fetch_array();
			$locationId = $row[0];
			$DB->UpdateSingle(LOCATION_TABLE, 'LocationCount', 'LocationCount+1', "LocationId=$locationId");
		}
		return $locationId;
	}
}
?>
Return current item: Kwalbum