ソースを参照

googl shortener

euromark 13 年 前
コミット
8f4d5b06ec
3 ファイル変更315 行追加0 行削除
  1. 132 0
      Lib/GooglLib.php
  2. 95 0
      Lib/MyModel.php
  3. 88 0
      Test/Case/Lib/GooglLibTest.php

+ 132 - 0
Lib/GooglLib.php

@@ -0,0 +1,132 @@
+<?php
+App::uses('CakeLog', 'Log');
+
+/**
+ * Googl Url Shortener
+ * @see http://goo.gl
+ *
+ * @author Eslam Mahmoud
+ * @url http://hunikal.com/
+ * @copyright Creative Commons Attribution-ShareAlike 3.0 Unported License.
+ * @version 0.1
+ * @access public
+ * 
+ * TODO: implement OAuth
+ * 
+ * @edited Mark Scherer
+ * 2012-06-24 ms
+ */
+class GooglLib {
+
+	const PROJECTION_FULL = 'FULL';
+	
+	const PROJECTION_CLICKS = 'ANALYTICS_CLICKS';
+	
+	const PROJECTION_TOP = 'ANALYTICS_TOP_STRINGS';
+
+	/**
+	 * application key
+	 */
+	protected $APIKey;
+
+	/**
+	 * api url
+	 */
+	protected $API = "https://www.googleapis.com/urlshortener/v1/url";
+
+	/**
+	 * @param string $apiKey (optional)
+	 * @return void
+	 */
+	public function __construct($apiKey = null) {
+		if ($apiKey === null) {
+			$apiKey = Configure::read('Googl.key');
+		}
+		if ($apiKey) {
+			$this->APIKey = $apiKey;
+		}
+	}
+
+	/**
+	 * reverse the shortening process
+	 * TODO: rename to expand
+	 *
+	 * @param strin $url
+	 * @return result as array
+	 */
+	public function getLong($shortURL, $projection = null) {
+		$vars = '?shortUrl=' . $shortURL;
+		if ($projection) {
+			$vars .= '&projection=' . $projection;
+		}
+		if ($this->APIKey) {
+			$vars .= '&key=' . $this->APIKey;
+		}
+		$ch = curl_init($this->API . $vars);
+		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
+		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+		$result = curl_exec($ch);
+		curl_close($ch);
+		$array = json_decode($result, true);
+		return $array;
+	}
+
+	/**
+	 * shorten a long url
+	 *
+	 * @param string $url
+	 * @return array $result as array or false on failure
+	 */
+	public function getShort($longURL) {
+		$vars = '';
+		if ($this->APIKey) {
+			$vars .= "?key=$this->APIKey";
+		}
+
+		$ch = curl_init($this->API . $vars);
+		curl_setopt($ch, CURLOPT_POST, 1);
+		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
+		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
+		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+		curl_setopt($ch, CURLOPT_POSTFIELDS, '{"key": "'.$this->APIKey.'", "longUrl": "' . $longURL . '"}');
+		$result = curl_exec($ch);
+		curl_close($ch);
+		$array = json_decode($result, true);
+		if (empty($array['id'])) {
+			# throw error?
+			CakeLog::write('googl', $longURL.' - '.print_r($array, true));
+			return false;
+		}
+		$separator = strrpos($array['id'], '/');
+		$array['key'] = substr($array['id'], $separator+1);
+		return $array;
+	}
+	
+	/**
+	 * FIXME: not working yet
+	 * TODO: use oacurl etc
+	 * @return array
+	 */
+	public function getHistory() {
+		$vars = '';
+		$url = $this->API . '/history';
+		$ch = curl_init($url . $vars);
+		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
+		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+		$result = curl_exec($ch);
+		curl_close($ch);
+		$array = json_decode($result, true);
+		return $array;
+	}
+	
+	/**
+	 * retrieve the url for the statistics page for this key
+	 * @param string $key
+	 * @return string $url
+	 */
+	public static function statisticsUrl($key) {
+		$url = 'http://goo.gl/#analytics/goo.gl/'.$key.'/all_time';
+		return $url;
+	}
+	
+}

+ 95 - 0
Lib/MyModel.php

@@ -40,6 +40,101 @@ class MyModel extends Model {
 		}
 	}
 
