Using SocialShare with WordPress to create custom social networks buttons

2013/02/14: Take care of the smarter caching system introduced in version 0.2.0.

Here is how to use the SocialShare PHP library to create custom Facebook, Twitter and Google Plus share buttons including the number of share.

The SocialShare library

Installing the library

The first step is to install SocialShare through the awesome Composer dependency manager. If you have not installed composer already, grab it!

In your custom WordPress themes directory (something like wp-content/themes/<mytheme-name>/), run the following command to get a copy of the library:

php /path/to/composer.phar require dunglas/php-socialshare:~0.1

Two Composer related files are created: composer.json and composer.lock. They contain the list dependencies of our project (only SocialShare for now). The code of SocialShare and Doctrine Cache (a dependecy of SocialShare) have been downloaded in the vendor/ directory.

Initializing SocialShare and creating helper functions

Put the following code in your theme’s functions.php file:

// Social share initialization

use Doctrine\Common\Cache\PhpFileCache;
use SocialShare\SocialShare;
use SocialShare\Provider\Facebook;
use SocialShare\Provider\Twitter;
use SocialShare\Provider\Google;

require 'vendor/autoload.php';

$cache = new PhpFileCache('/a/cache/directory'); // Use sys_get_temp_dir() to get the system temporary directory, but be aware of the security risk if your website is hosted on a shared server
$socialShare = new SocialShare($cache);

$socialShare->registerProvider(new Facebook());
$socialShare->registerProvider(new Twitter());
$socialShare->registerProvider(new Google());

function social_share_link($providerName, $url, $options = array())
    global $socialShare;

    return $socialShare->getLink($providerName, $url, $options);

function social_share_shares($providerName, $url)
    global $socialShare;

    return $socialShare->getShares($providerName, $url, true);

add_action('shutdown', array($socialShare, 'update'), 10000);

