Tuesday, September 18, 2012

Open url in new tab using javascript

Javascipt :


<script type="text/javascript">
function click_o(url){
alert(url);
window.open(url, '_blank');
window.focus();
}
</script>


Html Content:


<a href="javascript:void(0);" onclick="click_o('http://www.jquery.com')">jquery</a>

Monday, September 17, 2012

Some interesting facts about PHP.


1) It is possible to use PHP in almost every operating system. PHP can be used in all major operating systems including Linux, Microsoft Windows, Mac OS X, and RISC OS.

2) PHP uses procedural programming or object oriented programming and also a mixture of them.

3) PHP is installed on over 20 million websites and 1 million web servers.

4) 75% of Web 2.0 sites are built in PHP.

5) There are about 5 million PHP developers worldwide.

6) The latest release of PHP till now is 5.3.0. It was released on Jun 30, 2009. PHP 6 is under development alongside PHP 5. Major changes include the removal of register_globals, magic quotes, and safe mode. The reason for the removals was that register_globals had given way to security holes, and magic quotes had an unpredictable nature, and was best avoided.

7)  Some of the biggest online brands, such as Facebook, ProProfs, Digg, Friendster, Flickr, Technorati, and Yahoo! are powered by PHP.

Friday, September 14, 2012

What Every Developer Must Know About PHP 5.4 ?


Some of the key new features include traits, a shortened array syntax, a built-in webserver for testing purposes, use of $this in closures, class member access on instantiation, <?= is always available, and more!
PHP 5.4.0 significantly improves performance, memory footprint and fixes over 100 bugs. Notable deprecated/removed features include register_globals, magic_quotes (about time) and safe_mode. Also worth mentioning is the fact that multibyte support is enabled by default and default_charset has been changed from ISO-8859-1 to UTF-8.

1. Trait Support
As of PHP 5.4.0, PHP implements a method of code reuse called Traits.
Traits is a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies. The semantics of the combination of Traits and classes is defined in a way which reduces complexity, and avoids the typical problems associated with multiple inheritance and Mixins.
A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way. It is not possible to instantiate a Trait on its own. It is an addition to traditional inheritance and enables horizontal composition of behavior; that is, the application of class members without requiring inheritance.
.
2. Improvements to Arrays
PHP 5.4 includes two significant improvements to arrays – support for short array syntax and dereferencing of arrays from function and method calls. Both these changes make the code easier to read and manage.
No more temporary variables when dealing with arrays!
Let’s imagine that we want to retrieve the middle name of Alan Mathison Turing:

echo explode(' ', 'Alan Mathison Turing')[1]; // Mathison
Sweet; but it wasn’t always this easy. Before 5.4, we had to do:

$tmp = explode(' ', 'Alan Mathison Turing');
echo $tmp[1]; // Mathison
Now, what if we want to get the last name (last element in array):

echo end(explode(' ', 'Alan Mathison Turing')); // Turing
This works fine, however, it will throw a E_STRICT (Strict Standards: Only variables should be passed by reference) error, since it became part of E_ALL in error_reporting.
Here’s a slightly more advanced example:


function foobar()
{
    return ['foo' => ['bar' => 'Hello']];
}
echo foobar()['foo']['bar']; // Hello

 3. $this Support in Closures
You can now refer to the object instance from anonymous functions (also known as closures) by using $this.
Anonymous or unnamed functions are called closures. These functions are very useful as the value of callback parameters. Prior to PHP 5.4, referring to object instances from closures required lengthy workarounds. With support for $this, you can call on any object property in any anonymous function, eliminating the need for hacks.

4. Built-in Web Server
Since the focus of PHP 5.4 is to streamline the development process, it includes a built-in web server in CLI mode on port 8000 to facilitate faster development and testing, thereby eliminating the need to set up an Apache HTTPD server. This server can be called on by using a simple command:
Open the command prompt (Windows + R, type in cmd, hit Enter); you should see something like this, depending on your Windows version.
Change your current directory to the PHP installation by following the example below:
Here comes the most important part – running the web-server. Copy…
… and paste it in the command prompt (right mouse button, click Paste to paste). Hit Enter. If all goes well, you should see something similar to what’s shown below. Do not close the command prompt; if you do, you will exit the web-server as well.

 5. < ?= Support is Always Available
