Friday, September 22, 2017

Magento 1: How to override Paypal Model in your custom module

Task: Need to overrite magento paypal model method in your custom module

Solution:
For example, need to override /app/code/core/Mage/Paypal/Model/Config.php  method getBuildNotationCode

Create model in your extantion

app/code/local/YourFirm/ExtName/Model/Paypal/Config.php

code:

class YourFirm_ExtName_Model_Paypal_Config extends Mage_Paypal_Model_Config
{
    public function getBuildNotationCode($countryCode = null)
    {
        ... your code here....
       // if you need, you could run base function, use: parent::getBuildNotationCode($countryCode);
    }
}


open confix.xml in your extantion
/app/code/local/YourFirm/ExtName/etc/config.xml

and add next code in global section:

and add next code in global section:
    <global>
        <models>
            <paypal>
             <rewrite>
              <config>YourFirm_ExtName_Model_Paypal_Config</config>
             </rewrite>
            </paypal>            
        </models>
    </global>

           
           
                  

how to make redirect in .htaccess for url with specific symbols


The problem was to redirect wrong CodeIgniter url with %C2%A0 symbols to another pahe in .htaccess

For example
http://mysite.com/some-page%C2%A0
to
http://mysite.com/other-page


Redirect   301    /some-page%C2%A0     /other-page   does not work

Here I had found some solution:

RewriteCond   %{THE_REQUEST}   ^[A-Z]+\ /[^%?\ ]*\%
RewriteRule    ^. http://www.example.com/     [R=301,L]

This rule redirects all matches with %.. symbols

So I had tried next:

RewriteCond   %{THE_REQUEST}   some-page[^%?\ ]*\%
RewriteRule   ^.    /other-page [R=301,L]

But after testing, it adds to now url an old url as parameters
As the results I had something like this:

http://mysite.com/index.php/other-page?/some-page/&... etc

So, after some googling I have found this

So I had changed

RewriteRule   ^.   /other-page [R=301,L]
to
RewriteRule   .?   /other-page$1? [R=301,L]


So, to make 301 redirect from broken url with % symbols need to do something like this:

RewriteCond   %{THE_REQUEST}   some-page[^%?\ ]*\%
RewriteRule   .?  /other-page$1? [R=301,L]

How to clean clean github repository

Step 1: remove all history

rm -rf .git

Step 2: reconstruct the Git repo with only the current content

git init
git add .
git commit -m "Initial commit"

Step 3: push to GitHub.

git remote add origin <github-uri>
git push -u --force origin master


https://stackoverflow.com/questions/9683279/make-the-current-commit-the-only-initial-commit-in-a-git-repository

Partial text Replace in MySQL UPDATE - example

How to make partial text Replace in MySQL UPDATE

example:

UPDATE `my_table` SET `field` = REPLACE(`field`, 'old_text', 'new_text') WHERE ... condition ...

How to catch global ajax response event (jquery or magento prototype)

//jQuery ajax
$(document).ajaxSuccess(function (event, request, settings) {
alert(22);
});

// magento prototype
Ajax.Responders.register({
   onComplete: function() {
alert('bbb');
   }
});

Magento 1: How to display customer custom attribute value for selected option in report grid

in Grid.php in method  _prepareColumns()

// get all available options for custom attribute

$options = array();

$attribute = Mage::getSingleton('eav/config')->getAttribute('customer', 'attribute_name');
if(!empty($attribute)){
$opts = $attribute->getFrontend()->getSelectOptions();

foreach($opts as $opt){
if(empty($opt['value'])) // skip empty option
continue;
$options[$opt['value']] = $opt['label'];
}
}

// now add column in grid
  
  $this->addColumn('attribute_name', array(
  'header'    => Mage::helper('customer')->__('Some Attribute Name'),
  'index'     => 'attribute_name',
  'type' => 'options',
  'options' => $options  // gere is array with all available options
  ));



P.S. to select attribute value from database, need to open collection.php model for your report and use
->addAttributeToSelect('attribute_name');

I can't provide excat example, because each report may use other classes and method. this was just an example of what function exists, you can find examples in magento to see how it works and where you can use it

How to set chmod for a folder and files separately in Linux

source:
http://stackoverflow.com/questions/3740152/how-to-set-chmod-for-a-folder-and-all-of-its-subfolders-and-files-in-linux-ubunt

I suspect what you really want to do is set the directories to 755 and either leave the files alone or set them to 644. For this, you can use the find command. For example:
To change all the directories to 755 (-rwxr-xr-x):
find /opt/lampp/htdocs -type d -exec chmod 755 {} \;
To change all the files to 644 (-rw-r--r--):

