home | contact us
» Posts tagged "tip"

Items Tagged: tip


Like most frameworks and software packages PrestaShop has it’s own way of handling session variables.

PrestaShop uses the Cookie class to manage session variables. While this isn’t strictly a singleton you can get a pre initialised instance using Context::getContected-cookie if the FrontController-init() method has been called already.

The Cookie class uses the magic __get __isset __set __unset magic methods to handle parameters. Parameters set in the cookie are actually given to the client in an encrypted blob. This is good because it means sessions are not really stored on the server. This does mean, however, that only scalar values can be stored in the session. To store non-scalar values you can usually get away with serialising them but there are some restrictions even then. If you do struggle to store serialised values you can base64 encode them to fix any remaining issues.

Once you have set your variables you need to call the write method to save your variables to the cookie.


 

PrestaShop is a fully featured shopping platform and offers much of the functionality that other eCommerce shopping platforms do. Compared to, for example, Magento PrestaShop is significantly simpler to develop for.

Here is the run down of the key aspects that any one building a web site on PrestaShop should be aware of.

Modules

PrestaShop is based around a modular design which is quite similar to Joomlas module system.
A modules presence and position on the front end is defined by hooking the module into a particular section on the frontend. There are loads of hooks that can be used. Most modules will add them selves to the hook they think is most appropriate on install. The ordering of modules also defines the order they appear in a given hook.
A key point of managing modules that can easily be over looked is that you can grab and drag modules in a given hook by clicking and holding the position change buttons.

Themes

Off the shelf themes are usually not simply a new set of templates and CSS but also modules as well. Quite allot of themes are built around specific modules being in specific hooks some times in a specific order.

Creating your own module

Defining your own module is really straight forward:
Create a folder in modules called my_module.
Create a file called my_module.php, in this file create a class called My_module which extends Module.
Create a config.xml with the following template:


my_module
My Module
1
A test module, it does nothing
My self
front_office_features
0
1

Done, the module will appear in the module list but do nothing. You can look at the base module class to see all the function available that get called by PrestaShop are different times to do what you need to do.


 

Here is a little bash script we knocked together to track down some malicious activity on a clients server.

Using a bit of awk etc to parse the log files we could quickly track down an IP address that was overloading the server and then take steps to block that person.

Here is the script:

#!/bin/bash

###### SETUP ############
LOG_FOLDER=/var/www/vhosts/domain.co.uk/statistics/logs
ACCESS_LOG=$LOG_FOLDER/access_log

HOW_MANY_ROWS=20000



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


function title() {
    echo "
---------------------------------
$@
---------------------------------
"
}

function urls_by_ip() {
    local IP=$1
    tail -5000 $ACCESS_LOG | awk -v ip=$IP ' $1 ~ ip {freq[$7]++} END {for (x in freq) {print freq[x], x}}' | sort -rn | head -20
}


function ip_addresses_by_user_agent(){
    local USERAGENT_STRING="$1"
    local TOP_20_IPS=&quot;<code>tail  -$HOW_MANY_ROWS $ACCESS_LOG | grep &quot;${USERAGENT_STRING}&quot;  | awk '{freq[$1]++} END {for (x in freq) {print freq[x], x}}' | sort -rn | head -20</code>&quot;
    echo &quot;$TOP_20_IPS&quot;
}

####### RUN REPORTS #############


title &quot;top 20 URLs&quot;
TOP_20_URLS=&quot;<code>tail -$HOW_MANY_ROWS $ACCESS_LOG | awk '{freq[$7]++} END {for (x in freq) {print freq[x], x}}' | sort -rn | head -20</code>&quot;
echo &quot;$TOP_20_URLS&quot;


title &quot;top 20 URLS excluding POST data&quot;
TOP_20_URLS_WITHOUT_POST=&quot;<code>tail  -$HOW_MANY_ROWS $ACCESS_LOG | awk -F&quot;[ ?]&quot; '{freq[$7]++} END {for (x in freq) {print freq[x], x}}' | sort -rn | head -20</code>&quot;
echo &quot;$TOP_20_URLS_WITHOUT_POST&quot;


title &quot;top 20 IPs&quot;
TOP_20_IPS=&quot;<code>tail  -$HOW_MANY_ROWS $ACCESS_LOG | awk '{freq[$1]++} END {for (x in freq) {print freq[x], x}}' | sort -rn | head -20</code>&quot;
echo &quot;$TOP_20_IPS&quot;

