← Blog
How it works

The newest file is not the invoice

“We emailed an invoice from our accounting system and the customer received an XML file, or a draft, or a document they could not open. The right PDF was sitting in the same folder the whole time.”

A customer writes back to say they cannot open the invoice. The attachment is an XML file. Or it opens, and it is the countersigned copy from last month, or an ODT nobody outside the finance team has software for. The correct PDF exists. It is in the same folder the email was built from, and it was not chosen.

This is not a rendering bug or a mail bug. It happens at a step that is easy to miss, because it does not look like a decision: before anything can attach the invoice, something has to work out which file the invoice is. An invoice has a number, a total, a customer and a date, all stored as fields. The document, the actual bytes a customer opens, is usually a file on disk that nothing points at.

So the answer gets derived at send time, from whatever is to hand. Dolibarr is a good place to watch this happen, because it is open source, widely deployed for exactly this job, and it derives the answer in three different places with three different rules. Everything below is read from the source at commit a73b58c.

The code says it is guessing

One template builds the "send by email" form for every kind of document, invoices included: htdocs/core/tpl/card_presend.tpl.php. The attachment is chosen in eleven lines, and the comment above them is the honest part.

//$fileparams['fullname'] can be filled from the card
//Get also the main_lastdoc field of $object. If not found, try to guess with following code
if (!empty($object->last_main_doc) && is_readable(DOL_DATA_ROOT.'/'.$object->last_main_doc) && is_file(DOL_DATA_ROOT.'/'.$object->last_main_doc)) {
    $fileparams['fullname'] = DOL_DATA_ROOT.'/'.$object->last_main_doc;
} else {
    include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
    // Special case
    if ($object->element == 'invoice_supplier') {
        $fileparams = dol_most_recent_file($diroutput.'/'.get_exdir($object->id, 2, 0, 0, $object, $object->element).$ref, preg_quote($ref, '/').'([^\-])+');
    } else {
        $fileparams = dol_most_recent_file($diroutput.'/'.$ref, preg_quote($ref, '/').'[^\-]+');
    }
}

Two paths. A stored field, last_main_doc, if it names a readable file. Otherwise, in the words of the comment, "try to guess with following code".

A comment that says the code is guessing is worth taking literally. It is not hedging about an implementation detail. It is telling you that at this point in the program the information needed to answer the question is not available, and that what follows produces an answer anyway.

What the guess is

dol_most_recent_file is eight lines in htdocs/core/lib/files.lib.php, and its docblock describes itself plainly as "Return file(s) into a directory (by default most recent)".

function dol_most_recent_file($dir, $regexfilter = '', $excludefilter = array('(\.meta|_preview.*\.png)$', '^\.'), $nohook = 0, $mode = 0, $limit = 0)
{
	$tmparray = dol_dir_list($dir, 'files', 0, $regexfilter, $excludefilter, 'date', SORT_DESC, $mode, $nohook);
	if ($limit > 1) {
		return array_slice($tmparray, 0, $limit);
	}
	return isset($tmparray[0]) ? $tmparray[0] : null;
}

Two things in that call decide which file a customer receives.

The sort is 'date', descending, and in dol_dir_list that date is the filesystem modification time, dol_filemtime($utf8_fullpathfile). Not the invoice date, not a generation timestamp recorded in the database. The mtime, which is a property of the file as a file, and which any process that rewrites or copies the file will change.

The filter is a regular expression over the name, and it is applied like this:

$testpregmatch = preg_match('/'.$filter.'/i', $utf8_file);		// May failed if $filter too large

Unanchored, case-insensitive, and with no test of the extension anywhere. The filter the invoice path passes is preg_quote($ref, '/').'[^\-]+': the invoice reference, followed by at least one character that is not a hyphen. That is the whole constraint. A file called FA2611-0042.xml satisfies it exactly as well as FA2611-0042.pdf.

Running the rule

The rule is small enough to run directly. Below, a directory holds the four files an invoice reference plausibly accumulates: the generated PDF, an ODT the template produced on the way, an e-invoicing XML, and a countersigned copy that came back a day later. The mtimes are in that order.

The table comes from Dolibarr's own files.lib.php and functions.lib.php at that commit, loaded under PHP 8.3.6 and called directly on real files, with an independent Python 3.12.3 implementation of the same rule as a second engine. The two agree on every row. The boundary matters: these are Dolibarr's functions, not a running Dolibarr, so it shows what the quoted rule does, not a reproduction of anyone's installation.

filter used: /FA2611\-0042[^\-]+/i

