Friday 30 March 2012

Get Cart items in magento


Using checkout session you can find all items that in cart and also get subtotal and grand total of cart

$items = Mage::getSingleton('checkout/session')->getQuote()->getAllItems();

foreach($items as $item) {
    echo 'ID: '.$item->getProductId().'<br />';
    echo 'Name: '.$item->getName().'<br />';
    echo 'Sku: '.$item->getSku().'<br />';
    echo 'Quantity: '.$item->getQty().'<br />';
    echo 'Price: '.$item->getPrice().'<br />';
    echo "<br />";
}

Get total items and total quantity in cart
$totalItems = Mage::getModel('checkout/cart')->getQuote()->getItemsCount();
$totalQuantity = Mage::getModel('checkout/cart')->getQuote()->getItemsQty();

Get subtotal and grand total price of cart
$subTotal = Mage::getModel('checkout/cart')->getQuote()->getSubtotal();
$grandTotal = Mage::getModel('checkout/cart')->getQuote()->getGrandTotal();

Browser Detection Code

You can detect your browser using below code


<?php
function getBrowser()
{
    $u_agent = $_SERVER['HTTP_USER_AGENT'];
    $bname = 'Unknown';
    $platform = 'Unknown';
    $version= "";


    //First get the platform?
    if (preg_match('/linux/i', $u_agent)) {
        $platform = 'linux';
    }
    elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
        $platform = 'mac';
    }
    elseif (preg_match('/windows|win32/i', $u_agent)) {
        $platform = 'windows';
    }
   
    // Next get the name of the useragent yes seperately and for good reason
    if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent))
    {
        $bname = 'Internet Explorer';
        $ub = "MSIE";
    }
    elseif(preg_match('/Firefox/i',$u_agent))
    {
        $bname = 'Mozilla Firefox';
        $ub = "Firefox";
    }
    elseif(preg_match('/Chrome/i',$u_agent))
    {
        $bname = 'Google Chrome';
        $ub = "Chrome";
    }
    elseif(preg_match('/Safari/i',$u_agent))
    {
        $bname = 'Apple Safari';
        $ub = "Safari";
    }
    elseif(preg_match('/Opera/i',$u_agent))
    {
        $bname = 'Opera';
        $ub = "Opera";
    }
    elseif(preg_match('/Netscape/i',$u_agent))
    {
        $bname = 'Netscape';
        $ub = "Netscape";
    }
   
    // finally get the correct version number
    $known = array('Version', $ub, 'other');
    $pattern = '#(?<browser>' . join('|', $known) .
    ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
    if (!preg_match_all($pattern, $u_agent, $matches)) {
        // we have no matching number just continue
    }
   
    // see how many we have
    $i = count($matches['browser']);
    if ($i != 1) {
        //we will have two since we are not using 'other' argument yet
        //see if version is before or after the name
        if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){
            $version= $matches['version'][0];
        }
        else {
            $version= $matches['version'][1];
        }
    }
    else {
        $version= $matches['version'][0];
    }
   
    // check if we have a number
    if ($version==null || $version=="") {$version="?";}
   
    return array(
        'userAgent' => $u_agent,
        'name'      => $bname,
        'version'   => $version,
        'platform'  => $platform,
        'pattern'    => $pattern
    );
}


// now try it
$ua=getBrowser();
$yourbrowser= "Your browser: " . $ua['name'] . " " . $ua['version'] . " on " .$ua['platform'] . " reports: <br >" . $ua['userAgent'];
print_r($yourbrowser);
?>

may this code help you to find out detail about your browser

Magento – How to Reset the Admin Password


Use any password for admin username and after that you can change your password:

Only need FTP Access:



Use any password for admin username:

Only need FTP Access :


To login into magento admin, using only ftp access is a little tricky. Through FTP open the class Mage_Admin_Model_User located at app\code\core\Mage\Admin\Model\User.php
Next find the authenticate() function around line no: 225. Inside the authenticate function, this code is written

$this->loadByUsername($username);

You need to add the line return true; after this i.e

$this->loadByUsername($username);
return true;

And that’s it..
now find username using below script :


<?php
require_once 'app/Mage.php';
umask(0);
Mage::app('');
$tprefix = (string) Mage::getConfig()->getTablePrefix();
echo "<br/>".$tprefix;
        $connection = Mage::getSingleton('core/resource')->getConnection('core_write');
$b=$connection->query("select * from ".$tprefix."admin_user ");
$t=0;
while($roes2=$b->fetch(PDO::FETCH_ASSOC)) 
{
$adminemail=$roes2['email'];
$adminuser=$roes2['username'];
echo $adminemail.'=>'.$adminuser.'<br/>';
}
?>
make one php file and past above code in it,after that put that php file in root and run it ex. if php file name is findadnim.php than run http://yourdomainname.com/findadmin.php
so you get all usernames of admin select any of them , now you login in admin using any password for. Since, we have skipped the code for password checking, login using any password and then change the password in admin from System -> Permission -> Users.

