PHP Telnet Script to Connect to TOR and Refresh IP Address

Posted in Uncategorized on February 18, 2011 by psylencer

This is a quick little script I wrote which will hopefully save some people the headache I went through getting this to work.  There is one other script out there which everone seems to be using, trouble is it was obviously written for a different version of PHP and does not work.

This has been tested with PHP version 5.3.5. on a windows platform.

The problem I was having was with carriage return and new lines.  Both /r and /n we registering as litteral characters no matter what I did.  Replacing them with “

” fixed the problem.  Also ensuring there are no spaces between the opening inverted commas, the line break and the closing inverted commas ie “

Dreamweaver has a habbit of trying to format your code so it looks nice and neat – in this case it was causing a bunch of spaces to be inserted in between the inverted commas.

Does that make sense?  probably not – but who cares – here’s the code any way.

<?php
function tor_telnet($ip,$port,$auth,$command) {

$fp = fsockopen($ip,$port,$error_number,$err_string,10);
if(!$fp) {  echo “ERROR: $error_number : $err_string
“;
return false;

} else {
fwrite($fp,’AUTHENTICATE “‘.$auth.’”
‘);

$received = fread($fp,512);
echo $received;

fwrite($fp,$command.’
‘);

echo “<BR>”;
$received = fread($fp,512);
// list($rcode,$explanation) = explode(‘ ‘,$received,2);
echo $received;

}
fclose($fp);
}