find /opt/lampp/htdocs -type f -exec chmod 644 {} \;

Magento 1: Unknown SSL protocol error in connection to test.sagepay.com:443

Problems with curl
try to add
curl_setopt($curlSession, CURLOPT_SSLVERSION, 3);
into
local/Ebizmarts/SagePaySuite/Model/Api/Payment.php
method requestPost

magento backup usin backup.sh with php system command ro ssh shell

1. copy backup.sh file (code below) in root folder of your magento system
2. if you have ssh access to your server, run command:
/bin/sh /path/to/your/magento/backup.sh
3. if you do not have ssh access, but php function 'system' works, create simple php script in root folder:
backup.php

<?php
echo '<pre>';

$command = "/bin/sh /path/to/your/magento/backup.sh";
$last_line = system($command, $retval);

echo '
</pre>
<hr />Last line of the output: ' . $last_line . '
<hr />Return value: ' . $retval;
?>

and run this script in browser.
If everything fine - you will see two .gz archives, one with code dump, second with db dump

NOTE! code dump does not consist media and var folder (to do not have large size)
and DB dump does not have some tables like logs and tables, that described as 'skipped' in backup.sh file (you can edit this list)

Any way, before installing db dump on your other server, you can create dump of db structure (just tables without data) install it, and then install db dump from backup.sh on existing clean db, this way you will have all tables.

to create dump of db structure, use command:
mysqldump --user=your_db_user --password=db_pass db_name --no-data |gzip > /path/to/your/magento/db_structure.gz

if you do not have ssh access, put this command into php file as described above.

NOTE, sometimes backup.sh can not create db dump, in this case you can create full db dump yourself, using command above, but without --no-data parameter

mysqldump --user=your_db_user --password=db_pass db_name |gzip > /path/to/your/magento/db.gz

4. to load database from dump, you should create database on your other server, extract db dump from gz archive and run command:
mysql --user=db_user --password=db_pass db_name < /path/to/dump/db_dump_file

Here is code of backup.sh:

#!/bin/bash

################################################################################
# FUNCTIONS
################################################################################

# 1. Check required system tools
_check_installed_tools() {
    local missed=""

    until [ -z "$1" ]; do
        type -t $1 >/dev/null 2>/dev/null
        if (( $? != 0 )); then
            missed="$missed $1"
        fi
        shift
    done

    echo $missed
}

# 2. Selftest for checking tools which will used
checkTools() {
    REQUIRED_UTILS='nice sed tar mysqldump head gzip getopt'
    MISSED_REQUIRED_TOOLS=`_check_installed_tools $REQUIRED_UTILS`
    if (( `echo $MISSED_REQUIRED_TOOLS | wc -w` > 0 ));
    then
        echo -e "Unable to create backup due to missing required bash tools: $MISSED_REQUIRED_TOOLS"
        exit 1
    fi
}

# 3. Create code dump function
createCodeDump() {
    # Content of file archive
    DISTR="
    app
    downloader
    errors
    includes
    js
    lib
    pkginfo
    shell
    skin
    .htaccess
    cron.php
    get.php
    index.php
    install.php
    mage
    *.patch
    *.sh"

    # Create code dump
    DISTRNAMES=
    for ARCHPART in $DISTR; do
        if [ -r "$MAGENTOROOT$ARCHPART" ]; then
            DISTRNAMES="$DISTRNAMES $MAGENTOROOT$ARCHPART"
        fi
    done
    if [ -n "$DISTRNAMES" ]; then
        echo nice -n 15 tar -czhf $CODEFILENAME $DISTRNAMES
        nice -n 15 tar -czhf $CODEFILENAME $DISTRNAMES
    fi
}