if (function_exists('fastcgi_finish_request')) {
    add_action('shutdown', 'fastcgi_finish_request', 1);

It loads the library through the Composer autoloading system, initializes a file based cache system (be sure to set a directory writable by your web server)  and loads Facebook, Twitter and Google Plus providers.

If you want to use other social networks such as Pinterest (bundled with SocialShare) or the newly supported LinkedIn, register them here.

Then, we create two helper functions to use in our theme’s templates: social_share_links that returns a share link and social_share_shares that returns the share counter. The last parameter of \SocialShare\SocialShare::getShares() function is set to true. This allows to delay the retrieving of share counts from social network when the \SocialShare\SocialShare::update() method will be called. If a value is already in the cache (how old it is doesn’t matter) it will be used, otherwise 0 will be returned.

Finally, we register the call to the update method on the WordPress’ shutdown hook. Thanks to this tweak, HTTP requests retrieving shares counts from social networks will be issued after the page load. Of course, only the next visitor will see updated counts, but this allows fast pages loading even in the worst case: when the data must be updated from social networks servers.

A last trick: if WordPress is served through PHP FPM (the most performant solution for PHP websites), we take care of the fastcgi_finish_request method. This method (only available when using PHP FPM) allows flushing the buffer and closing the connection to the client before retrieving data from social networks. By default, WordPress flush the response buffer but does not close the connection, even on FPM.

I’ve submitted a patch upstream using this trick to increase performance of all WordPress installations on PHP FPM, so I hope that the last lines of code will become unnecessary soon!

Using the helpers

You can now use the registered helpers in any template. Here is an example to put inside The WordPress Loop (e.g. content.php) to display a link to share the post and it’s number of share on Twitter, Facebook and Google Plus:

        <ul class="entry-social">
            <li><a href="<?php echo social_share_link('facebook', get_permalink()) ?>" rel="nofollow" class="facebook-share"><span class="facebook">Facebook</span> <span class="number"><?php echo social_share_shares('facebook', get_permalink()) ?></span></a></li>
            <li><a href="<?php echo social_share_link('twitter', get_permalink(), array('text' => html_entity_decode(get_the_title()), 'via' => 'dunglas')) ?>" class="twitter-share" rel="nofollow"><span class="twitter">Twitter</span> <span class="number"><?php echo social_share_shares('twitter', get_permalink()) ?></span></a></li>
            <li><a href="<?php echo social_share_link('google', get_permalink()) ?>" class="google-share"><span class="google-plus">Google Plus</span> <span class="number"><?php echo social_share_shares('google', get_permalink()) ?></span></a></li>

Customize the apparence of your social buttons with all the CSS you want!

Introducing the SocialShare PHP library

I’ve released a new PHP library allowing to retrieve the number of shares of URLs on popular social networks. It currently supports Facebook, Twitter, Google Plus / Plus One, Pinterest, LinkedIn and!. This library is also able to generate sharing links for these networks.

The main advantages of this library over traditional JavaScript share buttons are:

  • Speed: counts are retrieved server-side and can be cached through a lot of backends including Memcache, MongoDB and Redis; no JavaScript SDK loading; no HTTP request from your visitor’s browser to social networks
  • Privacy: therefore, no data from your visitors is send to social networks, their privacy is respected
  • Customization: there is no need to use official social networks buttons, you can create beautiful custom buttons displaying the number of shares

This library is installable with Composer, is fully tested with phpSpec, gets a platinum medal on the SensioLabs Insight monitoring system and is compatible with HHVM.

As usual, download it and learn how to use it on GitHub.

Connection to a MS SQL Server from Symfony / Doctrine on Mac or Linux

Microsoft provides a SQL Server driver for PDO. Unfortunately, this driver only works on Windows. Linux and Mac OS X apps must use the FreeTDS compatibility layer: an open source implementation of the MS SQL Server protocol for Unix.

It’s possible to connect a Symfony app to a SQL Server instance on Unix through FreeTDS but this involve to use a Doctrine driver that is not provided with the standard distribution. Some tutorials already explain how to do that, but they encourage doing dirty things like editing files in the vendor/ directory. Here is the clean way! And if you are interested in creating your own server then read more here.

First, install FreeTDS.

On Mac OX X, use Homebrew:
brew install freetds

On Debian or Ubuntu:
apt-get install freetds-bin

The next step is to configure FreeTDS to be able to connect to the SQL Server instance.

Open the freetds.conf file (/etc/freetds/freetds.conf on Debian / Ubuntu and /usr/local/etc/freetds.conf on Mac OS X) and add the connection details of your server:

host =
port = 1433
tds version = 8.0
client charset = UTF-8
text size = 20971520

Be sure to set the protocol version to 8.0, the client charset and the text size.

Now, you should be able to connect to the SQL server from the command line:
tsql -S my_server -U myusername

Type your password when asked and Ctrl+D to disconnect from the server.

It’s time to install the DBLIB PDO Driver.

On Mac OS X (replace php55 by the version of PHP you are using):
brew install php55-pdo-dblib

On Debian or Ubuntu:
apt-get install php5-sybase

And add the DBLIB driver for Doctrine (packaged in a Symfony bundle) in your app:

# in your Symfony app directory
composer require realestateconz/mssql-bundle:dev-master

Enable the Symfony bundle. Add this line in the registerBundles() method of your AppKernel in app/AppKernel.php:

new Realestate\MssqlBundle\RealestateMssqlBundle(),

Finally, configure Doctrine to use this driver. Edit app/config/config.yml:

        driver_class: Realestate\MssqlBundle\Driver\PDODblib\Driver
        host: my_server
        dbname: MYDATABASE
        user: myuser
        password: mypassword

Note that you must use the driver_class parameter, and not driver. Of course, you should not hardcode these values. Use the interactive parameters system instead.

Your Symfony app is now able to connect to the SQL Server. Try to run a SQL query:
php app/console doctrine:query:sql "SELECT * FROM MY_TABLE"

As SQL Server is a bad default DBMS for a Symfony app, especially on Unix servers, you should be interested by using multiple database connection with Symfony and Doctrine.

Le profiling commercial, kézako

Courte réponse à une question posée par un collègue développeur à la suite d’une discussion sur le bienfondé de l’utilisation des CDN externes.

Question qui revient régulièrement : le profiling commercial, qu’est-ce que c’est ?

C’est le fait de collecter un grand nombre de données sur les internautes et d’établir sur eux un profil qui servira à leur envoyer de la publicité ciblée. C’est une spécialité de Google, Facebook et compagnie.

Le problème des CDN “gratuits” (et surtout ceux de Google, même si ils s’en défendent) ainsi que des systèmes de stats (et de toute resource venant d’un domaine externe comme les boutons Facebook, Pinterest…) c’est que qu’ils permettent aux boîtes qui contrôlent le serveur externe de savoir que t’es allé sur tel site, que t’as visité tel page, et donc d’enrichir ton profil commercial.

C’est impossible à détecter côté client car même si tu bloques les cookies, il est possible d’utiliser des heuristiques assez performantes pour identifier de manière fiable un internaute. En gros le système de Google détermine qu’une connexion avec la même IP, le même navigateur, les mêmes plugins… correspond à une personne unique et lui génère une empreinte. Ensuite c’est assez simple de savoir que la dite personne (via son empreinte) a visité le site A chargeant sont jQuery via Google Hosted Libraries, le site B qui utilise Google Analytics et le site C qui a un bouton “+1”), on enrichi son profil commercial, et quand il arrive sur le site D qui balance du AdWords, on sait qu’il aime la bière et les frites donc on essaie de lui vendre une place pour un match de Lens.