+/**
+ * Deconstructs a complex data type (array or object) into a single field value.
+ * BUGFIXED VERSION - autodetects type and allows manual override
+ *
+ * @param string $field The name of the field to be deconstructed
+ * @param array|object $data An array or object to be deconstructed into a field
+ * @return mixed The resulting data that should be assigned to a field
+ */
+	public function deconstruct($field, $data, $type = null) {
+		if (!is_array($data)) {
+			return $data;
+		}
+		if ($type === null) {
+			$type = $this->getColumnType($field);
+		}
+		if ($type === null) {
+			//try to autodetect
+			if (isset($data['day']) || isset($data['month']) || isset($data['year'])) {
+				$type = 'date';
+			}
+			if (isset($data['hour']) || isset($data['min']) || isset($data['sec'])) {
+				$type .= 'time';
+			}
+		}
+		
+		if (in_array($type, array('datetime', 'timestamp', 'date', 'time'))) {
+			$useNewDate = (isset($data['year']) || isset($data['month']) ||
+				isset($data['day']) || isset($data['hour']) || isset($data['minute']));
+
+			$dateFields = array('Y' => 'year', 'm' => 'month', 'd' => 'day', 'H' => 'hour', 'i' => 'min', 's' => 'sec');
+			$timeFields = array('H' => 'hour', 'i' => 'min', 's' => 'sec');
+			$date = array();
+
+			if (isset($data['meridian']) && empty($data['meridian'])) {
+				return null;
+			}
+
+			if (
+				isset($data['hour']) &&
+				isset($data['meridian']) &&
+				!empty($data['hour']) &&
+				$data['hour'] != 12 &&
+				'pm' == $data['meridian']
+			) {
+				$data['hour'] = $data['hour'] + 12;
+			}
+			if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] == 12 && 'am' == $data['meridian']) {
+				$data['hour'] = '00';
+			}
+			if ($type == 'time') {
+				foreach ($timeFields as $key => $val) {
+					if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
+						$data[$val] = '00';
+					} elseif ($data[$val] !== '') {
+						$data[$val] = sprintf('%02d', $data[$val]);
+					}
+					if (!empty($data[$val])) {
+						$date[$key] = $data[$val];
+					} else {
+						return null;
+					}
+				}
+			}
+
+			if ($type == 'datetime' || $type == 'timestamp' || $type == 'date') {
+				foreach ($dateFields as $key => $val) {
+					if ($val == 'hour' || $val == 'min' || $val == 'sec') {
+						if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
+							$data[$val] = '00';
+						} else {
+							$data[$val] = sprintf('%02d', $data[$val]);
+						}
+					}
+					if (!isset($data[$val]) || isset($data[$val]) && (empty($data[$val]) || $data[$val][0] === '-')) {
+						return null;
+					}
+					if (isset($data[$val]) && !empty($data[$val])) {
+						$date[$key] = $data[$val];
+					}
+				}
+			}
+
+			if ($useNewDate && !empty($date)) {
+				$format = $this->getDataSource()->columns[$type]['format'];
+				foreach (array('m', 'd', 'H', 'i', 's') as $index) {
+					if (isset($date[$index])) {
+						$date[$index] = sprintf('%02d', $date[$index]);
+					}
+				}
+				return str_replace(array_keys($date), array_values($date), $format);
+			}
+		}
+		return $data;
+	}
+
 	/**
 	 * The main method for any enumeration, should be called statically
 	 * Now also supports reordering/filtering

+ 88 - 0
Test/Case/Lib/GooglLibTest.php

@@ -0,0 +1,88 @@
+<?php
+
+App::uses('GooglLib', 'Tools.Lib');
+
+/**
+ * 2010-09-10 ms
+ */
+class GooglLibTest extends CakeTestCase {
+
+	public function setUp() {
+		//Configure::write('Googl.key', 'YOUR KEY');
+		
+		$this->Googl = new GooglLib();
+	}
+
+	public function tearDown() {
+		unset($this->Googl);
+	}
+	
+	//TODO
+	public function testOAuth() {
+		
+		
+	}
+	
+	public function testHistory() {
+		$this->skipIf(true);
+		
+		$is = $this->Googl->getHistory();
+		pr($is); ob_flush();		
+		die();
+	}
+
+
+	public function testShortenAndUnshorten() {
+		echo '<h2>Shorten without key (publically)</h2>';
+		Configure::write('Googl.key', '');
+		
+		$url = 'http://www.spiegel.de'; 
+		$is = $this->Googl->getShort($url);
+		pr($is); ob_flush();		
+		$res = $this->assertTrue(!empty($is) && is_array($is) && !empty($is['id']) && $is['kind'] == 'urlshortener#url' && $is['longUrl'] == $url.'/');
+		
+		
+		echo '<h2>Unshorten</h2>';
+		
+		$shortUrl = $is['id'];
+		$is = $this->Googl->getLong($shortUrl);
+		pr($is); ob_flush();	
+		$res = $this->assertTrue(!empty($is) && is_array($is) && !empty($is['id']) && $is['kind'] == 'urlshortener#url' && $is['status'] == 'OK' && $is['longUrl'] == $url.'/');
+		
+	}
+
+	public function testApi() {
+		$this->skipIf(!Configure::write('Googl.key'), 'No Api Key found');
+		
+		echo '<h2>Shorten with key</h2>';
+		
+		$url = 'http://www.gmx.de'; 
+		$is = $this->Googl->getShort($url);
+		pr($is); ob_flush();	
+		$res = $this->assertTrue(!empty($is) && is_array($is) && !empty($is['id']) && $is['kind'] == 'urlshortener#url' && $is['longUrl'] == $url.'/');
+		
+		
+		echo '<h2>Unshorten</h2>';
+		
+		$shortUrl = $is['id'];
+		$is = $this->Googl->getLong($shortUrl);
+		pr($is); ob_flush();
+		$res = $this->assertTrue(!empty($is) && is_array($is) && !empty($is['id']) && $is['kind'] == 'urlshortener#url' && $is['status'] == 'OK' && $is['longUrl'] == $url.'/');
+		
+		
+		echo '<h2>FULL INFOS</h2>';
+		
+		$url = 'http://www.web.de#123456'; 
+		$is = $this->Googl->getShort($url);
+		echo returns($is); ob_flush();
+		$res = $this->assertTrue(!empty($is) && is_array($is) && !empty($is['id']) && $is['kind'] == 'urlshortener#url' && $is['longUrl'] == 'http://www.web.de/#123456');
+		
+		$shortUrl = $is['id'];
+		$is = $this->Googl->getLong($shortUrl, GooglLib::PROJECTION_CLICKS);
+		
+		echo returns($is); ob_flush();
+		$res = $this->assertTrue(!empty($is) && is_array($is) && !empty($is['id']) && $is['kind'] == 'urlshortener#url' && $is['status'] == 'OK' && $is['longUrl'] == 'http://www.web.de/#123456');
+		 
+	}
+
+}