diff --git a/views_pdf_template.php b/views_pdf_template.php index 1a0f096..20bbda9 100644 --- a/views_pdf_template.php +++ b/views_pdf_template.php @@ -398,6 +398,53 @@ class PdfTemplate extends FPDI { return ''; } + // TCPDF uses cURL to fetch the image files. As a result, it looks like an + // anonymous user. If anonymous users don't have privileges to view the + // images, we'll get an error saying "TCPDF ERROR: [Image] Unable to get + // image", despite the current user having the proper privileges. + // + // Luckily, TCPDF can also add images from inline base64 encoded data. So, + // we check for images that the current user is allowed to see, but + // anonymous users aren't. We then replace the src-attribute contents with + // the base64-encoded image data for such images. + // + // Get all the src-attributes: + preg_match_all('/]+src="([^"]+)"/', $content, $matches); + foreach ($matches[1] as $match) { + // We're only interested in private files. We can recognize them by the + // standard URL. + if (substr($match, 0, 14) == '/system/files/') { + // Process the URL into a Drupal internal URI. + $uri = substr($match, 14); + $uri = 'private://' . file_stream_wrapper_uri_normalize($uri); + + // Check that the URI refers to a Drupal managed file object. + $efq = new EntityFieldQuery(); + $efq->entityCondition('entity_type', 'file'); + $efq->propertyCondition('uri', $uri); + $result = $efq->execute(); + if (isset($result['file']) && !empty($result['file'])) { + // Make sure anonymous users can't get the file. + global $base_url; + $access = drupal_http_request($base_url . $match); + if ($access->code == 403) { + // Make sure the current user can get the file. + $options = array( + 'headers' => array( + 'Cookie' => session_name() . '=' . $_COOKIE[session_name()], + ) + ); + $access = drupal_http_request($base_url . $match, $options); + if ($access->code == 200) { + // Replace the src attribute with the encoded data. TCPDF + // recognizes inline data by the leading '@'. + $content = str_replace($match, '@' . base64_encode($access->data), $content); + } + } + } + } + } + // Apply the hyphenation patterns to the content: if (!isset($options['text']['hyphenate']) && is_object($view) && is_object($view->display_handler)) { $options['text']['hyphenate'] = $view->display_handler->get_option('default_text_hyphenate');