tor_telnet(’127.0.0.1′,’9051′,’password’,'signal NEWNYM’);
?>

 

Let me know if you find this useful.

 

<?php
function tor_telnet($ip,$port,$auth,$command) {

$fp = fsockopen($ip,$port,$error_number,$err_string,10);
if(!$fp) {  echo “ERROR: $error_number : $err_string
“;
return false;

} else {
fwrite($fp,’AUTHENTICATE “‘.$auth.’”
‘);

$received = fread($fp,512);
echo $received;

fwrite($fp,$command.’
‘);

echo “<BR>”;
$received = fread($fp,512);
// list($rcode,$explanation) = explode(‘ ‘,$received,2);
echo $received;

}
fclose($fp);
}

tor_telnet(’127.0.0.1′,’9051′,’test’,'signal NEWNYM’);
?>

How to get a Brother MFC-250C to print with an empty colour catridge

Posted in Uncategorized on November 25, 2010 by psylencer

Hi People,

This is quite an easy one.  Basically if you are like me and unlucky enough to own a shitty Brother printer, you’ll be familiar with the regular pain of running out of a single colour of ink, and having the whole printer cease to work because of which.    These stupid pieces of crap will not print a BLACK and white page if any of the cyan, yellow or magenta cartridges are out.

Well here is the quick fix to get you back on track and operating with just a black cartridge and a bunch of empty other ones.

The brother printers use a sensor which scans the clear plastic parts of the cartridge to determine how much ink is left.  Basically, coloring in these sections tricks the printer into thinking the empty cartridge is full of ink.

All one needs is a black permanent marker.  Simply pull back the sheath on the cartridge to reveal the clear inner.  “Paint” all the clear plastic on all three sides as well as the clear part on the top of the cartridge.  Please see images below.

Replace the cartridges and you are all set.

Hope this helps.

Getting things in Magento by getModel and getData methods

Posted in Uncategorized on September 23, 2010 by psylencer

Hi all, Im posting this article because it is useful and not available on codeline anymore – I managed to copy the cached version before it disappears.  Thanks to Branko for such a great tutorial.

Psylencer

Getting things in Magento by getModel and getData methods

Posted by branko in Magento | 33 Comments

One of my previous articles was about getting a product information using getData method. This article is a step forward in that direction. I’m gonna show you how to retrieve almost anything in Magetno using getModel and getData methods (function if you prefer).

Before I start with the title related content let me say a word or two of my development tool. For the last few weeks I’m using only one tool while developing on PHP platform, NetBeans 6.5. My favorite text editor still remains Notepad++. Although the the official release is NetBeans 6.5 beta, I’m using the night build versions. In my modest opinion this is the best free IDE solution currently out there. I simply love the code completion in PHP and in HTML plus the coolest thing ever, jQuery code completion support. Since I’m a big fan of jQuery, NetBeans is my number one choice. Some of you probably don’t see HTML code completion as that big of a deal. Well, I do. It saves you a lot of time finishing all those quotes next to attributes and auto closing all those markup.

There is quite a number of threads and discussions on Magento form about getModel and getData methods. Here I will show you a few ways of using both. One thing to have in mind. I’m working on locally installed Magento with default sample data package. For some reason I like to use the app/design/frontend/default/mycustom/template/catalog/product/view.phtml file.

Where mycustom in the folder name is the name of my theme folder. Let’s get started.

If you open the view.phtml file and write down the $cModel = Mage::getModel(‘catalog/product’); you would basically say create an instance of Mage_Catalog_Model_Product class. So where does the catalog/product comes from? What are the other available parameters one can put into the getModel function? What are the methods of I can use on this new instance object? All of these are logical questions. Questions so poorly covered by current Magento documentation.

As I sad it before, I said it again; Magetno is great software, it’s biggest flaw is the current lack of good documentation. Let us try to answer the questions mentioned above.

Where does the catalog/product parameter comes from? If you browse to /app/code/core/Mage/ folder you would see a list of logically named subfolders like Catalog, Checkout, Contacts, Core, Dataflow and so on. If you browse deeper into the Catalog folder, you will see it’s structure contains Model directory among all others. Browse into the Model directory and there you will see a bunch of files, among which is Product.php. This Product.php is whats called when you write down getModel(‘catalog/product’). In short getModel(‘catalog/product’) says go into the /app/code/core/Mage/ folder, open the folder named product, and create an instance of Product.php file located inside the Model subfolder (to be more precise, create the instance of the class cotained inside the Product.php file).

If we now echo the get_class($cModel); we would get the Mage_Catalog_Model_Product text displayed in our browser. This means that our $cModel variable is actually an instance of Mage_Catalog_Model_Product class. This matches the class name contained inside the app/code/core/Mage/Catalog/Model/Product.php file. Inside this Product.php file we can clearly see that Mage_Catalog_Model_Product class extends the Mage_Catalog_Model_Abstract class. What this means is that our $cModel can use all of the methods (functions) declared inside the Mage_Catalog_Model_Product class plus those declared inside the Mage_Catalog_Model_Abstract class.

To see the list of the methods available you can use IDE like NetBeans. NetBeans lists you all the methods of a class in the Navigator window, like the one provided in the screenshot. Or you can use the foreach loop to iterate and echo out the available method names like

echo ‘<ul>’;
foreach (get_class_methods(get_class($cModel)) as $cMethod) {
echo ‘<li>’ . $cMethod . ‘</li>’;
}
echo ‘</ul>’;

You can look at the screenshot for the result. You can see some pretty cool and useful methods like getName, getPrice, getTypeId, getStatus which we can execute on our $cModel variable like

echo ‘Product name: ‘ . $cModel->getName();
echo ‘Product price: ‘ . $cModel->getPrice();

However, the above code wont give you anything. You will not see any price displayed in the browser. Why, you might and should ask? Well, for what product are you requesting a price? Magento does not know that at this point. Some of you might ask, how is it that it does not know? We have a product view page open after all. Well, we do, but I’m showing you a code that you can use no matter what page you have open.

We can tell it to him in a single line of code using load() method. This method is also displayed on the list of available methods for this variable. So the above code fore retrieving the product name and price would work if we were to write it like

$cModel->load(53);
/*
Number 53 is the id number in default sample data, it’s assigned to Couch product you can see in this screenshots
*/

echo ‘<p>Product name: ‘ . $cModel->getName() . ‘</p>’;
echo ‘<p>Product price: ‘ . $cModel->getPrice() . ‘</p>’;

View.phtml file already has the instance of Mage_Catalog_Model_Product class trough $_product = $this->getProduct() variable. Here you can see the Magento creaters are using the getProduct() method on the $this variable. Variable $this contains huge amount of data in it, among which is current instance of  Mage_Catalog_Model_Product class stored in some array structure. If you were to retrieve the list of available methods of $this variable, like we did on the $cModel variable, you were to see the getProduct() method among them like

echo ‘<ul>’;
foreach (get_class_methods(get_class($this)) as $cThis) {
echo ‘<li>’ . $cThis . ‘</li>’;
}
echo ‘</ul>’;

If you understood all of the stuff I showed you so far then you understand the power of getModel method. You create the instance of class and store it into some variable (like $cModel), load the data for that type of object by using load function, then ust the list of available functions on that variable (object).

Title of this post mentions getData method also. As you can see, getData is just one of multiple available methods for your new variable. So why mentioning it in the same context as getMethod?

Before I answer that question let me just explain how getData can be executed with or without any parameters passed to it. If you execute it without any parameters you get the array variable as a result. You can’t directly echo the array. You would have to map it to some field, like echo $arayVar['someField']. So I ask you, what are all the available fields? To find out you can do something like

echo ‘<pre>’;
print_r($cModel->getData());
echo ‘</pre>’;

Results are so tasteful. There is a bunch of data one can use in it’s custom design solutions. Let’s say you want to retrieve the SKU value. You can use some other method for that like getSku() method that needs to be executed on object of Product type or you can

echo $cModel->getData(‘sku’);

or

$cModelData = $cModel->getData();
echo $cModelData->sku;

Cool, right. If you look at the entire array of data thrown at us when we executed print_r($cModel->getData()); we can clearly see there are some nested arrays, and some array fields store entire objects, like stock_item field. It stores object of Mage_CatalogInventory_Model_Stock_Item type. When you run into stuff like this, you can do the following

$cStockItem = $cModel->getData(‘stock_item’);
or
$cStockItem = $cModelData->stock_item;

Now your $cStockItem variable is a object of type Mage_CatalogInventory_Model_Stock_Item and you can go ahead and use the same principle used until this point to find it’s methods and the data id holds.

Hope this was useful.

Loading comments… 

Glad you liked it. Would you like to share?

No thanks

Sharing this page …

Thanks! Close

Add New Comment

Showing 33 comments

Sort by Popular now Best rating Newest first Oldest first Subscribe by email Subscribe by RSS
  • suraj Surendran 7 months ago
    Thank you So much man you are great………….
  • Hi.. 

    $cModelData = $cModel->getData();
    echo $cModelData->sku;

    This code isnt working. It should be following….

    $cModelData = $cModel->getData();
    echo $cModelData['sku'];

    Because $cModel->getData() is returning array, it need to be accessed as an array element. Arrow operator here will give error.

  • @Mohit 

    There are number of articles and even some extensions you can download from this site that should cover your question.

  • Hi… 

    This post is useful to get data. My question is…

    How can I store new record into the database…?

  • hiii, 

    i have one question…

    when i write getData method it will give me proper data…but i am edit that data ..and now i want to save it.. so how can i save that data ???

    example : i make one attribute..now i fetch it on product view page now on add to cart i want to save that attribute data. so how can i do this thing ??

    thank you..

  • @Yogendra 

    Actually you can use full class name like

    $product = new Mage_Model_Catalog_Product();
    $product->load($productId);

  • I would like to thanks Branko for this article. Very helpful. Cheers Mate for this. Much appreciated. 

    I have put the code in this comment in case some people are still struggling to get the desired results -:

    This code you can copy as it is in /template/catalog/product/view.phtml file.

    $_helper = $this->helper(‘catalog/output’);
    $_product = $this->getProduct();

    $cModel_PC = Mage::getModel(‘catalog/product’);

    echo ”;
    foreach (get_class_methods(get_class($cModel_PC)) as $cMethod) {
    echo ” . $cMethod . ”;
    }
    echo ”;

    echo ‘====’;

    echo ”;
    foreach (get_class_methods(get_class($_helper)) as $cMethod) {
    echo ” . $cMethod . ”;
    }
    echo ”;

    $cModel_PC->load($_helper->productAttribute($_product, $this->htmlEscape($_product->getId()), ‘Id’));

    echo $cModel_PC->getData(‘description’);
    echo $cModel_PC->getData(‘name’);
    echo $cModel_PC->getData(‘manufacture’);

  • But how would I get a handle on the ProductAttribute Object? 

    $attributes = Mage::getModel(‘catalog/product/attribute’);

    … doesn’t work. Oddly enough, it returns the Product object.

  • Is it possible to use this code in say the breadcrumbs to retreive the product information of whatever page I’m on? I tried doing: 

    $idParams = $this->getRequest()->getParam(‘id’);
    $cModel = Mage::getModel(‘catalog/product’);
    $cModel->load($idParams);
    print_r($cModel->getSku());

    but even when I’m not on a product page, it still takes the ID of the page I’m on and runs it agains the product database and returns an SKU for whatever product I have that is matching up to the category page I’m on id-wise.

    Is there a different way to find what the current product is that’s being displayed?

    Thank You so much for your tutorials. They are straightforward and easy to read, unlike the offical source.

  • Anjanesh 1 year ago
    Cool ! But most of the attribute data are index keys.
    $cModel->getData(‘manufacturer’) returns an integer (index key).
    How do we retrieve the text associated with it ?
  • Jason Nardo 3 weeks ago
    Hi Mr. Branko 

    I just wanna ask it is possible to add some customized functionality when I clicked on the “Place Order” in onestepcheckout say.. after performing the place order request… a new page will open in a separate window..

    In that sense, we want to somehow edit the behavior when “Place Order” is clicked

  • Great article. You’re right, Magento is a powerful and well thought out application, but it has a lot of “secret” naming conventions that make it hard to learn. Thanks for explaining this.
  • Bob Brodie 9 months ago
    Hello, 

    How would you recommend creating a new root category using Mage::getModel(‘catalog/category’)?

    Thank you,
    Bob Brodie

  • Devin Olsen 11 months ago
    really helpful man! The only thing I cant figure out is why they dont allow you to gather a products type via getData(‘type’);
  • hiii, 

    thank u for nice post. it is very very useful post..

    thank you man

  • Thanks for quick reply. One another thing I am wondering is that how magento is storing the entities values in database. I have created my own module and I have also created few attributes related to my entity_set. And I am also able to create dynamically as per magento database. Please have a look to this thread:
    http://www.magentocommerce.com/boards/viewthread/41408/
    So if you can guide me than it will really help me to understand magento to great extent. One more thing, we can filter collection by attribute and if I want to filter my collection with field then how can I do this. Thanks in advance brother to guide me.
  • How can I create instace of Mage_Model_Catalog_Product in my phtml as I want to connect this with my helper. 

    Second thing I want to display some attributes to my customer dashboard page where I am displaying the item list of all order’s. So please guide me.

  • Khaliq 1 year ago
    Hi! 

    thanks for nice Article

    But i am in wonder that how do i read the Random Quotes through a
    file in magento.Is Magento support such features or Zend Provides some built-in Libraries for that.
    Please reply

  • NIRMESH 1 year ago
    hi branko, 

    can u tell me how magento search works i wanted to know where and how magento form the query so that i can customize that query.
    actually i need to add one more parameter while it search for a product.

    please throw some light. ASAP.

  • Sylvie 1 year ago
    Very useful article indeed. 

    I was wondering how I shoul use those functions to display the product details (image, descriptions…) in a light popup clicking on an image to avoid reloading the page.

    What should be the best way to do it, passing the product id to a js-php file that will create an instance of Mage_Catalog_Model_Product class, then load data?

    Could I pass the array variable $_product to dynamically generate the detail product popup ?

    Your suggestions are welcome :) .

    Sylvie

  • @nirmesh 

    Thank you for for reading my blog. This is relatively old article now :)

    Not sure what exactly you are trying to do in your example. Take a look at inchoo.net site (company I work for). You’ll find few additional Magento articles by me and my co-workers.

    Cheers…

  • NIRMESH 1 year ago
    hi branko, 

    thanx a lot this article proved to be very useful for me.

    just one doubt please clarify it:

    My only idea is to get an array of all product ids then have a php function randomly pick one out and get the details via a $cModel->load(); and write it, then repeat!!

    Seems a bit long winded,

    is there not any way so that i can put any variable in load so that it could retrieve all the product information

  • Nice post.. dude… thanx that helped me a lot..
  • I’ve used your blog post extensively in learning how to pull down product data but I can’t seem to find a method or even anything from print_r($cModel->getData()) that would indicate where a Bundle product’s price data is stored. It seems like it might be in the Tier price array (and associated arrays), but alas they are empty when I attempt to output them. Do you have any insight branko?
  • Same problem here. I’m trying to create a custom module and I need to show some products, but $product->getName() method doesn’t return anything. Any ideas? 

    Anyway, nice job with this blog,man. I found it very useful. Keep up the good work!

  • ok, so I tried using getSingleton instead by doing this: 

    $cSingleton = Mage::getSingleton(‘catalog/product’);
    echo ”;
    echo ‘Product name:’;
    echo $cSingleton->getName();
    echo ”;

    but I still can’t figure out how to retrieve the name of the product on the page from within the breadcrumbs. Anybody?

  • getModel(‘catalog/product’) is the same as if you did new Mage_Catalog_Model_Product(), autoloading will do the job. So first you try this second approach on your module
  • Ahsan Shahzad 1 year ago
    cool post, 

    i need a bit explanation on this sentence of your post in sense of custom modules:

    ” In short getModel(’catalog/product’) says go into the /app/code/core/Mage/ folder, open the folder named product, and create an instance of Product.php file located inside the Model subfolder (to be more precise, create the instance of the class cotained inside the Product.php file).”

    you told in above that getModel(’catalog/product’) will tell megento to pick the module from Mage but what if i need to pick data through my custom module, how i’ll explicitly mention if it is Mage module or my custom module. Will it automatically map getModule(‘abc/model’) ?

    please explain,
    thanks

  • P.S. Go to Zend Framework site and go trough some tutorials on MVC structure and passing parameters between Model, Controller, View and stuff like that. Should help you since Magento is Zend based.
  • You cant call the block directly since they all contain getChildHtml… does not work, they break and you are unable to see stuff that getChildHtml is suppose to output… do the getModel(of something)->load(by some id of something) play with it. There are infinite possibilities.
  • Dinesh 1 year ago
    getModel is used to call the function and get data from other model of the module, how do u i call the function in other block of the module.
  • Dinesh 1 year ago
    I want to display the block same as that of sales-order module in my custom module. How can i do that 

    thanks

  • Great post thanks alot, 

    this has really helped me with a section of my site. One thing i am still not sure on is how you retrieve a collection of products from the db for example i’d like to retrieve a random bunch of 6 products that are instock and sellable but have no idea how to go about it.

    My only idea is to get an array of all product ids then have a php function randomly pick one out and get the details via a $cModel->load(); and write it, then repeat!!

    Seems a bit long winded, but thanks for this article and keep up the good info, magento rocks but i agree it needs a bit more doc

