public static function upload($params)
 {
     if (!$_FILES) {
         throw new CRM_Extension_Exception('Sorry, the file you uploaded was too large or invalid. Code 1', 500);
     }
     if (empty($_FILES['file']['size'])) {
         throw new CRM_Extension_Exception('Sorry, the file you uploaded was too large or invalid. Code 2', 500);
     }
     $tempFile = $_FILES['file']['tmp_name'];
     $originalFilename = CRM_Simplemail_BAO_SimpleMailHelper::cleanFilename($_FILES['file']['name']);
     $fileName = CRM_Utils_File::makeFileName(CRM_Simplemail_BAO_SimpleMailHelper::cleanFilename($_FILES['file']['name']));
     $dirName = CRM_Simplemail_BAO_SimpleMailHelper::getUploadDirPath(static::DIRECTORY);
     // Create the upload directory, if it doesn't already exist
     CRM_Utils_File::createDir($dirName);
     $file = $dirName . $fileName;
     // Move the uploaded file to the upload directory
     if (move_uploaded_file($tempFile, $file)) {
         $url = CRM_Simplemail_BAO_SimpleMailHelper::getUploadUrl($fileName, static::DIRECTORY);
         $databaseId = static::saveToDatabase($params['simplemail_id'], $originalFilename, $url);
         $result['values'] = array(array('url' => $url, 'filename' => $originalFilename, 'databaseId' => $databaseId));
         return $result;
     } else {
         throw new CRM_Extension_Exception('Failed to move the uploaded file', 500);
     }
 }
 /**
  * handler for upload requests
  */
 static function processUpload()
 {
     $config = self::getConfig();
     global $http_return_code;
     $files = array();
     if ($_SERVER["REQUEST_METHOD"] == "GET") {
         $dir = scandir($config['BASE_DIR']);
         foreach ($dir as $file_name) {
             //issue - https://github.com/veda-consulting/uk.co.vedaconsulting.mosaico/issues/28
             //Change file name to unique by adding hash so every time uploading same image it will create new image name
             $file_name = CRM_Utils_File::makeFileName($file_name);
             $file_path = $config['BASE_DIR'] . $file_name;
             if (is_file($file_path)) {
                 $size = filesize($file_path);
                 $file = ["name" => $file_name, "url" => $config['BASE_URL'] . $file_name, "size" => $size];
                 if (file_exists($config['BASE_DIR'] . $config[THUMBNAILS_DIR] . $file_name)) {
                     $file["thumbnailUrl"] = $config['BASE_URL'] . $config[THUMBNAILS_URL] . $file_name;
                 }
                 $files[] = $file;
             }
         }
     } else {
         if (!empty($_FILES)) {
             foreach ($_FILES["files"]["error"] as $key => $error) {
                 if ($error == UPLOAD_ERR_OK) {
                     $tmp_name = $_FILES["files"]["tmp_name"][$key];
                     $file_name = $_FILES["files"]["name"][$key];
                     //issue - https://github.com/veda-consulting/uk.co.vedaconsulting.mosaico/issues/28
                     //Change file name to unique by adding hash so every time uploading same image it will create new image name
                     $file_name = CRM_Utils_File::makeFileName($file_name);
                     $file_path = $config['BASE_DIR'] . $file_name;
                     if (move_uploaded_file($tmp_name, $file_path) === TRUE) {
                         $size = filesize($file_path);
                         $image = new Imagick($file_path);
                         $image->resizeImage($config[THUMBNAIL_WIDTH], $config[THUMBNAIL_HEIGHT], Imagick::FILTER_LANCZOS, 1.0, TRUE);
                         // $image->writeImage( $config['BASE_DIR'] . $config[ THUMBNAILS_DIR ] . $file_name );
                         if ($f = fopen($config['BASE_DIR'] . $config[THUMBNAILS_DIR] . $file_name, "w")) {
                             $image->writeImageFile($f);
                         }
                         $image->destroy();
                         $file = array("name" => $file_name, "url" => $config['BASE_URL'] . $file_name, "size" => $size, "thumbnailUrl" => $config['BASE_URL'] . $config[THUMBNAILS_URL] . $file_name);
                         $files[] = $file;
                     } else {
                         $http_return_code = 500;
                         return;
                     }
                 } else {
                     $http_return_code = 400;
                     return;
                 }
             }
         }
     }
     header("Content-Type: application/json; charset=utf-8");
     header("Connection: close");
     echo json_encode(array("files" => $files));
     CRM_Utils_System::civiExit();
 }
 /**
  * @param $reportClass
  * @param array $inputParams
  *
  * @return string
  * @throws Exception
  */
 public function getReportOutputAsCsv($reportClass, $inputParams)
 {
     $config = CRM_Core_Config::singleton();
     $config->keyDisable = TRUE;
     $controller = new CRM_Core_Controller_Simple($reportClass, ts('some title'));
     $tmpReportVal = explode('_', $reportClass);
     $reportName = array_pop($tmpReportVal);
     $reportObj =& $controller->_pages[$reportName];
     $tmpGlobals = array();
     $tmpGlobals['_REQUEST']['force'] = 1;
     $tmpGlobals['_GET'][$config->userFrameworkURLVar] = 'civicrm/placeholder';
     $tmpGlobals['_SERVER']['QUERY_STRING'] = '';
     if (!empty($inputParams['fields'])) {
         $fields = implode(',', $inputParams['fields']);
         $tmpGlobals['_GET']['fld'] = $fields;
         $tmpGlobals['_GET']['ufld'] = 1;
     }
     if (!empty($inputParams['filters'])) {
         foreach ($inputParams['filters'] as $key => $val) {
             $tmpGlobals['_GET'][$key] = $val;
         }
     }
     if (!empty($inputParams['group_bys'])) {
         $groupByFields = implode(' ', $inputParams['group_bys']);
         $tmpGlobals['_GET']['gby'] = $groupByFields;
     }
     CRM_Utils_GlobalStack::singleton()->push($tmpGlobals);
     try {
         $reportObj->storeResultSet();
         $reportObj->buildForm();
         $rows = $reportObj->getResultSet();
         $tmpFile = $this->createTempDir() . CRM_Utils_File::makeFileName('CiviReport.csv');
         $csvContent = CRM_Report_Utils_Report::makeCsv($reportObj, $rows);
         file_put_contents($tmpFile, $csvContent);
     } catch (Exception $e) {
         // print_r($e->getCause()->getUserInfo());
         CRM_Utils_GlobalStack::singleton()->pop();
         throw $e;
     }
     CRM_Utils_GlobalStack::singleton()->pop();
     return $tmpFile;
 }