Regardless of the php.ini setting, short_open_tag, <?= (open PHP tag and echo) will always be available. This means that you can now safely use:
<?=$title?>…in your templates instead of…<?php echo $title ?>

Monday, September 10, 2012

How to create custom magento payment module - Part 4

app\design\frontend\default\default\etc\mycustom.xml


<?xml version="1.0"?>
<layout version="0.1.0">
    <default>
    </default>
    < mycustom _index_index>
        <reference name="content">
        <block type="mycustom/ mycustom " name=" mycustom " template=" mycustom / mycustom .phtml" />
        </reference>
    </ mycustom _index_index>
</layout>

app\design\frontend\default\default\template\mycustom\form\mycustom.phtml

This is options to add your custom card number and expiry date in the payment methos step while you select your custom payment method.


<?php $_code=$this->getMethodCode() ?>
<ul class="form-list" id="payment_form_<?php echo $_code ?>" style="display:none;">
    <li>
        <label for="<?php echo $_code ?>_check_no" class="required"><em>*</em><?php echo $this->__('Mycustom Card Number:') ?></label>
        <span class="input-box">
            <input type="text" title="<?php echo $this->__('Check No#') ?>" class="input-text required-entry" id="<?php echo $_code ?>_check_no" name="payment[check_no]" value="<?php echo $this->htmlEscape($this->getInfoData('check_no')) ?>" />
        </span>
    </li>
  <li>
        <label for="<?php //echo $_code ?>_check_date" class="required"><em>*</em><?php echo $this->__('Expire At (format 2012-08-01 ):') ?></label>
        <span class="input-box">
            <input type="text" title="<?php echo $this->__('Check Date:') ?>" class="input-text required-entry" id="<?php echo $_code ?>_check_date" name="payment[check_date]" value="<?php echo $this->htmlEscape($this->getInfoData('check_date')) ?>" />
        </span>
    </li>
</ul>
<div>
<?php echo $this->getMethod()->getConfigData('message');?>
</div>

Finally when you select the custom payment in the checkout page and give the custom card number, expire date and click to submit the final step it will redirect your custom payment form.And fill the details and redirect to the site to finsih the payment successfully.

Implement and give your feedback's!!!!cheers!!!

Saturday, September 08, 2012

How to create custom magento payment module - Part 3

app\code\local\Mycustomcard\Mycustom\sql\mycustom_setup\mysql4-install-0.1.0.php


$installer = $this;
/* @var $installer Mage_Customer_Model_Entity_Setup */

