Magento external Script and Session - session

I want to add an external script which gets a sku via GET check the ID and then redirect to the cart if available otherwise it sets en error and also redirecting to the cart.
The script is called from a product page:
http://myhost/scripts/addto.php?sku=12345
Here is the colmplete code
<?php
include_once '../../../../../app/Mage.php';
Mage::app();
$session = Mage::getSingleton('core/session', array('name' => 'frontend'));
$sku = $_GET['sku'];
if (!isset($_GET['qty'])) { $qty = '1'; } else { $qty = $_GET['qty']; }
$id = Mage::getModel('catalog/product')->getIdBySku($sku);
if ($id == '') {
$id = $sku;
Mage::getSingleton('checkout/session')->addError("Product not found!");
}
Works fine, but after logout and relogin the error message is missing. I found out that's because of a cookie which is set. After deleting that cookie the error message is working again after relogin.

What does not work?
You logout and login and then the script stop working? So the session is not found? The product ist not found? The product is not loaded? The user is not forwarded? :-)
Sure it does not. The Message is a Notice. If it is shown once, it is deleted.
What behaviour do you want?

use Mage::getSingleton('core/session')->addError("Product not found!");, maybe checkout/session is user specific...
cheers

Related

Get Product Url return 404 in Magento

I want to get product's url so i use getProductUrl() in result its return a url that seems be correct but its not ,When I want to open it ,the store return 404 not found error.
$product = Mage::getModel('catalog/product')->load($productId);
$url => $product->getProductUrl();
//It's return
// http://mg1.dev/index.php/catalog/product/view/id/905/s/plaid-cotton-shirt-royal-blue-l/
I got same error with you, here is my sollotion.
Add following line to your Query:
$collection->addFieldToFilter(array(array('attribute'=>'visibility', 'neq'=>"1" )));
IN my case that solved the 404/wrong url.
Check your catalog product model is really returning values or not...
If it is returning values, still you are not getting product url, then try with sku...
try this,
$sku = 'test'; // SKU you want to load.
$url = Mage::getModel('catalog/product')->loadByAttribute('sku',$sku)->getProductUrl();
echo $url;

add product to wishlist in magento API

I have checked in magento soap API but I can not find API for add product to wish list so I am developing own API but I don't know what is the problem with my code so please help me to find solution.
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
require_once '../app/Mage.php';
Mage::app();
$customer_id = $_GET['customer_id'];
$product_id = $_GET['product_id'];
$customer = Mage::getModel('customer/customer');
$wishlist = Mage::getModel('wishlist/wishlist');
$product = Mage::getModel('catalog/product');
$customer->load($customer_id);
$wishlist->loadByCustomer($customer_id);
$res = $wishlist->addNewItem($product->load($product_id));
if($res)
{
$status =1;
$message = "your product has been added in wishlist";
}
else
{
$status =0;
$message = "wrong data send";
}
$result = array("status" =>$status,"message"=>$message);
header('Content-type: application/json; charset=utf-8');
echo json_encode($result);
?>
There is a similar question you might want to check.
In your code you are not extending Magento API in any way but creating a standalone hackish script that inserts items to wishlist. I suggest that you take a look on how to develop a magento extension or if you need to create a backend (CLI) script, at least use the same structure as in shell/abstract.php and extend the shell base class - you will save yourself loads of headaches.
Moreover, your code is not secure, maintainable and removes all the benefits of using Magento as an ecommerce platform/framework (security, authorization & authentication etc)
Inchoo have quite some blog posts that could give you an idea where to begin
http://inchoo.net/magento/magento-api-v2/
http://inchoo.net/magento/extending-the-magento-api/
/* error_reporting(E_ALL);
ini_set("display_errors", 1);*/
You Have Comment This line And Write this
require_once './app/Mage.php';

Add user to group in Joomla not working