# 4. Create DB dump function
createDbDump() {
    # Set path of local.xml
    LOCALXMLPATH=${MAGENTOROOT}app/etc/local.xml

    # Get mysql credentials from local.xml
    getLocalValue() {
        PARAMVALUE=`sed -n "//,/<\/resources>/p" $LOCALXMLPATH | sed -n -e "s/.*<$PARAMNAME><!\[CDATA\[\(.*\)\]\]><\/$PARAMNAME>.*/\1/p" | head -n 1`
    }

    # Connection parameters
    DBHOST=
    DBUSER=
    DBNAME=
    DBPASSWORD=
    TBLPRF=

    # Include DB logs option
    SKIPLOGS=1

    # Ignored table names
    IGNOREDTABLES="
    core_cache
    core_cache_option
    core_cache_tag
    core_session
    log_customer
    log_quote
    log_summary
    log_summary_type
    log_url
    log_url_info
    log_visitor
    log_visitor_info
    log_visitor_online
    enterprise_logging_event
    enterprise_logging_event_changes
    index_event
    index_process_event
    report_event
    report_viewed_product_index
    dataflow_batch_export
    dataflow_batch_import"

    # Sanitize data
    SANITIZE=1

    # Sanitazed tables
    SANITIZEDTABLES="
    customer_entity
    customer_entity_varchar
    customer_address_entity
    customer_address_entity_varchar"

    # Get DB HOST from local.xml
    if [ -z "$DBHOST" ]; then
        PARAMNAME=host
        getLocalValue
        DBHOST=$PARAMVALUE
    fi

    # Get DB USER from local.xml
    if [ -z "$DBUSER" ]; then
        PARAMNAME=username
        getLocalValue
        DBUSER=$PARAMVALUE
    fi

    # Get DB PASSWORD from local.xml
    if [ -z "$DBPASSWORD" ]; then
        PARAMNAME=password
        getLocalValue
        DBPASSWORD=${PARAMVALUE//\"/\\\"}
    fi

    # Get DB NAME from local.xml
    if [ -z "$DBNAME" ]; then
        PARAMNAME=dbname
        getLocalValue
        DBNAME=$PARAMVALUE
    fi

    # Get DB TABLE PREFIX from local.xml
    if [ -z "$TBLPRF" ]; then
        PARAMNAME=table_prefix
        getLocalValue
        TBLPRF=$PARAMVALUE
    fi

    # Check DB credentials for existsing
    if [ -z "$DBHOST" -o -z "$DBUSER" -o -z "$DBNAME" ]; then
        echo "Skip DB dumping due lack of parameters host=$DBHOST; username=$DBUSER; dbname=$DBNAME;";
        exit 0
    fi

    # Set connection params
    if [ -n "$DBPASSWORD" ]; then
        CONNECTIONPARAMS=" -u$DBUSER -h$DBHOST -p\"$DBPASSWORD\" $DBNAME --force --triggers --single-transaction --opt --skip-lock-tables"
    else
        CONNECTIONPARAMS=" -u$DBUSER -h$DBHOST $DBNAME --force --triggers --single-transaction --opt --skip-lock-tables"
    fi

    # Create DB dump
    IGN_SCH=
    IGN_IGN=
    SAN_CMD=

    if [ -n "$SANITIZE" ] ; then

        for TABLENAME in $SANITIZEDTABLES; do
            SAN_CMD="$SAN_CMD $TBLPRF$TABLENAME"
            IGN_IGN="$IGN_IGN --ignore-table='$DBNAME'.'$TBLPRF$TABLENAME'"
        done
        PHP_CODE='
        while ($line=fgets(STDIN)) {
            if (preg_match("/(^INSERT INTO\s+\S+\s+VALUES\s+)\((.*)\);$/",$line,$matches)) {
                $row = str_getcsv($matches[2],",","\x27");
                foreach($row as $key=>$field) {
                    if ($field == "NULL") {
                        continue;
                    } elseif ( preg_match("/[A-Z]/i", $field)) {
                        $field = md5($field . rand());
                    }
                    $row[$key] = "\x27" . $field . "\x27";
                }
                echo $matches[1] . "(" . implode(",", $row) . ");\n";
                continue;
            }
            echo $line;
        }'
        SAN_CMD="nice -n 15 mysqldump $CONNECTIONPARAMS --skip-extended-insert $SAN_CMD | php -r '$PHP_CODE' ;"
    fi

    if [ -n "$SKIPLOGS" ] ; then
        for TABLENAME in $IGNOREDTABLES; do
            IGN_SCH="$IGN_SCH $TBLPRF$TABLENAME"
            IGN_IGN="$IGN_IGN --ignore-table='$DBNAME'.'$TBLPRF$TABLENAME'"
        done
        IGN_SCH="nice -n 15 mysqldump --no-data $CONNECTIONPARAMS $IGN_SCH ;"
    fi

    IGN_IGN="nice -n 15 mysqldump $CONNECTIONPARAMS $IGN_IGN"

    DBDUMPCMD="( $SAN_CMD $IGN_SCH $IGN_IGN) | sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/' | gzip > $DBFILENAME"

    echo ${DBDUMPCMD//"p\"$DBPASSWORD\""/p[******]}

    eval "$DBDUMPCMD"
}

################################################################################
# CODE
################################################################################

# Selftest
checkTools

# Magento folder
MAGENTOROOT=./

# Output path
OUTPUTPATH=$MAGENTOROOT

# Input parameters
MODE=
NAME=

OPTS=`getopt -o m:n:o: -l mode:,name:,outputpath: -- "$@"`

if [ $? != 0 ]
then
    exit 1
fi

eval set -- "$OPTS"

while true ; do
    case "$1" in
        -m|--mode) MODE=$2; shift 2;;
        -n|--name) NAME=$2; shift 2;;
        -o|--outputpath) OUTPUTPATH=$2; shift 2;;
        --) shift; break;;
    esac
