Thursday, September 1, 2011

jQuery UI Tab scroller plugin V 1.0

I have just create my first jQuery plugin for scrolling UI tabs. The plugin basically add next and previous link in jQuery tab when the number of tab exceeds the width of tab panel. When you add/delete tab it automatically august the remaining tabs.

You can check it on google code with full example. https://github.com/riteshjha/scrolltab or just click HERE






Does it work for you ?

Saturday, August 27, 2011

Facebook logout problem php solved

After two days of searching, i have found a problem solved link and i wanted to share it with you all. Put this line in your logout script before redirect to Facebook logout.

$session = $this->facebook->getSession();
$logoutUrl = $this->facebook->getLogoutUrl(array('next' => base_url(), 'session_key' => $session['session_key']));
setcookie('fbs_'.$this->facebook->getAppId(), '', time()-100, '/', '.domain.com');
$this->session->sess_destroy();
redirect($logoutUrl);

I got it from this link http://forum.developers.facebook.net/viewtopic.php?id=71219.

Hope it help someone.

Monday, August 22, 2011

Addthis and ajax response page

There are lots of post regarding Addthis api usage for AJAX page. But none of the post worked perfectly for me. However i got some idea from all that posts to implement it. Here is my code, made little changes from different post.

var addthisScript = "http://s7.addthis.com/js/250/addthis_widget.js#domready=1";/>

function initAddthis(){
if (window.addthis){
window.addthis.ost = 0;
window.addthis.init();
}
}

When you load page using ajax for example (here i have used jQuery)
$.load('http://example.com/lists',function(){
if(window.addthis != undefined) {
  delete window.addthis;
}
$.getScript( addthisScript , function(){
initAddthis
});
});
Please let me know, does it work for you.

Thursday, July 7, 2011

Zend Custom breadcrumb using XML file

As we know a breadcrumb can be generated using Zend_Navigation easily. But this will apply only to navigation menu items, not for other extra actions (outside from menu). Here i have overwrite Zend Navigation breadcrumb view helper, so that a separate XML file can be used for breadcrumb.

To implement this there are 6 simple steps. I have used Custom_ as namespace either change it to any namespace that you have used in your application or add this namespace in you application.

Step 1 : Create Custom_BreadCrumb class by extending Zend_Navigation_Container


class Custom_BreadCrumb extends Zend_Navigation_Container
{
/**
* Creates a new bread container from zend navigation help
*
* @param array|Zend_Config $pages [optional] pages to add
* @throws Zend_Navigation_Exception if $pages is invalid
*/
public function __construct($pages = null)
{
if (is_array($pages) || $pages instanceof Zend_Config) {
$this->addPages($pages);
} elseif (null !== $pages) {
require_once 'Zend/Navigation/Exception.php';
throw new Zend_Navigation_Exception(
'Invalid argument: $pages must be an array, an ' .
'instance of Zend_Config, or null');
}
}
}

Step 2: Create an empty view helper class

class Custom_View_Helper_Breadcrumbs extends Zend_View_Helper_Navigation_Breadcrumbs{}

you can override some feature of breadcrumbs view helper inside this class.

Step 3: Create XML File name breadcrumb.xml inside application/config/breadcrumbs.xml










Step 4: Load breadcrumb in bootstrap

protected function _initViewHelpers() {
$this->bootstrap('layout');
$layout = $this->getResource('layout');
$view = $layout->getView();
#breadcrumb
$breadCrubmConfig = new Zend_Config_Xml(APPLICATION_PATH . '/configs/breadcrumbs.xml');
$breadCrumb = new Custom_BreadCrumb($breadCrubmConfig);
$view->breadcrumbs($breadCrumb);
}


Step 5: Now set the breadcrumb active state in super action controller class

Note: Super action controller class means, all the controller class in an application should extend this class.

$module = $this->_request->getModuleName();
$controller = $this->_request->getControllerName();
$action = $this->_request->getActionName();
$mca = $module.'/'.$controller.'/'.$action;
$activeBreadCrumbs = $this->view->breadcrumbs()->findBymca($mca);
$activeBreadCrumbs->active = true;


Step 6: Usage

Just paste this line in your layout

echo $this->breadcrumbs()->setSeparator(' » ');

Happy coding...

Friday, June 10, 2011

Facebook login or permission page redirect loop

