/** * process the form after the input has been submitted and validated * @todo this is horrible copy & paste code because there is so much risk of breakage * in fixing the existing pdfLetter classes to be suitably generic * @access public * * @param $form * @param $membershipIDs * @param $skipOnHold * @param $skipDeceased * @param $contactIDs * * @return void */ static function postProcessMembers(&$form, $membershipIDs, $skipOnHold, $skipDeceased, $contactIDs) { list($formValues, $categories, $html_message, $messageToken, $returnProperties) = self::processMessageTemplate($form); $html = self::generateHTML($membershipIDs, $returnProperties, $skipOnHold, $skipDeceased, $messageToken, $html_message, $categories); self::createActivities($form, $html_message, $contactIDs); CRM_Utils_PDF_Utils::html2pdf($html, "CiviLetter.pdf", FALSE, $formValues); $form->postProcessHook(); CRM_Utils_System::civiExit(1); }
/** * process the form after the input has been submitted and validated * * @access public * @return None */ public function postProcess() { // get all the details needed to generate a receipt $contribIDs = implode(',', $this->_contributionIds); require_once 'CRM/Contribute/Form/Task/Status.php'; $details =& CRM_Contribute_Form_Task_Status::getDetails($contribIDs); require_once 'CRM/Core/Payment/BaseIPN.php'; $baseIPN = new CRM_Core_Payment_BaseIPN(); $message = array(); $template = CRM_Core_Smarty::singleton(); $params = $this->controller->exportValues($this->_name); $createPdf = false; if ($params['output'] == "pdf_receipt") { $createPdf = true; } $excludeContactIds = array(); if (!$createPdf) { $returnProperties = array('email' => 1, 'do_not_email' => 1, 'is_deceased' => 1, 'on_hold' => 1); require_once 'CRM/Mailing/BAO/Mailing.php'; list($contactDetails) = CRM_Mailing_BAO_Mailing::getDetails($this->_contactIds, $returnProperties, false, false); foreach ($contactDetails as $id => $values) { if (empty($values['email']) || CRM_Utils_Array::value('do_not_email', $values) || CRM_Utils_Array::value('is_deceased', $values) || CRM_Utils_Array::value('on_hold', $values)) { $suppressedEmails++; $excludeContactIds[] = $values['contact_id']; } } } foreach ($details as $contribID => $detail) { $input = $ids = $objects = array(); if (in_array($detail['contact'], $excludeContactIds)) { continue; } $input['component'] = $detail['component']; $ids['contact'] = $detail['contact']; $ids['contribution'] = $contribID; $ids['contributionRecur'] = null; $ids['contributionPage'] = null; $ids['membership'] = $detail['membership']; $ids['participant'] = $detail['participant']; $ids['event'] = $detail['event']; if (!$baseIPN->validateData($input, $ids, $objects, false)) { CRM_Core_Error::fatal(); } $contribution =& $objects['contribution']; // CRM_Core_Error::debug('o',$objects); // set some fake input values so we can reuse IPN code $input['amount'] = $contribution->total_amount; $input['is_test'] = $contribution->is_test; $input['fee_amount'] = $contribution->fee_amount; $input['net_amount'] = $contribution->net_amount; $input['trxn_id'] = $contribution->trxn_id; $input['trxn_date'] = isset($contribution->trxn_date) ? $contribution->trxn_date : null; // CRM_Core_Error::debug('input',$input); $values = array(); $mail = $baseIPN->sendMail($input, $ids, $objects, $values, false, $createPdf); if (!$mail['html']) { $mail = str_replace("\n\n", "<p>", $mail); $mail = str_replace("\n", "<br/>", $mail); } $message[] = $mail; // reset template values before processing next transactions $template->clearTemplateVars(); } if ($createPdf) { require_once 'CRM/Utils/PDF/Utils.php'; CRM_Utils_PDF_Utils::domlib($message, 'civicrmContributionReceipt.pdf', false, 'portrait', 'letter'); CRM_Utils_System::civiExit(); } else { if ($suppressedEmails) { $status = array('', ts('Email was NOT sent to %1 contacts (no email address on file, or communication preferences specify DO NOT EMAIL, or contact is deceased).', array(1 => $suppressedEmails))); } else { $status = array('', ts('Your mail has been sent.')); } CRM_Core_Session::setStatus($status); } }
/** * Retrieve DB object based on input parameters. * * It also stores all the retrieved values in the default array. * * @param array $params * (reference ) an assoc array of name/value pairs. * @param array $values * (reference ) an assoc array to hold the flattened values. * * @return CRM_Core_DAO_OptionValue */ public static function retrieve(&$params, &$values) { $optionValue = new CRM_Core_DAO_OptionValue(); $optionValue->copyValues($params); $optionValue->option_group_id = self::_getGid(); if ($optionValue->find(TRUE)) { // Extract fields that have been serialized in the 'value' column of the Option Value table. $values = json_decode($optionValue->value, TRUE); // Add any new fields that don't yet exist in the saved values. foreach (self::$optionValueFields as $name => $field) { if (!isset($values[$name])) { $values[$name] = $field['default']; if (isset($field['metric']) && $field['metric']) { $values[$name] = CRM_Utils_PDF_Utils::convertMetric($field['default'], self::$optionValueFields['metric']['default'], $values['metric'], 3); } } } // Add fields from the OptionValue base class CRM_Core_DAO::storeValues($optionValue, $values); return $optionValue; } return NULL; }
/** * End post processing. * * @param array|null $rows */ public function endPostProcess(&$rows = NULL) { if ($this->_storeResultSet) { $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); if ($this->_sendmail) { $config = CRM_Core_Config::singleton(); $attachments = array(); 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[] = array('fullPath' => $csvFullFilename, 'mime_type' => 'text/csv', 'cleanName' => 'CiviReport.csv'); } 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, array('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[] = array('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 TRUE; } elseif ($this->_outputMode == 'print') { echo $content; } else { if ($chartType = CRM_Utils_Array::value('charts', $this->_params)) { $config = CRM_Core_Config::singleton(); //get chart image name $chartImg = $this->_chartId . '.png'; //get image url path $uploadUrl = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL) . 'openFlashChart/'; $uploadUrl .= $chartImg; //get image doc path to overwrite $uploadImg = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir) . 'openFlashChart/' . $chartImg; //Load the image $chart = imagecreatefrompng($uploadUrl); //convert it into formatted png CRM_Utils_System::setHttpHeader('Content-type', 'image/png'); //overwrite with same image imagepng($chart, $uploadImg); //delete the object imagedestroy($chart); } CRM_Utils_PDF_Utils::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape')); } 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); } }
/** * Process the PDf and email with activity and attachment. * on click of Print Invoices * * @param array $contribIDs * Contribution Id. * @param array $params * Associated array of submitted values. * @param array $contactIds * Contact Id. * @param CRM_Core_Form $form * Form object. */ public static function printPDF($contribIDs, &$params, $contactIds, &$form) { // get all the details needed to generate a invoice $messageInvoice = array(); $invoiceTemplate = CRM_Core_Smarty::singleton(); $invoiceElements = CRM_Contribute_Form_Task_PDF::getElements($contribIDs, $params, $contactIds); // gives the status id when contribution status is 'Refunded' $contributionStatusID = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); $refundedStatusId = CRM_Utils_Array::key('Refunded', $contributionStatusID); // getting data from admin page $prefixValue = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings'); foreach ($invoiceElements['details'] as $contribID => $detail) { $input = $ids = $objects = array(); if (in_array($detail['contact'], $invoiceElements['excludeContactIds'])) { continue; } $input['component'] = $detail['component']; $ids['contact'] = $detail['contact']; $ids['contribution'] = $contribID; $ids['contributionRecur'] = NULL; $ids['contributionPage'] = NULL; $ids['membership'] = CRM_Utils_Array::value('membership', $detail); $ids['participant'] = CRM_Utils_Array::value('participant', $detail); $ids['event'] = CRM_Utils_Array::value('event', $detail); if (!$invoiceElements['baseIPN']->validateData($input, $ids, $objects, FALSE)) { CRM_Core_Error::fatal(); } $contribution =& $objects['contribution']; $input['amount'] = $contribution->total_amount; $input['invoice_id'] = $contribution->invoice_id; $input['receive_date'] = $contribution->receive_date; $input['contribution_status_id'] = $contribution->contribution_status_id; $input['organization_name'] = $contribution->_relatedObjects['contact']->organization_name; $objects['contribution']->receive_date = CRM_Utils_Date::isoToMysql($objects['contribution']->receive_date); $addressParams = array('contact_id' => $contribution->contact_id); $addressDetails = CRM_Core_BAO_Address::getValues($addressParams); // to get billing address if present $billingAddress = array(); foreach ($addressDetails as $key => $address) { if (isset($address['is_billing']) && $address['is_billing'] == 1 && (isset($address['is_primary']) && $address['is_primary'] == 1) && $address['contact_id'] == $contribution->contact_id) { $billingAddress[$address['contact_id']] = $address; break; } elseif ($address['is_billing'] == 0 && $address['is_primary'] == 1 || isset($address['is_billing']) && $address['is_billing'] == 1 && $address['contact_id'] == $contribution->contact_id) { $billingAddress[$address['contact_id']] = $address; } } if (!empty($billingAddress[$contribution->contact_id]['state_province_id'])) { $stateProvinceAbbreviation = CRM_Core_PseudoConstant::stateProvinceAbbreviation($billingAddress[$contribution->contact_id]['state_province_id']); } else { $stateProvinceAbbreviation = ''; } if ($contribution->contribution_status_id == $refundedStatusId) { $creditNoteId = CRM_Utils_Array::value('credit_notes_prefix', $prefixValue) . "" . $contribution->id; } $invoiceId = CRM_Utils_Array::value('invoice_prefix', $prefixValue) . "" . $contribution->id; //to obtain due date for PDF invoice $contributionReceiveDate = date('F j,Y', strtotime(date($input['receive_date']))); $invoiceDate = date("F j, Y"); $dueDate = date('F j ,Y', strtotime($contributionReceiveDate . "+" . $prefixValue['due_date'] . "" . $prefixValue['due_date_period'])); if ($input['component'] == 'contribute') { $eid = $contribID; $etable = 'contribution'; $lineItem = CRM_Price_BAO_LineItem::getLineItems($eid, $etable, NULL, TRUE, TRUE); } else { $eid = $contribution->_relatedObjects['participant']->id; $etable = 'participant'; $lineItem = CRM_Price_BAO_LineItem::getLineItems($eid, $etable); } //TO DO: Need to do changes for partially paid to display amount due on PDF invoice $amountDue = $input['amount'] - $input['amount']; // retreiving the subtotal and sum of same tax_rate $dataArray = array(); $subTotal = 0; foreach ($lineItem as $entity_id => $taxRate) { if (isset($dataArray[(string) $taxRate['tax_rate']])) { $dataArray[(string) $taxRate['tax_rate']] = $dataArray[(string) $taxRate['tax_rate']] + CRM_Utils_Array::value('tax_amount', $taxRate); } else { $dataArray[(string) $taxRate['tax_rate']] = CRM_Utils_Array::value('tax_amount', $taxRate); } $subTotal += CRM_Utils_Array::value('subTotal', $taxRate); } // to email the invoice $mailDetails = array(); $values = array(); if ($contribution->_component == 'event') { $daoName = 'CRM_Event_DAO_Event'; $pageId = $contribution->_relatedObjects['event']->id; $mailElements = array('title', 'confirm_from_name', 'confirm_from_email', 'cc_confirm', 'bcc_confirm'); CRM_Core_DAO::commonRetrieveAll($daoName, 'id', $pageId, $mailDetails, $mailElements); $values['title'] = CRM_Utils_Array::value('title', $mailDetails[$contribution->_relatedObjects['event']->id]); $values['confirm_from_name'] = CRM_Utils_Array::value('confirm_from_name', $mailDetails[$contribution->_relatedObjects['event']->id]); $values['confirm_from_email'] = CRM_Utils_Array::value('confirm_from_email', $mailDetails[$contribution->_relatedObjects['event']->id]); $values['cc_confirm'] = CRM_Utils_Array::value('cc_confirm', $mailDetails[$contribution->_relatedObjects['event']->id]); $values['bcc_confirm'] = CRM_Utils_Array::value('bcc_confirm', $mailDetails[$contribution->_relatedObjects['event']->id]); $title = CRM_Utils_Array::value('title', $mailDetails[$contribution->_relatedObjects['event']->id]); } elseif ($contribution->_component == 'contribute') { $daoName = 'CRM_Contribute_DAO_ContributionPage'; $pageId = $contribution->contribution_page_id; $mailElements = array('title', 'receipt_from_name', 'receipt_from_email', 'cc_receipt', 'bcc_receipt'); CRM_Core_DAO::commonRetrieveAll($daoName, 'id', $pageId, $mailDetails, $mailElements); $values['title'] = CRM_Utils_Array::value('title', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails)); $values['receipt_from_name'] = CRM_Utils_Array::value('receipt_from_name', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails)); $values['receipt_from_email'] = CRM_Utils_Array::value('receipt_from_email', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails)); $values['cc_receipt'] = CRM_Utils_Array::value('cc_receipt', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails)); $values['bcc_receipt'] = CRM_Utils_Array::value('bcc_receipt', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails)); $title = CRM_Utils_Array::value('title', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails)); } $source = $contribution->source; $config = CRM_Core_Config::singleton(); if (!isset($params['forPage'])) { $config->doNotAttachPDFReceipt = 1; } // get organization address $domain = CRM_Core_BAO_Domain::getDomain(); $locParams = array('contact_id' => $domain->id); $locationDefaults = CRM_Core_BAO_Location::getValues($locParams); if (isset($locationDefaults['address'][1]['state_province_id'])) { $stateProvinceAbbreviationDomain = CRM_Core_PseudoConstant::stateProvinceAbbreviation($locationDefaults['address'][1]['state_province_id']); } else { $stateProvinceAbbreviationDomain = ''; } if (isset($locationDefaults['address'][1]['country_id'])) { $countryDomain = CRM_Core_PseudoConstant::country($locationDefaults['address'][1]['country_id']); } else { $countryDomain = ''; } // parameters to be assign for template $tplParams = array('title' => $title, 'component' => $input['component'], 'id' => $contribution->id, 'source' => $source, 'invoice_id' => $invoiceId, 'resourceBase' => $config->userFrameworkResourceURL, 'defaultCurrency' => $config->defaultCurrency, 'amount' => $contribution->total_amount, 'amountDue' => $amountDue, 'invoice_date' => $invoiceDate, 'dueDate' => $dueDate, 'notes' => CRM_Utils_Array::value('notes', $prefixValue), 'display_name' => $contribution->_relatedObjects['contact']->display_name, 'lineItem' => $lineItem, 'dataArray' => $dataArray, 'refundedStatusId' => $refundedStatusId, 'contribution_status_id' => $contribution->contribution_status_id, 'subTotal' => $subTotal, 'street_address' => CRM_Utils_Array::value('street_address', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)), 'supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)), 'supplemental_address_2' => CRM_Utils_Array::value('supplemental_address_2', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)), 'city' => CRM_Utils_Array::value('city', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)), 'stateProvinceAbbreviation' => $stateProvinceAbbreviation, 'postal_code' => CRM_Utils_Array::value('postal_code', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)), 'is_pay_later' => $contribution->is_pay_later, 'organization_name' => $contribution->_relatedObjects['contact']->organization_name, 'domain_organization' => $domain->name, 'domain_street_address' => CRM_Utils_Array::value('street_address', CRM_Utils_Array::value('1', $locationDefaults['address'])), 'domain_supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1', CRM_Utils_Array::value('1', $locationDefaults['address'])), 'domain_supplemental_address_2' => CRM_Utils_Array::value('supplemental_address_2', CRM_Utils_Array::value('1', $locationDefaults['address'])), 'domain_city' => CRM_Utils_Array::value('city', CRM_Utils_Array::value('1', $locationDefaults['address'])), 'domain_postal_code' => CRM_Utils_Array::value('postal_code', CRM_Utils_Array::value('1', $locationDefaults['address'])), 'domain_state' => $stateProvinceAbbreviationDomain, 'domain_country' => $countryDomain, 'domain_email' => CRM_Utils_Array::value('email', CRM_Utils_Array::value('1', $locationDefaults['email'])), 'domain_phone' => CRM_Utils_Array::value('phone', CRM_Utils_Array::value('1', $locationDefaults['phone']))); if (isset($creditNoteId)) { $tplParams['creditnote_id'] = $creditNoteId; } $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_contribution', 'valueName' => 'contribution_invoice_receipt', 'contactId' => $contribution->contact_id, 'tplParams' => $tplParams, 'PDFFilename' => 'Invoice.pdf'); $session = CRM_Core_Session::singleton(); $contactID = $session->get('userID'); //CRM-16319 - we dont store in userID in case the user is doing multiple //transactions etc if (empty($contactID)) { $contactID = $session->get('transaction.userID'); } $contactEmails = CRM_Core_BAO_Email::allEmails($contactID); $emails = array(); $fromDisplayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'display_name'); foreach ($contactEmails as $emailId => $item) { $email = $item['email']; if ($email) { $emails[$emailId] = '"' . $fromDisplayName . '" <' . $email . '> '; } } $fromEmail = CRM_Utils_Array::crmArrayMerge($emails, CRM_Core_OptionGroup::values('from_email_address')); // from email address if (isset($params['from_email_address'])) { $fromEmailAddress = CRM_Utils_Array::value($params['from_email_address'], $fromEmail); } // condition to check for download PDF Invoice or email Invoice if ($invoiceElements['createPdf']) { list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams); if (isset($params['forPage'])) { return $html; } else { $mail = array('subject' => $subject, 'body' => $message, 'html' => $html); if ($mail['html']) { $messageInvoice[] = $mail['html']; } else { $messageInvoice[] = nl2br($mail['body']); } } } elseif ($contribution->_component == 'contribute') { $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contribution->contact_id); $sendTemplateParams['tplParams'] = array_merge($tplParams, array('email_comment' => $invoiceElements['params']['email_comment'])); $sendTemplateParams['from'] = $fromEmailAddress; $sendTemplateParams['toEmail'] = $email; $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_receipt', $values); $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_receipt', $values); list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams); // functions call for adding activity with attachment $fileName = self::putFile($html); self::addActivities($subject, $contribution->contact_id, $fileName, $params); } elseif ($contribution->_component == 'event') { $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contribution->contact_id); $sendTemplateParams['tplParams'] = array_merge($tplParams, array('email_comment' => $invoiceElements['params']['email_comment'])); $sendTemplateParams['from'] = $fromEmailAddress; $sendTemplateParams['toEmail'] = $email; $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_confirm', $values); $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_confirm', $values); list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams); // functions call for adding activity with attachment $fileName = self::putFile($html); self::addActivities($subject, $contribution->contact_id, $fileName, $params); } CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contribution->id, 'invoice_id', $invoiceId); if ($contribution->contribution_status_id == $refundedStatusId) { CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contribution->id, 'creditnote_id', $creditNoteId); } $invoiceTemplate->clearTemplateVars(); } if ($invoiceElements['createPdf']) { if (isset($params['forPage'])) { return $html; } else { CRM_Utils_PDF_Utils::html2pdf($messageInvoice, 'Invoice.pdf', FALSE, array('margin_top' => 10, 'margin_left' => 65, 'metric' => 'px')); // functions call for adding activity with attachment $fileName = self::putFile($html); self::addActivities($subject, $contactIds, $fileName, $params); CRM_Utils_System::civiExit(); } } else { if ($invoiceElements['suppressedEmails']) { $status = ts('Email was NOT sent to %1 contacts (no email address on file, or communication preferences specify DO NOT EMAIL, or contact is deceased).', array(1 => $invoiceElements['suppressedEmails'])); $msgTitle = ts('Email Error'); $msgType = 'error'; } else { $status = ts('Your mail has been sent.'); $msgTitle = ts('Sent'); $msgType = 'success'; } CRM_Core_Session::setStatus($status, $msgTitle, $msgType); } }
/** * render the page using a custom templating * system * * @param object $page the CRM_Core_Form page * @param boolean $ret should we echo or return output * * @return void * @access public */ function renderForm(&$page) { $this->_setRenderTemplates($page); $template = CRM_Core_Smarty::singleton(); $form = $page->toSmarty(); $json = CRM_Utils_Request::retrieve('json', 'Boolean', CRM_Core_DAO::$_nullObject); if ($json) { CRM_Utils_JSON::output($form); } $template->assign('form', $form); $template->assign('isForm', 1); $controller =& $page->controller; if ($controller->getEmbedded()) { return; } $template->assign('action', $page->getAction()); $pageTemplateFile = $page->getHookedTemplateFileName(); $template->assign('tplFile', $pageTemplateFile); $content = $template->fetch($controller->getTemplateFile()); if (!defined('CIVICRM_UF_HEAD') && ($region = CRM_Core_Region::instance('html-header', FALSE))) { CRM_Utils_System::addHTMLHead($region->render('')); } CRM_Utils_System::appendTPLFile($pageTemplateFile, $content, $page->overrideExtraTemplateFileName()); //its time to call the hook. CRM_Utils_Hook::alterContent($content, 'form', $pageTemplateFile, $page); $print = $controller->getPrint(); if ($print) { $html =& $content; } else { $html = CRM_Utils_System::theme($content, $print); } if ($controller->_QFResponseType == 'json') { $response = array('content' => $html); // CRM-11831 @see http://www.malsup.com/jquery/form/#file-upload $xhr = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'; if (!$xhr) { echo '<textarea>'; } echo json_encode($response); if (!$xhr) { echo '</textarea>'; } CRM_Utils_System::civiExit(); } if ($print) { if ($print == CRM_Core_Smarty::PRINT_PDF) { CRM_Utils_PDF_Utils::html2pdf($content, "{$page->_name}.pdf", FALSE, array('paper_size' => 'a3', 'orientation' => 'landscape')); } else { echo $html; } CRM_Utils_System::civiExit(); } print $html; }
/** * initialize label format settings. * * @param $format * @param $unit */ public function LabelSetFormat(&$format, $unit) { $this->defaults = CRM_Core_BAO_LabelFormat::getDefaultValues(); $this->format =& $format; $this->formatName = $this->getFormatValue('name'); $this->paperSize = $this->getFormatValue('paper-size'); $this->orientation = $this->getFormatValue('orientation'); $this->fontName = $this->getFormatValue('font-name'); $this->charSize = $this->getFormatValue('font-size'); $this->fontStyle = $this->getFormatValue('font-style'); $this->xNumber = $this->getFormatValue('NX'); $this->yNumber = $this->getFormatValue('NY'); $this->metricDoc = $unit; $this->marginLeft = $this->getFormatValue('lMargin', TRUE); $this->marginTop = $this->getFormatValue('tMargin', TRUE); $this->xSpace = $this->getFormatValue('SpaceX', TRUE); $this->ySpace = $this->getFormatValue('SpaceY', TRUE); $this->width = $this->getFormatValue('width', TRUE); $this->height = $this->getFormatValue('height', TRUE); $this->paddingLeft = $this->getFormatValue('lPadding', TRUE); $this->paddingTop = $this->getFormatValue('tPadding', TRUE); $paperSize = CRM_Core_BAO_PaperSize::getByName($this->paperSize); $w = CRM_Utils_PDF_Utils::convertMetric($paperSize['width'], $paperSize['metric'], $this->metricDoc); $h = CRM_Utils_PDF_Utils::convertMetric($paperSize['height'], $paperSize['metric'], $this->metricDoc); $this->paper_dimensions = array($w, $h); }
function endPostProcess(&$rows = null) { if ($this->_outputMode == 'print' || $this->_outputMode == 'pdf' || $this->_sendmail) { $templateFile = parent::getTemplateFileName(); $content = $this->_formValues['report_header'] . CRM_Core_Form::$_template->fetch($templateFile) . $this->_formValues['report_footer']; if ($this->_sendmail) { if (CRM_Report_Utils_Report::mailReport($content, $this->_id, $this->_outputMode)) { CRM_Core_Session::setStatus(ts("Report mail has been sent.")); } else { CRM_Core_Session::setStatus(ts("Report mail could not be sent.")); } if ($this->get('instanceId')) { exit; } CRM_Utils_System::redirect(CRM_Utils_System::url(CRM_Utils_System::currentPath(), 'reset=1')); } else { if ($this->_outputMode == 'print') { echo $content; } else { require_once 'CRM/Utils/PDF/Utils.php'; CRM_Utils_PDF_Utils::html2pdf($content, "CiviReport.pdf"); } } exit; } else { if ($this->_outputMode == 'csv') { CRM_Report_Utils_Report::export2csv($this, $rows); } else { if ($this->_outputMode == 'group') { $group = $this->_params['groups']; CRM_Report_Utils_Report::add2group($this, $group); } else { if ($this->_instanceButtonName == $this->controller->getButtonName()) { require_once 'CRM/Report/Form/Instance.php'; CRM_Report_Form_Instance::postProcess($this); } } } } }
/** * process the form after the input has been submitted and validated * * @access public * @return None */ static function postProcess(&$form) { $formValues = $form->controller->exportValues($form->getName()); // process message template require_once 'CRM/Core/BAO/MessageTemplates.php'; if (CRM_Utils_Array::value('saveTemplate', $formValues) || CRM_Utils_Array::value('updateTemplate', $formValues)) { $messageTemplate = array('msg_text' => NULL, 'msg_html' => $formValues['html_message'], 'msg_subject' => NULL, 'is_active' => true); if ($formValues['saveTemplate']) { $messageTemplate['msg_title'] = $formValues['saveTemplateName']; CRM_Core_BAO_MessageTemplates::add($messageTemplate); } if ($formValues['template'] && $formValues['updateTemplate']) { $messageTemplate['id'] = $formValues['template']; unset($messageTemplate['msg_title']); CRM_Core_BAO_MessageTemplates::add($messageTemplate); } } require_once 'dompdf/dompdf_config.inc.php'; $html = '<html><head><style>body { margin: 56px; }</style></head><body>'; require_once 'api/v2/Contact.php'; require_once 'CRM/Utils/Token.php'; $tokens = array(); CRM_Utils_Hook::tokens($tokens); $categories = array_keys($tokens); $html_message = $formValues['html_message']; require_once 'CRM/Activity/BAO/Activity.php'; $messageToken = CRM_Activity_BAO_Activity::getTokens($html_message); $returnProperties = array(); if (isset($messageToken['contact'])) { foreach ($messageToken['contact'] as $key => $value) { $returnProperties[$value] = 1; } } require_once 'CRM/Mailing/BAO/Mailing.php'; $mailing =& new CRM_Mailing_BAO_Mailing(); $first = TRUE; foreach ($form->_contactIds as $item => $contactId) { $params = array('contact_id' => $contactId); list($contact) = $mailing->getDetails($params, $returnProperties, false); if (civicrm_error($contact)) { $notSent[] = $contactId; continue; } $tokenHtml = CRM_Utils_Token::replaceContactTokens($html_message, $contact[$contactId], true, $messageToken); $tokenHtml = CRM_Utils_Token::replaceHookTokens($tokenHtml, $contact[$contactId], $categories, true); if ($first == TRUE) { $first = FALSE; $html .= $tokenHtml; } else { $html .= "<div STYLE='page-break-after: always'></div>{$tokenHtml}"; } } $html .= '</body></html>'; require_once 'CRM/Utils/PDF/Utils.php'; CRM_Utils_PDF_Utils::html2pdf($html, "CiviLetter.pdf", 'portrait'); exit(1); }
/** * process the form after the input has been submitted and validated * * @access public * @return None */ public function postProcess() { // get all the details needed to generate a receipt $contribIDs = implode(',', $this->_contributionIds); require_once 'CRM/Contribute/Form/Task/Status.php'; $details =& CRM_Contribute_Form_Task_Status::getDetails($contribIDs); require_once 'CRM/Core/Payment/BaseIPN.php'; $baseIPN = new CRM_Core_Payment_BaseIPN(); $message = array(); $template =& CRM_Core_Smarty::singleton(); foreach ($details as $contribID => $detail) { $input = $ids = $objects = array(); $input['component'] = $detail['component']; $ids['contact'] = $detail['contact']; $ids['contribution'] = $contribID; $ids['contributionRecur'] = null; $ids['contributionPage'] = null; $ids['membership'] = $detail['membership']; $ids['participant'] = $detail['participant']; $ids['event'] = $detail['event']; if (!$baseIPN->validateData($input, $ids, $objects, false)) { CRM_Core_Error::fatal(); } $contribution =& $objects['contribution']; // CRM_Core_Error::debug('o',$objects); // set some fake input values so we can reuse IPN code $input['amount'] = $contribution->total_amount; $input['is_test'] = $contribution->is_test; $input['fee_amount'] = $contribution->fee_amount; $input['net_amount'] = $contribution->net_amount; $input['trxn_id'] = $contribution->trxn_id; $input['trxn_date'] = isset($contribution->trxn_date) ? $contribution->trxn_date : null; // CRM_Core_Error::debug('input',$input); $values = array(); $mail = $baseIPN->sendMail($input, $ids, $objects, $values, false, true); $mail = str_replace("\n\n", "<p>", $mail); $mail = str_replace("\n", "<br/>", $mail); $message[] = $mail; // reset template values before processing next transactions $template->clearTemplateVars(); } require_once 'CRM/Utils/PDF/Utils.php'; CRM_Utils_PDF_Utils::domlib($message, "civicrmContributionReceipt.pdf"); exit; }
function render_beleg_pdf($contact_id, $address, $total, $items, $from_date, $to_date, $comment) { global $civicrm_root; $docs = get_docs_table(); $config = CRM_Core_Config::singleton(true, true); /* If receipts already exist for a date range overlapping the requested range, readjust the from date for the new receipt to follow the lastest date for which receipts were already generated. */ $query = "SELECT GREATEST(MAX(DATE_ADD({$docs['field_to']}, INTERVAL 1 DAY)), '{$from_date}' ) AS from_date\n FROM {$docs['table']}\n WHERE entity_id = {$contact_id}\n AND {$docs['field_from']} < '{$to_date}' -- Ignore existing receipts for a date range beginning after the end of the requested range.\n "; $from_ts = strtotime($from_date); $to_ts = strtotime($to_date); $res = CRM_Core_DAO::executeQuery($query); $res->fetch(); if ($res->from_date) { $from_date = $res->from_date; } $from_ts = strtotime($from_date); $to_ts = strtotime($to_date); $template = CRM_Core_Smarty::singleton(); list($html, $page_format) = get_template(); // select and set up template type if (count($items) > 1) { // more than one payment -> "Sammelbescheinigung" with itemized list $item_table = array(); foreach ($items as $item) { $item_table[] = array('date' => date("j.n.Y", strtotime($item["date"])), 'art' => $item["art"], 'amount' => number_format($item["amount"], 2, ',', '.'), 'amounttext' => num_to_text($item["amount"])); } $template->assign("items", $item_table); } else { // one payment only -> "Einzelbescheinigung" $template->assign("items", null); /* When generating multiple receipts in a batch (Jahresbescheinigungen), the smarty object is reused between the individual receipts (singleton) -- so need to reset this explicitly! */ $template->assign("date", date("d.m.Y", strtotime($items[0]["date"]))); } // fill further template fields if (date("m-d", $from_ts) == "01-01" && date("m-d", $to_ts) == "12-31") { $daterange = date("Y", $from_ts); } else { $daterange = date("j.n.", $from_ts) . " bis " . date("j.n.Y", $to_ts); } $template->assign("daterange", $daterange); $template->assign("donor", $address); $template->assign("total", number_format($total, 2, ',', '.')); $template->assign("totaltext", num_to_text($total)); $template->assign("today", date("j.n.Y", time())); if (date("m-d", $from_ts) == "01-01" && date("m-d", $to_ts) == "12-31") { $rangespec = date("Y", $from_ts); } else { $rangespec = date("Y-m-d", $from_ts) . "_" . date("m-d", $to_ts); } $domain = CRM_Core_BAO_Domain::getDomain(); $domain_tokens = array(); foreach (array('name', 'address') as $token) { $domain_tokens[$token] = CRM_Utils_Token::getDomainTokenReplacement($token, $domain, true, true); } $domain_tokens['address'] = str_replace('> <', '> <', $domain_tokens['address']); /* Hack to work around (yet another) bug in dompdf... */ $template->assign('organisation', $domain_tokens); $html = $template->fetch("string:{$html}"); // set up file names $basename = CRM_Utils_File::makeFileName("Zuwendungen_" . $rangespec . "_" . $contact_id . ".pdf"); $outfile = $config->customFileUploadDir; $outfile .= "/{$basename}"; // render PDF receipt file_put_contents($outfile, CRM_Utils_PDF_Utils::html2pdf($html, null, true, $page_format)); $file_id = saveDocument($contact_id, $basename, "application/pdf", "Spendenbescheinigung", date("Y-m-d h:i:s"), $from_date, $to_date, $comment); // return summary data and CiviCRM URL to generated file return array("contact_id" => $contact_id, "file_id" => $file_id, "from_date" => $from_date, "to_date" => $to_date, "total_amount" => $total, "filename" => "{$basename}", "url" => CRM_Utils_System::url("civicrm/file", "reset=1&id={$file_id}&eid={$contact_id}")); }
/** * @param $value * @param $metric * @return int */ public static function toTwip($value, $metric) { $point = CRM_Utils_PDF_Utils::convertMetric($value, $metric, 'pt'); return \PhpOffice\PhpWord\Shared\Converter::pointToTwip($point); }
/** * Process the form after the input has been submitted and validated. */ public function postProcess() { // get all the details needed to generate a receipt $message = array(); $template = CRM_Core_Smarty::singleton(); $params = $this->controller->exportValues($this->_name); $elements = self::getElements($this->_contributionIds, $params, $this->_contactIds); foreach ($elements['details'] as $contribID => $detail) { $input = $ids = $objects = array(); if (in_array($detail['contact'], $elements['excludeContactIds'])) { continue; } $input['component'] = $detail['component']; $ids['contact'] = $detail['contact']; $ids['contribution'] = $contribID; $ids['contributionRecur'] = NULL; $ids['contributionPage'] = NULL; $ids['membership'] = CRM_Utils_Array::value('membership', $detail); $ids['participant'] = CRM_Utils_Array::value('participant', $detail); $ids['event'] = CRM_Utils_Array::value('event', $detail); if (!$elements['baseIPN']->validateData($input, $ids, $objects, FALSE)) { CRM_Core_Error::fatal(); } $contribution =& $objects['contribution']; // set some fake input values so we can reuse IPN code $input['amount'] = $contribution->total_amount; $input['is_test'] = $contribution->is_test; $input['fee_amount'] = $contribution->fee_amount; $input['net_amount'] = $contribution->net_amount; $input['trxn_id'] = $contribution->trxn_id; $input['trxn_date'] = isset($contribution->trxn_date) ? $contribution->trxn_date : NULL; $input['receipt_update'] = $params['receipt_update']; $input['contribution_status_id'] = $contribution->contribution_status_id; $input['paymentProcessor'] = empty($contribution->trxn_id) ? NULL : CRM_Core_DAO::singleValueQuery("SELECT payment_processor_id\n FROM civicrm_financial_trxn\n WHERE trxn_id = %1\n LIMIT 1", array(1 => array($contribution->trxn_id, 'String'))); // CRM_Contribute_BAO_Contribution::composeMessageArray expects mysql formatted date $objects['contribution']->receive_date = CRM_Utils_Date::isoToMysql($objects['contribution']->receive_date); $values = array(); if (isset($params['fromEmailAddress']) && !$elements['createPdf']) { // CRM-19129 Allow useres the choice of From Email to send the receipt from. $fromEmail = $params['fromEmailAddress']; $from = CRM_Utils_Array::value($fromEmail, $this->_emails); $fromDetails = explode(' <', $from); $input['receipt_from_email'] = substr(trim($fromDetails[1]), 0, -1); $input['receipt_from_name'] = str_replace('"', '', $fromDetails[0]); } $mail = CRM_Contribute_BAO_Contribution::sendMail($input, $ids, $objects['contribution']->id, $values, FALSE, $elements['createPdf']); if ($mail['html']) { $message[] = $mail['html']; } else { $message[] = nl2br($mail['body']); } // reset template values before processing next transactions $template->clearTemplateVars(); } if ($elements['createPdf']) { CRM_Utils_PDF_Utils::html2pdf($message, 'civicrmContributionReceipt.pdf', FALSE, $elements['params']['pdf_format_id']); CRM_Utils_System::civiExit(); } else { if ($elements['suppressedEmails']) { $status = ts('Email was NOT sent to %1 contacts (no email address on file, or communication preferences specify DO NOT EMAIL, or contact is deceased).', array(1 => $elements['suppressedEmails'])); $msgTitle = ts('Email Error'); $msgType = 'error'; } else { $status = ts('Your mail has been sent.'); $msgTitle = ts('Sent'); $msgType = 'success'; } CRM_Core_Session::setStatus($status, $msgTitle, $msgType); } }
/** * Send an email from the specified template based on an array of params * * @param array $params a string-keyed array of function params, see function body for details * * @return array of four parameters: a boolean whether the email was sent, and the subject, text and HTML templates */ static function sendTemplate($params) { $defaults = array('groupName' => NULL, 'valueName' => NULL, 'messageTemplateID' => NULL, 'contactId' => NULL, 'tplParams' => array(), 'from' => NULL, 'toName' => NULL, 'toEmail' => NULL, 'cc' => NULL, 'bcc' => NULL, 'replyTo' => NULL, 'attachments' => NULL, 'isTest' => FALSE, 'PDFFilename' => NULL); $params = array_merge($defaults, $params); if ((!$params['groupName'] || !$params['valueName']) && !$params['messageTemplateID']) { CRM_Core_Error::fatal(ts("Message template's option group and/or option value or ID missing.")); } if ($params['messageTemplateID']) { // fetch the three elements from the db based on id $query = 'SELECT msg_subject subject, msg_text text, msg_html html, pdf_format_id format FROM civicrm_msg_template mt WHERE mt.id = %1 AND mt.is_default = 1'; $sqlParams = array(1 => array($params['messageTemplateID'], 'String')); } else { // fetch the three elements from the db based on option_group and option_value names $query = 'SELECT msg_subject subject, msg_text text, msg_html html, pdf_format_id format FROM civicrm_msg_template mt JOIN civicrm_option_value ov ON workflow_id = ov.id JOIN civicrm_option_group og ON ov.option_group_id = og.id WHERE og.name = %1 AND ov.name = %2 AND mt.is_default = 1'; $sqlParams = array(1 => array($params['groupName'], 'String'), 2 => array($params['valueName'], 'String')); } $dao = CRM_Core_DAO::executeQuery($query, $sqlParams); $dao->fetch(); if (!$dao->N) { if ($params['messageTemplateID']) { CRM_Core_Error::fatal(ts('No such message template: id=%1.', array(1 => $params['messageTemplateID']))); } else { CRM_Core_Error::fatal(ts('No such message template: option group %1, option value %2.', array(1 => $params['groupName'], 2 => $params['valueName']))); } } $subject = $dao->subject; $text = $dao->text; $html = $dao->html; $format = $dao->format; $dao->free(); // add the test banner (if requested) if ($params['isTest']) { $query = "SELECT msg_subject subject, msg_text text, msg_html html\n FROM civicrm_msg_template mt\n JOIN civicrm_option_value ov ON workflow_id = ov.id\n JOIN civicrm_option_group og ON ov.option_group_id = og.id\n WHERE og.name = 'msg_tpl_workflow_meta' AND ov.name = 'test_preview' AND mt.is_default = 1"; $testDao = CRM_Core_DAO::executeQuery($query); $testDao->fetch(); $subject = $testDao->subject . $subject; $text = $testDao->text . $text; $html = preg_replace('/<body(.*)$/im', "<body\\1\n{$testDao->html}", $html); $testDao->free(); } // replace tokens in the three elements (in subject as if it was the text body) $domain = CRM_Core_BAO_Domain::getDomain(); $hookTokens = array(); $mailing = new CRM_Mailing_BAO_Mailing(); $mailing->body_text = $text; $mailing->body_html = $html; $tokens = $mailing->getTokens(); CRM_Utils_Hook::tokens($hookTokens); $categories = array_keys($hookTokens); $contactID = CRM_Utils_Array::value('contactId', $params); if ($contactID) { $contactParams = array('contact_id' => $contactID); $returnProperties = array(); if (isset($tokens['text']['contact'])) { foreach ($tokens['text']['contact'] as $name) { $returnProperties[$name] = 1; } } if (isset($tokens['html']['contact'])) { foreach ($tokens['html']['contact'] as $name) { $returnProperties[$name] = 1; } } list($contact) = CRM_Utils_Token::getTokenDetails($contactParams, $returnProperties, FALSE, FALSE, NULL, CRM_Utils_Token::flattenTokens($tokens), 'CRM_Core_BAO_MessageTemplate'); $contact = $contact[$contactID]; } $subject = CRM_Utils_Token::replaceDomainTokens($subject, $domain, TRUE, $tokens['text'], TRUE); $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, TRUE, $tokens['text'], TRUE); $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, TRUE, $tokens['html'], TRUE); if ($contactID) { $subject = CRM_Utils_Token::replaceContactTokens($subject, $contact, FALSE, $tokens['text'], FALSE, TRUE); $text = CRM_Utils_Token::replaceContactTokens($text, $contact, FALSE, $tokens['text'], FALSE, TRUE); $html = CRM_Utils_Token::replaceContactTokens($html, $contact, FALSE, $tokens['html'], FALSE, TRUE); $contactArray = array($contactID => $contact); CRM_Utils_Hook::tokenValues($contactArray, array($contactID), NULL, CRM_Utils_Token::flattenTokens($tokens), 'CRM_Core_BAO_MessageTemplate'); $contact = $contactArray[$contactID]; $subject = CRM_Utils_Token::replaceHookTokens($subject, $contact, $categories, TRUE); $text = CRM_Utils_Token::replaceHookTokens($text, $contact, $categories, TRUE); $html = CRM_Utils_Token::replaceHookTokens($html, $contact, $categories, TRUE); } // strip whitespace from ends and turn into a single line $subject = "{strip}{$subject}{/strip}"; // parse the three elements with Smarty $smarty = CRM_Core_Smarty::singleton(); foreach ($params['tplParams'] as $name => $value) { $smarty->assign($name, $value); } foreach (array('subject', 'text', 'html') as $elem) { ${$elem} = $smarty->fetch("string:{${$elem}}"); } // send the template, honouring the target user’s preferences (if any) $sent = FALSE; // create the params array $params['subject'] = $subject; $params['text'] = $text; $params['html'] = $html; if ($params['toEmail']) { $contactParams = array(array('email', 'LIKE', $params['toEmail'], 0, 1)); list($contact, $_) = CRM_Contact_BAO_Query::apiQuery($contactParams); $prefs = array_pop($contact); if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] == 'HTML') { $params['text'] = NULL; } if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] == 'Text') { $params['html'] = NULL; } $config = CRM_Core_Config::singleton(); $pdf_filename = ''; if ($config->doNotAttachPDFReceipt && $params['PDFFilename'] && $params['html']) { $pdf_filename = $config->templateCompileDir . CRM_Utils_File::makeFileName($params['PDFFilename']); //FIXME : CRM-7894 //xmlns attribute is required in XHTML but it is invalid in HTML, //Also the namespace "xmlns=http://www.w3.org/1999/xhtml" is default, //and will be added to the <html> tag even if you do not include it. $html = preg_replace('/(<html)(.+?xmlns=["\'].[^\\s]+["\'])(.+)?(>)/', '\\1\\3\\4', $params['html']); file_put_contents($pdf_filename, CRM_Utils_PDF_Utils::html2pdf($html, $params['PDFFilename'], TRUE, $format)); if (empty($params['attachments'])) { $params['attachments'] = array(); } $params['attachments'][] = array('fullPath' => $pdf_filename, 'mime_type' => 'application/pdf', 'cleanName' => $params['PDFFilename']); } $sent = CRM_Utils_Mail::send($params); if ($pdf_filename) { unlink($pdf_filename); } } return array($sent, $subject, $text, $html); }
/** * render the page using a custom templating * system * * @param object $page the CRM_Core_Form page * @param boolean $ret should we echo or return output * * @return void * @access public */ function renderForm(&$page, $ret = false) { $this->_setRenderTemplates($page); $template =& CRM_Core_Smarty::singleton(); $template->assign('form', $page->toSmarty()); $template->assign('isForm', 1); $controller =& $page->controller; if ($controller->getEmbedded()) { return; } $template->assign('action', $page->getAction()); $template->assign('tplFile', $page->getTemplateFileName()); $content = $template->fetch($controller->getTemplateFile()); $print = $controller->getPrint(); if ($print) { $html =& $content; } else { $html = CRM_Utils_System::theme('page', $content, true, $print, $ret); } if ($ret) { return $html; } if ($print) { if ($print == CRM_Core_Smarty::PRINT_PDF) { require_once 'CRM/Utils/PDF/Utils.php'; CRM_Utils_PDF_Utils::domlib($content, "{$page->_name}.pdf"); } else { echo $html; } exit; } }
function generatePDF($send = FALSE, $template_id) { require_once 'CRM/Utils/PDF/Utils.php'; $fileName = $this->mandate->reference . ".pdf"; if ($send) { $config = CRM_Core_Config::singleton(); $pdfFullFilename = $config->templateCompileDir . CRM_Utils_File::makeFileName($fileName); file_put_contents($pdfFullFilename, CRM_Utils_PDF_Utils::html2pdf($this->html, $fileName, true, null)); list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail(); $params = array(); $params['groupName'] = 'SEPA Email Sender'; $params['from'] = '"' . $domainEmailName . '" <' . $domainEmailAddress . '>'; $params['toEmail'] = $this->contact->email; $params['toName'] = $params['toEmail']; if (empty($params['toEmail'])) { CRM_Core_Session::setStatus(sprintf(ts("Error sending %s: Contact doesn't have an email."), $fileName)); return false; } $params['subject'] = "SEPA " . $fileName; if (!CRM_Utils_Array::value('attachments', $instanceInfo)) { $instanceInfo['attachments'] = array(); } $params['attachments'][] = array('fullPath' => $pdfFullFilename, 'mime_type' => 'application/pdf', 'cleanName' => $fileName); $mail = $this->getMessage($template_id); $params['text'] = "this is the mandate, please return signed"; $params['html'] = $this->getTemplate()->fetch("string:" . $mail["msg_html"]); CRM_Utils_Mail::send($params); // CRM_Core_Session::setStatus(ts("Mail sent")); } else { CRM_Utils_PDF_Utils::html2pdf($this->html, $fileName, false, null); } }
/** * @param string $fileName * @param string $html * @param string $format * * @return array */ public static function appendPDF($fileName, $html, $format = NULL) { $pdf_filename = CRM_Core_Config::singleton()->templateCompileDir . CRM_Utils_File::makeFileName($fileName); // FIXME : CRM-7894 // xmlns attribute is required in XHTML but it is invalid in HTML, // Also the namespace "xmlns=http://www.w3.org/1999/xhtml" is default, // and will be added to the <html> tag even if you do not include it. $html = preg_replace('/(<html)(.+?xmlns=["\'].[^\\s]+["\'])(.+)?(>)/', '\\1\\3\\4', $html); file_put_contents($pdf_filename, CRM_Utils_PDF_Utils::html2pdf($html, $fileName, TRUE, $format)); return array('fullPath' => $pdf_filename, 'mime_type' => 'application/pdf', 'cleanName' => $fileName); }
function endPostProcess(&$rows = null) { if ($this->_outputMode == 'print' || $this->_outputMode == 'pdf' || $this->_sendmail) { $templateFile = parent::getTemplateFileName(); $content = $this->_formValues['report_header'] . CRM_Core_Form::$_template->fetch($templateFile) . $this->_formValues['report_footer']; if ($this->_sendmail) { if (CRM_Report_Utils_Report::mailReport($content, $this->_id, $this->_outputMode)) { CRM_Core_Session::setStatus(ts("Report mail has been sent.")); } else { CRM_Core_Session::setStatus(ts("Report mail could not be sent.")); } if ($this->get('instanceId')) { CRM_Utils_System::civiExit(); } CRM_Utils_System::redirect(CRM_Utils_System::url(CRM_Utils_System::currentPath(), 'reset=1')); } else { if ($this->_outputMode == 'print') { echo $content; } else { if ($chartType = CRM_Utils_Array::value('charts', $this->_params)) { $config =& CRM_Core_Config::singleton(); //get chart image name $chartImg = $chartType . '_' . $this->_id . '.png'; //get image url path $uploadUrl = str_replace('persist/contribute', 'upload/openFlashChart', $config->imageUploadURL); $uploadUrl .= $chartImg; //get image doc path to overwrite $uploadImg = $config->uploadDir . 'openFlashChart/' . $chartImg; //Load the image $chart = imagecreatefrompng($uploadUrl); //convert it into formattd png header('Content-type: image/png'); //overwrite with same image imagepng($chart, $uploadImg); //delete the object imagedestroy($chart); } require_once 'CRM/Utils/PDF/Utils.php'; CRM_Utils_PDF_Utils::html2pdf($content, "CiviReport.pdf"); } } CRM_Utils_System::civiExit(); } else { if ($this->_outputMode == 'csv') { CRM_Report_Utils_Report::export2csv($this, $rows); } else { if ($this->_outputMode == 'group') { $group = $this->_params['groups']; CRM_Report_Utils_Report::add2group($this, $group); } else { if ($this->_instanceButtonName == $this->controller->getButtonName()) { require_once 'CRM/Report/Form/Instance.php'; CRM_Report_Form_Instance::postProcess($this); } } } } }
/** * This function takes care of all the things common to all * pages. This typically involves assigning the appropriate * smarty variable :) * * @return string The content generated by running this page */ function run() { if ($this->_embedded) { return; } self::$_template->assign('mode', $this->_mode); self::$_template->assign('tplFile', $this->getTemplateFileName()); // invoke the pagRun hook, CRM-3906 require_once 'CRM/Utils/Hook.php'; CRM_Utils_Hook::pageRun($this); if ($this->_print) { if ($this->_print == CRM_Core_Smarty::PRINT_SNIPPET || $this->_print == CRM_Core_Smarty::PRINT_PDF) { $content = self::$_template->fetch('CRM/common/snippet.tpl'); } else { $content = self::$_template->fetch('CRM/common/print.tpl'); } if ($this->_print == CRM_Core_Smarty::PRINT_PDF) { require_once 'CRM/Utils/PDF/Utils.php'; CRM_Utils_PDF_Utils::domlib($content, "{$this->_name}.pdf"); } else { echo $content; } exit; } $config =& CRM_Core_Config::singleton(); $content = self::$_template->fetch('CRM/common/' . strtolower($config->userFramework) . '.tpl'); echo CRM_Utils_System::theme('page', $content, true, $this->_print); return; }
/** * process the form after the input has been submitted and validated * * @access public * * @return void */ static function postProcess(&$form) { list($formValues, $categories, $html_message, $messageToken, $returnProperties) = self::processMessageTemplate($form); // update dates ? $receipt_update = isset($formValues['receipt_update']) ? $formValues['receipt_update'] : FALSE; $thankyou_update = isset($formValues['thankyou_update']) ? $formValues['thankyou_update'] : FALSE; $nowDate = date('YmdHis'); $receipts = 0; $thanks = 0; $updateStatus = ''; // skip some contacts ? $skipOnHold = isset($form->skipOnHold) ? $form->skipOnHold : FALSE; $skipDeceased = isset($form->skipDeceased) ? $form->skipDeceased : TRUE; foreach ($form->getVar('_contributionIds') as $item => $contributionId) { // get contact information $contactId = civicrm_api("Contribution", "getvalue", array('version' => '3', 'id' => $contributionId, 'return' => 'contact_id')); $params = array('contact_id' => $contactId); list($contact) = CRM_Utils_Token::getTokenDetails($params, $returnProperties, $skipOnHold, $skipDeceased, NULL, $messageToken, 'CRM_Contribution_Form_Task_PDFLetterCommon'); if (civicrm_error($contact)) { $notSent[] = $contributionId; continue; } // get contribution information $params = array('contribution_id' => $contributionId); $contribution = CRM_Utils_Token::getContributionTokenDetails($params, $returnProperties, NULL, $messageToken, 'CRM_Contribution_Form_Task_PDFLetterCommon'); if (civicrm_error($contribution)) { $notSent[] = $contributionId; continue; } $tokenHtml = CRM_Utils_Token::replaceContactTokens($html_message, $contact[$contactId], TRUE, $messageToken); $tokenHtml = CRM_Utils_Token::replaceContributionTokens($tokenHtml, $contribution[$contributionId], TRUE, $messageToken); $tokenHtml = CRM_Utils_Token::replaceHookTokens($tokenHtml, $contact[$contactId], $categories, TRUE); if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY) { $smarty = CRM_Core_Smarty::singleton(); // also add the tokens to the template $smarty->assign_by_ref('contact', $contact); $tokenHtml = $smarty->fetch("string:{$tokenHtml}"); } $html[] = $tokenHtml; // update dates (do it for each contribution including grouped recurring contribution) if ($receipt_update) { $result = CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'receipt_date', $nowDate); // We can't use CRM_Core_Error::fatal here because the api error elevates the exception level. FIXME. dgg if ($result) { $receipts++; } } if ($thankyou_update) { $result = CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'thankyou_date', $nowDate); // We can't use CRM_Core_Error::fatal here because the api error elevates the exception level. FIXME. dgg if ($result) { $thanks++; } } } self::createActivities($form, $html_message, $form->_contactIds); CRM_Utils_PDF_Utils::html2pdf($html, "CiviLetter.pdf", FALSE, $formValues); $form->postProcessHook(); if ($receipts) { $updateStatus = ts('Receipt date has been updated for %1 contributions.', array(1 => $receipts)); } if ($thanks) { $updateStatus .= ' ' . ts('Thank-you date has been updated for %1 contributions.', array(1 => $thanks)); } if ($updateStatus) { CRM_Core_Session::setStatus($updateStatus); } CRM_Utils_System::civiExit(1); }
/** * Process the form after the input has been submitted and validated. * * @param CRM_Contribute_Form_Task $form */ public static function postProcess(&$form) { $formValues = $form->controller->exportValues($form->getName()); list($formValues, $categories, $html_message, $messageToken, $returnProperties) = self::processMessageTemplate($formValues); $isPDF = FALSE; $emailParams = array(); if (!empty($formValues['email_options'])) { $returnProperties['email'] = $returnProperties['on_hold'] = $returnProperties['is_deceased'] = $returnProperties['do_not_email'] = 1; $emailParams = array('subject' => $formValues['subject']); // We need display_name for emailLetter() so add to returnProperties here $returnProperties['display_name'] = 1; if (stristr($formValues['email_options'], 'pdfemail')) { $isPDF = TRUE; } } // update dates ? $receipt_update = isset($formValues['receipt_update']) ? $formValues['receipt_update'] : FALSE; $thankyou_update = isset($formValues['thankyou_update']) ? $formValues['thankyou_update'] : FALSE; $nowDate = date('YmdHis'); $receipts = $thanks = $emailed = 0; $updateStatus = ''; $task = 'CRM_Contribution_Form_Task_PDFLetterCommon'; $realSeparator = ', '; $tableSeparators = array('td' => '</td><td>', 'tr' => '</td></tr><tr><td>'); //the original thinking was mutliple options - but we are going with only 2 (comma & td) for now in case // there are security (& UI) issues we need to think through if (isset($formValues['group_by_separator'])) { if (in_array($formValues['group_by_separator'], array('td', 'tr'))) { $realSeparator = $tableSeparators[$formValues['group_by_separator']]; } elseif ($formValues['group_by_separator'] == 'br') { $realSeparator = "<br />"; } } $separator = '****~~~~'; // a placeholder in case the separator is common in the string - e.g ', ' $validated = FALSE; $groupBy = $formValues['group_by']; // skip some contacts ? $skipOnHold = isset($form->skipOnHold) ? $form->skipOnHold : FALSE; $skipDeceased = isset($form->skipDeceased) ? $form->skipDeceased : TRUE; $contributionIDs = $form->getVar('_contributionIds'); if ($form->_includesSoftCredits) { //@todo - comment on what is stored there $contributionIDs = $form->getVar('_contributionContactIds'); } list($contributions, $contacts) = self::buildContributionArray($groupBy, $contributionIDs, $returnProperties, $skipOnHold, $skipDeceased, $messageToken, $task, $separator, $form->_includesSoftCredits); $html = array(); foreach ($contributions as $contributionId => $contribution) { $contact =& $contacts[$contribution['contact_id']]; $grouped = $groupByID = 0; if ($groupBy) { $groupByID = empty($contribution[$groupBy]) ? 0 : $contribution[$groupBy]; $contribution = $contact['combined'][$groupBy][$groupByID]; $grouped = TRUE; } self::assignCombinedContributionValues($contact, $contributions, $groupBy, $groupByID); if (empty($groupBy) || empty($contact['is_sent'][$groupBy][$groupByID])) { if (!$validated && in_array($realSeparator, $tableSeparators) && !self::isValidHTMLWithTableSeparator($messageToken, $html_message)) { $realSeparator = ', '; CRM_Core_Session::setStatus(ts('You have selected the table cell separator, but one or more token fields are not placed inside a table cell. This would result in invalid HTML, so comma separators have been used instead.')); } $validated = TRUE; $html[$contributionId] = str_replace($separator, $realSeparator, self::resolveTokens($html_message, $contact, $contribution, $messageToken, $categories, $grouped, $separator)); $contact['is_sent'][$groupBy][$groupByID] = TRUE; if (!empty($formValues['email_options'])) { if (self::emailLetter($contact, $html[$contributionId], $isPDF, $formValues, $emailParams)) { $emailed++; if (!stristr($formValues['email_options'], 'both')) { unset($html[$contributionId]); } } } } // update dates (do it for each contribution including grouped recurring contribution) //@todo - the 2 calls below bypass all hooks. Using the api would possibly be slower than one call but not than 2 if ($receipt_update) { $result = CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'receipt_date', $nowDate); if ($result) { $receipts++; } } if ($thankyou_update) { $result = CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'thankyou_date', $nowDate); if ($result) { $thanks++; } } } //createActivities requires both $form->_contactIds and $contacts - //@todo - figure out why $form->_contactIds = array_keys($contacts); self::createActivities($form, $html_message, $form->_contactIds); if (!empty($html)) { CRM_Utils_PDF_Utils::html2pdf($html, "CiviLetter.pdf", FALSE, $formValues); } $form->postProcessHook(); if ($emailed) { $updateStatus = ts('Receipts have been emailed to %1 contributions.', array(1 => $emailed)); } if ($receipts) { $updateStatus = ts('Receipt date has been updated for %1 contributions.', array(1 => $receipts)); } if ($thanks) { $updateStatus .= ' ' . ts('Thank-you date has been updated for %1 contributions.', array(1 => $thanks)); } if ($updateStatus) { CRM_Core_Session::setStatus($updateStatus); } if (!empty($html)) { // ie. we have only sent emails - lets no show a white screen CRM_Utils_System::civiExit(1); } }
/** * process the form after the input has been submitted and validated * * @access public * @return None */ static function postProcess(&$form) { $formValues = $form->controller->exportValues($form->getName()); // process message template require_once 'CRM/Core/BAO/MessageTemplates.php'; if (CRM_Utils_Array::value('saveTemplate', $formValues) || CRM_Utils_Array::value('updateTemplate', $formValues)) { $messageTemplate = array('msg_text' => NULL, 'msg_html' => $formValues['html_message'], 'msg_subject' => NULL, 'is_active' => true); if ($formValues['saveTemplate']) { $messageTemplate['msg_title'] = $formValues['saveTemplateName']; CRM_Core_BAO_MessageTemplates::add($messageTemplate); } if ($formValues['template'] && $formValues['updateTemplate']) { $messageTemplate['id'] = $formValues['template']; unset($messageTemplate['msg_title']); CRM_Core_BAO_MessageTemplates::add($messageTemplate); } } require_once 'dompdf/dompdf_config.inc.php'; $html = '<html><head><style>body { margin: 56px; }</style></head><body>'; require_once 'api/v2/Contact.php'; require_once 'CRM/Utils/Token.php'; $tokens = array(); CRM_Utils_Hook::tokens($tokens); $categories = array_keys($tokens); $html_message = $formValues['html_message']; //time being hack to strip ' ' //from particular letter line, CRM-6798 self::formatMessage($html_message); require_once 'CRM/Activity/BAO/Activity.php'; $messageToken = CRM_Activity_BAO_Activity::getTokens($html_message); $returnProperties = array(); if (isset($messageToken['contact'])) { foreach ($messageToken['contact'] as $key => $value) { $returnProperties[$value] = 1; } } require_once 'CRM/Mailing/BAO/Mailing.php'; $mailing = new CRM_Mailing_BAO_Mailing(); if (defined('CIVICRM_MAIL_SMARTY')) { require_once 'CRM/Core/Smarty/resources/String.php'; civicrm_smarty_register_string_resource(); } $first = TRUE; foreach ($form->_contactIds as $item => $contactId) { $params = array('contact_id' => $contactId); list($contact) = $mailing->getDetails($params, $returnProperties, false); if (civicrm_error($contact)) { $notSent[] = $contactId; continue; } $tokenHtml = CRM_Utils_Token::replaceContactTokens($html_message, $contact[$contactId], true, $messageToken); $tokenHtml = CRM_Utils_Token::replaceHookTokens($tokenHtml, $contact[$contactId], $categories, true); if (defined('CIVICRM_MAIL_SMARTY')) { $smarty = CRM_Core_Smarty::singleton(); // also add the contact tokens to the template $smarty->assign_by_ref('contact', $contact); $tokenHtml = $smarty->fetch("string:{$tokenHtml}"); } if ($first == TRUE) { $first = FALSE; $html .= $tokenHtml; } else { $html .= "<div STYLE='page-break-after: always'></div>{$tokenHtml}"; } } $html .= '</body></html>'; require_once 'CRM/Activity/BAO/Activity.php'; $session = CRM_Core_Session::singleton(); $userID = $session->get('userID'); $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'Print PDF Letter', 'name'); $activityParams = array('source_contact_id' => $userID, 'activity_type_id' => $activityTypeID, 'activity_date_time' => date('YmdHis'), 'details' => $html_message); if ($form->_activityId) { $activityParams += array('id' => $form->_activityId); } if ($form->_cid) { $activity = CRM_Activity_BAO_Activity::create($activityParams); } else { // create Print PDF activity for each selected contact. CRM-6886 $activityIds = array(); foreach ($form->_contactIds as $contactId) { $activityID = CRM_Activity_BAO_Activity::create($activityParams); $activityIds[$contactId] = $activityID->id; } } foreach ($form->_contactIds as $contactId) { $activityTargetParams = array('activity_id' => empty($activity->id) ? $activityIds[$contactId] : $activity->id, 'target_contact_id' => $contactId); CRM_Activity_BAO_Activity::createActivityTarget($activityTargetParams); } require_once 'CRM/Utils/PDF/Utils.php'; CRM_Utils_PDF_Utils::html2pdf($html, "CiviLetter.pdf", 'portrait', 'letter'); // we need to call the hook manually here since we redirect and never // go back to CRM/Core/Form.php CRM_Utils_Hook::postProcess(get_class($form), $form); CRM_Utils_System::civiExit(1); }
/** * This function takes care of all the things common to all * pages. This typically involves assigning the appropriate smarty * variable :) * * @return void|string * The content generated by running this page */ public function run() { if ($this->_embedded) { return NULL; } self::$_template->assign('mode', $this->_mode); $pageTemplateFile = $this->getHookedTemplateFileName(); self::$_template->assign('tplFile', $pageTemplateFile); // invoke the pagRun hook, CRM-3906 CRM_Utils_Hook::pageRun($this); if ($this->_print) { if (in_array($this->_print, array(CRM_Core_Smarty::PRINT_SNIPPET, CRM_Core_Smarty::PRINT_PDF, CRM_Core_Smarty::PRINT_NOFORM, CRM_Core_Smarty::PRINT_JSON))) { $content = self::$_template->fetch('CRM/common/snippet.tpl'); } else { $content = self::$_template->fetch('CRM/common/print.tpl'); } CRM_Utils_System::appendTPLFile($pageTemplateFile, $content, $this->overrideExtraTemplateFileName()); //its time to call the hook. CRM_Utils_Hook::alterContent($content, 'page', $pageTemplateFile, $this); if ($this->_print == CRM_Core_Smarty::PRINT_PDF) { CRM_Utils_PDF_Utils::html2pdf($content, "{$this->_name}.pdf", FALSE, array('paper_size' => 'a3', 'orientation' => 'landscape')); } elseif ($this->_print == CRM_Core_Smarty::PRINT_JSON) { $this->ajaxResponse['content'] = $content; CRM_Core_Page_AJAX::returnJsonResponse($this->ajaxResponse); } else { echo $content; } CRM_Utils_System::civiExit(); } $config = CRM_Core_Config::singleton(); // Intermittent alert to admins CRM_Utils_Check::singleton()->showPeriodicAlerts(); if ($this->useLivePageJS && CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'ajaxPopupsEnabled', NULL, TRUE)) { CRM_Core_Resources::singleton()->addScriptFile('civicrm', 'js/crm.livePage.js', 1, 'html-header'); } $content = self::$_template->fetch('CRM/common/' . strtolower($config->userFramework) . '.tpl'); // Render page header if (!defined('CIVICRM_UF_HEAD') && ($region = CRM_Core_Region::instance('html-header', FALSE))) { CRM_Utils_System::addHTMLHead($region->render('')); } CRM_Utils_System::appendTPLFile($pageTemplateFile, $content); //its time to call the hook. CRM_Utils_Hook::alterContent($content, 'page', $pageTemplateFile, $this); echo CRM_Utils_System::theme($content, $this->_print); }
/** * This function takes care of all the things common to all * pages. This typically involves assigning the appropriate * smarty variable :) * * @return string The content generated by running this page */ function run() { if ($this->_embedded) { return; } self::$_template->assign('mode', $this->_mode); $pageTemplateFile = $this->getHookedTemplateFileName(); self::$_template->assign('tplFile', $pageTemplateFile); // invoke the pagRun hook, CRM-3906 CRM_Utils_Hook::pageRun($this); if ($this->_print) { if (in_array($this->_print, array(CRM_Core_Smarty::PRINT_SNIPPET, CRM_Core_Smarty::PRINT_PDF, CRM_Core_Smarty::PRINT_NOFORM, CRM_Core_Smarty::PRINT_JSON))) { $content = self::$_template->fetch('CRM/common/snippet.tpl'); } else { $content = self::$_template->fetch('CRM/common/print.tpl'); } CRM_Utils_System::appendTPLFile($pageTemplateFile, $content, $this->overrideExtraTemplateFileName()); //its time to call the hook. CRM_Utils_Hook::alterContent($content, 'page', $pageTemplateFile, $this); if ($this->_print == CRM_Core_Smarty::PRINT_PDF) { CRM_Utils_PDF_Utils::html2pdf($content, "{$this->_name}.pdf", FALSE, array('paper_size' => 'a3', 'orientation' => 'landscape')); } elseif ($this->_print == CRM_Core_Smarty::PRINT_JSON) { $this->ajaxResponse['content'] = $content; CRM_Core_Page_AJAX::returnJsonResponse($this->ajaxResponse); } else { echo $content; } CRM_Utils_System::civiExit(); } $config = CRM_Core_Config::singleton(); // TODO: Is there a better way to ensure these actions don't happen during AJAX requests? if (empty($_GET['snippet'])) { // Version check and intermittent alert to admins CRM_Utils_VersionCheck::singleton()->versionAlert(); CRM_Utils_Check_Security::singleton()->showPeriodicAlerts(); // Debug msg once per hour if ($config->debug && CRM_Core_Permission::check('administer CiviCRM') && CRM_Core_Session::singleton()->timer('debug_alert', 3600)) { $msg = ts('Warning: Debug is enabled in <a href="%1">system settings</a>. This should not be enabled on production servers.', array(1 => CRM_Utils_System::url('civicrm/admin/setting/debug', 'reset=1'))); CRM_Core_Session::setStatus($msg, ts('Debug Mode')); } } $content = self::$_template->fetch('CRM/common/' . strtolower($config->userFramework) . '.tpl'); // Render page header if (!defined('CIVICRM_UF_HEAD') && ($region = CRM_Core_Region::instance('html-header', FALSE))) { CRM_Utils_System::addHTMLHead($region->render('')); } CRM_Utils_System::appendTPLFile($pageTemplateFile, $content); //its time to call the hook. CRM_Utils_Hook::alterContent($content, 'page', $pageTemplateFile, $this); echo CRM_Utils_System::theme($content, $this->_print); return; }
/** * process the form after the input has been submitted and validated * * @access public * * @return void */ public function postProcess() { // get all the details needed to generate a receipt $contribIDs = implode(',', $this->_contributionIds); $details = CRM_Contribute_Form_Task_Status::getDetails($contribIDs); $baseIPN = new CRM_Core_Payment_BaseIPN(); $message = array(); $template = CRM_Core_Smarty::singleton(); $params = $this->controller->exportValues($this->_name); $createPdf = FALSE; if ($params['output'] == "pdf_receipt") { $createPdf = TRUE; } $excludeContactIds = array(); if (!$createPdf) { $returnProperties = array('email' => 1, 'do_not_email' => 1, 'is_deceased' => 1, 'on_hold' => 1); list($contactDetails) = CRM_Utils_Token::getTokenDetails($this->_contactIds, $returnProperties, FALSE, FALSE); $suppressedEmails = 0; foreach ($contactDetails as $id => $values) { if (empty($values['email']) || !empty($values['do_not_email']) || CRM_Utils_Array::value('is_deceased', $values) || !empty($values['on_hold'])) { $suppressedEmails++; $excludeContactIds[] = $values['contact_id']; } } } foreach ($details as $contribID => $detail) { $input = $ids = $objects = array(); if (in_array($detail['contact'], $excludeContactIds)) { continue; } $input['component'] = $detail['component']; $ids['contact'] = $detail['contact']; $ids['contribution'] = $contribID; $ids['contributionRecur'] = NULL; $ids['contributionPage'] = NULL; $ids['membership'] = CRM_Utils_Array::value('membership', $detail); $ids['participant'] = CRM_Utils_Array::value('participant', $detail); $ids['event'] = CRM_Utils_Array::value('event', $detail); if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) { CRM_Core_Error::fatal(); } $contribution =& $objects['contribution']; // CRM_Core_Error::debug('o',$objects); // set some fake input values so we can reuse IPN code $input['amount'] = $contribution->total_amount; $input['is_test'] = $contribution->is_test; $input['fee_amount'] = $contribution->fee_amount; $input['net_amount'] = $contribution->net_amount; $input['trxn_id'] = $contribution->trxn_id; $input['trxn_date'] = isset($contribution->trxn_date) ? $contribution->trxn_date : NULL; // CRM_Contribute_BAO_Contribution::composeMessageArray expects mysql formatted date $objects['contribution']->receive_date = CRM_Utils_Date::isoToMysql($objects['contribution']->receive_date); // CRM_Core_Error::debug('input',$input); $values = array(); $mail = $baseIPN->sendMail($input, $ids, $objects, $values, FALSE, $createPdf); if ($mail['html']) { $message[] = $mail['html']; } else { $message[] = nl2br($mail['body']); } // reset template values before processing next transactions $template->clearTemplateVars(); } if ($createPdf) { CRM_Utils_PDF_Utils::html2pdf($message, 'civicrmContributionReceipt.pdf', FALSE, $params['pdf_format_id']); CRM_Utils_System::civiExit(); } else { if ($suppressedEmails) { $status = ts('Email was NOT sent to %1 contacts (no email address on file, or communication preferences specify DO NOT EMAIL, or contact is deceased).', array(1 => $suppressedEmails)); $msgTitle = ts('Email Error'); $msgType = 'error'; } else { $status = ts('Your mail has been sent.'); $msgTitle = ts('Sent'); $msgType = 'success'; } CRM_Core_Session::setStatus($status, $msgTitle, $msgType); } }
/** * process the form after the input has been submitted and validated * * @access public * * @return None */ static function postProcess(&$form) { list($formValues, $categories, $html_message, $messageToken, $returnProperties) = self::processMessageTemplate($form); $skipOnHold = isset($form->skipOnHold) ? $form->skipOnHold : FALSE; $skipDeceased = isset($form->skipDeceased) ? $form->skipDeceased : TRUE; foreach ($form->_contactIds as $item => $contactId) { $params = array('contact_id' => $contactId); list($contact) = CRM_Utils_Token::getTokenDetails($params, $returnProperties, $skipOnHold, $skipDeceased, NULL, $messageToken, 'CRM_Contact_Form_Task_PDFLetterCommon'); if (civicrm_error($contact)) { $notSent[] = $contactId; continue; } $tokenHtml = CRM_Utils_Token::replaceContactTokens($html_message, $contact[$contactId], TRUE, $messageToken); $tokenHtml = CRM_Utils_Token::replaceHookTokens($tokenHtml, $contact[$contactId], $categories, TRUE); if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY) { $smarty = CRM_Core_Smarty::singleton(); // also add the contact tokens to the template $smarty->assign_by_ref('contact', $contact); $tokenHtml = $smarty->fetch("string:{$tokenHtml}"); } $html[] = $tokenHtml; } self::createActivities($form, $html_message, $form->_contactIds); CRM_Utils_PDF_Utils::html2pdf($html, "CiviLetter.pdf", FALSE, $formValues); $form->postProcessHook(); CRM_Utils_System::civiExit(1); }
/** * Render the page using a custom templating system. * * @param CRM_Core_Form $page * The CRM_Core_Form page. */ public function renderForm(&$page) { $this->_setRenderTemplates($page); $template = CRM_Core_Smarty::singleton(); $form = $page->toSmarty(); // Deprecated - use snippet=6 instead of json=1 $json = CRM_Utils_Request::retrieve('json', 'Boolean', CRM_Core_DAO::$_nullObject); if ($json) { CRM_Utils_JSON::output($form); } $template->assign('form', $form); $template->assign('isForm', 1); $controller =& $page->controller; // Stop here if we are in embedded mode. Exception: displaying form errors via ajax if ($controller->getEmbedded() && !(!empty($form['errors']) && $controller->_QFResponseType == 'json')) { return; } $template->assign('action', $page->getAction()); $pageTemplateFile = $page->getHookedTemplateFileName(); $template->assign('tplFile', $pageTemplateFile); $content = $template->fetch($controller->getTemplateFile()); if (!defined('CIVICRM_UF_HEAD') && ($region = CRM_Core_Region::instance('html-header', FALSE))) { CRM_Utils_System::addHTMLHead($region->render('')); } CRM_Utils_System::appendTPLFile($pageTemplateFile, $content, $page->overrideExtraTemplateFileName()); //its time to call the hook. CRM_Utils_Hook::alterContent($content, 'form', $pageTemplateFile, $page); $print = $controller->getPrint(); if ($print) { $html =& $content; } else { $html = CRM_Utils_System::theme($content, $print); } if ($controller->_QFResponseType == 'json') { $response = array('content' => $html); if (!empty($page->ajaxResponse)) { $response += $page->ajaxResponse; } if (!empty($form['errors'])) { $response['status'] = 'form_error'; $response['errors'] = $form['errors']; } CRM_Core_Page_AJAX::returnJsonResponse($response); } if ($print) { if ($print == CRM_Core_Smarty::PRINT_PDF) { CRM_Utils_PDF_Utils::html2pdf($content, "{$page->_name}.pdf", FALSE, array('paper_size' => 'a3', 'orientation' => 'landscape')); } else { echo $html; } CRM_Utils_System::civiExit(); } print $html; }
public function postProcess() { // get the acl clauses built before we assemble the query $this->buildACLClause($this->_aliases['civicrm_contact']); // get ready with post process params $this->beginPostProcess(); // build query $sql = $this->buildQuery(); // build array of result based on column headers. This method also allows // modifying column headers before using it to build result set i.e $rows. $rows = array(); $this->buildRows($sql, $rows); // format result set. $this->formatDisplay($rows); //call local post process for only print and pdf. //we do need special formatted o/p only when we do have grouping $orderBys = CRM_Utils_Array::value('order_bys', $this->_params, array()); if (in_array($this->_outputMode, array('print', 'pdf'))) { $outPut = array(); $templateFile = parent::getTemplateFileName(); if (array_key_exists('street_name', $orderBys) || array_key_exists('street_number', $orderBys)) { $orderByStreetName = CRM_Utils_Array::value('street_name', $orderBys); $orderByStreetNum = CRM_Utils_Array::value('street_number', $orderBys); $pageCnt = 0; $dataPerPage = array(); $lastStreetName = $lastStreetNum = NULL; foreach ($rows as $row) { //do we need to take new page. if ($orderByStreetName && $lastStreetName != CRM_Utils_Array::value('civicrm_address_street_name', $row)) { $pageCnt++; } elseif ($orderByStreetNum && $lastStreetNum != CRM_Utils_Array::value('civicrm_address_street_number', $row) % 2) { $pageCnt++; } //get the data per page. $dataPerPage[$pageCnt][] = $row; $lastStreetName = CRM_Utils_Array::value('civicrm_address_street_name', $row); $lastStreetNum = CRM_Utils_Array::value('civicrm_address_street_number', $row) % 2; } foreach ($dataPerPage as $page) { // assign variables to templates $this->doTemplateAssignment($page); $outPut[] = CRM_Core_Form::$_template->fetch($templateFile); } } else { $this->doTemplateAssignment($rows); $outPut[] = CRM_Core_Form::$_template->fetch($templateFile); } $header = $this->_formValues['report_header']; $footer = $this->_formValues['report_footer']; //get the cover sheet. $coverSheet = $this->_surveyCoverSheet(); $footerImage = preg_replace('/<\\/html>|<\\/body>|<\\/div>/i', '', $footer); $outPut = $header . $coverSheet . "<div style=\"page-break-after: always\"></div>" . implode($footerImage . "<div style=\"page-break-after: always\"></div>", $outPut) . $footer; if ($this->_outputMode == 'print') { echo $outPut; } else { CRM_Utils_PDF_Utils::html2pdf($outPut, "CiviReport.pdf"); } CRM_Utils_System::civiExit(); } else { $this->doTemplateAssignment($rows); $this->endPostProcess($rows); } }
/** * Process the form after the input has been submitted and validated. * * * @return void */ public function postProcess() { // get all the details needed to generate a receipt $message = array(); $template = CRM_Core_Smarty::singleton(); $params = $this->controller->exportValues($this->_name); $elements = self::getElements($this->_contributionIds, $params, $this->_contactIds); foreach ($elements['details'] as $contribID => $detail) { $input = $ids = $objects = array(); if (in_array($detail['contact'], $elements['excludeContactIds'])) { continue; } $input['component'] = $detail['component']; $ids['contact'] = $detail['contact']; $ids['contribution'] = $contribID; $ids['contributionRecur'] = NULL; $ids['contributionPage'] = NULL; $ids['membership'] = CRM_Utils_Array::value('membership', $detail); $ids['participant'] = CRM_Utils_Array::value('participant', $detail); $ids['event'] = CRM_Utils_Array::value('event', $detail); if (!$elements['baseIPN']->validateData($input, $ids, $objects, FALSE)) { CRM_Core_Error::fatal(); } $contribution =& $objects['contribution']; // set some fake input values so we can reuse IPN code $input['amount'] = $contribution->total_amount; $input['is_test'] = $contribution->is_test; $input['fee_amount'] = $contribution->fee_amount; $input['net_amount'] = $contribution->net_amount; $input['trxn_id'] = $contribution->trxn_id; $input['trxn_date'] = isset($contribution->trxn_date) ? $contribution->trxn_date : NULL; // CRM_Contribute_BAO_Contribution::composeMessageArray expects mysql formatted date $objects['contribution']->receive_date = CRM_Utils_Date::isoToMysql($objects['contribution']->receive_date); $values = array(); $mail = $elements['baseIPN']->sendMail($input, $ids, $objects, $values, FALSE, $elements['createPdf']); if ($mail['html']) { $message[] = $mail['html']; } else { $message[] = nl2br($mail['body']); } // reset template values before processing next transactions $template->clearTemplateVars(); if (!empty($params['receipt_update'])) { $objects['contribution']->receipt_date = date('Y-m-d H-i-s'); $objects['contribution']->save(); } } if ($elements['createPdf']) { CRM_Utils_PDF_Utils::html2pdf($message, 'civicrmContributionReceipt.pdf', FALSE, $elements['params']['pdf_format_id']); CRM_Utils_System::civiExit(); } else { if ($elements['suppressedEmails']) { $status = ts('Email was NOT sent to %1 contacts (no email address on file, or communication preferences specify DO NOT EMAIL, or contact is deceased).', array(1 => $elements['suppressedEmails'])); $msgTitle = ts('Email Error'); $msgType = 'error'; } else { $status = ts('Your mail has been sent.'); $msgTitle = ts('Sent'); $msgType = 'success'; } CRM_Core_Session::setStatus($status, $msgTitle, $msgType); } }
/** * This function takes care of all the things common to all * pages. This typically involves assigning the appropriate * smarty variable :) * * @return string The content generated by running this page */ function run() { if ($this->_embedded) { return; } self::$_template->assign('mode', $this->_mode); $pageTemplateFile = $this->getTemplateFileName(); self::$_template->assign('tplFile', $pageTemplateFile); // invoke the pagRun hook, CRM-3906 CRM_Utils_Hook::pageRun($this); if ($this->_print) { if (in_array($this->_print, array(CRM_Core_Smarty::PRINT_SNIPPET, CRM_Core_Smarty::PRINT_PDF, CRM_Core_Smarty::PRINT_NOFORM))) { $content = self::$_template->fetch('CRM/common/snippet.tpl'); } else { $content = self::$_template->fetch('CRM/common/print.tpl'); } CRM_Utils_System::appendTPLFile($pageTemplateFile, $content, $this->overrideExtraTemplateFileName()); //its time to call the hook. CRM_Utils_Hook::alterContent($content, 'page', $pageTemplateFile, $this); if ($this->_print == CRM_Core_Smarty::PRINT_PDF) { CRM_Utils_PDF_Utils::html2pdf($content, "{$this->_name}.pdf", FALSE, array('paper_size' => 'a3', 'orientation' => 'landscape')); } else { echo $content; } CRM_Utils_System::civiExit(); } $config = CRM_Core_Config::singleton(); $content = self::$_template->fetch('CRM/common/' . strtolower($config->userFramework) . '.tpl'); if ($region = CRM_Core_Region::instance('html-header', FALSE)) { CRM_Utils_System::addHTMLHead($region->render('')); } CRM_Utils_System::appendTPLFile($pageTemplateFile, $content); //its time to call the hook. CRM_Utils_Hook::alterContent($content, 'page', $pageTemplateFile, $this); echo CRM_Utils_System::theme('page', $content, TRUE, $this->_print); return; }