blog comments powered by Disqus

Live Keyword Desnity / Percentage Calculator. Calculate keyword density as you type.

Posted in Uncategorized on August 30, 2010 by psylencer

Whether you believe it makes a difference, this tool enables you to see the keyword density of a document you are typing, while you are typing it.  I modified some original code from the following source : http://rainbow.arch.scriptmania.com/tools/word_counter.html

The problem with the code above is that it does not calculate frequency percentage (useful if you DO believe keyword density has something to do with SEO results) and secondly, it does not work live.  One has to click a button every time they wish to see what the density is like.

I modified the code above so that percentage, repetition count and order is displayed live, as you are typing.  This I find is useful if you have a target percentage for a given word you wish to reach or if you simply want analyze large chunks of code in order to run your own experiments on competitors.  Strangely enough, I DID find a STRONG correlation between keyword density and page position.   This was despite a wealth of opinions from various bloggers that keyword density makes no difference to search engine rankings.

Regardless of opinions, this tool allows you to conduct your own experiments and keep a tab on Keyword density (numbers and  percentages) as you are typing. it will also order the keywords from most used to least used as you type.

Again most of the credit goes to whom ever wrote the code on http://rainbow.arch.scriptmania.com/tools/word_counter.html – I simply modified the code to make it show percentages and display results live. Hope you find it useful.

