diff --git a/htdocs/core/class/html.formmail.class.php b/htdocs/core/class/html.formmail.class.php
index e0d03d970d0..b0cdcd23a96 100644
--- a/htdocs/core/class/html.formmail.class.php
+++ b/htdocs/core/class/html.formmail.class.php
@@ -1154,6 +1154,12 @@ class FormMail extends Form
return -1;
}
+ $languagetosearch = (is_object($outputlangs) ? $outputlangs->defaultlang : '');
+ // Define $languagetosearchmain to fall back on main language (for example to get 'es_ES' for 'es_MX')
+ $tmparray = explode('_', $languagetosearch);
+ $languagetosearchmain = $tmparray[0].'_'.strtoupper($tmparray[0]);
+ if ($languagetosearchmain == $languagetosearch) $languagetosearchmain = '';
+
$sql = "SELECT rowid, label, topic, joinfiles, content, content_lines, lang";
$sql.= " FROM ".MAIN_DB_PREFIX.'c_email_templates';
$sql.= " WHERE (type_template='".$db->escape($type_template)."' OR type_template='all')";
@@ -1161,10 +1167,10 @@ class FormMail extends Form
$sql.= " AND (private = 0 OR fk_user = ".$user->id.")"; // Get all public or private owned
if ($active >= 0) $sql.=" AND active = ".$active;
if ($label) $sql.=" AND label ='".$db->escape($label)."'";
- if (! ($id > 0) && is_object($outputlangs)) $sql.= " AND (lang = '".$db->escape($outputlangs->defaultlang)."' OR lang IS NULL OR lang = '')";
+ if (! ($id > 0) && $languagetosearch) $sql.= " AND (lang = '".$db->escape($languagetosearch)."'".($languagetosearchmain ? " OR lang = '".$db->escape($languagetosearchmain)."'" : "")." OR lang IS NULL OR lang = '')";
if ($id > 0) $sql.= " AND rowid=".$id;
if ($id == -1) $sql.= " AND position=0";
- if (is_object($outputlangs)) $sql.= $db->order("position,lang,label", "ASC,DESC,ASC"); // We want line with lang set first, then with lang null or ''
+ if ($languagetosearch) $sql.= $db->order("position,lang,label", "ASC,DESC,ASC"); // We want line with lang set first, then with lang null or ''
else $sql.= $db->order("position,lang,label", "ASC,ASC,ASC"); // If no language provided, we give priority to lang not defined
$sql.= $db->plimit(1);
//print $sql;