Exemplo n.º 4
0
 function fileUpload()
 {
     $config = CRM_Core_Config::singleton();
     $postParams = $_POST;
     if ($postParams['entityID'] == 'undefined') {
         $result = civicrm_api3('HRJob', 'get', array('options' => array('sort' => "id DESC")));
         foreach ($result['values'] as $key => $val) {
             $id = $val['id'];
             break;
         }
         $postParams['entityID'] = ++$id;
     }
     $files = $_FILES;
     if (is_array($files) && !empty($files)) {
         foreach ($files as $k => $v) {
             $fileName = CRM_Utils_File::makeFileName(basename($v['name']));
             $maxSize = @filesize($v['tmp_name']);
             $dest = $config->customFileUploadDir;
             if ($dest != '' && substr($dest, -1) != '/') {
                 $dest .= '/';
             }
             $fileName = $fileName != '' ? $fileName : basename($v['name']);
             if (is_uploaded_file($v['tmp_name'])) {
                 if (move_uploaded_file($v['tmp_name'], $dest . $fileName)) {
                     $fileparam['name'] = $fileName;
                     $fileparam['uri'] = $fileName;
                     $file_params = array('version' => 3, 'file_type_id' => null, 'mime_type' => $v['type'], 'name' => $fileName, 'uri' => $fileName, 'upload_date' => date('Y-m-d h:i:s', time()));
                     $file_save = civicrm_api('File', 'Create', $file_params);
                     $newEntityFile = new CRM_Core_DAO_EntityFile();
                     $newEntityFile->entity_id = $postParams['entityID'];
                     $newEntityFile->entity_table = $postParams['entityTable'];
                     $newEntityFile->file_id = $file_save['id'];
                     $newEntityFile->save();
                     $fileName = basename($v['name']);
                 }
             }
         }
     }
     CRM_Utils_System::civiExit();
 }