<!doctype html public “-//w3c//dtd html 3.2//en”>

<html>
<head>

<script language = “JavaScript”>

function process1 (count)    {        // for words
m=new Array(10000);
m1=new Array(10000);
N=new Array (10000);
for (i=0;i<=1;i++)        // which is chosen
{    if ( count.radio1[i].checked)
{    ch=i;
}
}

A=count.message.value;            // original message
B=”";
A=” ” + A+” “;
A=A.toUpperCase();        // changes all alphas to Upper case

for (i=1;i<=A.length;i++)        //  trims leading spaces and multiple spaces
{    if ((!(A.charAt(i)==” “)) || (!(A.charAt(i-1)==” “)))
{B=B + A.charAt(i);
}
}
//count.result1.value=B;
B=B+” “;                // makes sure there is a space at end

k=0; str=” “;

for (i=0;i<=B.length;i++)
{    k1=B.indexOf(str,k);
if (k1==-1)        //end of string B
{    Numwords=i-1;
break;
}
m[i+1]=B.substring(k,k1); // places all the words into an array m
k=k1+1;
}
//count.result1.value=B;
C=”";
NN=0;
for (i=1;i<=Numwords; i++)    // Numwords is total number of words
{    if (!(m[i]==”"))    // only looks at m1 words that have not been processed before (not empty)
{    NN=NN+1;            //unique word stored in m1 array
m1[NN]=m[i];
N[NN]=1;            // initialize counter for word
for (j=i+1;j<=Numwords+1;j++)    //counts and makes m1 elements with unique word empty.
{    if (m1[NN]==m[j])
{    N[NN]=N[NN]+1;
m[j]=”";
}
}
}
}
C=C+”Unique:” + NN+”  Total:” + Numwords+”\n”;
C=C+”Freq.\tWord\n”;
for (i=1;i<=NN;i++)        // sets up C for showing
{
C=C +  N[i]+ “\t” + m1[i] + “\n”;
}
count.result1.value=C;
}

function roundNumber(num, dec) {
var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
return result;
}
function sortfreq(count)    {    // sorts words according to frequency
for (i=1;i<=NN-1;i++)
{    for (j=i+1;j<=NN;j++)
{    if (N[i]<N[j])
{    temp=m1[i];
m1[i]=m1[j];
m1[j]=temp;
temp=N[i];
N[i]=N[j];
N[j]=temp;
}
}
}
C=”Unique words:” + NN+”  Total words:” + Numwords+”\n”;
C=C+”Freq.\tWord\n”;
for (i=1;i<=NN;i++)
{    C=C + roundNumber((N[i] / Numwords)*100,2) +”%\t”+ N[i]+ “\t” + m1[i] + “\n”;
}
count.result1.value=C;
}

//– End
</script>

<link rel=”stylesheet” href=”styletools.css” type=”text/css”>
</head>

<body>
<FORM name =”count”>
<h5>&nbsp;</h5><BR> &nbsp;Count pure words<INPUT type=”radio” name=”radio1″ value=”1″ CHECKED>&nbsp;&nbsp;
Count everything as words <INPUT type =”radio” name=”radio1″  value=”0″><BR>

<TABLE border=”0″ cellPadding=”1″ cellSpacing=”1″>

<TR>
<TD><INPUT id=”button1″ name=”button1″ onClick=”process1(document.count);sortfreq(document.count)” style=”height: 24px; width: 165px; font-weight: bold” type=”button” value=”COUNT WORDS”></TD>
</TR></TABLE><BR>
<STRONG><font face=”Arial” color=”#000080″>Input your text into the box below:</font></STRONG><br><TEXTAREA onKeyDown=”process1(document.count);sortfreq(document.count)” cols=99 name=message rows=12 style=”background-color: #ffffff; font-size: 10pt” wrap=PHYSICAL>WORD COUNT INPUT BOX
Enter your TEXT here.
Control A to highlight all text in box.  Control V to paste text into box.  Control C to copy highlighted text.
Javascript runs on your local client so resources are yours to allocate.  Larger files take longer.  Read the Technical Notes below before using.</TEXTAREA>&nbsp;&nbsp;<TEXTAREA cols=33 name=result1 rows=12 style=”font-size: 10pt; font-family: Arial” wrap=PHYSICAL>WORD COUNT OUTPUT BOX</TEXTAREA>
<BR><input type=”reset” value=”Reset” name=”B1″>

<h2>&nbsp;</h2></FORM>
</body>
</html>

Magento – shopping cart rules fail for users who aren’t logged in

Posted in Uncategorized on June 14, 2010 by psylencer

Just a heads up, hopefully Magento is listening.  If I apply a shopping cart rule for users who are “not logged in”, the magento system fails to add the product to the cart.  This does not seem to apply to users who are logged in or have created an account.

Before you ask me to post somenthing to magento, I believe I’d have more chance of getting them to listen here that through their own forums.  Apparently magento tested this and could not reproduce the failure.  This begs the question, why are so many magento users reporting this problem?

Either magento have not read and thoroughly tested this failure, or we are all doing something wrong.  If anyone can shed any light on this subject, please let us know.

.

How to : Magento – Payment Type Surcharge Without Paying for an Extension. (Part 2)

Posted in Uncategorized on March 17, 2010 by psylencer

Open app/code/core/Mage/SaleRule/Model/Validator.php

Find the following about line 288

if ($cartRules[$rule->getId()] > 0) {
$quoteAmount        = $quote->getStore()->convertPrice($cartRules[$rule->getId()]);
/**
* We can’t use row total here because row total not include tax
*/
$discountAmount     = min($itemPrice*$qty – $item->getDiscountAmount(), $quoteAmount);
$baseDiscountAmount = min($baseItemPrice*$qty – $item->getBaseDiscountAmount(), $cartRules[$rule->getId()]);
$cartRules[$rule->getId()] -= $baseDiscountAmount;
}
$address->setCartFixedRules($cartRules);
break;

And replace with : (Note the small change in the first line from > to <>)

if ($cartRules[$rule->getId()] <> 0) {
$quoteAmount        = $quote->getStore()->convertPrice($cartRules[$rule->getId()]);
/**
* We can’t use row total here because row total not include tax
*/
$discountAmount     = min($itemPrice*$qty – $item->getDiscountAmount(), $quoteAmount);
$baseDiscountAmount = min($baseItemPrice*$qty – $item->getBaseDiscountAmount(), $cartRules[$rule->getId()]);
$cartRules[$rule->getId()] -= $baseDiscountAmount;
}
$address->setCartFixedRules($cartRules);
break;

And thats it.  I’ve not tested this fully yet.  Let me know how you go.

How to : Magento – Payment Type Surcharge Without Paying for an Extension.

Posted in Uncategorized on March 7, 2010 by psylencer

Just though I would share this little tid bit for the benefit of all who have asked for this type of functionality from magento and not been prepared to pay $64 USD for an extension to do so.

Just to clarify, this is a mod, not an extension.  Also, I’m not the worlds greatest Magento user and i’m sure there is a way of making an extension to do this.  But.. for the moment, the following instructional works very well and is very easy to do.

Usage:  Once mods have been made, admin users will be able to create a shopping cart rule “discount” which is not actually a discount based on a percentage of the value of their shopping cart.  I’m not going to educate you all how to make a shopping cart rule, but basically, until now there have been a few problems with using  shopping cart rules to apply a Surcharge.

The First. You can’t.  You can only enter a positive number as a percentage

The Second.  Magento in all their wisdom have an option to calculate the “discount” on shipping as well as shopping cart value, however the stupid system does not allow you to move the location of the “discount” / surcharge to after the shipping line.  This can be very confusing for customers trying to figure out how their “discount”/surcharge is calculated.

Lastly, again in all their Wisdom, Magento went and hard coded the word “Discount” in front of the name of your discount / surcharge.  So for instance if I wanted to add a surcharge using the mod below, it would read something like this :

(Discount) Credit Card Surcharge 1.5%  = $15.60

Obviously that is not the smartest way to do things which is surprising for an E-Commerce system which is supposed to be flexible. Did they need to hard code the word “Discount” especially given the fact one could easily pre pend  the word “discount” in the name of the  shopping cart rule if they wanted it displayed.

One more gripe before I proceed to the How to is the fact the only reason I wrote this is because Magento are so pathetically poor at answer extreemly simple questions such as this.  I could find absolutely no definitive solution to this issue other than to A) Pay Magento for support – which is laughable given how easy this was to resolve or B)Pay $64 for an extension.