FILE IN THE DIRECTORY        mtime                matches?  isRealPdf
----------------------------------------------------------------------------
FA2611-0042-signed.pdf       2026-12-02 14:30:00  NO        yes
FA2611-0042.odt              2026-12-01 09:00:05  yes       no
FA2611-0042.pdf              2026-12-01 09:00:00  yes       yes
FA2611-0042.xml              2026-12-01 09:00:11  yes       no

with the ref filter (single send, card_presend.tpl.php:89):
  attached: FA2611-0042.xml

The XML is attached. It is the newest file whose name matches, by six seconds, and nothing in the rule knows that a customer cannot read it. This is the failure a Dolibarr user reported on 2 November 2026 in issue #42538, which asks for the PDF to be preferred. It names two ways in: an e-invoicing extension, and ODT conversion, where both files are created at the same time and "the PDF is not always the most recent file".

There is a second result in that table worth sitting with. FA2611-0042-signed.pdf, the countersigned copy, is the newest file in the directory by more than a day, and it matches nothing. The one name constraint in the rule, [^\-]+, requires a non-hyphen character directly after the reference, and that file has a hyphen there. So the single nearest thing to a type filter in this code path does not select for PDFs. It excludes hyphenated variants, which in practice means the human-prepared versions: the countersigned copy, the reminder, the duplicate marked as such.

The rule therefore cannot reach the file most likely to be the one you want, and can reach every file least likely to be.

The stored field is also a guess

That leaves last_main_doc, the branch taken before any of this. It looks like the answer: a field on the invoice naming its document. Read how it is written and it turns out to be the same idea one layer up.

It is set in commonobject.class.php, after a document is generated, and only conditionally:

// Update the last_main_doc field into main object (if document generator has property ->update_main_doc_field set)
$update_main_doc_field = 0;
if (!empty($obj->update_main_doc_field)) {
    $update_main_doc_field = 1;
}

Then, if that flag is on:

$sql = "UPDATE ".$this->db->prefix().$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath."/".$ecmfile->filename)."'";

Two consequences follow, and they pull in opposite directions.

First, a generator has to opt in. Dolibarr's own templates do: the default invoice PDF template, pdf_sponge, sets $this->update_main_doc_field = 1;, and so does the generic ODT template, both with the same comment, "Save the name of generated file as the main doc when generating a doc with this template". A third-party template that does not set it leaves the field untouched, and the send form falls through to the guess. That is the path the issue reporter is on.

Second, and this is the part the field's own name admits, it stores the last document generated. Not the invoice. Generate the PDF, then generate the ODT, and the field names the ODT. The comment says so exactly: the name of the generated file, when generating a doc with this template. Whichever template ran most recently wins.

So the stored field and the fallback are both recency. One is recency of generation, recorded in the database. The other is recency of modification, read off the filesystem. Neither is a record of which file is the invoice, and the two can disagree with each other.

A third path, answering differently

Dolibarr can also send invoices as a mass action, over a selection of rows, which is the unattended case where nobody is looking at an attachment list. That code is in htdocs/core/actions_massactions.inc.php, and it does not use either of the rules above as its primary answer. It constructs a filename:

// TODO Use future field $objectobj->fullpathdoc to know where is stored default file
// TODO If not defined, use $objectobj->model_pdf (or default invoice config) to know what is template to use to regenerate doc.
$filename = dol_sanitizeFileName($objectobj->ref).'.pdf';

The reference plus .pdf, by convention, with no check that such a file was ever the invoice. The other two strategies appear only behind configuration that is off by default. Searching for the most recent file requires MAIL_MASS_ACTION_SEARCH_MOST_RECENT_FILE_IF_NOT_FOUND, and when it runs it appends '\.pdf$' to the filter only if MAIN_ODT_AS_PDF happens to be set. Consulting last_main_doc requires MAIL_MASS_ACTION_ADD_LAST_IF_MAIN_DOC_NOT_FOUND. The first candidate that exists on disk wins.

Note the first TODO. It names the missing thing precisely: a field that records where the default document is stored. The code knows what it does not have.

Three code paths in one application, then, answering "which file is the invoice" with a filename convention, a modification time, and a field meaning the last document generated. A deployment can send the same invoice two ways and attach two different files, and nothing in either path is wrong about anything it actually checked.

There is a fourth configuration worth naming because it is the newest. A change on 26 September 2026 added MAIN_FACTURE_EMAIL_ATTACH_MOST_RECENT_FILES, which attaches the N most recent files, and it calls the same function with the filter removed entirely:

$recentfiles = dol_most_recent_file($dir, '', array('(\.meta|_preview.*\.png)$', '^\.'), 0, 0, $nbmostrecentfiles);