C’est plus ou moins comme ça que fonctionne Criteo mais aussi et surtout Adwords et les pubs de “pages” Facebook.

New release of the ACL extension for Sonata Admin

This is the time of new releases! After the open-sourcing of the AngularJS CSRF protection system for Symfony and a new release of the Symfony TodoMVC sample app, a new version of CoopTilleulsAclSonataAdminExtensionBundle is available!

This bundle, brought to you by La Coopérative des Tilleuls, provides ACL list filtering for SonataAdminBundle. When enabled, list screens only display data the logged in user has right to view.

It is part of our effort to make the Sonata Project better.

What’s new? fête ses deux ans

Il y a deux ans éclosait le projet de La Coopérative des Tilleuls, un studio de développement logiciel, autogéré et éthique, qui travaille principalement autour du logiciel libre. J’ai l’honneur d’en avoir été le gérant jusqu’ici.

Nous sommes désormais 8 à travailler dans notre Scop, dont 6 sont déjà coopérateurs. Après quelques tâtonnements, notre mode de fonctionnement est maintenant plutôt rodé et efficace : nos deux premières années d’exercice furent bénéficiaires, nos clients se multiplient et nous dispensons des prestations de qualité : architecture logicielle, audit, développement, création graphique et formation. Nous  ne sommes pas encore à la parité (3 femmes pour 5 hommes) mais par contre, nous ne sommes pas près de réaliser les sites web d’un antisémite notoire.

Après plus d’un an et demi de bons moments à Co-Factory, nous disposons désormais de nos propres locaux à Euratechnologies. Nous continuons d’animer des conférences et workshops (le plus souvent gratuits) et nous contribuons autant que possible aux logiciels libres et en particulier à l’écosystème du framework Symfony.

Quelques chiffres :

Bilan 2013 La Coopérative des TilleulsMerci à ceux qui travaillent avec acharnement tous les jours de la semaine, à Olivier de l’UR Scop Nord, à la société Walibuy / Alice’s Garden qui nous a fait confiance depuis le départ, à Magali et David de Co-Factory et bien sûr nos à proches.

DunglasTodoMVCBundle compatible with Symfony 2.4

I’m pleased to announce the release of DunglasTodoMVCBundle 1.1.0.

Screenshot Symfony Todomvc

DunglasTodoMVCBundle is an implementation of TodoMVC, the popular site providing the same todo app implemented in a ton of different JavaScript frameworks.

This bundle provides a REST / JSON API built with Symfony and Doctrine, and an API client built with Chaplin.js and Backbone.js.

In this new release:


DunglasAngularCsrfBundle: protect your Symfony / AngularJS apps against CSRF attacks

I create and I see more and more web applications sharing the same powerful architecture:

 These components share the same philosophy (built on top of dependency injection and MVC-like patterns, designed to be intensively tested) and play very well together.

This stack allows to create awesome blazing-fast web applications. Better, the client part and the server part of the app are loosely coupled, can evolve separately and can even be maintained by different teams.

However, this kind of apps often suffer of security problems, and especially Cross-site Request Forgery (CSRF or XSRF) vulnerabilities.

Both Symfony and AngularJS provide their own CSRF protection mechanisms, but by default they are not interoperable and not enabled. Thanks to a recent refactoring of the Symfony’s security component, it’s now possible and clean to make both systems working together, and I’ve just released an open source bundle to do that: DunglasAngularCsrfBundle.

This bundle provides out of the box CSRF protection for AngularJS apps interacting with a Symfony-backed app.

Despite it’s name, it does not depend of AngularJS and can also be used with Chaplin.js / Backbone.js, jQuery or even raw JavaScript. To do so, install and configure the bundle, then just add to XHR requests a HTTP header called X-XSRF-TOKEN containing the value of the token set by a cookie on the first HTTP request. The bundle will automatically check the validity of the provided token. If it is not valid, an Access Denied error (HTTP 401) will be thrown.

The bundle is fully tested with phpspec and obtain a platinum medal on the brand new (awesome) SensioLabs Insight quality monitoring system.

Internals documentation and installation instructions are provided on the GitHub page of the bundle. Check it, test it, star it and tell me what you think of it!

Download DunglasAngularCsrfBundle on GitHub. 

Entities and Mapping Information with the Doctrine ORM

Persistence in PHP with the Doctrine ORM

Another free chapter of my book Persistence in PHP with the Doctrine ORM is available on the Pack Website. In this second chapter of the book, you will:

  • Create your first Doctrine entity class
  • Mapping it to its related database table and columns with annotations
  • Use Doctrine Command Line Tools to automatically generate the database schema
  • Create some fixtures data
  • deal with the Entity Manager

To get started with Doctrine entities, read this chapter on the PacktLib.