After 2 days of my head aching, i am able to find the problem of facebook login or permission infinite loop.

Actually the problem occurs when the facebook graph api ("makeRequest" function in base_facebook.php) make a curl request to https url then curl try to verify the ssl certificate and it returns false (specially in my case). So for quick fix, i have add

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

just after curl_init. Hope it helps you. As it works for me.

Let me know if it works for you.

Cheers

Monday, April 4, 2011

Mongodb and Zend Framework using Mongo php library

Here you can use Mongodb(NoSql) database with Zend Framework using Mongo php library. I have created three classes Custom_Mongo_Instance, Custom_Mongo_Db and Custom_Mongo_Collection extending Mongo, MongoDB and MongoCollection respectively. So that you can overrides its methods easily.

First download mongo library for php from here

Step 1 : Custom_Mongo_Instanc

class Custom_Mongo_Instance extends Mongo
{
public function __construct( $server = "mongodb://localhost:27017", $options = array("connect" => TRUE) ) {
parent::__construct($server, $options);
}
}
Step 2 : Custom_Mongo_Db

class Custom_Mongo_Db extends MongoDB
{
public function __construct( Mongo $conn, $name ) {
parent::__construct( $conn, $name );
}
}
Step 3 : Custom_Mongo_Collection

class Custom_Mongo_Collection extends MongoCollection
{
public function __construct ( $name, $db = null ){
if($db == null) $db = Zend_Registry::get('mongoDB');
parent::__construct ( $db , $name );
}

public function insert( array $a, $options = array())
{
$a['created'] = date('Y-m-d H:i');
parent::insert( $a, $options);
}
}

Step 4 : Usage

$cnn = "mongodb://username:password@localhost:27017";
try{
$mongo = new Custom_Mongo_Instance($cnn);
$mongoDB = new Custom_Mongo_Db($mongo, "dbname");
}catch(Exception $e){echo $e->getMessage();exit;}

$collection = new Custom_Mongo_Collection("my_collection", $mongoDB);
$data['first_name'] = "Ritesh";
$data['last_name'] = "jha"
$collection->insert($data);

Thats all. Now you can check the data either using mongo console or some third party GUI admin tools.

Monday, March 28, 2011

RabbitMQ adapter for Zend Framework and Zend Queue using AMQP php library

You can use this class as Zend_Queue adapter for RabbitMQ queue system using AMQP php library.

Download AMQP extension from here

To compile and install follow this link

There are three steps

Note: Here i have used Custom_ namespace for Zend. You can change the namespace as per your choice.

Step 1 (Create Adapter class)

/**
* Class for using a Rabbitmq as a queue
*
* @category Custom
* @package Custom_Queue_Rabbitmq
* @subpackage Adapter
* @author Ritesh Jha
* @copyright Copyright (c) (http://mailrkj(at)gmail(dot)com)
*/