I am trying to add a user to a group. I can run this PHP code without any errors, but the user group is still not changed.
<?php
define('_JEXEC', 1);
define('JPATH_BASE', realpath(dirname(__FILE__)));
require_once ( JPATH_BASE .'/includes/defines.php' );
require_once ( JPATH_BASE .'/includes/framework.php' );
require_once ( JPATH_BASE .'/libraries/joomla/factory.php' );
$userId = 358;
$groupId = 11;
echo JUserHelper::addUserToGroup($userId, $groupId);
?>
I run in the same issue with payment callback. I found that user groups save in the database correctly, but are not refreshed in Juser object (becouse You add user to group in different session). When user interacts on a page groups are restored.
Another think that i found is that changing groups in administrator panel works the same way if user is logged in.
To deal with it I made system plugin and in onAfterInitialise function i do:
//get user
$me = JFactory::getUser();
//check if user is logged in
if($me->id){
//get groups
$groups = JUserHelper::getUserGroups($me->id);
//check if current user object has right groups
if($me->groups != $groups){
//if not update groups and clear session access levels
$me->groups = $groups;
$me->set('_authLevels', null);
}
}
Hope it will help.
Possible "Easy" Solution:
The code is correct and it should put your $userId and $groupId in the db to be precise in #__user_usergroup_map .
Btw consider that this method is rising an error if you use a wrong groupId but it's not raising any error if you insert a wrong $userId and for wrong I mean that it doesn't exist.
So there are canches that the user with $userId = 358; doesn't exist.
Update - Hard Debugging:
Ok in this case I suggest you to digg in the code of the helper.
The file is :
libraries/joomla/user/helper.php
On line 33 You have JUserHelper::addUserToGroup.
This is the code:
public static function addUserToGroup($userId, $groupId)
{
// Get the user object.
$user = new JUser((int) $userId);
// Add the user to the group if necessary.
if (!in_array($groupId, $user->groups))
{
// Get the title of the group.
$db = JFactory::getDbo();
$query = $db->getQuery(true)
->select($db->quoteName('title'))
->from($db->quoteName('#__usergroups'))
->where($db->quoteName('id') . ' = ' . (int) $groupId);
$db->setQuery($query);
$title = $db->loadResult();
// If the group does not exist, return an exception.
if (!$title)
{
throw new RuntimeException('Access Usergroup Invalid');
}
// Add the group data to the user object.
$user->groups[$title] = $groupId;
// Store the user object.
$user->save();
}
if (session_id())
{
// Set the group data for any preloaded user objects.
$temp = JFactory::getUser((int) $userId);
$temp->groups = $user->groups;
// Set the group data for the user object in the session.
$temp = JFactory::getUser();
if ($temp->id == $userId)
{
$temp->groups = $user->groups;
}
}
return true;
}
The bit that save the group is $user->save();.
Try to var_dump() till there and see where is the issue.
Author already halfish solved this problem so this answer may help to others. It took me hours of debugging with Eclipse and XDebug to find the issue. This error was very tricky because addUserToGroup() was returning true for me and user object was as well with successful changes, but they were not saved in database. The problem was that onUserBeforeSave() method in my plugin was throwing exception whenever addUserToGroup() was trying to save a user. So check your implementation of onUserBeforeSave() if you touched it. If not you must install Eclipse with XDebug and try to debug what is your exact problem.

how to get sku and product name on the head.php page?

how to get sku and product name on the head.php (\app\code\core\Mage\Page\Block\Html\head.php) page? thank you.
when i used $this->_data['sku']; or $this->getSku(); are all not work.
The previous answer is fine, except it doesn't check if product exists in registry. So you will get fatal error on non-product pages. Always make a check if variable exists.
$product = Mage::registry('current_product');
if ($product) //sometimes need check for instanse, use instanseof
{
$product->getSku();
}
You should be able to pull the current product back from the registry and access the values from that.
$product = Mage::registry('current_product');
$product->getSku();
Working Code:
if($_product = Mage::registry('current_product')){
$id = $_product->getId();
$sku = $_product->getSku();
}

Checking for Magento login on external page

I'm hitting a wall here while trying to access items from Magento on an external page (same server, same domain, etc, etc). I want to see if the user is logged into Magento before showing them certain parts on the site.
Keep in mind that this code exists outside of Magento.
Mage::app("default");
Mage::getSingleton("core/session", array("name" => "frontend"));
if (empty($session))
{
$session = Mage::getSingleton("customer/session");
}
if($session->isLoggedIn())
echo "hi";
$cart = Mage::helper('checkout/cart')->getCart()->getItemsCount();
echo $cart;
$cart returns 0, where I definitely have products in my cart. isLoggedIn() also returns false. What am I doing wrong here? Is there an option in Magento that I need to turn on or off to be able to access this information outside of Magento?
Using the code above, I created a php file in the Magento folder. From there, added the number of items in the cart and whether you were logged in or not to an array and encoded it as json. I used some jquery on my external page to grab the file and pull the data I needed.
Not quite the ideal situation, but it works for now.
Are you including Mage.php (which defines getSingleton)?
require_once ($_SERVER['DOCUMENT_ROOT'] . '/app/Mage.php');
What does $session have in it after the getSingleton() call?
print_r ($session);
EDIT: I tried this on my end and was not able to get accurate isLoggedIn() or getItemsCount() data. When I dumped out $session its showing all the fields as 'protected.'
I'm not interested in requiring the user to log in...I merely want to access data from the already logged in session.
Anyone else have any thoughts on this? All the examples out there seem to be pre 1.4.x.
require_once "app/Mage.php";
umask(0);
Mage::app();
// require_once $_SERVER['DOCUMENT_ROOT'] . "/mage1/app/Mage.php";
// Customer Information
$firstname = "krishana";
$lastname = "singh";
$email = "krish.bhati#gmail.com";
$password = "myverysecretpassword";
// Website and Store details
$websiteId = Mage::app()->getWebsite()->getId();
$store = Mage::app()->getStore();
$customer = Mage::getModel("customer/customer");
$customer->website_id = $websiteId;
$customer->setStore($store);
$mageRunCode = isset ( $_SERVER ['MAGE_RUN_CODE'] ) ? $_SERVER ['MAGE_RUN_CODE'] : '';
$mageRunType = isset ( $_SERVER ['MAGE_RUN_TYPE'] ) ? $_SERVER ['MAGE_RUN_TYPE'] : 'store';
$app = Mage::app ( $mageRunCode, $mageRunType );
Mage::getSingleton('core/session', array('name' => 'frontend'));
$session = Mage::getSingleton('customer/session');
$session->start();
$customer->loadByEmail($email);
$customer_id= $customer->getId();
if($customer_id){
Mage_Core_Model_Session_Abstract_Varien::start();
$session->login($email, $password);
$session->setCustomerAsLoggedIn($session->getCustomer());
echo $session->isLoggedIn() ? $session->getCustomer()->getName().' is online!' : 'not logged in';
}

Resources