How to easily import multiple vCards into Google Contacts

Uncategorized

Google Contacts (the old version) allows you to import VCards, but you will have to import them one by one, this is clearly not very practical if you have more than 3 contacts that you want to import (you lazy!). Fear nothing, there is an easy workaround, you’ll merge your vCards before importing them, here’s how you do it. Continue reading “How to easily import multiple vCards into Google Contacts”

Heberjahiz réveille-toi on est en 2013

Uncategorized

N’achetez surtout pas votre nom de domaine chez Heberjahiz, ne faites pas la même erreur que moi!

Voici mon histoire avec Heberjahiz

Le 11 mai 2013: C’ést un samedi, j’achète un nom de domaine .ma en ligne sur le site de la société, je paye instantanément avec PayPal, après quelques secondes, je reçois des courriels de confirmation de PayPal et d’Heberjahiz, tout ce passe bien mais je remarque quand même des signes alarmants:

  • Le design très pauvre du site qui remonte à l’époque post web 2.0, une ergonomie qui fait défaut et une lenteur des requêtes de recherche
  • Un numéro de téléphone erroné dans l’accusé de réception de paiement PayPal, image:

    Heberjahiz donne un faux numéro de téléphone
    Heberjahiz donne un faux numéro de téléphone

Le 13 Mai 2013 (j+2): Le lundi après-midi j’appelle le 0802 00 2800, numéro surtaxé et ne me demandez pas pourquoi! J’appelle – Je disais – pour voir l’état de ma commande, on me répond d’un ton digne d’un grissoune à la gare d’Ouled Ziane (grissoune: graisseur je pense) et on me dit que le nom de domaine sera disponible dans cinq jours ouvrables. OK ça marche, je m’excuse et merci pour l’info.

Le 15 Mai 2013 (j+4): Deux jours plus tard, un peu impatient, je fais une petite requête whois sur le nom de domaine que j’ai acheté et je remarque qu’il est enregistré au nom de Amine Riadi, “Oh la vache!”, je ne connais pas ce Amine et je ne lui est pas délégué ni vendu mon nom de domaine, bréf, après une petite recherche (Google, Facebook, Linked In etc), il s’est avéré que Amine Riadi est le PDG de Arcanes Technologies. OK, j’appelle encore une fois, on m’informe que Maroc Telecom requiert que tous les noms de domaines soient enregistrés au nom du registraire (Arcanes Technologies dans notre cas).
Serious-Lee! On sait tous que les services de IAM sont lents, mais Amine Riadi n’est pas un registraire.
Revenons à nos moutons, j’informe la personne qui m’a répondu que le whois marocain officiel montre que le nom de domaine est actif, donc qu’on arrête SVP de me dire que c’est la faute à IAM. On me promet alors que les service technique m’everra les données d’accès dans “les plus bréfs délais”.

Le 17 Mai 2013 (j+6): Le vendredi matin, après la prière de Al Fajr j’envoie un courriel à Heberjahiz (commercial@arcanes.com et domaines@heberjahiz.com), là encore, bien sûr, je ne reçois aucune réponse, j’appelle vers 17h pour demander des explications, on me dit: “nous sommes dans les délais”, je demande alors à parler au service technique mais on me repond qu’ils sont injoignables au téléphone, je demande alors à parler à un responsable, on me dit qu’il n’y en a pas. A 17:50, je reçois un message générique me disant que le nom domaine sera activé dans les plus bréfs délais.

Je demande à parler à un responsable, le service commercial répond: “Il n’y a aucun responsable à Heberjahiz”

Le 18 Mai 2013 (j+7): On est samedi, le site est prêt, le client (ma femme) est les fans de sa page Facebook attendent toujours. Je vois que Heberjahiz dors toujours, je fais chauffer un peu le ton et je menace publiquement de monter l’affaire en justice, cela ne semble les déranger guère, puisqu’il n’ont pas répondu, ou peut-être pensent-ils que je les taquinaient.

Le 19 Mai 2013 (j+8): Je contacte le service technique qui me renvoie vers le service commercial, quelle galère! Je ne vous envie pas Heberjahiz.

Le 20 Mai 2013 (j+9): Eh ben, Heberjahiz, on se rappelle de moi! Enfin j’ai accès à nom de domain.

 Le bétisier

