All posts by mauro mascia

Create a POT file for themes and plugins

~$ cd /var/www/your-site-folder/wp-content/
~$ svn export makepot
~$ cd plugins/your-plugin-folder/languages
~$ php /var/www/your-site-folder/wp-content/makepot/makepot.php wp-plugin ../

With the last option you need to specify if you are creating a POT for a plugin or for a theme (for themes, use “wp-theme” instead of “wp-plugin”) and the last command line parameter is the plugin/theme folder (in this case ../ is pointing to /var/www/your-site-folder/wp-content/plugins/your-plugin-folder).
The resulting POT file will be saved under the “languages” folder (which of course must been already created).

GIT – merge selective files

To selectively merge files from one branch into another branch, run

git merge --no-ff --no-commit branchX

where: branchX is the branch you want to merge from into the current branch

The --no-commit option will stage the files that have been merged by Git without actually committing them. This will give you the opportunity to modify the merged files however you want to and then commit them yourself.

Depending on how you want to merge files, there are four cases:

1) You want a true merge. In this case, you accept the merged files the way Git merged them automatically and then commit them.

2) There are some files you don’t want to merge. For example, you want to retain the version in the current branch and ignore the version in the branch you are merging from.

To select the version in the current branch, run:

git checkout HEAD file1

This will retrieve the version of file1 in the current branch and overwrite the file automerged by Git.

3) If you want the version in branchX (and not a true merge), run:

git checkout branchX file1

This will retrieve the version of file1 in branchX and overwrite the file auto-merged by Git.

4) The last case is if you want to select only specific merges in file1. In this case, you can edit the modified file1 directly, update it to whatever you’d want the version of file1 to become, and then commit.

If Git cannot merge a file automatically, it will report it as “unmerged” file and produce a copy where you will need to resolve the conflicts manually.

To explain further with an example, let’s say you want to merge branchX into the current branch:

git merge --no-ff --no-commit branchX

You then run the git status command to view the status of modified files.

For example:

git status

# On branch master
# Changes to be committed:
#       modified:   file1
#       modified:   file2
#       modified:   file3
# Unmerged paths:
#   (use "git add/rm <file>..." as appropriate to mark resolution)
#       both modified:      file4

Where file1, file2, and file3 are the files git have successfully auto-merged.

What this means is that changes in the master and branchX for all those three files have been combined together without any conflicts.

You can inspect how the merge was done by running the git diff --cached file. For example:

git diff --cached file1
git diff --cached file2
git diff --cached file3

If you find some merge undesirable, you can edit the file directly, save, and then commit.

If you don’t want to merge file1 and want to retain the version in the current branch, run:

git checkout HEAD file1

If you don’t want to merge file2 and only want the version in branchX, run

git checkout branchX file2

If you want file3 to be merged automatically, don’t do anything. Git has already merged it at this point.

file4 above is a failed merge by Git. This means there are changes in both branches that occur on the same line. This is where you will need to resolve the conflicts manually. You can discard the merged done by editing the file directly or running the checkout command for the version in the branch you want file4 to become.

Finally, don’t forget to commit.

git commit



WooCommerce XPay Cartasì

After almost two years since its first release WooCommerce XPay is a payment gateway for e-commerce based on WordPress and WooCommerce.

Compatible with the offer of CartaSì and QuiPago, easy to install and configure, and constantly updated with direct technical support included.

Throughout the month of January will be sold at a discounted price.

Buy it now in my shop!

WooCommerce XPay CartaSì, beware of imitations! ;)

WooCommerce: Manually create orders

The problem

I’m the manager of an e-commerce based on WooCommerce and sometimes I need to manually create orders for my clients.
I also wish that my client receives an email with the link to pay that order.


– WooCommerce, preferably updated to one of the latest versions.