done

if [ -n "$NAME" ]; then
    CODEFILENAME="$OUTPUTPATH$NAME.tar.gz"
    DBFILENAME="$OUTPUTPATH$NAME.sql.gz"
else
    # Get random file name - some secret link for downloading from magento instance :)
    MD5=`echo \`date\` $RANDOM | md5sum | cut -d ' ' -f 1`
    DATETIME=`date -u +"%Y%m%d%H%M"`
    CODEFILENAME="$OUTPUTPATH$MD5.$DATETIME.tar.gz"
    DBFILENAME="$OUTPUTPATH$MD5.$DATETIME.sql.gz"
fi

if [ -n "$MODE" ]; then
    case $MODE in
        db) createDbDump; exit 0;;
        code) createCodeDump; exit 0;;
        check) exit 0;;
        *) echo Invalid mode; exit 1;;
    esac
fi

createCodeDump
createDbDump

exit 0

How to remove .svn folders in windows

I made dump of all files from server to localhost and I had found that all folders have .svn subfolders.
After googling I have found how to remove them.
Open command prompt, go to your folder and run this command:
for /r %R in (.svn) do if exist %R (rd /s /q "%R")

Source:
http://jeremyhixon.com/remove-all-svn-folders-recursively/

how to install magento community channel on localhost

I was trying to install module in magento community manager on localhost magento system, but it shows me an error:

connect error: the 'community' channel is not installed. please use the mage shell script to install the 'community' channel.

after some searching I found this:
https://gist.github.com/americkson/1373556

just open command line, go to your magento root folder and type command:

mage channel-add http://connect20.magentocommerce.com/community


jQuery .focus() and .blur() not working in Chrome or Safari for checkbox and radio


jquery focusout does not works in chrome and safari for checkbox and radio elements.

example:
<input type='checkbox' name='ch1' id='ch1' />

<script type='text/javascript'>
$(document).ready(function(){
$(document).on('focusout','#ch1', function(){
alert('Focus Out');
});

});
</script>

To fix this, try to setup focus for checkbox when click on it

<script type='text/javascript'>
$(document).ready(function(){

$(document).on('click','#ch1', function(){ // set focus for element on click for chrome and safari
$(this).trigger("focus");
});

$(document).on('focusout','#ch1', function(){
alert('Focus Out');
});

});
</script>

Peer certificate cannot be authenticated with known CA certificates

to fix it on localhost just use

$oauth->disableSSLChecks();

how to install PECL oAuth on xampp on windows 7

My situation was:
Win 7 x64
xampp 1.7.2 with php 5.2.9

I was trying to install php_oauth.dll into /xampp/php/ext/
But it failed.

After googling I had found an answer:
First of all need to have php 5.3 (I had install xampp 1.7.7)
And need to upload php_oauth.dll for x86 platform, because xampp is configured for x86 - not x64
And include new dll extansion in php.ini
reload apache

Sorce from here

How to add CSS/Javascript version number in Magento 1


app/code/core(or local)/Mage/Page/Block/Html/Head.php

Change this:
$html .= $this->_prepareStaticAndSkinElements('
' . "\n",
    empty($items['js_css']) ? array() : $items['js_css'],
    empty($items['skin_css']) ? array() : $items['skin_css'],
    $shouldMergeCss ? array(Mage::getDesign(), 'getMergedCssUrl') : null
);

To this:
$html .= $this->_prepareStaticAndSkinElements('
' . "\n",
    empty($items['js_css']) ? array() : $items['js_css'],
    empty($items['skin_css']) ? array() : $items['skin_css'],
    $shouldMergeCss ? array(Mage::getDesign(), 'getMergedCssUrl') : null
);

add external javascript in magento xml

An exmaple how to add external js script on magento pages in xml file

In cms.xml file for your template
place code


<default>
<reference name="head">
<block type="core/text" name="script.name">
<action method="setText"><text><![CDATA[<script src="script_path"></script>]]></text></action>
</block>
</reference>
</default>

Restore xampp database from backup

steps: stop mysql xampp 1 - create some backup folder "data_1"  2 - from your current xampp/mysql/data folder move core folders an...