Exemplo n.º 5
0
 /**
  * @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);
 }
Exemplo n.º 6
0
/**
 * Create an Attachment.
 *
 * @param array $params
 *
 * @return array
 * @throws API_Exception validation errors
 * @see Civi\API\Subscriber\DynamicFKAuthorization
 */
function civicrm_api3_attachment_create($params)
{
    if (empty($params['id'])) {
        // When creating we need either entity_table or field_name
        civicrm_api3_verify_one_mandatory($params, NULL, array('entity_table', 'field_name'));
    }
    $config = CRM_Core_Config::singleton();
    list($id, $file, $entityFile, $name, $content, $moveFile, $isTrusted, $returnContent) = _civicrm_api3_attachment_parse_params($params);
    $fileDao = new CRM_Core_BAO_File();
    $entityFileDao = new CRM_Core_DAO_EntityFile();
    if ($id) {
        $fileDao->id = $id;
        if (!$fileDao->find(TRUE)) {
            throw new API_Exception("Invalid ID");
        }
        $entityFileDao->file_id = $id;
        if (!$entityFileDao->find(TRUE)) {
            throw new API_Exception("Cannot modify orphaned file");
        }
    }
    if (!$id && !is_string($content) && !is_string($moveFile)) {
        throw new API_Exception("Mandatory key(s) missing from params array: 'id' or 'content' or 'options.move-file'");
    }
    if (!$isTrusted && $moveFile) {
        throw new API_Exception("options.move-file is only supported on secure calls");
    }
    if (is_string($content) && is_string($moveFile)) {
        throw new API_Exception("'content' and 'options.move-file' are mutually exclusive");
    }
    if ($id && !$isTrusted && isset($file['upload_date']) && $file['upload_date'] != CRM_Utils_Date::isoToMysql($fileDao->upload_date)) {
        throw new API_Exception("Cannot modify upload_date" . var_export(array($file['upload_date'], $fileDao->upload_date, CRM_Utils_Date::isoToMysql($fileDao->upload_date)), TRUE));
    }
    if ($id && $name && $name != CRM_Utils_File::cleanFileName($fileDao->uri)) {
        throw new API_Exception("Cannot modify name");
    }
    $fileDao->copyValues($file);
    if (!$id) {
        $fileDao->uri = CRM_Utils_File::makeFileName($name);
    }
    $fileDao->save();
    $entityFileDao->copyValues($entityFile);
    $entityFileDao->file_id = $fileDao->id;
    $entityFileDao->save();
    $path = $config->customFileUploadDir . DIRECTORY_SEPARATOR . $fileDao->uri;
    if (is_string($content)) {
        file_put_contents($path, $content);
    } elseif (is_string($moveFile)) {
        // CRM-17432 Do not use rename() since it will break file permissions.
        // Also avoid move_uplaoded_file() because the API can use options.move-file.
        copy($moveFile, $path);
        unlink($moveFile);
    }
    // Save custom field to entity
    if (!$id && empty($params['entity_table']) && isset($params['field_name'])) {
        civicrm_api3('custom_value', 'create', array('entity_id' => $params['entity_id'], $params['field_name'] => $fileDao->id));
    }
    $result = array($fileDao->id => _civicrm_api3_attachment_format_result($fileDao, $entityFileDao, $returnContent, $isTrusted));
    return civicrm_api3_create_success($result, $params, 'Attachment', 'create');
}
 /**
  * @param $params
  *
  * @return array
  * @throws CRM_Extension_Exception
  */
 public static function uploadImage($params)
 {
     $tempFile = $_FILES['file']['tmp_name'];
     $fileName = CRM_Utils_File::makeFileName($_FILES['file']['name']);
     $dirName = static::getImageDirPath($params['field']);
     // Create the upload directory, if it doesn't already exist
     CRM_Utils_File::createDir($dirName);
     $file = $dirName . $fileName;
     // Move the uploaded file to the upload directory
     if (move_uploaded_file($tempFile, $file)) {
         $imageUrl = static::getImageUrl($fileName, $params['field']);
         $result['values'] = array(array('imageUrl' => $imageUrl, 'imageFileName' => $fileName));
         return $result;
     } else {
         throw new CRM_Extension_Exception('Failed to move the uploaded file', 500);
     }
 }
 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);
     }
 }
