Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

dev/core#1855 - Allow different output formats for CiviReport results and untangle code #17901

Merged
merged 1 commit into from
Jul 21, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
228 changes: 124 additions & 104 deletions CRM/Report/Form.php
Original file line number Diff line number Diff line change
Expand Up @@ -1113,6 +1113,37 @@ public function getID() {
return $this->_id;
}

/**
* Getter for _outputMode
*
* Note you can implement hook_civicrm_alterReportVar('actions', ...)
* which indirectly allows setting _outputMode if the user chooses
* your action.
*
* @return string
*/
public function getOutputMode():string {
return $this->_outputMode;
}

/**
* Getter for report header form field value
*
* @return string
*/
public function getReportHeader():string {
return $this->_formValues['report_header'] ?? '';
}

/**
* Getter for report footer form field value
*
* @return string
*/
public function getReportFooter():string {
return $this->_formValues['report_footer'] ?? '';
}

/**
* Setter for $_force.
*
Expand Down Expand Up @@ -1681,6 +1712,8 @@ protected function getActions($instanceId) {
unset($actions['report_instance.csv']);
}

CRM_Utils_Hook::alterReportVar('actions', $actions, $this);

return $actions;
}

Expand Down Expand Up @@ -2839,25 +2872,35 @@ public function processReportMode() {
CRM_Core_DAO::$_nullObject
);

if ($this->_outputMode == 'print' ||
($this->_sendmail && !$this->_outputMode)
) {
$this->printOnly = TRUE;
$this->addPaging = FALSE;
if ($this->_sendmail && !$this->_outputMode) {
// If we're here from the mail_report job, then the default there gets
// set to pdf before we get here, but if we're somehow here and sending
// by email and don't have a format set, then use print.
// @todo Is this on purpose - why would they be different defaults?
$this->_outputMode = 'print';
}

// _outputMode means multiple things and can cover export to file formats,
// like csv, or actions with no output, like save. So this will only set
// a handler if it's one of the former. But it's also possible we have a
// really interesting handler out there. But the point is we don't need to
// know, just to know that a handler doesn't always get set by this call.
$this->setOutputHandler();

if (!empty($this->outputHandler)) {
if ($this->_sendmail) {
// If we're sending by email these are the only options that make
// sense.
$this->printOnly = TRUE;
$this->addPaging = FALSE;
$this->_absoluteUrl = TRUE;
}
}
elseif ($this->_outputMode == 'pdf') {
$this->printOnly = TRUE;
$this->addPaging = FALSE;
$this->_absoluteUrl = TRUE;
}
elseif ($this->_outputMode == 'csv') {
$this->printOnly = TRUE;
$this->_absoluteUrl = TRUE;
$this->addPaging = FALSE;
else {
// otherwise ask the handler
$this->printOnly = $this->outputHandler->isPrintOnly();
$this->addPaging = $this->outputHandler->isAddPaging();
$this->_absoluteUrl = $this->outputHandler->isAbsoluteUrl();
}
}
elseif ($this->_outputMode == 'copy' && $this->_criteriaForm) {
$this->_createNew = TRUE;
Expand Down Expand Up @@ -3413,98 +3456,21 @@ public function endPostProcess(&$rows = NULL) {
$this->_resultSet = $rows;
}

if ($this->_outputMode == 'print' ||
$this->_outputMode == 'pdf' ||
$this->_sendmail
) {

$content = $this->compileContent();
$url = CRM_Utils_System::url("civicrm/report/instance/{$this->_id}",
"reset=1", TRUE
);

// Add contacts to group
if ($this->_outputMode == 'group') {
$group = $this->_params['groups'];
$this->add2group($group);
}
else {
if ($this->_sendmail) {
$config = CRM_Core_Config::singleton();
$attachments = [];

if ($this->_outputMode == 'csv') {
$content
= $this->_formValues['report_header'] . '<p>' . ts('Report URL') .
": {$url}</p>" . '<p>' .
ts('The report is attached as a CSV file.') . '</p>' .
$this->_formValues['report_footer'];

$csvFullFilename = $config->templateCompileDir .
CRM_Utils_File::makeFileName('CiviReport.csv');
$csvContent = CRM_Report_Utils_Report::makeCsv($this, $rows);
file_put_contents($csvFullFilename, $csvContent);
$attachments[] = [
'fullPath' => $csvFullFilename,
'mime_type' => 'text/csv',
'cleanName' => 'CiviReport.csv',
'charset' => 'utf-8',
];
}
if ($this->_outputMode == 'pdf') {
// generate PDF content
$pdfFullFilename = $config->templateCompileDir .
CRM_Utils_File::makeFileName('CiviReport.pdf');
file_put_contents($pdfFullFilename,
CRM_Utils_PDF_Utils::html2pdf($content, "CiviReport.pdf",
TRUE, ['orientation' => 'landscape']
)
);
// generate Email Content
$content
= $this->_formValues['report_header'] . '<p>' . ts('Report URL') .
": {$url}</p>" . '<p>' .
ts('The report is attached as a PDF file.') . '</p>' .
$this->_formValues['report_footer'];

$attachments[] = [
'fullPath' => $pdfFullFilename,
'mime_type' => 'application/pdf',
'cleanName' => 'CiviReport.pdf',
];
}

if (CRM_Report_Utils_Report::mailReport($content, $this->_id,
$this->_outputMode, $attachments
)
) {
CRM_Core_Session::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
}
else {
CRM_Core_Session::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
}
return;
$this->sendEmail();
}
elseif ($this->_outputMode == 'print') {
echo $content;
}
else {
// Nb. Once upon a time we used a package called Open Flash Charts to
// draw charts, and we had a feature whereby a browser could send the
// server a PNG version of the chart, which could then be included in a
// PDF by including <img> tags in the HTML for the conversion below.
//
// This feature stopped working when browsers stopped supporting Flash,
// and although we have a different client-side charting library in
// place, we decided not to reimplement the (rather convoluted)
// browser-sending-rendered-chart-to-server process.
//
// If this feature is required in future we should find a better way to
// render charts on the server side, e.g. server-created SVG.
CRM_Utils_PDF_Utils::html2pdf($content, "CiviReport.pdf", FALSE, ['orientation' => 'landscape']);
elseif (!empty($this->outputHandler)) {
$this->outputHandler->download();
CRM_Utils_System::civiExit();
}
CRM_Utils_System::civiExit();
}
elseif ($this->_outputMode == 'csv') {
CRM_Report_Utils_Report::export2csv($this, $rows);
}
elseif ($this->_outputMode == 'group') {
$group = $this->_params['groups'];
$this->add2group($group);
// else we don't need to do anything here since it must have been
// outputMode=save or something like that
}
}

Expand Down Expand Up @@ -5989,4 +5955,58 @@ protected function generateFilterClause($field, $fieldName) {
return '';
}

/**
* Retrieve a suitable object from the factory depending on the report
* parameters, which typically might just be dependent on outputMode.
*
* If there is no suitable output handler, e.g. if outputMode is "copy",
* then this sets it to NULL.
*/
public function setOutputHandler() {
$this->outputHandler = \Civi\Report\OutputHandlerFactory::singleton()->create($this);
}