Pour garder un peu la bonne humeur, je vous fais part de quelques blagues mediocres que j’ai du supporter durant mes entretiens téléphoniques avec le service commercial:

  • Service commercial: “Vous n’avez pas activé votre nom de domaine”, ah bon! Et comment je fais?
  • Je demande le numéro du service technique, le service commercial me répond: “Le service technique est injoignable au téléphone”, je sous-entends: nous travaillons avec des freelances en Inde.
  • Service commercial: “Il n’y a aucun responsable à Heberjahiz”, zut alors!
  • Service commercial: “Le retard vient de chez Maroc Telecom”, j’aimerais bien vous croire, mais nous savons bien tous les deux que vous mentez, ou pensiez vous que je ne sache pas faire une requête whois?
  • Boucle infini (infinite loop): Appelez le 05 22 49 19 45 › Appelez le 05 22 52 88 68 › Appelez le 05 22 49 19 45, j’ai Phony mais sincérement j’ai pas le temps.

Conseils TRES pratiques

  1. Allez voir ailleurs
  2. Gardez les justificatifs de paiement pour ne pas perdre votre nom de domaine
  3. Demandez que l’enregistrement du whois porte votre nom, je parle de la partie “titulaire”.

Joomla 3.0 – Fix Application Instantiation Error

Uncategorized

Everything went smoothly as usual in my local machine, but as soon as I moved the website to the client server, it wouldn’t run normally, instead it gives me the dreaded error message:

Error displaying the error page: Application Instantiation Error

After a small search on Google, I found that all people were saying to check that the database connection credentials were correct in configuration.php, in fact, I’m not new to this thing but I checked again… Continue reading “Joomla 3.0 – Fix Application Instantiation Error”

PHP: empty() is your friend

Uncategorized

The right question is: Is it empty?

It’s easy to miss things that are very obvious, this is the proper way to check that a variable has a value that is not nothing (null, 0, FALSE, “false”, array(), etc) without getting PHP E_NOTICE messages (that I encourage you to show when developing):

// Check that $var is set and is not empty:

// 1. The WRONG way
if($var){
  // ... 
}

// 2. The LONG way
if(isset($var) && $var){
  // ...
}

// 3. The I ROCK way
if(!empty($var)){
  // ...
}

MySQL tip: Update a column with random values

Uncategorized

Random string in MySQL
Random string in MySQL

I’m always impressed with what you can do with MySQL (my favorite RDBMS), not long ago I needed to add a column in a table and fill it with some random values. Instead of using a PHP (could be C, Java, perl…) script that goes row by row and calculates a random value, I thought it would be challenging to do it with a single SQL query.

Generate a random character

This query returns a random character from the string chars_str, replace chars_str with a string containing the characters you want to allow:

SELECT SUBSTRING(chars_str , 1+ FLOOR(RAND()*LENGTH(chars_str)) ,1);

--Example

SELECT SUBSTRING('01234567' , 1+ FLOOR(RAND()*LENGTH('01234567')) ,1) AS random_octal;
+--------------+
| random_octal |
+--------------+
| 6            |
+--------------+

Generate a random string of characters

In order to generate a random string we need to generate many random characters, thus we need to repeat the previous query, or we can simply create a table and have the query executed on each rows of that table, MySQL will generate for us one random character per table row and we’ll concatenate them (with GROUP_CONCAT [...] SEPARATOR '' )to produce our final random string:

  • This query returns a random string constitud of characters from the string chars_str
  • Replace chars_str with a string containing the allowed characters
  • The string length is the length of dummy_tbl which corresponds to the number of SELECT you have in the FROM
SELECT GROUP_CONCAT(SUBSTRING(chars_str , 1+ FLOOR(RAND()*LENGTH(chars_str)) ,1) SEPARATOR '') 
FROM (SELECT 1 /* UNION SELECT 2 ... UNION SELECT n */) as dummy_tbl;

-- Example

SELECT GROUP_CONCAT(SUBSTRING('01' , 1+ FLOOR(RAND()*LENGTH('01')) ,1) SEPARATOR '') AS random_binary
FROM (SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4) AS dummy_tbl;
+---------------+
| random_binary |
+---------------+
| 0111          |
+---------------+

Update a column with random values

Now need to update the column of our database with random values, we will do so by nesting the query that generates random values into a normal UPDATE statement

-- column_name.tbl_name is the column we want to update