Exemplo n.º 9
0
 function processReceiptOptions($mode)
 {
     if ($mode == 'build') {
         $this->add('text', 'receipt_prefix', ts('Receipt Prefix', array('domain' => 'org.civicrm.cdntaxreceipts')));
         $this->add('text', 'receipt_authorized_signature_text', ts('Authorized Signature Text', array('domain' => 'org.civicrm.cdntaxreceipts')));
         $config = CRM_Core_Config::singleton();
         if ($config->maxImportFileSize >= 8388608) {
             $uploadFileSize = 8388608;
         } else {
             $uploadFileSize = $config->maxImportFileSize;
         }
         $uploadSize = round($uploadFileSize / (1024 * 1024), 2);
         $this->assign('uploadSize', $uploadSize);
         $this->setMaxFileSize($uploadFileSize);
         $this->addElement('file', 'receipt_logo', ts('Organization Logo', array('domain' => 'org.civicrm.cdntaxreceipts')), 'size=30 maxlength=60');
         $this->addUploadElement('receipt_logo');
         $this->addRule('receipt_logo', ts('File size should be less than %1 MBytes (%2 bytes)', array(1 => $uploadSize, 2 => $uploadFileSize)), 'maxfilesize', $uploadFileSize, array('domain' => 'org.civicrm.cdntaxreceipts'));
         $this->addElement('file', 'receipt_signature', ts('Signature Image', array('domain' => 'org.civicrm.cdntaxreceipts')), 'size=30 maxlength=60');
         $this->addUploadElement('receipt_signature');
         $this->addRule('receipt_signature', ts('File size should be less than %1 MBytes (%2 bytes)', array(1 => $uploadSize, 2 => $uploadFileSize)), 'maxfilesize', $uploadFileSize, array('domain' => 'org.civicrm.cdntaxreceipts'));
         $this->addElement('file', 'receipt_watermark', ts('Watermark Image', array('domain' => 'org.civicrm.cdntaxreceipts')), 'size=30 maxlength=60');
         $this->addUploadElement('receipt_watermark');
         $this->addRule('receipt_watermark', ts('File size should be less than %1 MBytes (%2 bytes)', array(1 => $uploadSize, 2 => $uploadFileSize)), 'maxfilesize', $uploadFileSize, array('domain' => 'org.civicrm.cdntaxreceipts'));
         $this->addElement('file', 'receipt_pdftemplate', ts('PDF Template', array('domain' => 'org.civicrm.cdntaxreceipts')), 'size=30 maxlength=60');
         $this->addUploadElement('receipt_pdftemplate');
         $this->addRule('receipt_pdftemplate', ts('File size should be less than %1 MBytes (%2 bytes)', array(1 => $uploadSize, 2 => $uploadFileSize)), 'maxfilesize', $uploadFileSize, array('domain' => 'org.civicrm.cdntaxreceipts'));
     } else {
         if ($mode == 'defaults') {
             $defaults = array('receipt_prefix' => CRM_Core_BAO_Setting::getItem(self::SETTINGS, 'receipt_prefix'), 'receipt_authorized_signature_text' => CRM_Core_BAO_Setting::getItem(self::SETTINGS, 'receipt_authorized_signature_text'));
             return $defaults;
         } else {
             if ($mode == 'post') {
                 $values = $this->exportValues();
                 CRM_Core_BAO_Setting::setItem($values['receipt_prefix'], self::SETTINGS, 'receipt_prefix');
                 CRM_Core_BAO_Setting::setItem($values['receipt_authorized_signature_text'], self::SETTINGS, 'receipt_authorized_signature_text');
                 $receipt_logo = $this->getSubmitValue('receipt_logo');
                 $receipt_signature = $this->getSubmitValue('receipt_signature');
                 $receipt_watermark = $this->getSubmitValue('receipt_watermark');
                 $receipt_pdftemplate = $this->getSubmitValue('receipt_pdftemplate');
                 $config = CRM_Core_Config::singleton();
                 foreach (array('receipt_logo', 'receipt_signature', 'receipt_watermark', 'receipt_pdftemplate') as $key) {
                     $upload_file = $this->getSubmitValue($key);
                     if (is_array($upload_file)) {
                         if ($upload_file['error'] == 0) {
                             $filename = $config->customFileUploadDir . CRM_Utils_File::makeFileName($upload_file['name']);
                             if (!move_uploaded_file($upload_file['tmp_name'], $filename)) {
                                 CRM_Core_Error::fatal(ts('Could not upload the file'));
                             }
                             CRM_Core_BAO_Setting::setItem($filename, self::SETTINGS, $key);
                         }
                     }
                 }
             }
         }
     }
 }
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('> <', '>&nbsp;<', $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}"));
}
 function run()
 {
     if (!file_exists("/usr/bin/pdftk")) {
         CRM_Core_Error::fatal("'pdftk' nicht installiert, Erstellung des Sammel-PDF nicht moeglich");
     }
     require_once 'backend.php';
     $year = CRM_Utils_Request::retrieve('year', 'Positive', $_ = null, true);
     CRM_Utils_System::setTitle("Jahresbescheinigungen {$year}");
     $from_date = "{$year}-01-01 00:00:00";
     if ($year == date("Y")) {
         $to_date = date("Y-m-d");
     } else {
         $to_date = "{$year}-12-31";
     }
     $to_date .= " 23:59:59";
     $params = array("from_date" => $from_date, "to_date" => $to_date, "comment" => "Jahresbescheinigung {$year}");
     // Creating a lot of documents can take quite long...
     set_time_limit(0);
     $result = generate_receipts($params);
     if (!empty($result)) {
         $this->assign("have_result", true);
         /*
          * Create a merged document containing all the individual receipts.
          *
          * The actual merging is done by invoking an external tool (pdftk)
          * with all the individual receipt documents as command line parameters.
          *
          * However, as most operating systems (except GNU Hurd) have a limited maximal command line length,
          * trying to merge all documents in one go would cause an overflow if we have a lot of receipts.
          * Thus, we have to merge them in smaller batches first, before combining these into the final result.
          *
          * We do this in an iterative process, with potentially multiple intermediate levels.
          * This is most probably overkill -- but better safe than sorry :-)
          */
         define('BATCH_SIZE', 1000);
         // With a typical command line length limit of 64 KiB, this should give us enough leeway...
         $tempDir = CRM_Utils_File::tempdir('donationreceipts-');
         $config = CRM_Core_Config::singleton();
         // In the first pass, we start with the individual receipt documents we just generated.
         $inFiles = array_map(function ($elem) {
             return $elem['filename'];
         }, $result);
         $inDir = $config->customFileUploadDir;
         for ($pass = 1, $isFinalPass = false; !$isFinalPass; ++$pass) {
             // Do at least one pass; and further ones as necessary.
             $batches = array_chunk($inFiles, BATCH_SIZE);
             $isFinalPass = !(count($batches) > 1);
             // If the current input files fit into a single batch, we will be done after this pass; otherwise, we need further passes.
             $outFiles = array();
             foreach ($batches as $batchID => $filesInBatch) {
                 // If this is the final pass, the current output will be the actual result file to save; otherwise, we generate temporary files for further merging.
                 $outDir = $isFinalPass ? $config->customFileUploadDir : $tempDir;
                 $baseName = $isFinalPass ? CRM_Utils_File::makeFileName("Jahresbescheinigungen-{$year}.pdf") : "{$pass}-{$batchID}.pdf";
                 $outFile = $outDir . $baseName;
                 $inputs = join(" ", $filesInBatch);
                 system("cd {$inDir} && pdftk {$inputs} cat output {$outFile}");
                 $outFiles[] = $baseName;
                 // If our inputs are temporary results from the previous pass, we can drop them now.
                 if ($inDir == $tempDir) {
                     foreach ($filesInBatch as $file) {
                         unlink($tempDir . $file);
                     }
                 }
             }
             // Outputs from this pass are inputs for next one.
             $inFiles = $outFiles;
             $inDir = $tempDir;
         }
         // for ($pass)
         rmdir($tempDir);
         if (file_exists($outFile)) {
             $session = CRM_Core_Session::singleton();
             $user = $session->get('userID');
             $file_id = saveDocument($user, $baseName, "application/pdf", "Jahresbescheinigungen", date("Y-m-d h:i:s"), $from_date, $to_date, "Sammeldatei Jahresbescheinigungen {$year}");
             $this->assign("url", CRM_Utils_System::url("civicrm/file", "reset=1&id={$file_id}&eid={$user}"));
         } else {
             CRM_Core_Error::fatal("Erstellen des Sammeldokuments fehlgeschlagen");
         }
     }
     /* !empty($result) */
     parent::run();
 }