title &quot;top 20 user agents&quot;
TOP_20_USER_AGENTS=&quot;<code>tail  -$HOW_MANY_ROWS $ACCESS_LOG | cut -d\  -f12- | sort | uniq -c | sort -rn | head -20</code>&quot;
echo &quot;$TOP_20_USER_AGENTS&quot;


title &quot;IP Addresses for Top 3 User Agents&quot;

for ((I=1; I&lt;=3; I++))
do
    UA=&quot;<code>echo &quot;$TOP_20_USER_AGENTS&quot; | head -n $I | tail -n 1 | awk '{$1=&quot;&quot;; print $0}'</code>&quot;
    echo &quot;$UA&quot;
    echo &quot;~~~~~~~~~~~~~~~~~~&quot;
    ip_addresses_by_user_agent &quot;$UA&quot;
    echo &quot;
    &quot;
done


 

The function below is one that we have used a few times to allow certain “admin only” assets to be accessed or visible on the front end of a website.

The theory is that the htaccess file in the admin folder will be kept up to date and can therefore be used as the authoritative list of IP addresses that are allowed to access admin assets.

This function is simple enough and should be useful anywhere that you use htaccess to protect a certain folder and would like to implement the same white list rules in other places without having to maintain a duplicate list of authorised IP addresses.

The function also uses static variables – a lesser known bit of PHP functionality which can be a nice easy performance optimisation when working with procedural PHP code. If a function will be called many times and will always return the same result in a single request, you can actually cache that result to a static variable and serve that on any subsequent requests.

function isAllowedIp() {
    static $pass = null;
    if ($pass !== null) {
        return $pass;
    }
    $pass=false;
    $customer_ip = $_SERVER['REMOTE_ADDR'];    
    $htaccess = file_get_contents('admin/.htaccess');
    preg_match_all('%allow from ([0-9.]+)%', $htaccess, $matches);
    foreach ($matches[1] as $ip) {
        if ($ip == $customer_ip) {
            $pass = true; //this is stored statically for perfomance reasons
            return true;
        }
    }
    return false;
}

 

If you have a bash script that you want to make sure there is only ever one instance of, for example something triggered by cron that might not have finished the next time cron tries to trigger it then you might like this little snippet:

This is built for running Magento shell scripts (if you don’t know about these, check them out) that are run on cron.

Also note the logging that keeps log files

Note the use of a character class in grep means it wont match itself – nice eh :)

#!/bin/bash
HOUR=<code>date +'%H:%M'</code>
RUNNING=<code>ps waux | grep &quot;longrunner[.]php&quot;</code>
if [ &quot;&quot; == &quot;$RUNNING&quot; ]
then
    echo &quot;Its not running, we can now run it&quot;
    php -f /home/my/public_html/shell/longrunner.php -- import &gt; /home/my/public_html/var/log/mylog.txt 2&gt;&amp;1
    cp -f  /home/my/public_html/var/log/my.txt /home/my/public_html/var/log/${HOUR}.my.txt
    echo &quot;COMPLETED&quot;
else
    echo &quot;It is running, aborting running this time&quot;
fi

 

If you have a page that keeps getting longer because new items appear on it at the bottom and what’s at the bottom of the page is most important it can be a paint to have to keep scrolling done to see it.

You can make it auto scroll continuously with JQuery but that’s potentially really awkward if at any point you need to scroll up (it basically means you can’t).

The best solution is to make the page auto scroll in a sticky fashion. So when the page is already scrolled all the way to the bottom it auto scrolls, when it’s not at the bottom it does not scroll.

This can be achieved quite easily with the following code:

var num = (lastDocumentHeight - $(window).height()) - $(document).scrollTop();
if(num == 0) {
	$("html, body").animate({ scrollTop: $(document).height() }, "slow");
}
lastDocumentHeight = $(document).height();

In this example lastDocumentHeight is a global. It works by determining if the current position is the same as it was previously and this position equates to being at the bottom of the page then scroll. This needs to run after your page length has increased.


 

I have recently been running some MySql scripts that wrote to a file.

These worked fine locally, but as soon as I deployed them I started to get the error above.

After much looking around I came across this solution.

When I was developing locally, I was connecting with a user that had global privileges. When I was running the code on the server I was connecting with a user that only had privileges for the database I was using.

The issue is that then FILE privilege is a Global setting, so the user did not have access to it, hence the access denied message.

Grant FILE privileges and you can connect as expected


 