Programmatically Add Product In Cart in Magento

Adding a Product to the Cart via Querystring


For Simple Product :

$this->getUrl('checkout/cart').'add?product='.$pro_id.'&qty='.$qty.';
where : $pro_id= 'Product id' ; $qty = 'Product Quentity'

For Simple Product with Custome Option:

$this->getUrl('checkout/cart').'add?product = '.$pro_id.'&qty = '.$qty.'&options['.$pro_value.'] = '.$pro_opt_val.'
where : $pro_value= 'Product option_id';$pro_opt_val= 'Product option_type_id';

For Bundle Product :

$this->getUrl('checkout/cart').'add/product/['.$pro_id.']/?bundle_option[['.option_id.']][]=['.selection_id.']

like if bundle product's id is 2790 than :
      $_product = Mage::getModel('catalog/product')->load(2790);
      if ($_product->getTypeId() == 'bundle') 
     {
        $w = Mage::getSingleton('core/resource')->getConnection('core_write');
        $result = $w->query("select `option_id`, `selection_id` from `catalog_product_bundle_selection` where        `parent_product_id`=$id");
        $route = "checkout/cart/add";
        $params = array('product' => $id);
        while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
            $params['bundle_option['. $row[option_id] .']'][] = $row['selection_id'];
       };
        header("Location: ". Mage::getUrl($route, $params));
   }

For Adding a Configurable Product to the Cart via Querystring:

http://www.your_domain.com/checkout/cart/add?product = 68&qty = 1&super_attribute[528] = 55& super_attribute[525] = 56


Here  68  is the product entity id displayed in magento admin panel.  528 and 525  is the attribute associated with this product and  55 and 56  is the selected value of that attribute. 

Another way to add product in cart :

For Simple Product :

$params = array(
    'product' => 23,
    'qty' => 2,
);
$cart = Mage::getSingleton('checkout/cart'); 
$product = new Mage_Catalog_Model_Product();
$product->load(23); 
$cart->addProduct($product, $params);
$cart->save(); 
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);



For  Configurable  Product  :



$params = array(
    'product' => 23,
    'super_attribute' => array(
         528 =>55,
    ),
    'qty' => 2,
);

$cart = Mage::getSingleton('checkout/cart'); 
$product = new Mage_Catalog_Model_Product();
$product->load(23); 
$cart->addProduct($product, $params);
$cart->save(); 
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);

Programmatically Create New Magento Admin User


<?php
/*
 * Create New Admin User
 */


//define USERNAME, EMAIL and PASSWORD below whta ever you want and uncomment this 3 lines (remove # sign)


#define('USERNAME','admin');
#define('EMAIL','xyz@xyz.com');
#define('PASSWORD','admin123');




if(!defined('USERNAME') || !defined('EMAIL') || !defined('PASSWORD')){
echo 'Edit this file and define USERNAME, EMAIL and PASSWORD.';
exit;
}


//load Magento
$mageFilename = 'app/Mage.php';
if (!file_exists($mageFilename)) {
echo $mageFilename." was not found";
exit;
}
require_once $mageFilename;
Mage::app();


try {
//create new user write you firstname,lastname
$user = Mage::getModel('admin/user')
->setData(array(
'username'  => USERNAME,
'firstname' => 'Gz',
'lastname' => 'Chauhan',
'email'     => EMAIL,
'password'  => PASSWORD,
'is_active' => 1
))->save();


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


try {
//create new role
$role = Mage::getModel("admin/roles")
->setName('Inchoo')
->setRoleType('G')
->save();

//give "all" privileges to role
Mage::getModel("admin/rules")
->setRoleId($role->getId())
->setResources(array("all"))
->saveRel();


} catch (Mage_Core_Exception $e) {
echo $e->getMessage();
exit;
} catch (Exception $e) {
echo 'Error while saving role.';
exit;
}


try {
//assign user to role
$user->setRoleIds(array($role->getId()))
->setRoleUserId($user->getUserId())
->saveRelations();


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


echo 'Admin User sucessfully created!<br /><br /><b>THIS FILE WILL NOW TRY TO DELETE ITSELF, BUT PLEASE CHECK TO BE SURE!</b>';
@unlink(__FILE__);


?>

create php file like newuser.php and past above code in that file, put newuser.php file in magento root and run script like http://yourdomain.com/newuser.php thats it, now you can login in magento admin using username and password that you enter above code