/**
* Send report by email
*/
public function sendEmail() {
if (empty($this->outputHandler)) {
// It's possible to end up here with outputMode unset, so we use
// the "print" handler which was the default before, i.e. include
// it as html in the body.
$oldOutputMode = $this->_outputMode ?? NULL;
$this->_outputMode = 'print';
$this->setOutputHandler();
$this->_outputMode = $oldOutputMode;
}

$mailBody = $this->outputHandler->getMailBody();

$attachments = [];
$attachmentFileName = $this->outputHandler->getFileName();
// It's not always in the form of an attachment, e.g. for 'print' the
// output ends up in $mailBody above.
if ($attachmentFileName) {
$fullFilename = CRM_Core_Config::singleton()->templateCompileDir . CRM_Utils_File::makeFileName($attachmentFileName);
file_put_contents($fullFilename, $this->outputHandler->getOutputString());
$attachments[] = [
'fullPath' => $fullFilename,
'mime_type' => $this->outputHandler->getMimeType(),
'cleanName' => $attachmentFileName,
'charset' => $this->outputHandler->getCharset(),
];
}

// Send the email
// @todo outputMode doesn't seem to get used by mailReport, which is good
// since it shouldn't have any outputMode-related `if` statements in it.
// Someday could remove the param from the function call.
if (CRM_Report_Utils_Report::mailReport($mailBody, $this->_id, $this->_outputMode, $attachments)) {
CRM_Core_Session::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
}
else {
CRM_Core_Session::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
}
}

}
105 changes: 105 additions & 0 deletions CRM/Report/OutputHandler/Csv.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
<?php
/*
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC. All rights reserved. |
| |
| This work is published under the GNU AGPLv3 license with some |
| permitted exceptions and without any warranty. For full license |
| and copyright information, see https://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/

use Civi\Report\OutputHandlerInterface;
use Civi\Report\OutputHandlerBase;

/**
* CSV Report Output Handler
*/
class CRM_Report_OutputHandler_Csv extends OutputHandlerBase implements OutputHandlerInterface {

/**
* Are we a suitable output handler based on the given form?
*
* The class member $form isn't set yet at this point since we don't
* even know if we're in play yet, so the form is a parameter.
*
* @param CRM_Report_Form $form
*
* @return bool
*/
public function isOutputHandlerFor(CRM_Report_Form $form):bool {
return ($form->getOutputMode() === 'csv');
}

/**
* Return the download filename. This should be the "clean" name, not
* a munged temporary filename.
*
* @return string
*/
public function getFileName():string {
return 'CiviReport.csv';
}

/**
* Return the html body of the email.
*
* @return string
*/
public function getMailBody():string {
// @todo It would be nice if this was more end-user configurable, but
// keeping it the same as it was before for now.
$url = CRM_Utils_System::url('civicrm/report/instance/' . $this->getForm()->getID(), 'reset=1', TRUE);
return $this->getForm()->getReportHeader() . '<p>' . ts('Report URL') .
": {$url}</p>" . '<p>' .
ts('The report is attached as a CSV file.') . '</p>' .
$this->getForm()->getReportFooter();
}

/**
* Return the report contents as a string, in this case the csv output.
*
* @return string
*/
public function getOutputString():string {
//@todo Hmm. See note in CRM_Report_Form::endPostProcess about $rows.
$rows = $this->getForm()->getTemplate()->get_template_vars('rows');

// avoid pass-by-ref warning
$form = $this->getForm();

return CRM_Report_Utils_Report::makeCsv($form, $rows);
}

/**
* Set headers as appropriate and send the output to the browser.
*/
public function download() {
//@todo Hmm. See note in CRM_Report_Form::endPostProcess about $rows.
$rows = $this->getForm()->getTemplate()->get_template_vars('rows');

// avoid pass-by-ref warning
$form = $this->getForm();

CRM_Report_Utils_Report::export2csv($form, $rows);
}

/**
* Mime type of the attachment.
*
* @return string
*/
public function getMimeType():string {
return 'text/csv';
}

/**
* Charset of the attachment.
*
* @return string
*/
public function getCharset():string {
return 'utf-8';
}

}
Loading