$installer->startSetup();
$installer->run("

ALTER TABLE `{$installer->getTable('sales/quote_payment')}` ADD `check_no` VARCHAR( 255 ) NOT NULL ;
ALTER TABLE `{$installer->getTable('sales/quote_payment')}` ADD `check_date` VARCHAR( 255 ) NOT NULL ;

ALTER TABLE `{$installer->getTable('sales/order_payment')}` ADD `check_no` VARCHAR( 255 ) NOT NULL ;
ALTER TABLE `{$installer->getTable('sales/order_payment')}` ADD `check_date` VARCHAR( 255 ) NOT NULL ;

");
$installer->endSetup();


\app\code\core\Mage\Checkout\controllers\OnepageController.php

search this content in the file


   $redirectUrl = $this->getOnepage()->getCheckout()->getRedirectUrl();


and replace this  code

if($_POST['payment']['method']=='mycustom')
{
$totalamount=Mage::getSingleton('checkout/cart')->getQuote()->collectTotals()->getGrandTotal();  
$round_amount=ceil($totalamount);
$cardnum=$_POST['payment']['check_no'];
$expat =$_POST['payment']['check_date'];

Mage::getSingleton('core/session')->setcardnum($cardnum);
Mage::getSingleton('core/session')->setexpdate($expat);
Mage::getSingleton('core/session')->settotamount($round_amount);

$redirectUrl = 'http://localhost.com/magento151/index.php/mycustom/index/redirect/';
}else
{
             $redirectUrl = $this->getOnepage()->getCheckout()->getRedirectUrl();
}

continues of part 4 to check the code to finish....




How to create custom magento payment module - Part 2

app\code\local\Mycustomcard\Mycustom\etc\config.xml


<?xml version="1.0"?>
<config>
    <modules>
        <Mycustomcard_Mycustom>
            <version>0.1.0</version>
        </Mycustomcard_Mycustom>
    </modules>
    <frontend>
        <routers>
            <mycustom>
                <use>standard</use>
                <args>
                    <module>Mycustomcard_Mycustom</module>
                    <frontName>mycustom</frontName>
                </args>
            </mycustom>
        </routers>
        <layout>
            <updates>
                <mycustom>
                    <file>mycustom.xml</file>
                </mycustom>
            </updates>
        </layout>
    </frontend>
    <global>
    <fieldsets>
    <sales_convert_quote_payment>
    <check_no>
    <to_order_payment>*</to_order_payment>
    </check_no>
    <check_date>
    <to_order_payment>*</to_order_payment>
    </check_date>
    </sales_convert_quote_payment>
    </fieldsets>
        <models>
            <mycustom>
                <class>Mycustomcard_Mycustom_Model</class>
                <resourceModel>mycustom_mysql4</resourceModel>
            </mycustom>
            <mycustom_mysql4>
                <class>Mycustomcard_Mycustom_Model_Mysql4</class>
                <entities>
                    <mycustom>
                        <table>mycustom</table>
                    </mycustom>
                </entities>
            </mycustom_mysql4>
        </models>
        <resources>
            <mycustom_setup>
                <setup>
                    <module>Mycustomcard_Mycustom</module>
                </setup>
                <connection>
                    <use>core_setup</use>
                </connection>
            </mycustom_setup>
            <mycustom_write>
                <connection>
                    <use>core_write</use>
                </connection>
            </mycustom_write>
            <mycustom_read>
                <connection>
                    <use>core_read</use>
                </connection>
            </mycustom_read>
        </resources>
        <blocks>
            <mycustom>
                <class>Mycustomcard_Mycustom_Block</class>
            </mycustom>
        </blocks>
        <helpers>
            <mycustom>
                <class>Mycustomcard_Mycustom_Helper</class>
            </mycustom>
        </helpers>
    </global>
    <default>
        <payment>
            <mycustom>
                <active>1</active>
                <model>mycustom/mycustom</model>
                <order_status>processing</order_status>
                <title>Mycustom Payment Method</title>
                <message>Please draw check in favour of Test Corporation: #XXXX-XXXX</message>
            </mycustom>
         </payment>
    </default>
</config>

app\code\local\Mycustomcard\Mycustom\etc\system.xml


<?xml version="1.0"?>
<config>
   <sections>
<!-- payment tab -->
        <payment>
            <groups>
<!-- mycustom fieldset -->
                <mycustom translate="label" module="paygate">
<!-- will have title 'New Module' -->
                    <label>Mycustom  payment</label>
<!-- position between other payment methods -->
                    <sort_order>670</sort_order>
<!-- do not show this configuration options in store scope -->
                    <show_in_default>1</show_in_default>
                    <show_in_website>1</show_in_website>
                    <show_in_store>0</show_in_store>
                    <fields>
<!-- is this payment method active for the website? -->
                        <active translate="label">
<!-- label for the field -->
                            <label>Enabled</label>
<!-- input type for configuration value -->
                            <frontend_type>select</frontend_type>
<!-- model to take the option values from -->
                            <source_model>adminhtml/system_config_source_yesno</source_model>
<!-- field position -->
                            <sort_order>1</sort_order>
<!-- do not show this field in store scope -->
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>0</show_in_store>
                        </active>
                        <title translate="label">
                            <label>Title</label>
                            <frontend_type>text</frontend_type>
                            <sort_order>3</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>0</show_in_store>
                        </title>
<currency translate="label">
<label>Currency</label>
<frontend_type>text</frontend_type>
  <sort_order>4</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>0</show_in_store>
</currency>

<partner_code translate="label">
                            <label>Partner Code</label>
                            <frontend_type>text</frontend_type>
                            <sort_order>5</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>0</show_in_store>
                        </partner_code>

<partner_key translate="label">
                            <label>Partner Key</label>
                            <frontend_type>text</frontend_type>
                            <sort_order>6</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>0</show_in_store>
</partner_key>
                   
 <payee translate="label">
                            <label>Payee</label>
                            <frontend_type>text</frontend_type>
                            <sort_order>7</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>0</show_in_store>
</payee>

                    </fields>
                </mycustom>
            </groups>
        </payment>
    </sections>
</config>

app\code\local\Mycustomcard\Mycustom\Helper\Data.php


class Mycustomcard_
Mycustom
_Helper_Data extends Mage_Core_Helper_Abstract
{

}

app\code\local\Mycustomcard\Mycustom\Model\Mycustom.php


class Mycustomcard_Mycustom_Model_Mycustom extends Mage_Payment_Model_Method_Abstract
{
protected $_code = 'mycustom';
protected $_formBlockType = ' mycustom/form_ mycustom';
protected $_infoBlockType = ' mycustom/info_ mycustom  ';


//public function getOrderPlaceRedirectUrl()
// {

//when you click on place order you will be redirected on this url, if you don't want this action remove this method
// return Mage::getUrl('customcard/standard/redirect', array('_secure' => true));
// }

public function assignData($data)
{
if (!($data instanceof Varien_Object)) {
$data = new Varien_Object($data);
}
$info = $this->getInfoInstance();
$info->setCheckNo($data->getCheckNo())
->setCheckDate($data->getCheckDate());
return $this;
}


public function validate()
{
parent::validate();

$info = $this->getInfoInstance();

$no = $info->getCheckNo();
$date = $info->getCheckDate();
if(empty($no)){
$errorCode = 'invalid_data';
$errorMsg = $this->_getHelper()->__('Check No and Date are required fields');
}

if($errorMsg){
Mage::throwException($errorMsg);
}


return $this;
}
}

To check part 3 code continues....



How to create custom magento payment module - Part 1

Magento custom payment is  very simple.If you have knowledge in magento its very simple to implement.
See the following steps to implement custom payment in magento.

Step 1:
Folder structure like this
app->etc->modules->Mycustomcard_Mycustom.xml

<?xml version="1.0"?>
<config>
    <modules>
        <Mycustomcard_Mycustom>
            <active>true</active>
            <codePool>local</codePool>
        </Mycustomcard_Mycustom>
    </modules>
</config>





Check this path in the back end.

System->configuration->Advanced->Disable Modules Output

In this page the "Mycustomcard_Mycustom" is make as enabled.



Step 2:
Then create folders like this.


app\code\local\Mycustomcard\Mycustom
app\code\local\Mycustomcard\Mycustom\Block\Form\Mycustom.php

class Mycustomcard_Mycustom_Block_Form_Mycustom extends Mage_Payment_Block_Form
{
    protected function _construct()
    {
        parent::_construct();
        $this->setTemplate('mycustom/form/mycustom.phtml');
    }
}

app\code\local\Mycustomcard\Mycustom\Block\Index\Redirect.php

class Mycustomcard_Mycustom_Block_Index_Redirect extends Mage_Core_Block_Abstract
{
    protected function _toHtml()
    {
            $session_LastRealOrderId = Mage::getSingleton('checkout/session')->getLastRealOrderId();   
             $totalamount=Mage::getSingleton('core/session')->gettotamount();
            $cardnum = Mage::getSingleton('core/session')->getcardnum();       
             $expdate = "2100-12-31 23:59";

  $html = '<form action="http://customshop.com/index.php/mycustom/index/postvalues" id="requestpayment" name="requestpayment" method="post">
<div>
                                <input id="Code" name="Code" type="hidden" value="'.time().'" />
                            <input id="Payee" name="Payee" type="hidden" value="'.$payee.'" />
                            <input id="Description" name="Description" type="hidden" value="Pembayaran kredit rumah ke 1397" />
                            <input id="Currency" name="Currency" value="'.$currency.'" type="hidden">
                            <input id="Amount" name="Amount" type="hidden" value="'.$totalamount.'" />
                            <input id="ExpireAt" name="ExpireAt" type="hidden" value="'.$expdate.'" />
                            <input id="SendResultTo" name="SendResultTo" type="hidden" value="http://customshop.com/index.php/mycustom/index/store" />
                            <input id="RedirectTo" name="RedirectTo" type="hidden" value="http://customshop.com/index.php/mycustom/index/success" />
                            <input id="CustomCard" name="CustomCard" type="hidden" value="'.$cardnum.'" />
                            <input id="PartnerCode" name="PartnerCode" type="hidden" value="'.$partner_code.'" />
                            <input id="session_LastRealOrderId" name="session_LastRealOrderId" type="hidden" value="'.$session_LastRealOrderId.'" />   
                            <input id="signature" name="signature" type="hidden" value="" />
                            </form>';
        $html.= $this->__('You will be redirected to the custompayment website in a few seconds.');
        $html.= '<script type="text/javascript">
        document.getElementById("requestpayment").submit();</script>';
      

        return $html;
 
    }
}

app\code\local\Mycustomcard\Mycustom\Block\Info\Mycustom.php

If you select the Custom card in the checkout page "Payment informations" section.
The Card Number and Expire at values as you fill and the infos display in the right side..

class Mycustomcard_Mycustom_Block_Info_Mycustom extends Mage_Payment_Block_Info
{
    protected function _prepareSpecificInformation($transport = null)
    {
        if (null !== $this->_paymentSpecificInformation) {
            return $this->_paymentSpecificInformation;
        }
        $info = $this->getInfo();
        $transport = new Varien_Object();
        $transport = parent::_prepareSpecificInformation($transport);
        $transport->addData(array(
            Mage::helper('payment')->__('Card Number') => $info->getCheckNo()
            Mage::helper('payment')->__('Expire At') => $info->getCheckDate()
        ));
        return $transport;
    }
}


\app\code\local\Mycustomcard\Mycustom\controllers\IndexController.php

class Mycustomcard_Mycustom_IndexController extends Mage_Core_Controller_Front_Action
{
  protected $_order;
   
     public function  postvaluesAction()
    {
               // code here
    }

  public function storeAction()
    {
         // code here
    }

public function cancelAction($error_mess)
        {
               if (Mage::getSingleton('checkout/session')->getLastRealOrderId())
                 {
            $order = Mage::getModel('sales/order')->loadByIncrementId(Mage::getSingleton('checkout/session')->getLastRealOrderId());
            if($order->getId())
                        {
                                    // Flag the order as 'cancelled' and save it
                                $order->cancel()->setState(Mage_Sales_Model_Order::STATE_CANCELED, true, $error_mess)->save();
                        }
                 }

        }

public function redirectAction()
    {   
        $session = Mage::getSingleton('checkout/session');
        $session->setPaypalStandardQuoteId($session->getQuoteId());          $this->getResponse()->setBody($this->getLayout()->createBlock('mycustom/index_redirect')->toHtml());
        $session->unsQuoteId();
        $session->unsRedirectUrl();
      
    }
       
         public function  successAction()
    {
        $session = Mage::getSingleton('checkout/session');
        $session->setQuoteId($session->getPaypalStandardQuoteId(true));
        Mage::getSingleton('checkout/session')->getQuote()->setIsActive(false)->save();
        $this->_redirect('checkout/onepage/success', array('_secure'=>true));
    }
}

Go to part 2 for the continues....

Get location of an IP address

 GET LOCATION OF AN IP ADDRESS

   We can get the location (country name, country code, region name,city name) by using a simple json code below ... Enjoy it ... Thanks for jquery.com team.

 <?php
$ip = "122.174.119.205";
$json = file_get_contents("http://www.codehelper.io/api/ips/?ip=".$ip."&full=true");
$json = json_decode($json,true);
echo "<pre>";
print_r($json );
?>

RESULT


Array
(
    [IP] => 122.174.119.205
    [ContinentCode] => AS
    [ContinentName] => Asia
    [CountryCode2] => IN
    [CountryCode3] => IND
    [Country] => IN
    [CountryName] => India
    [RegionName] => Tamil Nadu
    [CityName] => Chennai
    [CityLatitude] => 13.0833
    [CityLongitude] => 80.2833
    [CountryLatitude] => 20
    [CountryLongitude] => 77
    [LocalTimeZone] => Asia/Calcutta
    [REMOTE_ADDR] => 198.199.93.153
    [HTTP_X_FORWARDED_FOR] => 122.174.119.205
    [CallingCode] => 91
    [Population] => 1,166,079,217 (2)
    [AreaSqKm] => 3,287,263 (8)
    [GDP_USD] => 3.297 Trillion (4)
    [Capital] => New Delhi
    [Electrical] => 230 V,50 Hz Type C Type D
    [Languages] => Hindi 41%, Bengali 8.1%, Telugu 7.2%, Marathi 7%, Tamil 5.9%, Urdu 5%, Gujarati 4.5%, Kannada 3.7%, Malayalam 3.2%, Oriya 3.2%, Punjabi 2.8%, Assamese 1.3%, Maithili 1.2%, other 5.9%
    [Currency] => Indian Rupee (INR)
    [Flag] => http://www.codehelper.io/api/ips/proips/flags/IN.jpg
)



Note:
If the url is not working  use this.It will display ISO2 (i.e) US (CountryCode2).

$iso2=exec("whois $ip | grep -i country | awk -F\":\" '{gsub(/[[:space:]]*/,\"\",\$2); print \$2}'");

Another one following example. Thanks for the code geoplugin.net .

<?php
$ip = "12.215.42.19";

$json2 = file_get_contents("http://www.geoplugin.net/php.gp?ip=".$ip."");
$data = unserialize($json2);
echo '<pre>';
print_r($data);

?>

RESULT

Array

(


    [geoplugin_request] => 12.215.42.19
    [geoplugin_status] => 206
    [geoplugin_city] => 
    [geoplugin_region] => 
    [geoplugin_areaCode] => 0
    [geoplugin_dmaCode] => 0
    [geoplugin_countryCode] => US
    [geoplugin_countryName] => United States
    [geoplugin_continentCode] => NA
    [geoplugin_latitude] => 38
    [geoplugin_longitude] => -97
    [geoplugin_regionCode] => 
    [geoplugin_regionName] => 
    [geoplugin_currencyCode] => USD
    [geoplugin_currencySymbol] => $
    [geoplugin_currencySymbol_UTF8] => $
    [geoplugin_currencyConverter] => 1

)




Sunday, September 02, 2012

Display youtube video

Simply display youtube video in your site.Read the following steps to display youtube video in your site.


1)$youtubelink = "http://www.youtube.com/watch?v=tu_XJidrGLI";

2) $explode_url = explode("=",$youtubelink);

3)$get_val = $explode_url [1];

4)
<object width="425" height="350" data="http://www.youtube.com/v/<?php echo $get_val ;?>" type="application/x-shockwave-flash">
<param name="src" value="http://www.youtube.com/v/<?php echo $get_val ;?>" />
<param name="allowFullScreen" value="true" />
</object>



Finally you get the you tube video in your site. Enjoy cheers :)