JSON is a well structure interoperable way of passing data between systems. It’s a good way of passing large amount of data into a web page for JavaScript to process and between system on the internet regardless of there architecture or programming language.

JSON is one of the hardest data structure to read directly as a human in it’s RAW format compared to other formal grammars such as XML, YAML or ini.

Fortunately there is an easy trick that you can do with Chrome, Firefox with Firebug and even Opera and IE9!

Take the JSON you have, wrap it in “eval()” the same as you would if you where writing a web page (because it is just JavaScript after all) run it and every modern browser this was tested with should allow you to inspect the resulting data structure.

Example JSON:

{"glossary":{"title":"example glossary","GlossDiv":{"title":"S","GlossList":{"GlossEntry":{"ID":"SGML","SortAs":"SGML","GlossTerm":"Standard Generalized Markup Language","Acronym":"SGML","Abbrev":"ISO 8879:1986","GlossDef":{"para":"A meta-markup language, used to create markup languages such as DocBook.","GlossSeeAlso":["GML","XML"]},"GlossSee":"markup"}}}}}

Firefox with Firebug:
Chrome:
Opera:
Internet Explorer 9:
Note: To see this structure you need to click the “Add watcher” link displayed upon running the code.

 

Using sub modules in git is incredibly useful and allows for easier and more flexible working when working on component based large projects. In a nut shell the use of sub modules (as the name suggests) allows you to include a git repository as a part of another git repository in order to allow you to use the sub modules code without having to duplicate it’s content in to your repository.

Important commands you will need when working with sub modules

git submodule init
This tells git to read the modules file and make your local repository aware of any sub modules. When you checkout a repository that uses sub modules nothing is done with them until you do this. You will need to run this at least after cloning a repo but possibly after pulling if new sub modules are added.
git submodule update
This makes git to update the sub modules to match what the config says it should be. You will probably need this after cloning a repository for the first time or when you pull changes from a remote as some one may have updated the position of the sub module. When running this you should make sure that you don’t have any uncommitted changes in any submodules other wise you will lose them and find it hard to retrieve them.
git submodule add absolute_path/url_to_repo location_of_repo_in_project
This command tells git to add the repository at the specified URL/path to the repository. Git will add it to the modules file. After adding it you need to commit. The path to the repo either needs to be the absolute path if you are working locally or the URL that is accessible via the Internet/LAN depending on your environment. It has to be like this so that it doesn’t matter where the repository that will be cloning the sub module is located
git help submodule
Gives you the man page for the submodule command, an invaluable resource

Key facts when working with sub modules

Working in sub modules

If you want to modify contents of the sub module, that is make changes and commit them back to the sub modules repository, you can work just as normal. The only thing to watch out off is that when you first do git submodule init; git submodule update; it will checkout what ever commit was specified. This means that the sub module might not be on an actual branch but instead only have a particular commit checkout. Make sure to checkout the relevant branch on the sub module before commencing work.

Updating a sub modules position on a remote repo

When git submodule update runs it checkouts out the specified commit by the main repository. If there is no commit specified it will checkout the default branch (usually master). If you want it to checkout a specific branch this cannot be done in a literal sense. Instead what you have to do is checkout the top commit of that branch, then commit the changes to the sub module in main repository. This will ensure that the sub module is now at that position when git submodule update is run. You will have to do this every time you want to update it’s position.


 

If you have a load of terminals open you might find it handy to be able to rename the window title on the fly.

You can do this easily by copying this code into your ~/.bashrc file (or even pasting it into your terminal if you like)

function nameTerminal() {
    [ "${TERM:0:5}" = "xterm" ]   && local ansiNrTab=0
    [ "$TERM"       = "rxvt" ]    && local ansiNrTab=61
    [ "$TERM"       = "konsole" ] && local ansiNrTab=30 ansiNrWindow=0
        # Change tab title
    [ $ansiNrTab ] && echo -n $'\e'"]$ansiNrTab;$1"$'\a'
        # If terminal support separate window title, change window title as well
    [ $ansiNrWindow -a "$2" ] && echo -n $'\e'"]$ansiNrWindow;$2"$'\a'
}

If you have pasted this into your ~/.bashrc file you need to launch a new terminal or run:

source ~/.bashrc

From this point the function is now ready to use and you can run:

nameTerminal "My Custom Terminal Window Title"

Now you can easily choose the terminal you want based upon the window title.

Of course this then opens the door to automatically changing the window title based on all kinds of events that you might like, isn’t bash scripting fun!


 
rss icon