An empty filter matches everything in the directory. In the same run, that configuration puts FA2611-0042-signed.pdf first: the file the default path cannot reach becomes the file that gets picked. Both behaviours are the same function, called with a different argument, in the same template.

The proposed fix changes the proxy

Issue #42538 has an open pull request, #42539, from the same reporter. It removes the last_main_doc branch and instead walks the directory listing and takes the first entry that passes isRealPdf, a check Dolibarr already has and uses before handing a file to Imagick. It is this:

	$header = fread($handle, 5);
	fclose($handle);

	if ($header !== '%PDF-') {
		return false;
	}

Five bytes. Applying that rule to the same directory attaches FA2611-0042.pdf, which is the right answer for this failure. On 3 December 2026 the pull request was open and unmerged, with no review and no comments, so this describes a proposal and not Dolibarr's behaviour.

It is a clear improvement on sorting by mtime, and it is still a proxy. %PDF- tells you a file is a PDF. It does not tell you the file is this invoice, as opposed to a payment reminder for it, a delivery note filed beside it, a proforma that preceded it, or the countersigned copy. Each of those is a real PDF, and in a directory selected by name and ordered by mtime, each of them can come first.

Swapping one proxy for a better proxy raises the floor. It does not answer the question, because the question is about identity and all three attributes used here, when the file was last touched, what its name looks like, and what its first five bytes are, are attributes of files in general.

Record it when it is true

The pattern generalises past invoices, and past Dolibarr. Any system that produces documents and later has to send, archive or retain "the" document faces the same step, and the same temptation, because at the moment of generation the answer is obvious and so it feels unnecessary to write down. There is one file. It is the newest. It is named after the record. All three proxies are true, simultaneously, and they are true because the directory is empty of anything else.

They stop being true later, and nothing announces it. An e-invoicing module writes an XML. An export writes a CSV. A template regenerates and loses a race. Someone drops a countersigned copy in. Every one of those is a normal event, none is an error, and each one quietly invalidates one of the proxies without touching the others.

What survives those events is a stored fact, written by the code that generated the document, at the moment it generated it, because that code is the only thing in the system that knows the answer without inferring it. Dolibarr has most of the machinery: a field on the record, an opt-in flag, and an index of files in ecm_files. What it lacks is a field whose meaning is "this is the document", as distinct from "this is the last one generated". Its own TODO asks for exactly that.

Two practical consequences for anyone running into this. If you are configuring one of these systems, the question to ask is not which option attaches the right file today, but what each option would attach after a module you install next year starts writing a second file to that directory. And if you are building one, the test that catches this is not "does the email have an attachment". It is: put a newer file in the directory, one that matches the naming convention and is not the document, then send.

A related failure sits one level further in, in files that carry the invoice twice. A hybrid e-invoice is a PDF with an XML attachment inside it, and the two halves can disagree while the file validates: we built one deliberately and watched it pass. That is about two representations inside one file. This post is about which file gets sent at all, and the two can bite in sequence: the rule above can attach a standalone XML instead of the document, and the document it should have attached can itself be internally inconsistent.

Where our products fit

Nowhere, deliberately. None of the Mitikasha apps selects a document by modification time, by filename convention or by file signature, so there is no product angle here and this post has apps: []. All five product repositories were checked at their deployed prod commits for recency-based or convention-based document selection and none has any. That check is listed in the sources file.

What was and was not verified

Read directly from Dolibarr source at commit a73b58c, and quoted above verbatim: the attachment selection in card_presend.tpl.php, dol_most_recent_file and the filter and sort behaviour of dol_dir_list in files.lib.php, the last_main_doc write in commonobject.class.php, the update_main_doc_field flag in the default PDF and generic ODT invoice templates, the mass-action selection in actions_massactions.inc.php, and isRealPdf. Each file was re-fetched at that pinned commit and checksummed against the copy these quotes came from.

The table was produced by calling Dolibarr's own dol_most_recent_file, dol_dir_list and isRealPdf, loaded from that commit under PHP 8.3.6 with minimal stubs, against real files with the modification times shown. An independent Python 3.12.3 implementation of the same rule gave the same answers on every row. Neither is a running Dolibarr: the database, hooks and the ecm_files index are not involved. Treat the table as a demonstration of the quoted rule, not as a reproduction of the bug.

Issue #42538 and pull request #42539, including the pull request's diff, were read through GitHub's API on 3 December 2026; the sentence quoted from the issue is verbatim.

Not verified: how often this fires in practice, which third-party templates omit update_main_doc_field, and whether any Dolibarr version ships the fix. No claim is made about any other accounting system, and none about Dolibarr releases other than the commit named.