class Custom_Queue_Adapter_Rabbitmq extends Zend_Queue_Adapter_AdapterAbstract
{
/**
* @var object AMQP connection object
*/
protected $_cnn = array();

/**
*
* @var object AMQP excahnge object
*/
protected $_exchange = null;

/**
*
* @var object AMQP queue object
*/
protected $Queue = null;


/**
*
* @var object AMQP queue object
*/
protected $QueueFlag = AMQP_DURABLE;

/**
* Constructor
*
* @param array|Zend_Config $options
* options (host,port,login,password)
* @return AMQPConnection instance
*/
public function __construct($options, Zend_Queue $queue = null)
{
parent::__construct($options, $queue);

if(is_array($options))
{
try
{
$cnn = new AMQPConnection($options);
$cnn->connect();

if(!$cnn->isConnected())
{
throw new Zend_Queue_Exception("Unable to connect RabbitMQ server");
}
else
{
$this->_cnn = $cnn;
$this->Queue = new AMQPQueue($this->_cnn);
}
}catch(Exception $e){throw new Zend_Queue_Exception($e->getMessage());}
}
else
{
throw new Zend_Queue_Exception("The options must be an associative array of host,port,login, password ...");
}
}

/**
* Get AMQPConnection object
* @return object
*/
public function getConnection()
{
return $this->_cnn;
}


/**
* Set exchange for sending message to queue
* @param string $name
* @param string $type (AMQP_EX_TYPE_DIRECT, AMQP_EX_TYPE_FANOUT, AMQP_EX_TYPE_TOPIC or AMQP_EX_TYPE_HEADER)
* @param int $flags (AMQP_PASSIVE, AMQP_DURABLE, AMQP_AUTODELETE)
* @return boolean
*/
public function setExchange($exchange , $routingKey = "*", $type = AMQP_EX_TYPE_DIRECT, $flags = AMQP_DURABLE)
{
if($exchange instanceof Custom_Queue_Exchange)
{
$this->_exchange = $exchange;
}
else
{
$exchange = new Custom_Queue_Exchange($this->_cnn, $exchange , $type, $flags);
$this->_exchange = $exchange;
}
$this->setRoutingKey($routingKey);

return $exchange;
}

/**
* Set routing key for queu
* @param string $routing_key
* @param Custom_Queue $queue
* @return bool
*/
public function setRoutingKey($routingKey, Custom_Queue $queue = null)
{
if($queue)
$queueName = $queue->getName ();
else
$queueName = $this->_queue->getName();

return $this->_exchange->bind($queueName, $routingKey);
}

/**
* get AMQPQueue object
* @return
*/
public function setQueueFlag($flag)
{
return $this->QueueFlag = $flag;
}

/**
* create queue
* @param $name
* @param $timeout
*/
public function create($name, $timeout=null)
{
return $this->Queue->declare($name, $this->QueueFlag);
}

/**
* delete queue
* @param $name
* @param $timeout
*/
public function delete($name)
{
return $this->Queue->delete($name);
}

/**
* Publish message to queue
* @param mixed $message (array or string)
* @param Custom_Queue $queue
* @return boolean
*/
public function send($message, Zend_Queue $queue = null)
{
if(is_array($message))
{
$message = Zend_Json_Encoder::encode($message);
}

if($queue)
$routingKey = $queue->getOption('routingKey');
else
$routingKey = $this->_queue->getOption('routingKey');

if($this->_exchange)
{
return $this->_exchange->publish($message, $routingKey, AMQP_MANDATORY, array('delivery_mode' => 2));
}
else
{
throw new Zend_Queue_Exception("Rabbitmq exchange not found");
}
}

/**
*
* @param array $options (min, max. ack)
* @param int $timeout
* @param Zend_Queue $queue
* @return
*/
public function receive($options = null, $timeout = null, Zend_Queue $queue = null)
{
$messages = $this->Queue->get();
return $messages;
}

public function getCapabilities(){
return array(
'create' => true,
'delete' => true,
'send' => true,
);
}

public function isExists($name){}
public function getQueues(){}
public function count(Zend_Queue $queue = null){}
public function deleteMessage(Zend_Queue_Message $message){}
}


Step 2(Create Exchange Class)


class Custom_Queue_Exchange extends AMQPExchange
{
public function __construct ( AMQPConnection $connection , $exchange_name , $type = AMQP_EX_TYPE_DIRECT, $flags = AMQP_AUTODELETE)
{
parent::__construct ($connection);
$this->declare($exchange_name, $type, $flags);
}
}


Step 3(Overwrite Zend_Queue Class)

/**
* Class for using a Rabbitmq as a queue
*
* @category Custom
* @package Custom_Queue
* @subpackage Adapter
* @author Ritesh Jha
* @copyright Copyright (c) (http://mailrkj(at)gmail(dot)com)
*/

class Custom_Queue extends Zend_Queue
{
var $_instance = null;

public function __construct($adapter, $options = array())
{
if($adapter instanceof Custom_Queue_Adapter_Rabbitmq)
{
parent::__construct($adapter, $options);

#declare new queue
$queueName = (array_key_exists('name', $options))?$options['name']:'queue';
if(array_key_exists('flag', $options)) $adapter->setQueueFlag ($options['flag']);
$queue = $adapter->create($queueName);
$this->_setName($queueName);
#declare exchange
$routingKey = (array_key_exists('routingKey', $options))?$options['routingKey']:'*';
$exchangeName = (array_key_exists('exchange', $options))?$options['exchange']:'exchange';
$ex = $adapter->setExchange($exchangeName, $routingKey);
$this->setOptions($options);
}
else
{
throw new Zend_Queue_Exception("Invalid Rabbitmq adapter");
}
}

/**
* Create a new queue
* @param string $name queue name
* @param int $flag A bitmask of any of the flags: AMQP_AUTODELETE, AMQP_PASSIVE, AMQP_DURABLE, AMQP_NOACK.
* @return int (message count)
*/
public function createQueue($name, $flag = AMQP_DURABLE)
{
$this->getAdapter()->setQueueFlag($flag);
parent::createQueue($name);
}


/**
* Delete a queue and all of it's messages
* Returns false if the queue is not delete, true if the queue deleted
* @param string $name queue name
* @return boolean
*/
public function deleteQueue($name)
{
return $this->getAdapter()->delete($name);
}

/**
* Send a message to the queue
*
* @param array|string $message message
* @return Zend_Queue_Message
* @throws Zend_Queue_Exception
*/
public function send($message)
{
return $this->getAdapter()->send($message);
}

/**
* Consume message
*
* @param array $options
* @param int $timeout
* @return array
*/
public function receive($options = null, $timeout = null)
{
return $this->getAdapter()->receive($options, $timeout);
}
}
Usage:

Sending Message
try{
$adapter = new Custom_Queue_Adapter_Rabbitmq($adapteroptions);
$queue = new Custom_Queue($adapter, $queueoptions);
$message = 'Testing queue';
if($queue->send($message))
echo "Message published \n";
else
echo "Not";

} catch (Exception $e){echo $e->getMessage(); }

Receive Message

try{
$adapter = new Custom_Queue_Adapter_Rabbitmq($adapteroptions);
$queue = new Custom_Queue($adapter, $queueoptions);
$messages = $queue->receive($options);
} catch (Exception $e){echo $e->getMessage(); }

Thursday, March 10, 2011

PHP Convert GMT time to local time

Get user timezone offset(ex. Timezone offset for nepal +5:45)
$userTzOffset = +5:45
$gmtDateTime = "2011-03-10 9:00"
$osts = explode(":",$userTzOffset);
$sec = ($osts[0] * 60 * 60) + $osts[1] * 60 ;
$gmtTimeStamp = strtotime($gmtDateTime, time()) + $sec;
$dt = date('Y-m-d::H:i:s',$gmtTimeStamp);

echo $dt;
Hope this will help someone.

Related post PHP Convert local time to GMT time

For getting timezone and offset see this post Get TimeZone with Daylight saving in PHP

PHP Convert local time to GMT time

Get user timezone offset(ex. Timezone offset for nepal +5:45)

$userTzOffset = +5:45
$userDateTime = "2011-03-10 14:00"

$osts = explode(":",$userTzOffset);
$secs = ($osts[0] * 60 * 60) + $osts[1] * 60 ;
$userTimeStamp = strtotime(date('Y-m-d H:i:s',time()+$secs));
$dt = date('Y-m-d H:i:s',strtotime($dateTime,$userTimeStamp) - $sec);
echo $dt;


Related Post PHP Convert GMT time to local time

For getting timezone and offset see this post Get TimeZone with Daylight saving in PHP

Wednesday, January 19, 2011

Get TimeZone with Daylight saving in PHP

function timeZones()
{
$list = DateTimeZone::listAbbreviations();
$idents = DateTimeZone::listIdentifiers();

$data = $offset = $added = array();
foreach ($list as $abbr => $info)
{
foreach ($info as $zone)
{
if ( ! empty($zone['timezone_id']) &&
! in_array($zone['timezone_id'], $added))
{
$z = new DateTimeZone($zone['timezone_id']);
$c = new DateTime('now', $z);
$value['offset'] = formatOffset($z->getOffset($c));

if($zone['dst'])
$day_light_saving = 'DST Yes';
else
$day_light_saving = 'DST No';

$value['timezone'] = $c->format('H:i a')." -- GMT ".$value['offset']." ".$zone['timezone_id']."--".$day_light_saving;
$data[$zone['timezone_id']] = $value;
$added[] = $zone['timezone_id'];
}
}

}

ksort($data);
return $data;

}

static private function formatOffset($offset)
{
$hours = $offset / 3600;
$remainder = $offset % 3600;
$sign = $hours > 0 ? '+' : '-';
$hour = (int) abs($hours);
$minutes = (int) abs($remainder / 60);

return $sign . str_pad($hour, 2, '0', STR_PAD_LEFT)
.':'. str_pad($minutes,2, '0');

}

Made simple correction from the below link discussions
http://stackoverflow.com/questions/1727077/generating-a-drop-down-list-of-timezones-with-php