You are here

function fillpdf_merge_pdf in FillPDF 7.2

Same name and namespace in other branches
  1. 6 fillpdf.module \fillpdf_merge_pdf()
  2. 7 fillpdf.module \fillpdf_merge_pdf()
2 calls to fillpdf_merge_pdf()
fillpdf_parse_uri in ./fillpdf.module
Get the data and form that need to be merged, from the $_GET, and print the PDF
fillpdf_rules_action_merge_webform in ./fillpdf.rules.inc
Populates a loaded FillPDF configuration's PDF with data.

File

./fillpdf.module, line 293
Allows mappings of PDFs to site content

Code

function fillpdf_merge_pdf($fid, $nids = NULL, $webform_arr = NULL, $sample = NULL, $force_download = FALSE, $skip_access_check = FALSE, $flatten = TRUE, $handle = TRUE, $uc_order_ids = NULL, $uc_order_product_ids) {

  // Case 1: No $fid
  if (is_null($fid)) {
    drupal_set_message(t('FillPDF Form ID required to print a PDF.'), 'warning');
    drupal_goto();
  }
  $fillpdf_info = fillpdf_load($fid);

  // Case 1.5: $fid is not valid.
  if ($fillpdf_info === FALSE) {
    drupal_set_message(t('Non-existent FillPDF Form ID.'), 'error');
    drupal_not_found();
    drupal_exit();
  }
  global $user;
  $nodes = $webforms = $uc_orders = $uc_order_products = array();

  // If $webform_arr contains entries with an sid, but not an nid, set the nid to the default.
  if (!empty($fillpdf_info->default_nid) && is_array($webform_arr)) {
    foreach (array_keys($webform_arr) as $key) {
      if (empty($webform_arr[$key]['nid'])) {
        $webform_arr[$key]['nid'] = $fillpdf_info->default_nid;
      }
    }
  }

  // If no nid is given, use the default.
  if (!empty($fillpdf_info->default_nid) && empty($nids) && empty($webform_arr)) {
    $default_node = node_load($fillpdf_info->default_nid);
    if ($default_node) {
      if (empty($default_node->webform)) {

        // Default node is a non-webform node.
        $nodes[] = $default_node;
      }
      else {

        // Default node is a webform.
        $webform_arr = array(
          array(
            'nid' => $fillpdf_info->default_nid,
            'node' => $default_node,
          ),
        );
      }
    }
  }

  // Nodes
  if (is_array($nids)) {
    foreach ($nids as $nid) {
      $nodes[] = node_load($nid);
    }
  }

  // Webforms
  if (module_exists('webform') && is_array($webform_arr)) {

    // Load the proper submission helper file and account for the different
    // versions of Webform.
    $included = module_load_include('inc', 'webform', 'includes/webform.submissions');
    if ($included === FALSE) {
      module_load_include('inc', 'webform', 'webform_submissions');
    }
    foreach ($webform_arr as $webform) {
      if (!empty($webform['nid'])) {
        if (empty($webform['sid'])) {

          // User did not specify submission ID, meaning they want most recent.
          $webform['sid'] = db_query('SELECT sid FROM {webform_submissions}
            WHERE nid = :nid AND uid = :uid ORDER BY submitted DESC', array(
            ':nid' => $webform['nid'],
            ':uid' => $user->uid,
          ))
            ->fetchField();
        }
        if ($webform['sid'] !== FALSE) {
          $webforms[] = array(
            'webform' => empty($webform['node']) ? node_load($webform['nid']) : $webform['node'],
            'submission' => webform_get_submission($webform['nid'], $webform['sid']),
          );
        }
      }
    }
  }

  // Ubercart Orders
  if (module_exists('uc_order') && is_array($uc_order_ids)) {
    foreach ($uc_order_ids as $uc_order_id) {
      $uc_orders[] = uc_order_load($uc_order_id);
    }
  }

  // Ubercart Ordered Products
  if (module_exists('uc_order') && is_array($uc_order_product_ids)) {
    foreach ($uc_order_product_ids as $uc_order_product_id) {
      $uc_order_products[] = uc_order_product_load($uc_order_product_id);
    }
  }
  if ($skip_access_check !== TRUE) {
    if (!fillpdf_merge_pdf_access($nodes, $webforms, $uc_orders, $uc_order_products)) {
      drupal_access_denied();
      drupal_exit();
    }
  }

  // TODO: Debug filling with uc_orders.
  $fields = $token_objects = $image_data = array();
  $query = db_query("SELECT * FROM {fillpdf_fields} WHERE fid = :fid", array(
    ':fid' => $fid,
  ));
  foreach ($query as $obj) {
    $obj->replacements = _fillpdf_replacements_to_array($obj->replacements);

    // Keep track of whether we're dealing with an image or not
    $transform_string = FALSE;

    // Fill a sample PDF & return
    if ($sample == 'true') {
      $fields[$obj->pdf_key] = $obj->pdf_key;

      // If sampling, return to the form edit page
      $_GET['destination'] = "admin/structure/fillpdf/{$fid}";
    }
    else {

      // multiple nids, #516840
      // we want the last nid in $_GET to override previous ones (aka, of fillpdf?nids[]=1&nids[]=2, 2 wins)
      $nodes = array_reverse($nodes);
      $webforms = array_reverse($webforms);
      $uc_orders = array_reverse($uc_orders);
      $uc_order_products = array_reverse($uc_order_products);

      // --- node token replacements
      if (!empty($nodes)) {
        foreach ($nodes as $node) {
          $token_objects['node'] = $node;

          // The third parameter says to clear the value if no token can be generated
          $token = token_replace($obj->value, array(
            'node' => $node,
          ), array(
            'clear' => TRUE,
            'sanitize' => FALSE,
          ));
          if ($token && $token != $obj->value) {
            break;
          }
        }
        $transform_string = TRUE;

        // If they're populating with an Image field
        if (strstr($obj->value, '[stamp:')) {

          // HACK: Use a pseudo-token to stamp images.
          // Find the two sides of the square bracket contents.
          // 7 is the length of [stamp:. We don't want the brackets themselves.
          $left_side = strpos($obj->value, '[stamp:') + 7;
          $right_side = strpos($obj->value, ']');
          $field_name = substr($obj->value, $left_side, $right_side - $left_side);
          if (isset($node->{$field_name}[$node->language])) {
            $image_path = $node->{$field_name}[$node->language][0]['uri'];
            $transform_string = FALSE;
            $fields[$obj->pdf_key] = '{image}' . drupal_realpath($image_path);
            $image_path_info = pathinfo(drupal_realpath($image_path));

            // Store the image data to transmit to the remote service if necessary
            $file_data = file_get_contents(drupal_realpath($image_path));
            if ($file_data) {
              $image_data[$obj->pdf_key] = array(
                'data' => base64_encode($file_data),
                'filenamehash' => md5($image_path_info['filename']) . '.' . $image_path_info['extension'],
              );
            }
          }
        }
      }

      // /--- node token replacements ---
      // --- webform token replacements
      if (!empty($webforms)) {
        foreach ($webforms as $webform) {
          $token_objects += array(
            'webform-submission' => $webform['submission'],
            'submission' => $webform['submission'],
            'node' => $webform['webform'],
          );
          $token = token_replace($obj->value, $token_objects, array(
            'clear' => TRUE,
            'sanitize' => FALSE,
          ));
          if ($token) {
            break;
          }
        }
        $transform_string = TRUE;
      }

      // /--- webform token replacements ---
      // --- Ubercart Order token replacements
      if (!empty($uc_orders)) {
        foreach ($uc_orders as $uc_order) {
          $token_objects += array(
            'uc_order' => $uc_order,
          );
          $token = token_replace($obj->value, $token_objects, array(
            'clear' => TRUE,
            'sanitize' => FALSE,
          ));
          if ($token) {
            break;
          }
        }
        $transform_string = TRUE;
      }

      // /--- Ubercart Order token replacements ---
      // --- Ubercart Order Product token replacements
      if (!empty($uc_order_products)) {
        foreach ($uc_order_products as $uc_order_product) {
          $token_objects += array(
            'uc_order_product' => $uc_order_product,
            'uc_order' => uc_order_load($uc_order_product->order_id),
            'node' => node_load($uc_order_product->nid),
          );
          $token = token_replace($obj->value, $token_objects, array(
            'clear' => TRUE,
            'sanitize' => FALSE,
          ));
          if ($token) {
            break;
          }
        }
        $transform_string = TRUE;
      }

      // /--- Ubercart Order Product token replacements ---
      if ($transform_string) {

        // Replace <br /> occurrences with newlines
        $str = preg_replace('|<br />|', '
', $token);
        $str = _fillpdf_transform_field_value($str, $fillpdf_info->replacements, $obj->replacements);
        $fields[$obj->pdf_key] = $str;
      }
    }

    // Apply prefix and suffix, if applicable
    if (isset($fields[$obj->pdf_key]) && $fields[$obj->pdf_key]) {
      if ($obj->prefix) {
        $fields[$obj->pdf_key] = $obj->prefix . $fields[$obj->pdf_key];
      }
      if ($obj->suffix) {
        $fields[$obj->pdf_key] .= $obj->suffix;
      }
    }
  }

  // Provide hook_fillpdf_merge_fields_alter() to let other modules
  // alter fields before pdf generation.
  $context = array(
    'nodes' => $nodes,
    'webforms' => $webforms,
    'uc_orders' => $uc_orders,
    'uc_order_products' => $uc_order_products,
  );
  drupal_alter('fillpdf_merge_fields_alter', $fields, $context);

  // Prep options for pdf_forms_fill().
  $fill_options = array(
    'flatten' => $flatten,
    'image data' => $image_data,
  );
  $data = pdf_forms_fill($fillpdf_info->url, $fields, $fill_options);
  if ($webform_arr && isset($webform['webform'])) {
    $node = $webform['webform'];
  }
  if (!empty($node)) {

    // Log this, could be useful
    watchdog('fillpdf', 'User generated form "%form" for node "%node".', array(
      '%form' => $fillpdf_info->title,
      '%node' => $node->title,
    ));
  }

  // Assemble some metadata that will be useful for the handling phase.
  $fillpdf_object = _fillpdf_build_options_object($force_download, $flatten, $fillpdf_info, $data, $nodes, $webforms, $uc_orders, $uc_order_products, $token_objects);
  if ($handle === TRUE) {

    // Allow modules to step in here and change the way the PDF is handled
    module_invoke_all('fillpdf_merge_pre_handle', $fillpdf_object);

    // Perform the default action on the PDF - in other words, the one it was
    // configured to do in the administrative area.
    fillpdf_merge_handle_pdf($fillpdf_object->info, $fillpdf_object->data, $fillpdf_object->token_objects, 'default', $force_download);
  }
  else {
    return $fillpdf_object;
  }
}