Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Added library for twitter API and made a simple auth in magento contr…

…oller and a push of a message
  • Loading branch information...
commit 1438612b18a5f21edb16e84b2f41e45bf4710cc2 1 parent dc7f435
@brain-xy brain-xy authored
View
37 app/code/community/Hackathon/DiscountForATweet/Block/Tweetapp.php
@@ -0,0 +1,37 @@
+<?php
+
+
+
+
+class Hackathon_DiscountForATweet_Block_Tweetapp extends Hackathon_DiscountForATweet_Block_Abstract
+{
+ protected $twitterObj;
+
+
+ public function _construct()
+ {
+
+
+ }
+
+
+ public function buildTweetButton()
+ {
+
+ }
+
+
+ public function isAuthenticated()
+ {
+ $customer = Mage::getSingleton('customer/session');
+ return $customer->getIsReadyForTweet();
+ }
+
+
+ public function getFormActionUrl()
+ {
+ return $this->getUrl('discountforatweet/index/post');
+ }
+
+}
+
View
74 app/code/community/Hackathon/DiscountForATweet/Block/Tweetbutton.php
@@ -0,0 +1,74 @@
+<?php
+/**
+ * License: GNU General Public License
+ *
+ * Copyright (c) 2012 Magento Hackathon. All rights reserved.
+ * Note: Original work copyright to respective authors
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * @category Hackathon
+ * @package Hackathon_DiscountForATweet
+ * @subpackage Block
+ * @copyright Copyright (c) 2012 Magento Hackathon
+ * @license http://www.gnu.org/licenses/gpl.html GPL, version 3
+ * @version 0.1.0
+ * @link http://magento-hackathon.de
+ * @since File available since Release 0.1.0
+ * @author Hackathon Core Team <core@hackathon>
+ */
+
+/**
+ * Implements abstract block functionality for module.
+ *
+ * @category Hackathon
+ * @package Hackathon_DiscountForATweet
+ * @subpackage Block
+ * @copyright Copyright (c) 2012 Magento Hackathon
+ * @license http://www.gnu.org/licenses/gpl.html GPL, version 3
+ * @version Release: 0.1.0
+ * @since Class available since Release 0.1.0
+ * @author Hackathon Core Team <core@hackathon>
+ */
+
+class Hackathon_DiscountForATweet_Block_Tweetbutton extends Hackathon_DiscountForATweet_Block_Abstract
+{
+
+ /**
+ * Constructor. Set template.
+ */
+ protected function _construct()
+ {
+ parent::_construct();
+ Mage::log('test');
+ }
+
+
+ public function getExtremelyEncryptedHash()
+ {
+
+ return $this->getUrl(
+ 'discountforatweet/index/apply',
+ array(
+ 'tweetysfood' => $this->buildTweetysFood()
+ )
+ );
+ }
+
+ protected function buildTweetysFood()
+ {
+ return '12345';
+ }
+
+}
View
199 app/code/community/Hackathon/DiscountForATweet/controllers/IndexController.php
@@ -1,58 +1,143 @@
-<?php
-/**
- * License: GNU General Public License
- *
- * Copyright (c) 2012 Magento Hackathon. All rights reserved.
- * Note: Original work copyright to respective authors
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- *
- * @category Hackathon
- * @package Hackathon_DiscountForATweet
- * @subpackage Controller
- * @copyright Copyright (c) 2012 Magento Hackathon
- * @license http://www.gnu.org/licenses/gpl.html GPL, version 3
- * @version 0.1.0
- * @link http://magento-hackathon.de
- * @since File available since Release 0.1.0
- * @author Hackathon Core Team <core@hackathon>
- */
-
-/**
- * Implements front controller actions
- *
- * @category Hackathon
- * @package Hackathon_DiscountForATweet
- * @subpackage Controller
- * @copyright Copyright (c) 2012 Magento Hackathon
- * @license http://www.gnu.org/licenses/gpl.html GPL, version 3
- * @version Release: 0.1.0
- * @since Class available since Release 0.1.0
- * @author Hackathon Core Team <core@hackathon>
- */
-
-class Hackathon_DiscountForATweet_IndexController
- extends Mage_Core_Controller_Front_Action
-{
- /**
- * Standard action for rendering layout.
- *
- * @return void
- */
- public function indexAction()
- {
- $this->loadLayout();
- $this->renderLayout();
- }
+<?php
+/**
+ * License: GNU General Public License
+ *
+ * Copyright (c) 2012 Magento Hackathon. All rights reserved.
+ * Note: Original work copyright to respective authors
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * @category Hackathon
+ * @package Hackathon_DiscountForATweet
+ * @subpackage Controller
+ * @copyright Copyright (c) 2012 Magento Hackathon
+ * @license http://www.gnu.org/licenses/gpl.html GPL, version 3
+ * @version 0.1.0
+ * @link http://magento-hackathon.de
+ * @since File available since Release 0.1.0
+ * @author Hackathon Core Team <core@hackathon>
+ */
+
+/**
+ * Implements front controller actions
+ *
+ * @category Hackathon
+ * @package Hackathon_DiscountForATweet
+ * @subpackage Controller
+ * @copyright Copyright (c) 2012 Magento Hackathon
+ * @license http://www.gnu.org/licenses/gpl.html GPL, version 3
+ * @version Release: 0.1.0
+ * @since Class available since Release 0.1.0
+ * @author Hackathon Core Team <core@hackathon>
+ */
+
+
+require_once('Hackathon/DiscountForATweet/lib/EpiCurl.php');
+require_once('Hackathon/DiscountForATweet/lib/EpiOAuth.php');
+require_once('Hackathon/DiscountForATweet/lib/EpiTwitter.php');
+require_once('Hackathon/DiscountForATweet/lib/secret.php');
+
+
+
+class Hackathon_DiscountForATweet_IndexController
+ extends Mage_Core_Controller_Front_Action
+{
+
+ public function _construct()
+ {
+ $consumer_key = 'N960N886lxxT0GCg74rmUg';
+ $consumer_secret = '5R1DroadOWQ5gDltla5HWWEldDkdM5eB2MJdWqqpAfo';
+
+ $this->twitterObj = new EpiTwitter($consumer_key, $consumer_secret);
+ $this->customer = $this->_getCustomer();
+
+
+ if($this->getRequest()->getParam('oauth_token', false)) {
+
+ $this->twitterObj->setToken($this->getRequest()->getParam('oauth_token', false));
+
+ $token = $this->twitterObj->getAccessToken();
+ $this->twitterObj->setToken($token->oauth_token, $token->oauth_token_secret);
+
+ $this->customer->setTwitterAuthToken($token->oauth_token);
+ $this->customer->setTwitterAuthTokenSecret($token->oauth_token_secret);
+
+ $twitterInfo = $this->twitterObj->get_accountVerify_credentials();
+
+ $this->customer->setTwitterUsername($twitterInfo->screen_name);
+
+ // check if we really have access
+ if($twitterInfo->screen_name) {
+ $this->customer->setIsReadyForTweet(true);
+ }
+
+ }
+
+ }
+
+
+ /**
+ * Standard action for rendering layout.
+ *
+ * @return void
+ */
+ public function indexAction()
+ {
+ $link = 'twitter sign in: <a href="'.$this->twitterObj->getAuthorizationUrl().'">sign in!</a>';
+
+ $customer = $this->_getCustomer();
+
+ $this->loadLayout();
+ $this->getLayout()
+ ->getBlock('tweetapp')
+ ->assign('status', 'status')
+ ->assign('link', $link)
+ ->assign('username', $customer->getTwitterUsername());
+
+ $this->renderLayout();
+
+ }
+
+
+
+ public function postAction()
+ {
+ if ($this->getRequest()->isPost() && $this->getRequest()->getPost('comment')) {
+
+ $this->twitterObj->setToken($this->customer->getTwitterAuthToken(), $this->customer->getTwitterAuthTokenSecret());
+
+ $update_status = $this->twitterObj->post_statusesUpdate(array('status' => $this->getRequest()->getPost('comment')));
+ $temp = $update_status->response;
+
+ }
+ }
+
+
+
+ /**
+ * applying a discount code from the twitter ajax callback
+ */
+ public function applyAction()
+ {
+
+ }
+
+
+
+ public function _getCustomer()
+ {
+ return Mage::getSingleton('customer/session');
+ }
+
}
View
128 app/code/community/Hackathon/DiscountForATweet/lib/EpiCurl.php
@@ -0,0 +1,128 @@
+<?php
+class EpiCurl
+{
+ const timeout = 3;
+ static $inst = null;
+ static $singleton = 0;
+ private $mc;
+ private $msgs;
+ private $running;
+ private $requests = array();
+ private $responses = array();
+ private $properties = array();
+
+ function __construct()
+ {
+ if(self::$singleton == 0)
+ {
+ throw new Exception('This class cannot be instantiated by the new keyword. You must instantiate it using: $obj = EpiCurl::getInstance();');
+ }
+
+ $this->mc = curl_multi_init();
+ $this->properties = array(
+ 'code' => CURLINFO_HTTP_CODE,
+ 'time' => CURLINFO_TOTAL_TIME,
+ 'length'=> CURLINFO_CONTENT_LENGTH_DOWNLOAD,
+ 'type' => CURLINFO_CONTENT_TYPE
+ );
+ }
+
+ public function addCurl($ch)
+ {
+ $key = (string)$ch;
+ $this->requests[$key] = $ch;
+
+ $res = curl_multi_add_handle($this->mc, $ch);
+
+ // (1)
+ if($res === CURLM_OK || $res === CURLM_CALL_MULTI_PERFORM)
+ {
+ do {
+ $mrc = curl_multi_exec($this->mc, $active);
+ } while ($mrc === CURLM_CALL_MULTI_PERFORM);
+
+ return new EpiCurlManager($key);
+ }
+ else
+ {
+ return $res;
+ }
+ }
+
+ public function getResult($key = null)
+ {
+ if($key != null)
+ {
+ if(isset($this->responses[$key]))
+ {
+ return $this->responses[$key];
+ }
+
+ $running = null;
+ do
+ {
+ $resp = curl_multi_exec($this->mc, $runningCurrent);
+ if($running !== null && $runningCurrent != $running)
+ {
+ $this->storeResponses($key);
+ if(isset($this->responses[$key]))
+ {
+ return $this->responses[$key];
+ }
+ }
+ $running = $runningCurrent;
+ }while($runningCurrent > 0);
+ }
+
+ return false;
+ }
+
+ private function storeResponses()
+ {
+ while($done = curl_multi_info_read($this->mc))
+ {
+ $key = (string)$done['handle'];
+ $this->responses[$key]['data'] = curl_multi_getcontent($done['handle']);
+ foreach($this->properties as $name => $const)
+ {
+ $this->responses[$key][$name] = curl_getinfo($done['handle'], $const);
+ curl_multi_remove_handle($this->mc, $done['handle']);
+ }
+ }
+ }
+
+ static function getInstance()
+ {
+ if(self::$inst == null)
+ {
+ self::$singleton = 1;
+ self::$inst = new EpiCurl();
+ }
+
+ return self::$inst;
+ }
+}
+
+class EpiCurlManager
+{
+ private $key;
+ private $epiCurl;
+
+ function __construct($key)
+ {
+ $this->key = $key;
+ $this->epiCurl = EpiCurl::getInstance();
+ }
+
+ function __get($name)
+ {
+ $responses = $this->epiCurl->getResult($this->key);
+ return $responses[$name];
+ }
+}
+
+/*
+ * Credits:
+ * - (1) Alistair pointed out that curl_multi_add_handle can return CURLM_CALL_MULTI_PERFORM on success.
+ */
+?>
View
233 app/code/community/Hackathon/DiscountForATweet/lib/EpiOAuth.php
@@ -0,0 +1,233 @@
+<?php
+session_start();
+class EpiOAuth
+{
+ public $version = '1.0';
+
+ protected $requestTokenUrl;
+ protected $accessTokenUrl;
+ protected $authorizeUrl;
+ protected $consumerKey;
+ protected $consumerSecret;
+ protected $token;
+ protected $tokenSecret;
+ protected $signatureMethod;
+
+ public function getAccessToken()
+ {
+ $resp = $this->httpRequest('GET', $this->accessTokenUrl);
+ return new EpiOAuthResponse($resp);
+ }
+
+ public function getAuthorizationUrl()
+ {
+ $retval = "{$this->authorizeUrl}?";
+ $token = $this->getRequestToken();
+ return $this->authorizeUrl . '?oauth_token=' . $token->oauth_token;
+ }
+
+ public function getRequestToken()
+ {
+ $resp = $this->httpRequest('GET', $this->requestTokenUrl);
+ return new EpiOAuthResponse($resp);
+ }
+
+ public function httpRequest($method = null, $url = null, $params = null)
+ {
+ if(empty($method) || empty($url))
+ return false;
+
+ if(empty($params['oauth_signature']))
+ $params = $this->prepareParameters($method, $url, $params);
+
+ switch($method)
+ {
+ case 'GET':
+ return $this->httpGet($url, $params);
+ break;
+ case 'POST':
+ return $this->httpPost($url, $params);
+ break;
+ }
+ }
+
+ public function setToken($token = null, $secret = null)
+ {
+ $params = func_get_args();
+ $this->token = $token;
+ $this->tokenSecret = $secret;
+ }
+
+ public function encode($string)
+ {
+ return rawurlencode(utf8_encode($string));
+ }
+
+ protected function addOAuthHeaders(&$ch, $url, $oauthHeaders)
+ {
+ $_h = array('Expect:');
+ $urlParts = parse_url($url);
+ $oauth = 'Authorization: OAuth realm="' . $urlParts['path'] . '",';
+ foreach($oauthHeaders as $name => $value)
+ {
+ $oauth .= "{$name}=\"{$value}\",";
+ }
+ $_h[] = substr($oauth, 0, -1);
+
+ curl_setopt($ch, CURLOPT_HTTPHEADER, $_h);
+ }
+
+ protected function generateNonce()
+ {
+ if(isset($this->nonce)) // for unit testing
+ return $this->nonce;
+
+ return md5(uniqid(rand(), true));
+ }
+
+ protected function generateSignature($method = null, $url = null, $params = null)
+ {
+ if(empty($method) || empty($url))
+ return false;
+
+
+ // concatenating
+ $concatenatedParams = '';
+ foreach($params as $k => $v)
+ {
+ $v = $this->encode($v);
+ $concatenatedParams .= "{$k}={$v}&";
+ }
+ $concatenatedParams = $this->encode(substr($concatenatedParams, 0, -1));
+
+ // normalize url
+ $normalizedUrl = $this->encode($this->normalizeUrl($url));
+ $method = $this->encode($method); // don't need this but why not?
+
+ $signatureBaseString = "{$method}&{$normalizedUrl}&{$concatenatedParams}";
+ return $this->signString($signatureBaseString);
+ }
+
+ protected function httpGet($url, $params = null)
+ {
+ if(count($params['request']) > 0)
+ {
+ $url .= '?';
+ foreach($params['request'] as $k => $v)
+ {
+ $url .= "{$k}={$v}&";
+ }
+ $url = substr($url, 0, -1);
+ }
+ $ch = curl_init($url);
+ $this->addOAuthHeaders($ch, $url, $params['oauth']);
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+ $resp = $this->curl->addCurl($ch);
+
+ return $resp;
+ }
+
+ protected function httpPost($url, $params = null)
+ {
+ $ch = curl_init($url);
+ $this->addOAuthHeaders($ch, $url, $params['oauth']);
+ curl_setopt($ch, CURLOPT_POST, 1);
+ curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params['request']));
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+ $resp = $this->curl->addCurl($ch);
+ return $resp;
+ }
+
+ protected function normalizeUrl($url = null)
+ {
+ $urlParts = parse_url($url);
+ $scheme = strtolower($urlParts['scheme']);
+ $host = strtolower($urlParts['host']);
+ $port = intval($urlParts['port']);
+
+ $retval = "{$scheme}://{$host}";
+ if($port > 0 && ($scheme === 'http' && $port !== 80) || ($scheme === 'https' && $port !== 443))
+ {
+ $retval .= ":{$port}";
+ }
+ $retval .= $urlParts['path'];
+ if(!empty($urlParts['query']))
+ {
+ $retval .= "?{$urlParts['query']}";
+ }
+
+ return $retval;
+ }
+
+ protected function prepareParameters($method = null, $url = null, $params = null)
+ {
+ if(empty($method) || empty($url))
+ return false;
+
+ $oauth['oauth_consumer_key'] = $this->consumerKey;
+ $oauth['oauth_token'] = $this->token;
+ $oauth['oauth_nonce'] = $this->generateNonce();
+ $oauth['oauth_timestamp'] = !isset($this->timestamp) ? time() : $this->timestamp; // for unit test
+ $oauth['oauth_signature_method'] = $this->signatureMethod;
+ $oauth['oauth_version'] = $this->version;
+
+ // encoding
+ array_walk($oauth, array($this, 'encode'));
+ if(is_array($params))
+ array_walk($params, array($this, 'encode'));
+ $encodedParams = array_merge($oauth, (array)$params);
+
+ // sorting
+ ksort($encodedParams);
+
+ // signing
+ $oauth['oauth_signature'] = $this->encode($this->generateSignature($method, $url, $encodedParams));
+ return array('request' => $params, 'oauth' => $oauth);
+ }
+
+ protected function signString($string = null)
+ {
+ $retval = false;
+ switch($this->signatureMethod)
+ {
+ case 'HMAC-SHA1':
+ $key = $this->encode($this->consumerSecret) . '&' . $this->encode($this->tokenSecret);
+ $retval = base64_encode(hash_hmac('sha1', $string, $key, true));
+ break;
+ }
+
+ return $retval;
+ }
+
+ public function __construct($consumerKey, $consumerSecret, $signatureMethod='HMAC-SHA1')
+ {
+ $this->consumerKey = $consumerKey;
+ $this->consumerSecret = $consumerSecret;
+ $this->signatureMethod = $signatureMethod;
+ $this->curl = EpiCurl::getInstance();
+ }
+}
+
+class EpiOAuthResponse
+{
+ private $__resp;
+
+ public function __construct($resp)
+ {
+ $this->__resp = $resp;
+ }
+
+ public function __get($name)
+ {
+ if($this->__resp->code < 200 || $this->__resp->code > 299)
+ return false;
+
+ parse_str($this->__resp->data, $result);
+ foreach($result as $k => $v)
+ {
+ $this->$k = $v;
+ }
+
+ return $result[$name];
+ }
+}
View
49 app/code/community/Hackathon/DiscountForATweet/lib/EpiTwitter.php
@@ -0,0 +1,49 @@
+<?php
+class EpiTwitter extends EpiOAuth
+{
+ const EPITWITTER_SIGNATURE_METHOD = 'HMAC-SHA1';
+ protected $requestTokenUrl = 'http://twitter.com/oauth/request_token';
+ protected $accessTokenUrl = 'http://twitter.com/oauth/access_token';
+ protected $authorizeUrl = 'http://twitter.com/oauth/authorize';
+ protected $apiUrl = 'http://twitter.com';
+
+ public function __call($name, $params = null)
+ {
+ $parts = explode('_', $name);
+ $method = strtoupper(array_shift($parts));
+ $parts = implode('_', $parts);
+ $url = $this->apiUrl . '/' . preg_replace('/[A-Z]|[0-9]+/e', "'/'.strtolower('\\0')", $parts) . '.json';
+ if(!empty($params))
+ $args = array_shift($params);
+
+ return new EpiTwitterJson(call_user_func(array($this, 'httpRequest'), $method, $url, $args));
+ }
+
+ public function __construct($consumerKey = null, $consumerSecret = null, $oauthToken = null, $oauthTokenSecret = null)
+ {
+ parent::__construct($consumerKey, $consumerSecret, self::EPITWITTER_SIGNATURE_METHOD);
+ $this->setToken($oauthToken, $oauthTokenSecret);
+ }
+}
+
+class EpiTwitterJson
+{
+ private $resp;
+
+ public function __construct($resp)
+ {
+ $this->resp = $resp;
+ }
+
+ public function __get($name)
+ {
+ $this->responseText = $this->resp->data;
+ $this->response = (array)json_decode($this->responseText, 1);
+ foreach($this->response as $k => $v)
+ {
+ $this->$k = $v;
+ }
+
+ return $this->$name;
+ }
+}
View
4 app/code/community/Hackathon/DiscountForATweet/lib/secret.php
@@ -0,0 +1,4 @@
+<?php
+$consumer_key = 'N960N886lxxT0GCg74rmUg';
+$consumer_secret = '5R1DroadOWQ5gDltla5HWWEldDkdM5eB2MJdWqqpAfo';
+?>
Please sign in to comment.
Something went wrong with that request. Please try again.