The solution

  • Create a WordPress user, specifying the role “Customer” and save.
  • Change the newly created user, because in the meantime, Billing fields – added by WooCommerce – will be appeared. Complete these fields, and in particular the e-mail address (without which no e-mails will be sent).
  • Create a product, if not present.
  • Create an order:
    • Associate the user to the order
    • Load Billing Details
    • Add the product (or products)
    • Be sure that the status of the order is “pending”
    • Calculate totals using the appropriate button (without this, the total would be zero and the payment gateways would not appear on the payment page)
    • Save
  • From the menu “Actions” select “Customer Invoice” and click on the button to the side: this will send the email to the customer.
  • WordPress Tips: extend the Text Widget allowing shortcodes and custom classes

    What follows is a small tip to create an extension of the base “text” widget of WordPress, to allow the execution of shortcodes and to allow to specify one or more classes (space separated) per-widget.
    In this way it will be really simple identify the widget in our CSS.

    The class is really simple to manage and extend (if you know what this class does: if not, you can read more at

    To give it a try, just replace “Mytheme” and “mytheme” with your theme (or child theme) name and put the code into the function.php file.
    You can alternatively create a simple plugin, but this is left as an exercise for the reader :P

     * Advanced Text widget class
    class Mytheme_Widget_Text extends WP_Widget {
    	function __construct() {
    			__('Mytheme: Arbitrary Text/HTML and shortcodes.'),
    			array( 'description' => __( 'Output an arbitrary text/HTML and/or shortcodes.', 'mytheme' ), ) 
    	function widget( $args, $instance ) {
    		$title = apply_filters( 'mytheme_widget_text', empty( $instance['title'] ) ? '' : $instance['title'], $instance, $this->id_base );
    		$text = apply_filters( 'mytheme_widget_text', empty( $instance['text'] ) ? '' : $instance['text'], $instance );
    		$class = apply_filters( 'mytheme_widget_text', empty( $instance['class'] ) ? '' : $instance['class'], $instance );
    		echo $before_widget;
    		if ( !empty( $title ) ) { echo $before_title . $title . $after_title; } ?>
    			<div class="mytheme-textwidget <?php echo $class; ?>"><?php echo !empty( $instance['filter'] ) ? wpautop( $text ) : $text; ?></div>
    		echo $after_widget;
    	function update( $new_instance, $old_instance ) {
    		$instance = $old_instance;
    		$instance['title'] = strip_tags($new_instance['title']);
    		$instance['class'] = strip_tags($new_instance['class']);
    		if ( current_user_can('unfiltered_html') )
    			$instance['text'] =  $new_instance['text'];
    			$instance['text'] = stripslashes( wp_filter_post_kses( addslashes($new_instance['text']) ) ); // wp_filter_post_kses() expects slashed
    		$instance['filter'] = isset($new_instance['filter']);
    		return $instance;
    	function form( $instance ) {
    		$instance = wp_parse_args( (array) $instance, array(
    				'title' => '',
    				'text' => '',
    				'class' => ''
    		$title = strip_tags($instance['title']);
    		$text = esc_textarea($instance['text']);
    		$class = esc_textarea($instance['class']);
    		<p><label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:'); ?></label>
    		<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo esc_attr($title); ?>" /></p>
    		<p><label for="<?php echo $this->get_field_id('class'); ?>"><?php _e('Class:'); ?></label>
    		<input class="widefat" id="<?php echo $this->get_field_id('class'); ?>" name="<?php echo $this->get_field_name('class'); ?>" type="text" value="<?php echo esc_attr($class); ?>" /></p>
    		<textarea class="widefat" rows="16" cols="20" id="<?php echo $this->get_field_id('text'); ?>" name="<?php echo $this->get_field_name('text'); ?>">
    		    <?php echo $text; ?>
    		<p><input id="<?php echo $this->get_field_id('filter'); ?>" name="<?php echo $this->get_field_name('filter'); ?>" type="checkbox" <?php checked(isset($instance['filter']) ? $instance['filter'] : 0); ?> />&nbsp;<label for="<?php echo $this->get_field_id('filter'); ?>"><?php _e('Automatically add paragraphs'); ?></label></p>
    // Register and load the widget
    function mytheme_load_widget() {
    	register_widget( 'mytheme_widget_text' );
    	// Allow to execute shortcodes on mytheme_widget_text
    	add_filter('mytheme_widget_text', 'do_shortcode');
    add_action( 'widgets_init', 'mytheme_load_widget' );

    El Born NYC

    El Born is a restaurant and bar bringing the Barcelona experience to Brooklyn.

    Made with CSS and Javascript over the Expression Engine CMS, is a simple but well finished web site, where we have placed a great attention to details and to the compatibility of browsers and mobile devices.

    Extending Drupal Search on other User fields

    The default Drupal “search by user” is performed by the hook search_execute implemented by the user module (here is the full code), which searches on the “name” field (if you can administer users it searches also on the email).
    But what about searching on other fields?

    As a user is an entity on Drupal 7, it can be extended with other fields, such as the first name, the last name, a biography, a city, and so on.
    Let’s say we have defined these fields:

    • field_first_name
    • field_last_name
    • field_biography

    and we want that searches can be performed also on these fields.
    To do so, when using the standard Drupal search and therefore without creating indexes with the Search APIs or with Apache Solr, we can implement two hooks in our module:

     * Implements hook_search_info().
     * @see hook_search_info()
    function YOUR_MODULE_search_info() {
      return array(
        'title' => 'People',
     * Implements hook_search_execute().
     * @see hook_search_execute()
    function YOUR_MODULE_search_execute($keys = NULL, $conditions = NULL) {
       $find = array();
      // Replace wildcards with MySQL/PostgreSQL wildcards.
      $keys = preg_replace('!\*+!', '%', $keys);
      $query = db_select('users', 'u')->extend('PagerDefault');
      $query->fields('u', array('uid'));
      // Additional tables
      $query->join('field_data_field_first_name', 'fn', 'fn.entity_id = u.uid');
      $query->join('field_data_field_last_name', 'ln', 'ln.entity_id = u.uid');
      $query->join('field_data_field_biography', 'sb', 'sb.entity_id = u.uid');
      $query->fields('u', array('mail'));
          ->condition('', '%' . db_like($keys) . '%', 'LIKE')
          ->condition('u.mail', '%' . db_like($keys) . '%', 'LIKE')
          // Additional fields
          ->condition('field_first_name_value', '%' . db_like($keys) . '%', 'LIKE')
          ->condition('field_last_name_value', '%' . db_like($keys) . '%', 'LIKE')
          ->condition('field_biography_value', '%' . db_like($keys) . '%', 'LIKE')
      $uids = $query->limit(15)->execute()->fetchCol();
      $accounts = user_load_multiple($uids);
      $results = array();
      foreach ($accounts as $account) {
        $result = array(
          'title' => format_username($account),
          'link' => url('user/' . $account->uid, array('absolute' => TRUE)),
        if (user_access('administer users')) {
          $result['title'] .= ' (' . $account->mail . ')';
        $results[] = $result;
      return $results;

    The first hook adds an additional ‘People’ (or name it as you like) tab to the Drupal search page which can be enabled in admin/config/search/settings under “Active search modules” (you should uncheck the default “User” tab).
    The second hook joins the field’s tables in the query and the value of these fields in the conditions of the query.

    In this way a searched key can be found also inside the additional fields of the user.

    Limiting concurrent connections per IP

    After playing around with ab (apache benchmark) in a test server, I’ve found particulary annoying that with this simple tool I could break this test server.

    The problem is that a server have a limitate number of resources (CPU/RAM) and for that reason is not possible to accept too many concurrent requests from the same source. This is the base of DoS attacks: saturating the target machine with many requests, so much so that it cannot respond (or it can do it realy slowly) to legitimate traffic.

    What ab does is to open a new TCP connection every time he makes a request and each of them is a new thread of apache which consumes CPU and RAM; after an X number of concurrent connections, the server becomes overloaded with a consequent impossibility to take back it’s control (it needs a forced reboot).

    To mitigate this annoying situations there are many tutorials on the net but many of them are simply old, bad documented or simply does not do the work they should do.

    Many pages report iptable rules like that:

    iptables -A INPUT -p tcp --syn --dport 80 -m connlimit --connlimit-above 15 --connlimit-mask 32 -j REJECT --reject-with tcp-reset

    but this rule simply won’t work for this case because it’s about packets, not connections.

    Other pages which talk about apache’s modules (like mod_security) are really far to be really useful.

    At the end, what worked for me is the great article written by Alessio Rocchi on his Mitigate DDoS with iptables and ipt_recent. He describe line by line what happens and after a little bit of trial and error, I’ve also found what works for my test case:

    iptables -F
    iptables -X
    iptables -N ATTACKED
    iptables -N ATTK_CHECK
    iptables -N SYN_FLOOD
    iptables -A INPUT -p tcp ! --syn -m state --state NEW -j DROP
    iptables -A INPUT -f -j DROP
    iptables -A INPUT -p tcp --tcp-flags ALL ALL -j DROP
    iptables -A INPUT -p tcp --tcp-flags ALL NONE -j DROP
    iptables -A INPUT -p tcp --syn -j SYN_FLOOD
    iptables -A SYN_FLOOD -p tcp --syn -m hashlimit --hashlimit 2/sec --hashlimit-burst 3 --hashlimit-htable-expire 3600 --hashlimit-mode srcip  --hashlimit-name synflood -j ACCEPT
    iptables -A SYN_FLOOD -j ATTK_CHECK
    iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
    iptables -A INPUT -p tcp -m tcp --dport 80 -m recent --update --seconds 1800 --name BANNED --rsource -j DROP
    iptables -A INPUT -p tcp -m tcp --dport 80 -m state --state NEW -j ATTK_CHECK
    iptables -A ATTACKED -m limit --limit 5/min -j LOG --log-prefix "IPTABLES (Rule ATTACKED): " --log-level 7
    iptables -A ATTACKED -m recent --set --name BANNED --rsource -j DROP
    iptables -A ATTK_CHECK -m recent --set --name ATTK
    iptables -A ATTK_CHECK -m recent --update --seconds 120 --hitcount 20 --name ATTK --rsource -j ATTACKED
    iptables -A ATTK_CHECK -m recent --update --seconds 60 --hitcount 6 --name ATTK --rsource -j ATTACKED
    iptables -A ATTK_CHECK -j ACCEPT

    The really important rule is where the hashlimit sets the max number of concurrent connections in each second for each ip (thanks to –hashlimit-mode srcip).
    I’ve put it at 2/sec because of the small test server I was using but I think you can adjust it for your needs ;)

    Ubuntu Edge – Uno smartphone che è un PC ma anche un progetto ambizioso e rivoluzionario


    E’ in corso una piccola rivoluzione tecnologica, sappiatelo! La notizia rimbalza tra i social network e i blog e non posso astenermi dal dare il mio contributo alla divulgazione di questo progetto tanto ambizioso quanto promettente.

    Nel primo paragrafo “What is Ubuntu Edge” presente nella pagina di indiegogo si può leggere:

    In the car industry, Formula 1 provides a commercial testbed for cutting-edge technologies. The Ubuntu Edge project aims to do the same for the mobile phone industry — to provide a low-volume, high-technology platform, crowdfunded by enthusiasts and mobile computing professionals. A pioneering project that accelerates the adoption of new technologies and drives them down into the mainstream.

    Di cosa stiamo parlando esattamente? Il succo del discorso sarebbe “uno smartphone” ma fin qui nessuno farebbe tanto caso alla cosa, abituati come siamo (chi più, chi meno) a vederli in svariate forme e dimensioni, potenza e colori, in casa Samsung, Apple, Nokia, ecc (non me ne vogliano le altre innumerevoli aziende!). Se aggiungiamo che collegandolo a un’apposita dock trasforma il monitor di casa in un PC vero e proprio, cominciamo a rizzare le orecchie!


    Ma la reale differenza fra uno smartphone prodotto dalle suddette multinazionali e il gioiellino oggetto di questo articolo è come si arriva ad averlo: il team di Ubuntu/Canonical ha scelto una strada differente per “commercializzare” il suo prodotto, una strada che parla direttamente con il mercato attraverso il web. Non è stato inventato nulla, questo è bene precisarlo, ma nell’utilizzare il crowdfunding, una soluzione ormai consolidata da anni, si è scelto di sfruttarlo fino in fondo, proponendo una soglia mai vista prima di 32 milioni di dollari cioè circa 25 milioni di euro!

    Questa cifra potrebbe sembrare risibile per società come Apple che hanno un fatturato annuo di circa 150 miliardi di dollari e un utile netto di circa 40, ma come tutti sanno, Ubuntu (o meglio la società Canonical che sta dietro), non naviga nell’oro (fonti come Wiki segnalano 30 milioni di dollari nel 2009, ma non riesco a trovare una fonte più aggiornata) per via della sua natura.
    Volendo proseguire il confronto parliamo di 70 mila dipendenti di Apple contro i 500 di Canonical. Insomma, stiamo parlando di due realtà diverse, su questo nessuno potrà sollevare alcun dubbio.

    Non mi dilungherò nell’elogio delle qualità tecniche di questo smartphone:

    • Ubuntu e Android in dual boot
    • CPU da 2.4GHz quad-core
    • 4GB RAM
    • 128GB storage
    • Display da 4.5 inch 1280×720 HD (in zaffiro)
    • Corpo in metallo

    Insomma, paragonandolo alle auto di Formula 1 ci intendiamo.

    Il progetto ha 30 giorni di tempo per raggiungere l’altissima cifra fissata e procedere all’eventuale produzione:

    If we don’t reach our target then we will focus only on commercially available handsets and there will not be an Ubuntu Edge.

    Il primo giorno è passato con un “incasso” di circa 100 mila dollari all’ora e continuando di questo passo potrebbero raggiungere l’ambizioso obiettivo in soli 15 giorni!

    Update 23/08/2013

    Per molti il sogno finisce qui (almeno per ora) ma dopo 30 giorni “folli” non si può parlare di trionfo, ma neppure di sconfitta!
    Rimangono sicuramente alcuni dati di fatto:

    • Il progetto di crowdfunding Ubuntu Edge ha battuto ogni record, totalizzando quasi 13 milioni di dollari ($12809906) in 30 giorni, il 40% di quanto preventivato
    • Non avendo raggiunto la cifra prestabilita, tutti i soldi versati saranno rimborsati nel giro di 5 giorni
    • Quasi 20 mila persone hanno creduto in questo progetto, pagando per un prodotto che avrebbero potuto avere solo dopo quasi un anno (Maggio 2014)
    • Diverse società hanno messo gli occhi sul progetto Ubuntu Edge e sul sistema Ubuntu per smartphone

    Infine, non si esclude un secondo tentativo: nel post di fine campagna Mark Shuttleworth dice:

    […] And who knows, perhaps one day we’ll take everything we’ve learned from this campaign — achievements and mistakes — and try it all over again.

    Beh, non ci resta che augurare buona fortuna al futuro di Ubuntu!