UPDATE tbl_name SET column_name = (
  SELECT GROUP_CONCAT(SUBSTRING(chars_str , 1+ FLOOR(RAND()*LENGTH(chars_str)) ,1) SEPARATOR '')
  FROM (SELECT 1 /* UNION SELECT 2 ... UNION SELECT n */) AS dummy_tbl
);

-- Example

UPDATE tickets SET code = (
  SELECT GROUP_CONCAT(SUBSTRING('123abcABC-_$@' , 1+ FLOOR(RAND()*LENGTH('123abcABC-_$@')) ,1) SEPARATOR '')
  FROM (SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5) as dummy_tbl
);

There you have it, there is probably a better –and more of less complicated– way to do it, you may want to try doing the same thing with procedures, if you do so, please share your results on the comments section.

What is MVC?

Uncategorized

The MVC design pattern separates business logic from user interface

Model–View–Controller is a design pattern or a software engineering concept that separates the model, the view and the controller from each others, thus dividing the labour in your application in such a way that:

The model is the brain, the knowledge, or simply data and means to using it:

  • it knows where data is, how to access it and how to change it
  • it responds to requests about data state
  • it responds to instructions to change data state

The view holds the presentation logic like templating and caching, in a PHP MVC application it may range from a few  html templates with PHP tags for inserting request specific data to a bunch of templates using a templating engine such as Smarty.

The controller acts as the mediator, like a  front desk agent or the guy that takes your order and serves your dish at a McDonald’s:

  • it receives the client (visitor’s browser) input in the form of GET or POST requests
  • it could possibly verify and validate user input
  • it instructs a the model to execute a specific action depending on the input it received

The Key benefits of using MVC

Separation of concerns

By separating the data logic (the model), the presentation logic (the view) and the application logic (the controller) you make sure that there is no interference between the three allowing you to work on and optimize each one dependently from the other two.

Let’s assume a scenario where we have a data driven website that we made with MVC in mind, this website needs a graphical redesign, we’ll simply hire an excellent web designer, which happens to be not so good at programming but we don’t care, all he will see is the website template files (our views).

Now we heard that PostgreSQL offers better performance and we want to switch from X to PostgreSQL, fine, all we have to do is migrate our database and modify our model, of course we will not modify a single line on the controller or view logic.

Code reuse

Data returned by the model  is “pure” data, free from any formatting or presentation, when you need to present data to the user you write a view or more if you are offering the same data in many formats (HTML, XML, file for download…). The model is written only once and is reused by the views, there is no code duplication and you don’t waste your time rewriting code that does the same or almost the same thing.

By using MVC, you will end up having a library of well organized components that you can reuse on the same application and in other applications as well, this will drastically increase your productivity.

Drupal Views: Show count

Uncategorized

The view results count is stored in the view object and you can display it by adding a PHP header or footer to your view. In order to have PHP in views you need the module Views PHP, so install it first then add a header or footer with this code.

<?php
// Dispaly count
$view = views_get_current_view();
echo '

'.$view->total_rows.' result(s)'.'

'; ?>

Drupal: Send email

Uncategorized

This is a quick and easy solution to send an email from Drupal using PHP, i.e a custom module. you will do it in 2 steps (I assume your module is called “mod”):

  • Define mod_mail() (implementing hook_mail() ), this function will prepare the email
  • Send the email using drupal_mail()

Define mod_mail()

/**
 * Implementation of hook_mail.
 */
function mod_mail($key, &$message, $params) {
  switch ($key) {
    case 'basic':
      $message['subject'] = t('Greetings');
      $message['body'] = array(t('I just wanted to say hello!'));
      break;
    case 'advanced':
      $message['subject'] = t('Hello @username', array('@username' => $params['username']));
      $message['body'] = array(t('Thank you for joining @site_name!', array('@site_name' => $params['site_name'])));
      break;
    default:
      ; /* Do nothing */
  }
}

Sending the email

In order to send the email you need to decide on 2 parameters (optionally, a 3rd):

  1. The recipent (email address)
  2. The key, in this example this would be ‘basic’ or ‘advanced’
  3. The $params to pass to mod_mail(), in our example it’s only needed if we are using the key ‘advanced’
// Basic example ($key = 'basic')
$email = "someone@example.com";
drupal_mail('mod', 'basic', $email, language_default());


// Advanced example ($key = 'advanced')
$email = "someone@example.com";
$params = array(
  'username' = 'Someone',
  'site_name' = variable_get('site_name'),
);
drupal_mail('mod', 'advanced', $email, language_default(), $params);