Exemplo n.º 12
0
 /**
  * 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);
 }
/**
 * Implements hook_civicrm_alterMailParams().
 *
 * Intercepts outgoing report emails, in order to attach the
 * excel2007 version of the report.
 *
 * TODO: we should really propose a patch to CRM_Report_Form::endPostProcess().
 */
function civiexportexcel_attach_to_email(&$form, &$rows, &$attachments)
{
    $config = CRM_Core_Config::singleton();
    $filename = 'CiviReport.xlsx';
    $fullname = $config->templateCompileDir . CRM_Utils_File::makeFileName($filename);
    CRM_CiviExportExcel_Utils_Report::generateFile($form, $rows, $fullname);
    $attachments[] = array('fullPath' => $fullname, 'mime_type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'cleanName' => $filename);
}
Exemplo n.º 14
0
 /**
  * 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);
     }
 }
Exemplo n.º 15
0
 /**
  * @param $mail
  *
  * @return array
  */
 public static function parseMailingObject(&$mail)
 {
     $config = CRM_Core_Config::singleton();
     // get ready for collecting data about this email
     // and put it in a standardized format
     $params = array('is_error' => 0);
     $params['from'] = array();
     self::parseAddress($mail->from, $field, $params['from'], $mail);
     // we definitely need a contact id for the from address
     // if we dont have one, skip this email
     if (empty($params['from']['id'])) {
         return NULL;
     }
     $emailFields = array('to', 'cc', 'bcc');
     foreach ($emailFields as $field) {
         $value = $mail->{$field};
         self::parseAddresses($value, $field, $params, $mail);
     }
     // define other parameters
     $params['subject'] = $mail->subject;
     $params['date'] = date("YmdHi00", strtotime($mail->getHeader("Date")));
     $attachments = array();
     $params['body'] = self::formatMailPart($mail->body, $attachments);
     // format and move attachments to the civicrm area
     if (!empty($attachments)) {
         $date = date('Ymdhis');
         $config = CRM_Core_Config::singleton();
         for ($i = 0; $i < count($attachments); $i++) {
             $attachNum = $i + 1;
             $fileName = basename($attachments[$i]['fullName']);
             $newName = CRM_Utils_File::makeFileName($fileName);
             $location = $config->uploadDir . $newName;
             // move file to the civicrm upload directory
             rename($attachments[$i]['fullName'], $location);
             $mimeType = "{$attachments[$i]['contentType']}/{$attachments[$i]['mimeType']}";
             $params["attachFile_{$attachNum}"] = array('uri' => $fileName, 'type' => $mimeType, 'upload_date' => $date, 'location' => $location);
         }
     }
     return $params;
 }
function wordmailmerge_civicrm_post($op, $objectName, $objectId, &$objectRef)
{
    if ($objectName == 'MessageTemplate') {
        $config = CRM_Core_Config::singleton();
        $uploaddir = $config->customFileUploadDir;
        $value = $_FILES['attachFile_1'];
        $fileFormat = explode(".", $value['name']);
        if (isset($fileFormat[1]) && ($fileFormat[1] == 'docx' || $fileFormat[1] == 'odt' && !empty($fileFormat[0]))) {
            $newName = CRM_Utils_File::makeFileName($value['name']);
            $mime_type = $_FILES['attachFile_1']['type'];
            $uploadfile = $uploaddir . $newName;
            if (move_uploaded_file($_FILES['attachFile_1']['tmp_name'], $uploadfile)) {
                $sql = "INSERT INTO `civicrm_file` ( mime_type, uri )\n                VALUES ( %1, %2 )";
                $params = array(1 => array($mime_type, 'String'), 2 => array($newName, 'String'));
                CRM_Core_DAO::executeQuery($sql, $params);
                $query = " SELECT * FROM `civicrm_file` WHERE `uri` = %1";
                $params = array(1 => array($newName, 'String'));
                $dao = CRM_Core_DAO::executeQuery($query, $params);
                while ($dao->fetch()) {
                    $msgId = $dao->id;
                }
                $sql = "INSERT INTO `civicrm_entity_file` ( entity_table, entity_id, file_id )\n                VALUES ( %1, %2, %3 )";
                $params = array(1 => array('civicrm_msg_template', 'String'), 2 => array($objectId, 'Integer'), 3 => array($msgId, 'Integer'));
                CRM_Core_DAO::executeQuery($sql, $params);
                $mysql = "INSERT INTO `veda_civicrm_wordmailmerge` ( msg_template_id, file_id )\n                VALUES ( %1, %2 )";
                $params = array(1 => array($objectId, 'Integer'), 2 => array($msgId, 'Integer'));
                CRM_Core_DAO::executeQuery($mysql, $params);
            } else {
                $mysql = "DELETE FROM `veda_civicrm_wordmailmerge` WHERE msg_template_id = %1";
                $params = array(1 => array($objectId, 'Integer'));
                CRM_Core_DAO::executeQuery($mysql, $params);
                CRM_Core_Session::setStatus(ts("No attach doc in your new template."));
                CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/admin/messageTemplates', 'reset=1'));
            }
        } else {
            if ($op == 'create' && !empty($fileFormat[0])) {
                CRM_Core_Session::setStatus(ts("Attachment file is not doc format."));
                CRM_Utils_System::redirect(CRM_Utils_System::url("civicrm/admin/messageTemplates/add", "action=add&reset=1"));
            }
            if ($op == 'edit' && !empty($fileFormat[0])) {
                CRM_Core_Session::setStatus(ts("Attachment file is not doc format."));
                CRM_Utils_System::redirect(CRM_Utils_System::url("civicrm/admin/messageTemplates/add", "action=update&id={$objectId}&reset=1"));
            }
        }
    }
}
Exemplo n.º 17
-1
 /**
  * upload and move the file if valid to the uploaded directory
  *
  * @param object $page       the CRM_Core_Form object
  * @param object $data       the QFC data container
  * @param string $pageName   the name of the page which index the data container with
  * @param string $uploadName the name of the uploaded file
  *
  * @return void
  * @access private
  */
 function upload(&$page, &$data, $pageName, $uploadName)
 {
     // make sure uploadName exists in the QF array
     // else we skip, CRM-3427
     if (empty($uploadName) || !isset($page->_elementIndex[$uploadName])) {
         return;
     }
     // get the element containing the upload
     $element =& $page->getElement($uploadName);
     if ('file' == $element->getType()) {
         if ($element->isUploadedFile()) {
             // rename the uploaded file with a unique number at the end
             $value = $element->getValue();
             $newName = CRM_Utils_File::makeFileName($value['name']);
             $status = $element->moveUploadedFile($this->_uploadDir, $newName);
             if (!$status) {
                 CRM_Core_Error::statusBounce(ts('We could not move the uploaded file %1 to the upload directory %2. Please verify that the \'Temporary Files\' setting points to a valid path which is writable by your web server.', array(1 => $value['name'], 2 => $this->_uploadDir)));
             }
             if (!empty($data['values'][$pageName][$uploadName]['name'])) {
                 @unlink($this->_uploadDir . $data['values'][$pageName][$uploadName]);
             }
             $data['values'][$pageName][$uploadName] = array('name' => $this->_uploadDir . $newName, 'type' => $value['type']);
         }
     }
 }