And for the disclaimer.  This will involve very small modifications to core Magento files.  Always make backups before changing any of the files mentioned herin.  Also apparently it is illegal to apply Credit Card (or any other payment type for that matter) surcharges in some countries.  Check with your Merchant provider in your country to see if this is a problem.

Let me know if you have any questions and please provide credit if you intend on posting this elsewhere.

MAGNETO CHANGES :
To create credit card surcharge :

Change the following file :
app/code/core/Mage/rule/model/rule.php

Find :

protected function _beforeSave()
{
check if discount amount > 0
if ((int)$this->getDiscountAmount() < 0) {
Mage::throwException(Mage::helper(‘rule’)->__(‘Invalid discount amount.’));
}

Change to :

protected function _beforeSave()
{
// check if discount amount > 0
//if ((int)$this->getDiscountAmount() < 0) {
//    Mage::throwException(Mage::helper(‘rule’)->__(‘Invalid discount amount.’));
//}

Change the following file :
app/code/core/Mage/Adminhtml/block/promo/quote/edit/tab/actions.php

Find :

$fieldset->addField(‘discount_amount’, ‘text’, array(
‘name’ => ‘discount_amount’,
‘required’ => true,
‘class’ => ‘validate-not-negative-number’,
‘label’ => Mage::helper(‘salesrule’)->__(‘Discount amount’),

Change to :

$fieldset->addField(‘discount_amount’, ‘text’, array(
‘name’ => ‘discount_amount’,
‘required’ => true,
// ‘class’ => ‘validate-not-negative-number’,
‘label’ => Mage::helper(‘salesrule’)->__(‘Discount amount’),

Find :

app/locale/en_us/mage_sales.csv <–you may be using a different language definition file folder ie /en_au – copy changed file to both folders.

This part is important : open the file in Excel the first column is the variable name, the second is the variable value.  ONLY CHANGE THE VARIABLE VALUE!! DO NOT CHANGE THE

VARIABLE NAME.

Find the row which says “Discount” in column 1 and “Discount” in column 2.
Erase the value of Discount in Column 2 ie Column 1 should read “Discount”  (without the inverted commas) and column 2 should be empty.

The next step is optional and will depend if you want your surcharge to show AFTER shipping or before shipping.  The Magento default is to display discounts (surcharge) BEFORE shipping- regardless of whether you’ve opted to have your surcharge/discount applied to shipping in the admin console.  If you wish to have discount/surcharge displayed AFTER shipping, then proceed with the next step. Otherwise you’re all done.

Change the following file ***THIS STEP IS OPTIONAL AND IS SUITED TO VERSIONS LOWER THAN 1.4.01  For versions Later than 1.4.01 This change can be made via the admin console Admin ->Sales – >Checkout Total Sort Order.  Change “Shipping” to “20″ and change the blank line above it to 30.

For versions prior to 1.4.01

app/code/core/Mage/Sales/etc/config.xml

Change the following :

<totals_sort>
<discount>20</discount>
<grand_total>100</grand_total>
<shipping>30</shipping>
<subtotal>10</subtotal>
<tax>40</tax>
</totals_sort>

To:

<totals_sort>
<discount>30</discount>
<grand_total>100</grand_total>
<shipping>20</shipping>
<subtotal>10</subtotal>
<tax>40</tax>
</totals_sort>

All Done.  You should now be able to set negative values in the “Shopping Cart Price Rules” from your admin console.  Make sure all rule names are descriptive so your customers know what is going on.

Categorisation Categorization, Search engines and tagging. Alternative anyone?

Posted in Uncategorized on March 7, 2010 by psylencer

Why do we keep plates in the kitchen, clothes in our cupboards with socks in the top drawer?  Humans call this categorization.  The process of organizing our life into logical boundaries, allowing us to find the things we need without having to think logically about it again (should we remember for instance that socks are kept in the top drawer).

“Categorization isn’t about what you or I think you know; its about stuff making sense. The purpose in the most practical and relevant sense to myself is allowing my customers to find the products they are looking for while allowing those who don’t know what they’re looking for to browse for ideas and settle upon something relevant and meaningful; all while spending as little time doing so as absolutely necessary. Both ideas can be serviced separately with existing technology, however the technology generally works in competition with the alternative, instead of working for the alternative.

OK you ask. But how can I make life easy for my customers, clients, readers or otherwise?

Lets just assume everyone thinks the way I do.  Lets assume I am the best judge of everyone else and make them think the way I do: Traditional Categorization.

Lets assume they know what they’re looking for :Traditional search engine.

Lets assume they will “Tag” everything they look at logically; all of them:Traditional tagging

These are the most popular ways of ordering products logically.

Lets start with the pros and cons of each:

Categorization:

Pros:

Logical to at least one user,
Can be logical to many users,
Most accepted method of finding products,
Cons:

Can be under considered or over considered by both the user and categorizer.
Assumes knowledge,
Regardless of effort or consideration, can be confusing for users,
Is not practical for large product databases or companies/businesses without resources to invest,
Involves manual category mapping from suppliers some of which may have 1000′s of category combinations,

Search Engines:

Pros:

Flexible,
Little or no assumed knowledge,
Requires little effort or resources to categories,
Cheap and efficient to implement,

Cons:

Inaccurate,
Indexed by computers,
Cumbersome to use and achieves desired results from both users and those who wish users to find information,

Tagging (Tags):

Pros;
Easy to implement,
By nature intuitive,
Accurate (ideally),

Cons:

Requires assumed knowledge from the user,
Assumed unrealistic effort from the user,
Can be completely inaccurate for the previous reason,
is not efficient, for the user which negates its purpose,
Requires dedication or loyalty or status from the user to work at best.

As you can see the pros of all these methods don’t outweigh the pros.  All methods are far from perfect and the most popular is most probably the worst.

Why is the worst solution the most meaningful to most humans of all these methods?  We’re still monkeys, but its time to think modern. I believe this crap way of “finding relevance”  is prehistoric and animal like.

Solution prerequisites:

Easy to implement,
Easy to use,
Requires little ongoing human resources to maintain,
Is not based on assumed knowledge,
Is accurate for most,
Feasible to sites with large regularly changing databases and those who source datafeeds from multiple suppliers.

Or; lets work with all of those ideas to create  a way of categorizing anything in a more logical way;

To Be Continued.   In Part 2 I will discuss a possible solution to this problem which answers all of the above solution prerequisites.

Introduction

Posted in Uncategorized on October 31, 2009 by psylencer

Everyone gets surprised.  I’m relatively young (30). Have a missus and 3 kids all under 3.  Nothing surprising. I’m one of those nobody’s who thinks they have an idea. Research, persist with and think I’ve got the answer, only a few months later to find out some one else had a better idea.  This blog is to publicize the benefit of an unusual persistence; in the hope others like me will get the answers they need.

Follow

Get every new post delivered to your Inbox.