dolibarr 25.0.0-alpha
report.lib.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2008-2012 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2012 Regis Houssin <regis.houssin@inodbox.com>
4 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
5 * Copyright (C) 2026 Frédéric France <frederic.france@free.fr>
6 * Copyright (C) 2026 Nick Fragoulis
7 * Copyright (C) 2026 Christos Kanotidis <christoskanotidis@gmail.com>
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 * or see https://www.gnu.org/
22 */
23
45function report_header($reportname, $notused, $period, $periodlink, $description, $builddate, $exportlink = '', $moreparam = array(), $calcmode = '', $varlink = '')
46{
47 global $langs;
48
49 print "\n\n<!-- start banner of report -->\n";
50
51 if (!empty($varlink)) {
52 $varlink = '?'.$varlink;
53 }
54
55 $title = $langs->trans("Report");
56
57 print_barre_liste($title, 0, '', '', '', '', '', -1, '', 'generic', 0, '', '', -1, 1, 1);
58
59 print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].$varlink.'">'."\n";
60 print '<input type="hidden" name="token" value="'.newToken().'">'."\n";
61
62 print dol_get_fiche_head();
63
64 foreach ($moreparam as $key => $value) {
65 print '<input type="hidden" name="'.$key.'" value="'.$value.'">'."\n";
66 }
67
68 print '<table class="border tableforfield centpercent">'."\n";
69
70 $variant = ($periodlink || $exportlink);
71
72 // Title line
73 print '<tr>';
74 print '<td width="150">'.$langs->trans("ReportName").'</td>';
75 print '<td>';
76 print $reportname;
77 print '</td>';
78 if ($variant) {
79 print '<td></td>';
80 }
81 print '</tr>'."\n";
82
83 // Calculation mode
84 if ($calcmode) {
85 print '<tr>';
86 print '<td width="150">'.$langs->trans("CalculationMode").'</td>';
87 print '<td>';
88 print $calcmode;
89 if ($variant) {
90 print '<td></td>';
91 }
92 print '</td>';
93 print '</tr>'."\n";
94 }
95
96 // Report analysis period row
97 print '<tr>';
98 print '<td>'.$langs->trans("ReportPeriod").'</td>';
99 print '<td>';
100 if ($period) {
101 print $period;
102 }
103 if ($variant) {
104 print '<td class="nowraponall">'.$periodlink.'</td>';
105 }
106 print '</td>';
107 print '</tr>'."\n";
108
109 // Description row
110 print '<tr>';
111 print '<td>'.$langs->trans("ReportDescription").'</td>';
112 print '<td>'.$description.'</td>';
113 if ($variant) {
114 print '<td></td>';
115 }
116 print '</tr>'."\n";
117
118 // Export row
119 print '<tr>';
120 print '<td>'.$langs->trans("GeneratedOn").'</td>';
121 print '<td>';
122 print dol_print_date($builddate, 'dayhour');
123 print '</td>';
124 if ($variant) {
125 print '<td>'.($exportlink ? $langs->trans("Export").': '.$exportlink : '').'</td>';
126 }
127 print '</tr>'."\n";
128
129 print '</table>'."\n";
130
131 print dol_get_fiche_end();
132
133 print '<div class="center"><input type="submit" class="button" name="submit" value="'.$langs->trans("Refresh").'"></div>';
134
135 print '</form>';
136 print '<br>';
137
138 print "\n<!-- end banner of report -->\n\n";
139}
140
148{
149 global $conf;
150
151 if (getDolGlobalInt('PDF_DISABLE_MYCOMPANY_LOGO') || empty($mysoc->logo)) {
152 return '';
153 }
154
155 $logodir = $conf->mycompany->dir_output;
156 if (!empty($conf->mycompany->multidir_output[$conf->entity])) {
157 $logodir = $conf->mycompany->multidir_output[$conf->entity];
158 }
159 if (!getDolGlobalInt('MAIN_PDF_USE_LARGE_LOGO') && !empty($mysoc->logo_small)) {
160 $logo = $logodir.'/logos/thumbs/'.$mysoc->logo_small;
161 } else {
162 $logo = $logodir.'/logos/'.$mysoc->logo;
163 }
164 if (!is_readable($logo)) {
165 dol_syslog(__FUNCTION__.' logo not readable '.$logo, LOG_WARNING);
166 return '';
167 }
168
169 return $logo;
170}
171
181function reportGetCompanyLines($outputlangs, $mysoc)
182{
183 global $hookmanager;
184
185 require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php';
186
187 $outputlangs->loadLangs(array("main", "companies"));
188
189 $lines = explode("\n", pdf_build_address($outputlangs, $mysoc, '', '', 0, 'source'));
190
191 if (is_object($hookmanager)) {
192 $parameters = array('outputlangs' => $outputlangs, 'lines' => $lines);
193 $action = '';
194 $reshook = $hookmanager->executeHooks('reportBuildCompanyLines', $parameters, $mysoc, $action);
195 if ($reshook < 0) {
196 dol_syslog(__FUNCTION__.' hook error '.$hookmanager->error, LOG_ERR);
197 } elseif ($reshook > 0 && isset($hookmanager->resArray['lines']) && is_array($hookmanager->resArray['lines'])) {
198 $lines = $hookmanager->resArray['lines'];
199 }
200 }
201
202 $result = array();
203 foreach ($lines as $line) {
204 $line = trim((string) $line);
205 if ($line !== '') {
206 $result[] = $line;
207 }
208 }
209
210 return $result;
211}
212
222function reportPdfInit($outputlangs, $title, $subject, $orientation = 'P')
223{
224 global $mysoc, $user;
225
226 require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php';
227
228 $format = pdf_getFormat($outputlangs);
229 $pdf = pdf_getInstance(array($format['width'], $format['height']), 'mm', ($orientation == 'L' ? 'l' : 'P'));
230 $fontsize = (int) pdf_getPDFFontSize($outputlangs);
231 $margin = 10.0;
232
233 $pdf->SetFont(pdf_getPDFFont($outputlangs));
234 $pdf->setPrintHeader(false);
235 $pdf->setPrintFooter(false);
236 $pdf->SetMargins($margin, $margin, $margin);
237 $pdf->SetAutoPageBreak(false);
238 $pdf->Open();
239 $pdf->SetDrawColor(128, 128, 128);
240 $pdf->SetTitle($outputlangs->convToOutputCharset($title));
241 $pdf->SetSubject($outputlangs->convToOutputCharset($subject));
242 $pdf->SetCreator("Dolibarr ".DOL_VERSION);
243 $author = (is_object($mysoc) ? (string) $mysoc->name : '');
244 if (is_object($user) && $user->id > 0) {
245 $author .= ($author !== '' ? ' - ' : '').$user->getFullName($outputlangs);
246 }
247 $pdf->SetAuthor($outputlangs->convToOutputCharset($author));
248 if (getDolGlobalString('MAIN_DISABLE_PDF_COMPRESSION')) {
249 $pdf->SetCompression(false);
250 }
251 $pdf->AddPage();
252
253 // Real page size, after orientation is applied
254 $pagewidth = (float) $pdf->getPageWidth();
255 $pageheight = (float) $pdf->getPageHeight();
256
257 return array(
258 'pdf' => $pdf,
259 'margin' => $margin,
260 'pagewidth' => $pagewidth,
261 'pageheight' => $pageheight,
262 'usablewidth' => $pagewidth - 2 * $margin,
263 'fontsize' => $fontsize
264 );
265}
266
277function reportPdfCompanyHeader($pdf, $outputlangs, $mysoc, $margin, $fontsize)
278{
279 require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php';
280
281 $bottom = $margin;
282
283 $logo = reportGetLogoPath($mysoc);
284 if ($logo !== '') {
285 $height = pdf_getHeightForLogo($logo);
286 $pdf->Image($logo, $margin, $margin, 0, $height);
287 $bottom = $margin + $height;
288 }
289
290 $w = 100;
291 $posx = (float) $pdf->getPageWidth() - $margin - $w;
292 $pdf->SetTextColor(0, 0, 0);
293 $pdf->SetXY($posx, $margin);
294 if (!getDolGlobalString('MAIN_PDF_HIDE_SENDER_NAME')) {
295 $pdf->SetFont('', 'B', $fontsize);
296 $pdf->MultiCell($w, 4, $outputlangs->convToOutputCharset($mysoc->name), 0, 'L');
297 }
298 $pdf->SetFont('', '', $fontsize - 1);
299 foreach (reportGetCompanyLines($outputlangs, $mysoc) as $line) {
300 $pdf->SetX($posx);
301 $pdf->MultiCell($w, 4, $outputlangs->convToOutputCharset($line), 0, 'L');
302 }
303
304 return max($bottom, (float) $pdf->GetY()) + 4;
305}
306
315function reportFileName($title, $name, $ext)
316{
317 $prefix = trim((string) preg_replace('/_+/', '_', dol_sanitizeFileName(str_replace(' ', '_', $title), '_', 0)), '_');
318 $name = trim((string) preg_replace('/_+/', '_', dol_sanitizeFileName(str_replace(' ', '_', $name), '_', 0)), '_.');
319
320 return $prefix.($name !== '' ? '-'.$name : '').'.'.$ext;
321}
322
331function reportPeriodLabel($outputlangs, $datestart, $dateend)
332{
333 if ($datestart && $dateend) {
334 return $outputlangs->transnoentitiesnoconv("DateFromTo", dol_print_date($datestart, 'day', 'tzserver', $outputlangs), dol_print_date($dateend, 'day', 'tzserver', $outputlangs));
335 } elseif ($datestart) {
336 return $outputlangs->transnoentitiesnoconv("DateFrom", dol_print_date($datestart, 'day', 'tzserver', $outputlangs));
337 } elseif ($dateend) {
338 return $outputlangs->transnoentitiesnoconv("DateUntil", dol_print_date($dateend, 'day', 'tzserver', $outputlangs));
339 }
340
341 return '';
342}
343
350function reportSheetTitle($label)
351{
352 $title = trim((string) preg_replace('/\s+/u', ' ', str_replace(array('[', ']', ':', '*', '?', '/', '\\'), ' ', $label)), " '");
353 $title = trim(dol_substr($title, 0, 31, 'UTF-8'), " '");
354
355 return ($title === '' ? 'Sheet1' : $title);
356}
357
366function reportXlsxInit($outputlangs, $title, $sheetlabel)
367{
368 global $user;
369
370 require_once DOL_DOCUMENT_ROOT.'/includes/phpoffice/phpspreadsheet/src/autoloader.php';
371 require_once DOL_DOCUMENT_ROOT.'/includes/Psr/autoloader.php';
372 require_once PHPEXCELNEW_PATH.'Spreadsheet.php';
373
374 $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
375 $spreadsheet->getProperties()->setCreator($user->getFullName($outputlangs).' - '.DOL_APPLICATION_TITLE.' '.DOL_VERSION);
376 $spreadsheet->getProperties()->setTitle($title);
377 $sheet = $spreadsheet->getActiveSheet();
378 $sheet->setTitle(reportSheetTitle($sheetlabel));
379 $sheet->getDefaultRowDimension()->setRowHeight(16);
380
381 return $spreadsheet;
382}
383
394function reportXlsxCompanyHeader($sheet, $outputlangs, $mysoc, $firstcol, $lastcol)
395{
396 $infolines = array();
397 if (!getDolGlobalString('MAIN_PDF_HIDE_SENDER_NAME')) {
398 $infolines[] = array((string) $mysoc->name, true);
399 }
400 foreach (reportGetCompanyLines($outputlangs, $mysoc) as $line) {
401 $infolines[] = array($line, false);
402 }
403
404 $logo = reportGetLogoPath($mysoc);
405 if ($logo !== '') {
406 $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
407 $drawing->setPath($logo);
408 $drawing->setCoordinates('A1');
409 $drawing->setOffsetX(2);
410 $drawing->setOffsetY(2);
411 $drawing->setHeight(70);
412 $drawing->setWorksheet($sheet);
413 }
414
415 foreach ($infolines as $i => $infoline) {
416 $cell = $firstcol.($i + 1);
417 $sheet->setCellValueExplicit($cell, $infoline[0], \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
418 $sheet->mergeCells($cell.':'.$lastcol.($i + 1));
419 $sheet->getStyle($cell)->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT);
420 if ($infoline[1]) {
421 $sheet->getStyle($cell)->getFont()->setBold(true);
422 }
423 }
424
425 return max(count($infolines), ($logo !== '' ? 5 : 0));
426}
427
435function reportXlsxOutput($spreadsheet, $filename)
436{
437 // ASCII fallback for old browsers, non ASCII chars become '_'
438 $asciiname = (string) preg_replace('/[^\x20-\x7e]/', '_', dol_sanitizeFileName($filename));
439 $asciiname = trim((string) preg_replace(array('/_+/', '/_?-_?/', '/_?\._?/'), array('_', '-', '.'), $asciiname), '_-');
440 if ($asciiname === '' || $asciiname[0] === '.') {
441 $asciiname = 'export'.$asciiname;
442 }
443
444 header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
445 header('Content-Disposition: attachment; filename="'.$asciiname.'"; filename*=UTF-8\'\''.rawurlencode($filename));
446 header('Cache-Control: max-age=0');
447
448 $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
449 $writer->save('php://output');
450 $spreadsheet->disconnectWorksheets();
451}
452
462function reportExportButtons($param, $idprefix, $enabled = 1)
463{
464 global $langs;
465
466 $langs->load("accountancy");
467
468 $url = $_SERVER["PHP_SELF"].'?action=exportpdf&token='.newToken().$param;
469 $out = dolGetButtonTitle($langs->trans("ExportToPdf"), '', 'fa fa-file-pdf', $url, $idprefix.'exportpdf', $enabled, array('attr' => array('target' => '_blank', 'rel' => 'noopener')));
470 $url = $_SERVER["PHP_SELF"].'?action=exportxlsx&token='.newToken().$param;
471 $out .= dolGetButtonTitle($langs->trans("Export").' (XLSX)', '', 'fa fa-file-excel', $url, $idprefix.'exportxlsx', $enabled);
472
473 return $out;
474}
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
global $mysoc
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
newToken()
Return the value of token currently saved into session with name 'newtoken'.
dol_substr($string, $start, $length=null, $stringencoding='', $trunconbytes=0)
Make a substring.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limittoshow=0, $moretabssuffix='', $dragdropfile=0, $morecssdiv='')
Show tabs of a record.
Definition html.lib.php:542
dolGetButtonTitle($label, $helpText='', $iconClass='fa fa-file', $url='', $id='', $status=1, $params=array())
Function dolGetButtonTitle : this kind of buttons are used in title in list.
dol_get_fiche_end($notab=0)
Return tab footer of a card.
Definition html.lib.php:740
pdf_getFormat($outputlangs=null, $mode='setup')
Return array with format properties of default PDF format.
Definition pdf.lib.php:87
pdf_getPDFFontSize($outputlangs)
Return font size to use for PDF generation.
Definition pdf.lib.php:296
pdf_getHeightForLogo($logo, $url=false)
Return height to use for Logo onto PDF.
Definition pdf.lib.php:319
pdf_getPDFFont($outputlangs)
Return font name to use for PDF generation.
Definition pdf.lib.php:275
pdf_build_address($outputlangs, $sourcecompany, $targetcompany='', $targetcontact='', $usecontact=0, $mode='source', $object=null)
Return a string with full address formatted for output on PDF documents.
Definition pdf.lib.php:481
pdf_getInstance($format='', $metric='mm', $pagetype='P')
Return a PDF instance object.
Definition pdf.lib.php:129
reportPeriodLabel($outputlangs, $datestart, $dateend)
Return the label of a filtered period.
reportXlsxCompanyHeader($sheet, $outputlangs, $mysoc, $firstcol, $lastcol)
Write logo (left) and company info (right) at top of a report worksheet.
reportPdfInit($outputlangs, $title, $subject, $orientation='P')
Create a PDF instance for a report, with first page added.
reportGetCompanyLines($outputlangs, $mysoc)
Return our company info lines (without the name) for a report header.
reportGetLogoPath($mysoc)
Return the readable path of our company logo for a report, or '' if none.
reportSheetTitle($label)
Return a valid worksheet title from a free label.
reportFileName($title, $name, $ext)
Return a report export file name.
reportPdfCompanyHeader($pdf, $outputlangs, $mysoc, $margin, $fontsize)
Print our company logo (left) and company info (right) at top of a report PDF page.
reportXlsxInit($outputlangs, $title, $sheetlabel)
Create a spreadsheet for a report.
reportExportButtons($param, $idprefix, $enabled=1)
Return the PDF and XLSX export buttons of a report page.
reportXlsxOutput($spreadsheet, $filename)
Send a report spreadsheet to the browser as an xlsx download.
report_header($reportname, $notused, $period, $periodlink, $description, $builddate, $exportlink='', $moreparam=array(), $calcmode='', $varlink='')
Show header of a report.